DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(dsh-tauri): 账号登录进入 waiting-browser 时自动打开系统浏览器
hairyfab307aea2b9c
diff --git a/packages/dsh-tauri/src/client/apply.test.ts b/packages/dsh-tauri/src/client/apply.test.tsindex acb7049a..97269170 100644--- a/packages/dsh-tauri/src/client/apply.test.ts+++ b/packages/dsh-tauri/src/client/apply.test.ts@@ -3,7 +3,7 @@** `5b3b9534` 重建时 `client/apply.ts` 连同四个注册器被整体删除,宿主侧发送方* (`src/layout/components/webview.tsx`、`iframe.tsx`)原地保留,结果「壳的收起侧边栏」- * 等控件全部空转。这里锁住四条 effect 都被登记,且登记过程确实挂上了父窗口桥监听。+ * 等控件全部空转。这里锁住每条 effect 都被登记,且登记过程确实挂上了父窗口桥监听。*/import type { ClientContext, ParentMessage } from './types'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -16,6 +16,7 @@ const EXPECTED_LABELS = ['dsh-tauri: navigation (new session, add workspace)','dsh-tauri: zoom shortcuts (ctrl/cmd +/-/0)','dsh-tauri: sidebar tweaks (hide collapse toggle, center brand)',+ 'dsh-tauri: account sign-in (auto-open the authorize url)',]/** 假 MutationObserver:只保证 controller.observe 可用。 */diff --git a/packages/dsh-tauri/src/client/apply.ts b/packages/dsh-tauri/src/client/apply.tsindex c3c7c8cf..4cd2fb89 100644--- a/packages/dsh-tauri/src/client/apply.ts+++ b/packages/dsh-tauri/src/client/apply.ts@@ -11,6 +11,7 @@* 收敛到插件客户端;插件缺席时宿主控件只会空转,没有任何降级路径。*/import type { ClientContext } from './types'+import { accountSignInFeature } from './register/account'import { navigationFeature } from './register/navigation'import { sidebarFeature } from './register/sidebar'import { sidebarTweaksFeature } from './register/sidebar-tweaks'@@ -23,7 +24,8 @@ const NAVIGATION_EFFECT = 'dsh-tauri: navigation (new session, add workspace)'const ZOOM_SHORTCUT_EFFECT = 'dsh-tauri: zoom shortcuts (ctrl/cmd +/-/0)'const SIDEBAR_TWEAKS_EFFECT = 'dsh-tauri: sidebar tweaks (hide collapse toggle, center brand)'const STYLE_EFFECT = 'dsh-tauri: style (sidebar background)'-/** 插件体:注册侧边栏桥、导航命令、缩放快捷键与侧边栏 UI 微调。 */+const ACCOUNT_SIGN_IN_EFFECT = 'dsh-tauri: account sign-in (auto-open the authorize url)'+/** 插件体:注册侧边栏桥、导航命令、缩放快捷键、账号登录接管与侧边栏 UI 微调。 */export function apply(ctx: ClientContext): void {// issue #573:独立浏览器没有桌面宿主,保留原生侧栏控件与缩放快捷键。if (typeof window === 'undefined' || typeof document === 'undefined' || window.parent === window)@@ -34,4 +36,5 @@ export function apply(ctx: ClientContext): void {ctx.effect(navigationFeature, NAVIGATION_EFFECT)ctx.effect(zoomShortcutFeature, ZOOM_SHORTCUT_EFFECT)ctx.effect(sidebarTweaksFeature, SIDEBAR_TWEAKS_EFFECT)+ ctx.effect(accountSignInFeature, ACCOUNT_SIGN_IN_EFFECT)}diff --git a/packages/dsh-tauri/src/client/register/account.test.ts b/packages/dsh-tauri/src/client/register/account.test.tsnew file mode 100644index 00000000..3ac48061--- /dev/null+++ b/packages/dsh-tauri/src/client/register/account.test.ts@@ -0,0 +1,138 @@+/**+ * register/account.test.ts — 桌面端官方登录「自动打开浏览器」的回归测试。+ *+ * 锁住的契约:桌面载体(`dshDesktop` 标记在场)下,账号流进入 `waiting-browser` 时经壳层+ * `open_external_url` 打开系统浏览器,同一地址只开一次;服务必须经 `ctx.inject` 的作用域读取+ * (用外层 ctx 读会抛 `cannot get property "remote.account" without inject`——真实故障);+ * 浏览器直开(无标记)与非法地址都不得触发。+ */+import type { ClientContext } from '../types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { accountSignInFeature } from './account'++const mocks = vi.hoisted(() => ({+ invoke: vi.fn(async (_cmd: string, _args?: Record<string, unknown>) => undefined),+}))++vi.mock('../service/invoke', () => ({ invoke: mocks.invoke }))++const AUTHORIZE_A = 'https://platform.deepseek.com/dsh/authorize?state=a'+const AUTHORIZE_B = 'https://platform.deepseek.com/dsh/authorize?state=b'++interface AttemptView {+ attempt?: { phase?: string, authorizeUrl?: string } | null+}++/** 账号远程面:`watch()` 给原始值,`$stream()` 与官方一样把值包成 `{ value, accept }` 帧。 */+function makeRemote(views: AttemptView[]) {+ const account = {+ watch: () => (async function* () {+ for (const view of views)+ yield view+ })(),+ }+ return {+ account,+ $stream: (options: { open: (signal: AbortSignal) => AsyncIterable<AttemptView> }) => ({+ async* [Symbol.asyncIterator]() {+ for await (const value of options.open(new AbortController().signal))+ yield { value, accept: () => {} }+ },+ dispose: async () => {},+ }),+ }+}++/**+ * 外层 ctx 的 `remote` 取用与 cordis 的守卫行为一致:直接抛错。+ * 实现只能读 `ctx.inject` 回调给出的作用域 ctx(本用例把它作为回调首参传入)。+ */+function ctxWithRemote(remote: () => unknown): ClientContext {+ const outer = {+ get remote(): never {+ throw new Error('cannot get property "remote.account" without inject')+ },+ inject: (_deps: string[], callback: (scoped: unknown) => void) => {+ callback({ remote: remote() })+ return () => {}+ },+ }+ return outer as unknown as ClientContext+}++beforeEach(() => {+ vi.stubGlobal('dshDesktop', null)+})++afterEach(() => {+ mocks.invoke.mockClear()+ mocks.invoke.mockImplementation(async () => undefined)+ vi.unstubAllGlobals()+})++describe('accountSignInFeature', () => {+ it('opens each authorize url once through the injected account scope', async () => {+ const ctx = ctxWithRemote(() => makeRemote([+ { attempt: { phase: 'initializing' } },+ { attempt: { phase: 'waiting-browser', authorizeUrl: AUTHORIZE_A } },+ { attempt: { phase: 'waiting-browser', authorizeUrl: AUTHORIZE_A } },+ { attempt: { phase: 'waiting-browser', authorizeUrl: AUTHORIZE_B } },+ { attempt: { phase: 'exchanging', authorizeUrl: AUTHORIZE_B } },+ ]))++ const dispose = accountSignInFeature.call(ctx)++ await vi.waitFor(() => expect(mocks.invoke).toHaveBeenCalledTimes(2))+ expect(mocks.invoke.mock.calls.map(call => call[1])).toEqual([+ { url: AUTHORIZE_A },+ { url: AUTHORIZE_B },+ ])+ expect(mocks.invoke.mock.calls.every(call => call[0] === 'open_external_url')).toBe(true)+ dispose()+ })++ /** 壳层打开失败不能静默:错误进控制台,不吞掉。 */+ it('reports a failed shell open without throwing', async () => {+ mocks.invoke.mockRejectedValue(new Error('NODE_NOT_ANSWERED: timeout'))+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const ctx = ctxWithRemote(() => makeRemote([+ { attempt: { phase: 'waiting-browser', authorizeUrl: AUTHORIZE_A } },+ ]))++ const dispose = accountSignInFeature.call(ctx)++ await vi.waitFor(() => expect(warn).toHaveBeenCalled())+ expect(warn.mock.calls[0]?.[0]).toContain('opening the account authorize url failed')+ warn.mockRestore()+ dispose()+ })++ it('ignores authorize urls the host could not open', async () => {+ const ctx = ctxWithRemote(() => makeRemote([+ { attempt: { phase: 'waiting-browser', authorizeUrl: 'javascript:alert(1)' } },+ { attempt: { phase: 'waiting-browser' } },+ ]))++ const dispose = accountSignInFeature.call(ctx)+ await Promise.resolve()+ await Promise.resolve()++ expect(mocks.invoke).not.toHaveBeenCalled()+ dispose()+ })++ /** 浏览器直开同一端口时没有桌面载体标记:不得替用户打开浏览器。 */+ it('stays inert without the desktop marker', async () => {+ vi.unstubAllGlobals()+ const ctx = ctxWithRemote(() => makeRemote([+ { attempt: { phase: 'waiting-browser', authorizeUrl: AUTHORIZE_A } },+ ]))++ const dispose = accountSignInFeature.call(ctx)+ await Promise.resolve()+ await Promise.resolve()++ expect(mocks.invoke).not.toHaveBeenCalled()+ dispose()+ })+})diff --git a/packages/dsh-tauri/src/client/register/account.ts b/packages/dsh-tauri/src/client/register/account.tsnew file mode 100644index 00000000..88b133a9--- /dev/null+++ b/packages/dsh-tauri/src/client/register/account.ts@@ -0,0 +1,107 @@+import { invoke } from '../service/invoke'+import { defineRegister } from './index'++/** 官方账号流中与「自动打开浏览器」相关的最小投影(`AccountView.attempt` 子集)。 */+interface AccountAttemptView {+ phase?: string+ authorizeUrl?: string+}++interface AccountViewLike {+ attempt?: AccountAttemptView | null+}++/** `$stream` 的帧:官方 `RemoteStream.read()` 把 open() 的每个原始值包成 `{ value, accept }`。 */+interface AccountStreamFrame {+ value?: AccountViewLike+ accept?: () => void+}++interface AccountStreamLike extends AsyncIterable<AccountStreamFrame> {+ dispose?: () => Promise<void> | void+}++interface AccountRemoteLike {+ account?: {+ watch?: (signal: AbortSignal) => AsyncIterable<AccountViewLike>+ }+ $stream?: (options: {+ name: string+ open: (signal: AbortSignal) => AsyncIterable<AccountViewLike>+ ended: (accepted: boolean) => Error+ }) => AccountStreamLike+}++/** `ctx.inject` 给出的作用域上下文:只在这里读 `remote` / `remote.account`。 */+interface InjectedScope {+ remote?: AccountRemoteLike+}++/**+ * 官方桌面端由 Electron 主进程监听账号流并把授权地址交给系统浏览器(`shell.openExternal`);+ * 桌面壳没有主进程,这里在 iframe 内做同一件事:账号尝试进入 `waiting-browser` 时打开系统+ * 浏览器,用户不必再手抄弹窗里的链接(弹窗里那个转圈的主按钮正是 waiting-browser)。+ *+ * 两条必须遵守的约束,都是踩过的坑:+ * - `remote` / `remote.account` 由 `dsh-client-connection` **稍后**提供,且 cordis 的 ctx 代理+ * 对未声明服务直接抛 `cannot get property "remote.account" without inject`。必须用动态+ * `ctx.inject` 声明依赖,并**只在使用它给出的作用域 ctx** 读服务——用外层 ctx 读会抛。+ * - 订阅走官方 `$stream`(把 `watch()` 的原始值包成带 `accept()` 的帧),与官方+ * `ui-settings-account` 的消费方式逐字一致。+ *+ * 只在桌面载体生效:浏览器直开没有 `dshDesktop` 标记,也不该替用户开浏览器。+ */+export const accountSignInFeature = defineRegister((controller, ctx) => {+ if (!('dshDesktop' in globalThis))+ return++ let opened: string | undefined++ ctx.inject(['remote', 'remote.account'], (scoped) => {+ const remote = (scoped as unknown as InjectedScope).remote+ const account = remote?.account+ const watch = account?.watch+ if (typeof watch !== 'function' || typeof remote?.$stream !== 'function') {+ console.warn('[dsh-tauri] account stream unavailable — the authorize url cannot be opened automatically')+ return+ }++ const stream = remote.$stream({+ name: 'account',+ open: signal => watch.call(account, signal),+ ended: () => new Error('account stream ended'),+ })+ controller.add(() => {+ void stream.dispose?.()+ })++ void (async () => {+ for await (const frame of stream) {+ const attempt = frame.value?.attempt+ frame.accept?.()+ const url = attempt?.authorizeUrl+ if (attempt?.phase !== 'waiting-browser' || !isBrowserUrl(url) || url === opened)+ continue+ opened = url+ await invoke('open_external_url', { url }).catch((error: unknown) => {+ console.warn('[dsh-tauri] opening the account authorize url failed:', error)+ })+ }+ })().catch(() => undefined)+ })+})++// --- internal ---++/** 只放行宿主 `open_external_url` 能处理的 http(s) 浏览器地址。 */+function isBrowserUrl(value: unknown): value is string {+ if (typeof value !== 'string')+ return false+ try {+ const { protocol } = new URL(value)+ return protocol === 'https:' || protocol === 'http:'+ }+ catch {+ return false+ }+}diff --git a/src/hooks/use-invoke-iframe.ts b/src/hooks/use-invoke-iframe.tsindex 1dfe160d..aa602e32 100644--- a/src/hooks/use-invoke-iframe.ts+++ b/src/hooks/use-invoke-iframe.ts@@ -35,6 +35,9 @@ interface InvokeBridgeRequest {const ALLOWED_INVOKE_CMDS = new Set([// 只读布尔量,供 dsh-tauri-ui 决定是否挂载仅 dev 可见的调试面板。'is_dev_build',+ // dsh-tauri 客户端接管官方登录:账号流进入 waiting-browser 时把授权地址交给系统浏览器+ // (命令自身只放行 http(s),见 bridge/system_os.rs)。+ 'open_external_url','get_pet_status','set_pet_enabled','set_active_pet',