From 817623750aac9578b4e8cfa381f3d7eb5004f8f7 Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Tue, 22 Sep 2026 12:02:54 +0800 Subject: [PATCH 1/4] fix(desktop): match Platform login theme Opened and copied authorization links carried no palette, so the Platform login page rendered its own stored preference. Append the effective Desktop palette as theme=light or theme=dark, resolving system through the theme source the preload publishes. The theme source now reaches nativeTheme on Windows as well: the preload drops its macOS-only guard, since shouldUseDarkColors is read for every platform, and gates the DOMContentLoaded listener with once. --- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- apps/desktop/src/main.ts | 18 +++++- apps/desktop/src/preload-theme.ts | 15 +++-- apps/desktop/tests/main-startup.spec.ts | 20 ++++++- .../tests/preload-theme.client.spec.ts | 58 +++++++++++++++++++ apps/desktop/tests/welcome-startup.spec.ts | 11 +++- 8 files changed, 112 insertions(+), 18 deletions(-) create mode 100644 apps/desktop/tests/preload-theme.client.spec.ts diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index d74baaa4b8..6e44ed8a7c 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/desktop/README.md -README.md: 711e65fb5feaea601800218801d138a0df9b3f97 -README.zh.md: 183d195a9af485c9ffe5a3e5bf65e3a459582b93 +README.md: 59f18ea269f303e267d5e9597d8748e2a8fed134 +README.zh.md: eb1594e032fea2da38f778e6b2217bd52587af91 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 711e65fb5f..59f18ea269 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -405,7 +405,7 @@ An unpackaged Electron process uses `.desktop-build/development/project` under i - Dependency lifecycle scripts follow pnpm’s build permissions; Desktop provides no separate approval dialog. - The desktop shell shares sessions, settings, credentials, workspaces, and storage under `$DSH_HOME` with CLI dsh, while executable packages, plugin activation, and lockfiles remain separate. -Sign in opens the configured platform page in the system browser. The Host owns PKCE and a temporary loopback callback, saves the credential before entering the workspace, and redirects the browser to the platform completion page. Cancel withdraws the local attempt even if the platform page later approves it. Settings offers Account sign-out; without a separate API key, sign-out returns to the welcome window. Packaged applications register dsh://open to show the window without passing credentials. On macOS, the development launcher prepares an ad-hoc-signed `Harness Dev.app` under `.desktop-build/development`, declares `dsh` in its Info.plist, and registers it with Launch Services. It loads the current workspace and records the selected development home, browser-data path, and debug settings for cold starts. Starting this bundle makes it the default `dsh://` handler; starting the packaged application registers the packaged handler again. The generated bundle does not contain account tokens and requires the workspace and prepared runtime to remain available. +Sign in opens the configured platform page in the system browser. The Host owns PKCE and a temporary loopback callback, saves the credential before entering the workspace, and redirects the browser to the platform completion page. Opened and copied authorization links carry the effective Desktop theme as `theme=light` or `theme=dark`; `system` resolves at the time of the action. Cancel withdraws the local attempt even if the platform page later approves it. Settings offers Account sign-out; without a separate API key, sign-out returns to the welcome window. Packaged applications register dsh://open to show the window without passing credentials. On macOS, the development launcher prepares an ad-hoc-signed `Harness Dev.app` under `.desktop-build/development`, declares `dsh` in its Info.plist, and registers it with Launch Services. It loads the current workspace and records the selected development home, browser-data path, and debug settings for cold starts. Starting this bundle makes it the default `dsh://` handler; starting the packaged application registers the packaged handler again. The generated bundle does not contain account tokens and requires the workspace and prepared runtime to remain available. An expired login displays a timeout heading with explicit Sign in again and Add API Key actions. Opening the API-key form dismisses the authorization view; late account-state notifications do not replace an in-progress key entry. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 183d195a9a..eb1594e032 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -405,7 +405,7 @@ node apps/desktop/node_modules/pnpm/bin/pnpm.mjs --dir apps/desktop run test:upd - 依赖的生命周期脚本遵循 pnpm 的构建权限;Desktop 不提供单独的审批对话框。 - 桌面壳与 CLI dsh 共享 `$DSH_HOME` 下的会话、设置、凭据、工作区和存储,但可执行包、插件激活和锁文件彼此隔离。 -登录会在系统浏览器中打开配置的平台页面。Host 负责 PKCE 和临时本机回调,在进入工作区前保存凭证,再将浏览器跳转到平台完成页。即使平台页面随后批准,取消仍会撤销本地尝试。设置中的账号页面提供退出;没有独立 API Key 时,退出后返回欢迎窗。打包应用注册 dsh://open,只显示窗口而不传递凭证。macOS 开发启动器在 `.desktop-build/development` 下准备经临时签名的 `Harness Dev.app`,在 Info.plist 中声明 `dsh` 并注册到 Launch Services。它加载当前工作区,并记录选定的开发 home、浏览器数据路径和调试设置,以供冷启动使用。启动此应用会将其设为 `dsh://` 默认处理程序;启动打包应用会重新注册打包版处理程序。生成的应用包不包含账号 token,依赖工作区和已准备的运行环境继续存在。 +登录会在系统浏览器中打开配置的平台页面。Host 负责 PKCE 和临时本机回调,在进入工作区前保存凭证,再将浏览器跳转到平台完成页。打开和复制的授权链接通过 `theme=light` 或 `theme=dark` 携带当前生效的 Desktop 主题;`system` 在执行操作时解析。即使平台页面随后批准,取消仍会撤销本地尝试。设置中的账号页面提供退出;没有独立 API Key 时,退出后返回欢迎窗。打包应用注册 dsh://open,只显示窗口而不传递凭证。macOS 开发启动器在 `.desktop-build/development` 下准备经临时签名的 `Harness Dev.app`,在 Info.plist 中声明 `dsh` 并注册到 Launch Services。它加载当前工作区,并记录选定的开发 home、浏览器数据路径和调试设置,以供冷启动使用。启动此应用会将其设为 `dsh://` 默认处理程序;启动打包应用会重新注册打包版处理程序。生成的应用包不包含账号 token,依赖工作区和已准备的运行环境继续存在。 登录超时后显示超时标题,并提供重新登录和添加 API Key 按钮。打开 API Key 表单会关闭授权视图;后续账号状态通知不会覆盖正在填写的密钥。 diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 46ce1f45c1..9d5497101e 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -127,6 +127,20 @@ function chromeFallbackFill(): string { return nativeTheme.shouldUseDarkColors ? '#1b1b1c' : '#f9fafb' } +/** + * Add the effective Desktop palette to a Platform authorization URL so the + * login page opens in the application's theme. `system` resolves through + * `nativeTheme.shouldUseDarkColors`, which follows the theme source the + * application preload publishes. + * @param authorizeUrl - validated Platform authorization URL. + * @returns the authorization URL carrying `theme=light` or `theme=dark`. + */ +function platformLoginUrl(authorizeUrl: string): string { + const url = new URL(authorizeUrl) + url.searchParams.set('theme', nativeTheme.shouldUseDarkColors ? 'dark' : 'light') + return url.href +} + function createWindow(preload: string, show = false, primary = false): BrowserWindow { const window = new BrowserWindow({ width: 1280, @@ -333,7 +347,7 @@ async function main(): Promise { const attempt = state.attempt if (attempt?.phase === 'waiting-browser' && attempt.authorizeUrl !== undefined && openedAttempt !== attempt.id) { openedAttempt = attempt.id - void shell.openExternal(attempt.authorizeUrl).catch(() => undefined) + void shell.openExternal(platformLoginUrl(attempt.authorizeUrl)).catch(() => undefined) } if ((attempt?.phase === 'failed' || attempt?.phase === 'expired') && returnedAttempt !== attempt.id) { returnedAttempt = attempt.id @@ -892,7 +906,7 @@ async function main(): Promise { if (state?.attempt?.id !== id || state.attempt.phase !== 'waiting-browser' || state.attempt.authorizeUrl === undefined) { throw new Error('desktop welcome: login link is unavailable') } - await clipboard.writeText(state.attempt.authorizeUrl) + await clipboard.writeText(platformLoginUrl(state.attempt.authorizeUrl)) }, saveApiKey: async (apiKey) => { if (backend.host === undefined || welcomeBackend === undefined) return { ok: false } diff --git a/apps/desktop/src/preload-theme.ts b/apps/desktop/src/preload-theme.ts index cb1acb9699..1274e5b3c4 100644 --- a/apps/desktop/src/preload-theme.ts +++ b/apps/desktop/src/preload-theme.ts @@ -1,4 +1,4 @@ -/** Mirrors the Web UI's theme source into the macOS native theme so window vibrancy follows the app palette. */ +/** Mirrors the Web UI's theme source into Electron's native theme so native chrome and Platform login pages follow the app palette. */ import { ipcRenderer } from 'electron' import { DESKTOP_IPC } from './ipc.ts' @@ -7,14 +7,13 @@ import { DESKTOP_IPC } from './ipc.ts' const THEME_SOURCE_ATTRIBUTE = 'data-ds-theme-source' /** - * On macOS, watches `html[data-ds-theme-source]` and forwards each value to - * the main process, which sets `nativeTheme.themeSource` — the sidebar - * vibrancy material then follows the app's theme preference instead of the - * OS appearance, while `system` keeps following the OS. Other platforms - * never send. + * Watches `html[data-ds-theme-source]` and forwards each value to the main + * process, which sets `nativeTheme.themeSource`. The macOS sidebar vibrancy + * material then follows the app's theme preference instead of the OS + * appearance while `system` keeps following the OS, and the resolved + * `shouldUseDarkColors` palette travels with the Platform login link. */ export function syncNativeTheme(): void { - if (process.platform !== 'darwin') return let sent: string | undefined const send = (): void => { const value = document.documentElement.getAttribute(THEME_SOURCE_ATTRIBUTE) @@ -28,6 +27,6 @@ export function syncNativeTheme(): void { } // The preload runs before the document root exists; the theme bootstrap // script writes the attribute before DOMContentLoaded. - if (document.readyState === 'loading') window.addEventListener('DOMContentLoaded', observe) + if (document.readyState === 'loading') window.addEventListener('DOMContentLoaded', observe, { once: true }) else observe() } diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 26c31d906c..00a79e9963 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -165,7 +165,7 @@ const harness = await vi.hoisted(async () => { get publishUpdate() { return publishUpdate! }, set publishUpdate(value: (state: DesktopUpdateState) => DesktopUpdateState) { publishUpdate = value }, dialog: { showOpenDialog: vi.fn(), showErrorBox: vi.fn(), showMessageBox: vi.fn() }, - openExternal: vi.fn(), + openExternal: vi.fn(async () => {}), protocolHandle: vi.fn<(scheme: string, handler: (request: Request) => Response | Promise) => void>(), applyRelease: vi.fn(() => { preparing.resolve(); return prepared.promise }), disableAllPlugins: vi.fn(async () => { @@ -1617,3 +1617,21 @@ it.each(['failed', 'expired'] as const)('focuses DSH once when browser authoriza harness.publishAccount(state) expect(window.focus).toHaveBeenCalledTimes(1) }) + +it.each([['light', false], ['dark', true]] as const)('opens Platform authorization in the effective %s palette', async (theme, shouldUseDarkColors) => { + await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() + await harness.hostStarted.promise + harness.hosts[0]!.ready.resolve() + await Promise.resolve(invoke(DESKTOP_IPC.boot)) + harness.nativeTheme.shouldUseDarkColors = shouldUseDarkColors + const state: AccountView = { + status: 'signed-out', links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' }, + attempt: { id: 'test-theme-attempt' as NonNullable['id'], phase: 'waiting-browser', + authorizeUrl: 'https://platform.deepseek.com/dsh/authorize?state=state-1' }, + } + harness.publishAccount(state) + harness.publishAccount(state) + expect(harness.openExternal).toHaveBeenCalledExactlyOnceWith(`https://platform.deepseek.com/dsh/authorize?state=state-1&theme=${theme}`) +}) diff --git a/apps/desktop/tests/preload-theme.client.spec.ts b/apps/desktop/tests/preload-theme.client.spec.ts new file mode 100644 index 0000000000..90cd23eab0 --- /dev/null +++ b/apps/desktop/tests/preload-theme.client.spec.ts @@ -0,0 +1,58 @@ +// @vitest-environment jsdom +import { afterEach, expect, it, vi } from 'vitest' +import { DESKTOP_IPC } from '../src/ipc.ts' +import { syncNativeTheme } from '../src/preload-theme.ts' + +const send = vi.hoisted(() => vi.fn()) +vi.mock('electron', () => ({ ipcRenderer: { send } })) + +/** Observers created by the module under test; jsdom keeps one document per file. */ +const observers = new Set() +const NativeMutationObserver = MutationObserver + +/** Records every observer so teardown detaches it from the shared document. */ +class TrackedMutationObserver extends NativeMutationObserver { + constructor(callback: MutationCallback) { + super(callback) + observers.add(this) + } +} + +afterEach(() => { + for (const observer of observers) observer.disconnect() + observers.clear() + document.documentElement.removeAttribute('data-ds-theme-source') + vi.unstubAllGlobals() + vi.restoreAllMocks() + send.mockClear() +}) + +it.each(['darwin', 'win32'] as const)('mirrors the application theme source on %s', async (platform) => { + vi.stubGlobal('MutationObserver', TrackedMutationObserver) + vi.spyOn(process, 'platform', 'get').mockReturnValue(platform) + document.documentElement.setAttribute('data-ds-theme-source', 'dark') + syncNativeTheme() + expect(send).toHaveBeenCalledExactlyOnceWith(DESKTOP_IPC.nativeThemeSet, 'dark') + document.documentElement.setAttribute('data-ds-theme-source', 'system') + await vi.waitFor(() => { expect(send).toHaveBeenLastCalledWith(DESKTOP_IPC.nativeThemeSet, 'system') }) + expect(send).toHaveBeenCalledTimes(2) + for (const observer of observers) observer.disconnect() + send.mockClear() + document.documentElement.setAttribute('data-ds-theme-source', 'light') + await new Promise((resolve) => { queueMicrotask(resolve) }) + expect(send).not.toHaveBeenCalled() +}) + +it('waits for the document root and then stops listening for it', () => { + vi.stubGlobal('MutationObserver', TrackedMutationObserver) + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + vi.spyOn(document, 'readyState', 'get').mockReturnValue('loading') + syncNativeTheme() + expect(send).not.toHaveBeenCalled() + document.documentElement.setAttribute('data-ds-theme-source', 'light') + window.dispatchEvent(new Event('DOMContentLoaded')) + expect(send).toHaveBeenCalledExactlyOnceWith(DESKTOP_IPC.nativeThemeSet, 'light') + document.documentElement.setAttribute('data-ds-theme-source', 'dark') + window.dispatchEvent(new Event('DOMContentLoaded')) + expect(send).toHaveBeenCalledOnce() +}) diff --git a/apps/desktop/tests/welcome-startup.spec.ts b/apps/desktop/tests/welcome-startup.spec.ts index db461e59e2..6dd4080692 100644 --- a/apps/desktop/tests/welcome-startup.spec.ts +++ b/apps/desktop/tests/welcome-startup.spec.ts @@ -31,6 +31,7 @@ const state = vi.hoisted(() => ({ windowOptions: undefined as BrowserWindowConstructorOptions | undefined, menu: vi.fn(), operations: undefined as WelcomeOperations | undefined, + nativeTheme: { themeSource: 'system', shouldUseDarkColors: false }, })) vi.mock('electron', () => ({ @@ -67,7 +68,7 @@ vi.mock('electron', () => ({ async loadURL(url: string) { state.contents = this.webContents; await state.loadWorkspace(url); this.ready?.() } }, net: { fetch: vi.fn() }, - nativeTheme: { themeSource: 'system' }, + nativeTheme: state.nativeTheme, session: { defaultSession: { setPermissionCheckHandler: vi.fn(), setPermissionRequestHandler: vi.fn(), webRequest: { onBeforeSendHeaders: vi.fn() }, } }, @@ -177,11 +178,15 @@ it('starts the Host for welcome onboarding and opens the workspace on skip witho attempt: { id: attemptId, phase: 'waiting-browser', authorizeUrl: 'https://example.test/login' } } state.accountState.mockResolvedValue(account) await state.operations!.copySignInLink(attemptId) - expect(state.copy).toHaveBeenCalledExactlyOnceWith('https://example.test/login') + expect(state.copy).toHaveBeenCalledExactlyOnceWith('https://example.test/login?theme=light') + state.nativeTheme.shouldUseDarkColors = true + await state.operations!.copySignInLink(attemptId) + expect(state.copy).toHaveBeenLastCalledWith('https://example.test/login?theme=dark') + state.nativeTheme.shouldUseDarkColors = false await expect(state.operations!.copySignInLink('stale' as typeof attemptId)).rejects.toThrow('login link is unavailable') state.accountState.mockResolvedValue({ ...account, attempt: { id: attemptId, phase: 'expired' } }) await expect(state.operations!.copySignInLink(attemptId)).rejects.toThrow('login link is unavailable') - expect(state.copy).toHaveBeenCalledOnce() + expect(state.copy).toHaveBeenCalledTimes(2) await state.operations!.skip() expect(state.loadWorkspace).not.toHaveBeenCalled() expect(state.showWorkspace).toHaveBeenCalledOnce() From 13fe312e154a5b855a3f56c3e3ff357e1db1c9e1 Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Tue, 22 Sep 2026 15:26:39 +0800 Subject: [PATCH 2/4] test(desktop): fix login theme CI fixtures --- apps/desktop/tests/preload.e2e.ts | 49 ++++++++++++++++++- .../tests/account.spec.ts | 16 +++--- 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/apps/desktop/tests/preload.e2e.ts b/apps/desktop/tests/preload.e2e.ts index 1926d811ee..1022b3a8b8 100644 --- a/apps/desktop/tests/preload.e2e.ts +++ b/apps/desktop/tests/preload.e2e.ts @@ -6,26 +6,73 @@ import { describe, expect, it, vi } from 'vitest' const preload = (name: string): string => fileURLToPath(new URL(`../lib/${name}.cjs`, import.meta.url)) +/** + * Browser globals a sandboxed Electron preload sees. A preload runs while the + * document is still loading, so the theme preload defers its first read to + * `DOMContentLoaded` and observes later `html[data-ds-theme-source]` changes. + * @returns context globals plus the root attribute transitions the Web UI performs. + */ +function browserEnvironment() { + const attributes = new Map() + const listeners = new Map void>>() + const observers: Array<() => void> = [] + const document = { + readyState: 'loading', + documentElement: { + dataset: {} as Record, + getAttribute: (name: string): string | null => attributes.get(name) ?? null, + setAttribute: (name: string, value: string): void => { attributes.set(name, value) }, + }, + } + const window = { + addEventListener: (type: string, listener: () => void): void => { + listeners.set(type, [...listeners.get(type) ?? [], listener]) + }, + } + class SandboxMutationObserver { + constructor(callback: () => void) { observers.push(callback) } + observe(): void {} + } + return { + globals: { document, window, MutationObserver: SandboxMutationObserver }, + /** Writes the theme root attribute and settles the document, as the theme bootstrap does before DOMContentLoaded. */ + loadTheme(value: string): void { + attributes.set('data-ds-theme-source', value) + for (const listener of listeners.get('DOMContentLoaded') ?? []) listener() + }, + /** Applies a later theme preference change through the observer the preload registered. */ + changeTheme(value: string): void { + attributes.set('data-ds-theme-source', value) + for (const observer of observers) observer() + }, + } +} + describe.skipIf(!existsSync(preload('preload-app')))('built sandboxed Desktop preloads', () => { it.each(['preload-app', 'preload-welcome'])('%s loads without filesystem module access', (name) => { const exposed = new Map>() const invoke = vi.fn(() => Promise.resolve({ languages: ['en-US'], preference: 'zh' })) const send = vi.fn() + const browser = browserEnvironment() const electron = { contextBridge: { exposeInMainWorld: (key: string, value: Record) => { exposed.set(key, value) } }, ipcRenderer: { invoke, send, on: vi.fn(), off: vi.fn() }, } runInNewContext(readFileSync(preload(name), 'utf8'), { + ...browser.globals, require: (id: string) => { if (id !== 'electron') throw new Error(`sandbox cannot load ${id}`) return electron }, process: { argv: ['electron', '--dsh-welcome-locale=en'] }, location: new URL('dsh-app://app/'), - document: { documentElement: { dataset: {} } }, exports: {}, }) if (name === 'preload-app') { + browser.loadTheme('dark') + expect(send).toHaveBeenCalledWith('dsh-desktop:native-theme-set', 'dark') + browser.changeTheme('light') + expect(send).toHaveBeenCalledWith('dsh-desktop:native-theme-set', 'light') const bridge = exposed.get('__DSH_LOCALE__') as { read(): unknown; onChange(locale: string): void } bridge.read() expect(invoke).toHaveBeenCalledWith('dsh-desktop:locale-bootstrap') diff --git a/packages/credentials/deepseek-account-platform/tests/account.spec.ts b/packages/credentials/deepseek-account-platform/tests/account.spec.ts index f1b22c47b0..e71e0d7b94 100644 --- a/packages/credentials/deepseek-account-platform/tests/account.spec.ts +++ b/packages/credentials/deepseek-account-platform/tests/account.spec.ts @@ -483,12 +483,16 @@ it('adds private deployment cookies to every Platform request without exposing t expect(JSON.stringify(await f.account.getState())).not.toContain('test_gate') await f.account.signOut() await expect.poll(f.logoutCount).toBe(1) - expect(f.receivedHeaders.map(item => item.path)).toEqual([ - '/auth-api/v0/dsh/auth_init', '/auth-api/v0/dsh/auth_exchange', - '/auth-api/v0/users/current', '/api/v0/users/get_user_summary', '/auth-api/v0/users/logout', - ]) - expect(f.receivedHeaders.every(item => item.cookie === 'test_gate=synthetic')).toBe(true) - expect(f.receivedHeaders.slice(2).every(item => item.authorization === 'dsh_mock_test')).toBe(true) + const headers = f.receivedHeaders + const paths = headers.map(item => item.path) + // The profile and wallet queries are independent requests, so their arrival order is scheduler-dependent. + expect(paths.slice(0, 2)).toEqual(['/auth-api/v0/dsh/auth_init', '/auth-api/v0/dsh/auth_exchange']) + expect(paths.slice(2, -1).sort()).toEqual(['/api/v0/users/get_user_summary', '/auth-api/v0/users/current']) + expect(paths.at(-1)).toBe('/auth-api/v0/users/logout') + expect(headers.every(item => item.cookie === 'test_gate=synthetic')).toBe(true) + const grantedPaths = new Set(['/auth-api/v0/users/current', '/api/v0/users/get_user_summary', '/auth-api/v0/users/logout']) + expect(headers.filter(item => grantedPaths.has(item.path ?? '')).every(item => item.authorization === 'dsh_mock_test')).toBe(true) + expect(headers.filter(item => !grantedPaths.has(item.path ?? '')).every(item => item.authorization === undefined)).toBe(true) }) it('rejects reserved, duplicate and malformed deployment headers without disclosing values', () => { From f50059e425c15b902a22b73e9af474885097f40e Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Tue, 22 Sep 2026 15:34:58 +0800 Subject: [PATCH 3/4] fix(desktop): theme workspace sign-in links --- apps/desktop/src/preload-theme.ts | 5 +- .../tests/preload-theme.client.spec.ts | 10 +-- .../ui-settings-account/README.i18n.yaml | 4 +- packages/client/ui-settings-account/README.md | 2 +- .../client/ui-settings-account/README.zh.md | 2 +- .../client/ui-settings-account/package.json | 4 +- .../src/client/AccountMenu.tsx | 6 +- .../src/client/AccountOnboarding.tsx | 5 +- .../src/client/AccountSection.tsx | 16 +++-- .../src/client/SignInDialog.tsx | 7 +- .../src/client/authorize-url.ts | 14 ++++ .../ui-settings-account/src/client/index.ts | 17 +++-- .../tests/account.client.spec.tsx | 64 +++++++++++++++---- .../tests/apply.client.spec.ts | 11 ++++ .../tests/onboarding.client.spec.tsx | 7 ++ .../tests/sign-in-dialog.client.spec.tsx | 28 +++++++- .../client/ui-settings-account/tsconfig.json | 3 + pnpm-lock.yaml | 3 + 18 files changed, 161 insertions(+), 47 deletions(-) create mode 100644 packages/client/ui-settings-account/src/client/authorize-url.ts diff --git a/apps/desktop/src/preload-theme.ts b/apps/desktop/src/preload-theme.ts index 1274e5b3c4..19d390b490 100644 --- a/apps/desktop/src/preload-theme.ts +++ b/apps/desktop/src/preload-theme.ts @@ -10,8 +10,9 @@ const THEME_SOURCE_ATTRIBUTE = 'data-ds-theme-source' * Watches `html[data-ds-theme-source]` and forwards each value to the main * process, which sets `nativeTheme.themeSource`. The macOS sidebar vibrancy * material then follows the app's theme preference instead of the OS - * appearance while `system` keeps following the OS, and the resolved - * `shouldUseDarkColors` palette travels with the Platform login link. + * appearance while `system` keeps following the OS; the main process reads + * the same value back as `shouldUseDarkColors` when it needs the resolved + * palette for a Platform login link. */ export function syncNativeTheme(): void { let sent: string | undefined diff --git a/apps/desktop/tests/preload-theme.client.spec.ts b/apps/desktop/tests/preload-theme.client.spec.ts index 90cd23eab0..2f0da9b97a 100644 --- a/apps/desktop/tests/preload-theme.client.spec.ts +++ b/apps/desktop/tests/preload-theme.client.spec.ts @@ -36,14 +36,9 @@ it.each(['darwin', 'win32'] as const)('mirrors the application theme source on % document.documentElement.setAttribute('data-ds-theme-source', 'system') await vi.waitFor(() => { expect(send).toHaveBeenLastCalledWith(DESKTOP_IPC.nativeThemeSet, 'system') }) expect(send).toHaveBeenCalledTimes(2) - for (const observer of observers) observer.disconnect() - send.mockClear() - document.documentElement.setAttribute('data-ds-theme-source', 'light') - await new Promise((resolve) => { queueMicrotask(resolve) }) - expect(send).not.toHaveBeenCalled() }) -it('waits for the document root and then stops listening for it', () => { +it('defers observation until the document root exists', () => { vi.stubGlobal('MutationObserver', TrackedMutationObserver) vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') vi.spyOn(document, 'readyState', 'get').mockReturnValue('loading') @@ -52,7 +47,4 @@ it('waits for the document root and then stops listening for it', () => { document.documentElement.setAttribute('data-ds-theme-source', 'light') window.dispatchEvent(new Event('DOMContentLoaded')) expect(send).toHaveBeenCalledExactlyOnceWith(DESKTOP_IPC.nativeThemeSet, 'light') - document.documentElement.setAttribute('data-ds-theme-source', 'dark') - window.dispatchEvent(new Event('DOMContentLoaded')) - expect(send).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-settings-account/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index e5508b767d..0dbd02cfdc 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings-account/README.md -README.md: f024f7ef6506c1c9317d80660aaa0c8221e6a51e -README.zh.md: 2868d46a11db60cfec57f1eee6b146316b989288 +README.md: 016d1161214cf5723de6d5d63dc54542b8382571 +README.zh.md: 56ff93217bf97126878a0c7d5fed889a5e3f56f2 diff --git a/packages/client/ui-settings-account/README.md b/packages/client/ui-settings-account/README.md index f024f7ef65..016d116121 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -46,7 +46,7 @@ The Account section appears first in Settings only while signed in; it is hidden The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storage APIs; the [architecture](../../../docs/architecture.md) explains application composition. -Account login uses a dismissible dialog before the model onboarding credential editor. The dialog uses a compact, right-aligned action row with the primary action last. The sidebar displays the profile name, falling back to the server-masked phone number or email when the name is absent; it stays blank while the profile is loading. Dialog copy and the sidebar account label are not text-selectable; the copy-link button remains available and restores its label two seconds after each successful copy. Clipboard failures show Copy failed on the link for two seconds without interrupting sign-in. Waiting shows a copyable authorization link and a loading indicator; timeout and failure require an explicit retry. Sign-in failures render in that dialog; the launcher's inline failure line reports only a failed sign-out. Closing a waiting dialog cancels its Host attempt. The sidebar can reopen the same API-key editor through the settings coordinator. +Account login uses a dismissible dialog before the model onboarding credential editor. The dialog uses a compact, right-aligned action row with the primary action last. The sidebar displays the profile name, falling back to the server-masked phone number or email when the name is absent; it stays blank while the profile is loading. Dialog copy and the sidebar account label are not text-selectable; the copy-link button remains available and restores its label two seconds after each successful copy. Clipboard failures show Copy failed on the link for two seconds without interrupting sign-in. Waiting shows a copyable authorization link and a loading indicator; timeout and failure require an explicit retry. The dialog's Copy sign-in link and the Settings Open link append the resolved Desktop palette as `theme=light` or `theme=dark` from the live theme snapshot, so both routes reach the Platform page in the current application theme without touching the stored preference. Sign-in failures render in that dialog; the launcher's inline failure line reports only a failed sign-out. Closing a waiting dialog cancels its Host attempt. The sidebar can reopen the same API-key editor through the settings coordinator. A terminal account-state stream failure appears in the sign-in dialog or Account settings. Plugin unload suppresses late failure reports. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index 2868d46a11..56ff93217b 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -46,7 +46,7 @@ Desktop 的用量和充值操作在 48px 返回栏下方打开隔离的原生 Pl [凭证子系统](../../../docs/subsystems/credentials.zh.md)定义存储接口;[架构](../../../docs/architecture.zh.md)说明应用组合。 -账号登录在模型引导的凭证编辑器之前显示可关闭的弹窗。弹窗底部采用紧凑的右对齐横排操作,主操作位于末尾。侧边栏优先显示昵称,缺少昵称时显示服务端返回的脱敏手机号或邮箱;资料加载期间保持留空。 弹窗文字和侧边栏账号状态文字不可选中,复制登录链接按钮始终可用,并在每次复制成功两秒后恢复原文案。剪贴板失败时,链接原位显示“复制失败”两秒,不中断登录。等待状态提供可复制的授权链接和加载图标;超时和失败均须用户手动重试。登录失败在该弹窗内呈现;侧边栏入口的内联失败提示仅用于退出登录失败。关闭等待弹窗会取消对应 Host 登录流程。侧边栏通过设置协调器重新打开同一个 API Key 编辑器。 +账号登录在模型引导的凭证编辑器之前显示可关闭的弹窗。弹窗底部采用紧凑的右对齐横排操作,主操作位于末尾。侧边栏优先显示昵称,缺少昵称时显示服务端返回的脱敏手机号或邮箱;资料加载期间保持留空。 弹窗文字和侧边栏账号状态文字不可选中,复制登录链接按钮始终可用,并在每次复制成功两秒后恢复原文案。剪贴板失败时,链接原位显示“复制失败”两秒,不中断登录。等待状态提供可复制的授权链接和加载图标;超时和失败均须用户手动重试。弹窗的“复制登录链接”和设置页的“打开”链接会从当前主题快照读取 Desktop 生效配色,追加 `theme=light` 或 `theme=dark`,使两条路径都以当前应用主题打开 Platform 页面,且不写入已保存的主题偏好。登录失败在该弹窗内呈现;侧边栏入口的内联失败提示仅用于退出登录失败。关闭等待弹窗会取消对应 Host 登录流程。侧边栏通过设置协调器重新打开同一个 API Key 编辑器。 账户状态流的终止错误会显示在登录对话框或账户设置中。插件卸载后不再报告延迟到达的错误。 diff --git a/packages/client/ui-settings-account/package.json b/packages/client/ui-settings-account/package.json index c2701b6f22..6ebc0756ed 100644 --- a/packages/client/ui-settings-account/package.json +++ b/packages/client/ui-settings-account/package.json @@ -30,7 +30,8 @@ "inject": [ "@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-client-ui-settings", - "@deepseek-ai/dsh-client-locale" + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-theme" ], "platform": "web" } @@ -52,6 +53,7 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:^", "@deepseek-ai/dsh-client-ui-settings": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", + "@deepseek-ai/dsh-client-ui-theme": "workspace:^", "@deepseek-ai/dsh-deepseek-account": "workspace:^", "@testing-library/react": "^16.1.0", "@types/big.js": "^6.2.2", diff --git a/packages/client/ui-settings-account/src/client/AccountMenu.tsx b/packages/client/ui-settings-account/src/client/AccountMenu.tsx index 5a2a07b71f..606312ae2d 100644 --- a/packages/client/ui-settings-account/src/client/AccountMenu.tsx +++ b/packages/client/ui-settings-account/src/client/AccountMenu.tsx @@ -16,9 +16,10 @@ export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsLocale<' * @returns account menu launcher. */ export function AccountMenu({ - wide, openSettings, openOnboarding, useAccount, signOut, contactUs, showLogin, start, cancel, t, + wide, openSettings, openOnboarding, useAccount, useTheme, signOut, contactUs, showLogin, start, cancel, t, }: AccountMenuProps) { const account = useAccount(state => state) + const colorScheme = useTheme(snapshot => snapshot.active.colorScheme) const signedIn = account.view?.status === 'credential-stored' const profile = account.details?.profile const label = profile === undefined ? null : profile.status === 'ready' @@ -55,7 +56,8 @@ export function AccountMenu({ else if (id === 'signin') beginSignIn() else void logout() }} /> - {account.loginVisible && !account.onboarding && { showLogin(false) }} useApiKey={() => { showLogin(false); openOnboarding('deepseek-official') }} />} {logoutFailed && {t('failed')}} diff --git a/packages/client/ui-settings-account/src/client/AccountOnboarding.tsx b/packages/client/ui-settings-account/src/client/AccountOnboarding.tsx index 8dfcb08c48..e07c81c6db 100644 --- a/packages/client/ui-settings-account/src/client/AccountOnboarding.tsx +++ b/packages/client/ui-settings-account/src/client/AccountOnboarding.tsx @@ -6,12 +6,13 @@ import type { AccountSectionInjected } from './AccountSection.tsx' import { SignInDialog } from './SignInDialog.tsx' /** @param props - onboarding completion, account state and actions. @returns account dialog while signed out. */ -export function AccountOnboarding({ complete, useApiKey, useAccount, setOnboarding, showLogin, start, cancel, t }: +export function AccountOnboarding({ complete, useApiKey, useAccount, useTheme, setOnboarding, showLogin, start, cancel, t }: PropsRuntime<'settings.models.sign-in'> & PropsLocale<'settings.account'> & InjectFace) { const account = useAccount(value => value) + const colorScheme = useTheme(snapshot => snapshot.active.colorScheme) useEffect(() => { setOnboarding(true); return () => { setOnboarding(false) } }, [setOnboarding]) useEffect(() => { if (account.view?.status === 'credential-stored') complete() }, [account.view?.status, complete]) if (!account.view || account.view.status === 'credential-stored') return null - return { showLogin(false); complete() }} useApiKey={() => { showLogin(false); useApiKey() }} /> } diff --git a/packages/client/ui-settings-account/src/client/AccountSection.tsx b/packages/client/ui-settings-account/src/client/AccountSection.tsx index 89616b9cc8..1dccd18f84 100644 --- a/packages/client/ui-settings-account/src/client/AccountSection.tsx +++ b/packages/client/ui-settings-account/src/client/AccountSection.tsx @@ -4,9 +4,11 @@ import { useEffect, useState } from 'react' import { Button, IconRightUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { AccountDetails, AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' import type { PropsRuntime, PropsLocale, InjectFace, HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client' import { PlatformOverlay, type PlatformBridge } from './PlatformOverlay.tsx' import { formatBalance } from './formatBalance.ts' import { AccountAvatar } from './AccountAvatar.tsx' +import { authorizeUrlWithTheme } from './authorize-url.ts' import css from './AccountSection.module.css' /** Safe account snapshot shared by the settings page and launcher. */ @@ -30,8 +32,12 @@ export interface AccountSectionInjected { /** Desktop-only commands; absent in ordinary browsers. */ platform?: PlatformBridge - /** Host-owned account stream observed through framework hooks. */ - hooks: { account: HostObservable } + /** Host-owned account stream and theme snapshots observed through framework hooks. */ + hooks: { + account: HostObservable + /** Palette the Platform login pages follow. */ + theme: HostObservable + } /** @returns after account details are refreshed; concurrent refreshes share a request. */ refresh: () => Promise /** Open the external support questionnaire with the current account and environment. */ @@ -51,8 +57,9 @@ export interface AccountSectionInjected { export type AccountSectionProps = PropsRuntime<'settings.section'> & PropsLocale<'settings.account'> & InjectFace /** @param props - localized actions and account subscription. @returns account settings UI. */ -export function AccountSection({ t, useAccount, start, cancel, refresh, platform }: AccountSectionProps) { +export function AccountSection({ t, useAccount, useTheme, start, cancel, refresh, platform }: AccountSectionProps) { const { view: state, details, failed: streamFailed } = useAccount(value => value) + const colorScheme = useTheme(snapshot => snapshot.active.colorScheme) const [platformPage, setPlatformPage] = useState<'usage' | 'top-up'>() const [failed, setFailed] = useState(false) const [busy, setBusy] = useState(false) @@ -107,7 +114,8 @@ export function AccountSection({ t, useAccount, start, cancel, refresh, platform } {active &&
- {attempt.authorizeUrl && + {attempt.authorizeUrl && {t('open')} }