From fcf5908ff7cf1fe748e92c6c5d60bde69eb6246d Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sun, 8 Nov 2026 04:36:33 +0800 Subject: [PATCH 1/2] fix(connector-account): keep the activation prompt while the account is connecting An MCP server switched on connects before it reports that it needs authorization, so the prompt now waits while the account is checking or connecting and dismisses itself only once the account is connected, unavailable, or not running. --- packages/client/ui-connector-account/README.i18n.yaml | 4 ++-- packages/client/ui-connector-account/README.md | 2 +- packages/client/ui-connector-account/README.zh.md | 2 +- .../ui-connector-account/src/client/components.tsx | 7 ++++--- .../tests/components.client.spec.tsx | 9 +++++++-- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml index 347d021162..010f9d34c4 100644 --- a/packages/client/ui-connector-account/README.i18n.yaml +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -21,8 +21,8 @@ en: e618281ea7721daf zh: a5d5f5e307ea3435 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/present-the-section: - en: 73ca134d685b5872 - zh: 05b929fd28dc955e + en: 4ed05fa030f31fed + zh: 4d9597b68959be93 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: en: a9e64f316efcac3e zh: d059d31b65573bf5 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md index 1013fb4f48..a8c6386a7b 100644 --- a/packages/client/ui-connector-account/README.md +++ b/packages/client/ui-connector-account/README.md @@ -63,7 +63,7 @@ The registrant imports the registry's types with `import type` from the package |---|---| | Section | Title, status, buttons, detail, notes, failure, and hint. Buttons are disabled while a call the section made is pending or the Host stream is down. A failure shows the registrant's text, then its diagnostic items | | Title tag | The display's `badge`, shown only on the enabled bundle's page or one of its row pages, and only while the display has one | -| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It dismisses itself once the phase settles elsewhere | +| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It waits while the account is checking or connecting and dismisses itself once the account is connected, unavailable, or not running | | Notice | The latest outcome in this browser, outside the Plugins panel's lifetime: the operation's success text, or the shared failure copy with a warning icon | ### Following operations diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md index a32ed876b2..2de3b35071 100644 --- a/packages/client/ui-connector-account/README.zh.md +++ b/packages/client/ui-connector-account/README.zh.md @@ -63,7 +63,7 @@ export function apply(ctx: Context): void { |---|---| | 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮不可用。失败时先显示注册方的文案,再显示其诊断项 | | 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | -| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。阶段确定为其他值后自动关闭 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。账号检查中或连接中时继续等待,已连接、不可用或服务未运行时自动关闭 | | 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | ### 跟随操作 diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx index 93bc807582..9d115051cd 100644 --- a/packages/client/ui-connector-account/src/client/components.tsx +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -194,14 +194,15 @@ export interface ConnectorAccountActivationProps { /** * Guidance after the user switches a bundle on while its account is not connected. * @param props - the phase, the registrant's text, the dismiss and connect callbacks, and the translator. - * @returns a prompt shown while disconnected; it dismisses itself once the phase settles elsewhere. + * @returns a prompt shown while disconnected; it waits while the account is checking or connecting, which may still end + * disconnected, and dismisses itself once the account is connected or unavailable. */ export function ConnectorAccountActivation(props: ConnectorAccountActivationProps): ReactNode { const { t, phase, title, body, connect, onDismiss, onConnect } = props const needed = phase === 'disconnected' useEffect(() => { - if (phase !== 'checking' && !needed) onDismiss() - }, [phase, needed, onDismiss]) + if (phase === 'connected' || phase === 'unavailable' || phase === 'stopped') onDismiss() + }, [phase, onDismiss]) return ( diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx index c84907ffed..df9a0d0e80 100644 --- a/packages/client/ui-connector-account/tests/components.client.spec.tsx +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -110,12 +110,14 @@ it('explains a stopped stream with the shared copy and reopens it even while off expect(onRetry).toHaveBeenCalledOnce() }) -it('prompts to connect only while disconnected and steps aside once the phase settles elsewhere', () => { +it('prompts to connect only while disconnected, waits while checking or connecting, and steps aside once settled', () => { const onDismiss = vi.fn() const onConnect = vi.fn() - const prompt = (phase: 'checking' | 'disconnected' | 'connected') => + const prompt = (phase: 'checking' | 'connecting' | 'disconnected' | 'connected' | 'unavailable' | 'stopped') => const { rerender } = render(prompt('checking')) + // An account still connecting after the bundle is switched on may end disconnected. + rerender(prompt('connecting')) expect(screen.queryByRole('dialog')).toBeNull() expect(onDismiss).not.toHaveBeenCalled() rerender(prompt('disconnected')) @@ -127,6 +129,9 @@ it('prompts to connect only while disconnected and steps aside once the phase se expect(onDismiss).toHaveBeenCalledOnce() rerender(prompt('connected')) expect(onDismiss).toHaveBeenCalledTimes(2) + rerender(prompt('unavailable')) + rerender(prompt('stopped')) + expect(onDismiss).toHaveBeenCalledTimes(4) }) it('shows the latest notice with the registrant text or the shared failure copy', () => { From 3f718d826c7d90a5203e4160a19ea13ce9a66c84 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sun, 8 Nov 2026 20:09:29 +0800 Subject: [PATCH 2/2] refactor(connector-account): reconnect through the Remote stream and render each surface from its slot entry The browser half no longer reopens a failed stream itself: `$stream` reconnects after a lost connection, and a stream that fails for good keeps the last accounts with their buttons disabled and logs a warning, as other client streams do. The not-running status, tag, detail, and Retry button, with their four shared strings, are removed. Each surface is now one slot entry that reads the browser state and calls the Remote; the separate presentational components and their props types are removed. --- .../ui-connector-account/README.i18n.yaml | 16 +- .../client/ui-connector-account/README.md | 10 +- .../client/ui-connector-account/README.zh.md | 10 +- .../src/client/components.tsx | 295 +++++------------- .../ui-connector-account/src/client/index.ts | 1 - .../src/client/locales.ts | 32 -- .../ui-connector-account/src/client/state.ts | 56 ++-- .../ui-connector-account/src/client/types.ts | 4 - .../tests/apply.client.spec.ts | 5 +- .../tests/components.client.spec.tsx | 227 ++++++-------- .../tests/state.client.spec.ts | 37 +-- 11 files changed, 227 insertions(+), 466 deletions(-) diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml index 010f9d34c4..63dcb56e37 100644 --- a/packages/client/ui-connector-account/README.i18n.yaml +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -21,17 +21,17 @@ en: e618281ea7721daf zh: a5d5f5e307ea3435 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/present-the-section: - en: 4ed05fa030f31fed - zh: 4d9597b68959be93 + en: f2bb2f05e2e122a4 + zh: f3dc9945b3f30736 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: - en: a9e64f316efcac3e - zh: d059d31b65573bf5 + en: 0f6140d7ed6427b9 + zh: feadef500ee4fd98 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/shared-copy: - en: f88db8d50a68a0ca - zh: 6169fd1ffc9c79a0 + en: 353a48db7e7dd0f7 + zh: 653f3d983d3fd572 /deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: - en: da424b56f995bef5 - zh: 298fc8e50149fea5 + en: 890bd2109a5b5c4f + zh: f4373b71cb4f2018 /deepseek-ai-dsh-client-ui-connector-account/further-exploration: en: 029949903a73d283 zh: 6f9a8c2f7620de69 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md index a8c6386a7b..9f1ac26602 100644 --- a/packages/client/ui-connector-account/README.md +++ b/packages/client/ui-connector-account/README.md @@ -63,16 +63,16 @@ The registrant imports the registry's types with `import type` from the package |---|---| | Section | Title, status, buttons, detail, notes, failure, and hint. Buttons are disabled while a call the section made is pending or the Host stream is down. A failure shows the registrant's text, then its diagnostic items | | Title tag | The display's `badge`, shown only on the enabled bundle's page or one of its row pages, and only while the display has one | -| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It waits while the account is checking or connecting and dismisses itself once the account is connected, unavailable, or not running | +| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It waits while the account is checking or connecting and dismisses itself once the account is connected or unavailable | | Notice | The latest outcome in this browser, outside the Plugins panel's lifetime: the operation's success text, or the shared failure copy with a warning icon | ### Following operations -Each browser opens one stream when the Web app loads, and the Host checks every account that runs no operation for each new stream; an account registered while a stream is open is checked at once. A browser follows the operation its latest start returned, from that answer until the stream delivers the operation's result. Each page the followed operation offers opens once in a new tab, over HTTPS or over HTTP on a loopback address; other browsers show the same section but open no page and report no notice. A second click before the first call answers starts nothing. A stream that fails for good shows the account service as not running with Retry, which reopens the stream once however often it is pressed. Unloading the browser half closes the stream; Host-owned operations keep running. +Each browser opens one stream when the Web app loads, and the Host checks every account that runs no operation for each new stream; an account registered while a stream is open is checked at once. A browser follows the operation its latest start returned, from that answer until the stream delivers the operation's result. Each page the followed operation offers opens once in a new tab, over HTTPS or over HTTP on a loopback address; other browsers show the same section but open no page and report no notice. A second click before the first call answers starts nothing. The stream reconnects after a lost connection; when it fails for good, the sections keep the last accounts with their buttons disabled until the page reloads. Unloading the browser half closes the stream; Host-owned operations keep running. ### Shared copy -The `connectorAccount` dictionary holds the copy every account shares: Close, Cancel, Retry, Later, the diagnostic label, the failure notice, and the not-running status, tag, and detail. Every other string comes from the registrant. +The `connectorAccount` dictionary holds the copy every account shares: Close, Cancel, Later, the diagnostic label, and the failure notice. Every other string comes from the registrant. ----- @@ -84,7 +84,7 @@ The `connectorAccount` dictionary holds the copy every account shares: Close, Ca The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes the account's source, and each `watch` stream reads every account's entry after each change, coalescing changes that arrive before the next read: the key and package, the copy, `present(view)`, the operation in progress, and the latest result with its success text. `start` and `cancel` route by key to the account's source. -[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering or has stopped, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The buttons call `start` and `cancel` on the Remote themselves and report the started operation to `BrowserAccounts`. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. +[`dsh-api-remotes`](../../api/remotes/README.md) mounts the generated `connectorAccounts` Remote. The browser half opens one `watch` stream through `BrowserAccounts`, whose one store holds the Host's accounts by key, whether the stream is delivering, and the latest notice; it also remembers the operations this browser started. It registers one `plugins.detail.badge` entry and one `shell.overlay` notice for the page, and for each account with a package, `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, all under the `connectorAccount` namespace. The buttons call `start` and `cancel` on the Remote themselves and report the started operation to `BrowserAccounts`. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. | File | Role | |---|---| @@ -92,7 +92,7 @@ The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes t | [`src/types.ts`](src/types.ts) | Registration, source, view, display, and entry types | | [`src/client/index.ts`](src/client/index.ts) | The browser entry: the dictionary and the slot registrations | | [`src/client/state.ts`](src/client/state.ts) | The stream store, the operations this browser started, and their pages and notices | -| [`src/client/components.tsx`](src/client/components.tsx) | The surfaces, the slot entries, and the buttons' Remote calls | +| [`src/client/components.tsx`](src/client/components.tsx) | The slot entries of each surface and the buttons' Remote calls | | [`src/client/locales.ts`](src/client/locales.ts) | The shared dictionary | | [`src/client/types.ts`](src/client/types.ts) | Browser state, notice, Remote, and face types | diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md index 2de3b35071..5c00f7a229 100644 --- a/packages/client/ui-connector-account/README.zh.md +++ b/packages/client/ui-connector-account/README.zh.md @@ -63,16 +63,16 @@ export function apply(ctx: Context): void { |---|---| | 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮不可用。失败时先显示注册方的文案,再显示其诊断项 | | 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | -| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。账号检查中或连接中时继续等待,已连接、不可用或服务未运行时自动关闭 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。账号检查中或连接中时继续等待,已连接或不可用时自动关闭 | | 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | ### 跟随操作 -每个浏览器在 Web 应用加载时打开一条流,Host 为每条新流检查每个没有在运行操作的账号;流打开期间注册的账号会立即检查。浏览器跟随其最近一次启动返回的操作,从返回时起,直到流推送该操作的结果。被跟随的操作提供的每个页面只在新标签页中打开一次,只打开 HTTPS 页面或回环地址上的 HTTP 页面;其他浏览器显示同样的区块,但不打开页面,也不报告提示。第一次调用返回前的第二次点击不会启动任何操作。流永久失败时,区块显示账号服务未运行,并提供“重试”;无论按多少次,都只重新打开流一次。卸载浏览器一半会关闭流;Host 持有的操作继续运行。 +每个浏览器在 Web 应用加载时打开一条流,Host 为每条新流检查每个没有在运行操作的账号;流打开期间注册的账号会立即检查。浏览器跟随其最近一次启动返回的操作,从返回时起,直到流推送该操作的结果。被跟随的操作提供的每个页面只在新标签页中打开一次,只打开 HTTPS 页面或回环地址上的 HTTP 页面;其他浏览器显示同样的区块,但不打开页面,也不报告提示。第一次调用返回前的第二次点击不会启动任何操作。连接断开后流会自动重连;流永久失败时,区块保留最后的账号,按钮不可用,直到页面重新加载。卸载浏览器一半会关闭流;Host 持有的操作继续运行。 ### 共用文案 -`connectorAccount` 字典包含所有账号共用的文案:关闭、取消、重试、稍后、排障信息标签、失败提示,以及未运行时的状态、标签和说明。其余文案都来自注册方。 +`connectorAccount` 字典包含所有账号共用的文案:关闭、取消、稍后、排障信息标签和失败提示。其余文案都来自注册方。 ----- @@ -84,7 +84,7 @@ export function apply(ctx: Context): void { Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账号来源,每条 `watch` 流在每次变化后读取每个账号的条目,并合并在下一次读取前到达的变化:键和包、文案、`present(view)`、进行中的操作,以及带成功文本的最新结果。`start` 和 `cancel` 按键路由到该账号的来源。 -[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送或已停止,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。按钮自己调用 Remote 的 `start` 和 `cancel`,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 +[`dsh-api-remotes`](../../api/remotes/README.zh.md) 挂载生成的 `connectorAccounts` Remote。浏览器一半通过 `BrowserAccounts` 打开一条 `watch` 流;它的一个 store 保存按键索引的 Host 账号、流是否在推送,以及最新提示,同时记住本浏览器发起的操作。它为页面注册一个 `plugins.detail.badge` 条目和一个 `shell.overlay` 提示,并为每个带包名的账号注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`,全部使用 `connectorAccount` 命名空间。按钮自己调用 Remote 的 `start` 和 `cancel`,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 | 文件 | 职责 | |---|---| @@ -92,7 +92,7 @@ Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账 | [`src/types.ts`](src/types.ts) | 注册、来源、视图、display 和条目类型 | | [`src/client/index.ts`](src/client/index.ts) | 浏览器入口:字典和插槽注册 | | [`src/client/state.ts`](src/client/state.ts) | 流的 store、本浏览器发起的操作,以及它们的页面和提示 | -| [`src/client/components.tsx`](src/client/components.tsx) | 各界面、插槽条目,以及按钮的 Remote 调用 | +| [`src/client/components.tsx`](src/client/components.tsx) | 各界面的插槽条目,以及按钮的 Remote 调用 | | [`src/client/locales.ts`](src/client/locales.ts) | 共用字典 | | [`src/client/types.ts`](src/client/types.ts) | 浏览器状态、提示、Remote 和 face 类型 | diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx index 9d115051cd..e0293d02b2 100644 --- a/packages/client/ui-connector-account/src/client/components.tsx +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -1,38 +1,29 @@ /** - * The account surfaces the Plugins page shows for registered connector accounts: a bundle's section, title tag, and - * activation prompt, the confirmation a button asks for, and the notice, with the slot entries that read them. + * The account surfaces the Plugins page shows for registered connector accounts: a bundle's section with the + * confirmation a button asks for, the title tag, the activation prompt, and the notice. Each is the slot entry that reads + * this browser's state and calls the Remote. */ import { useEffect, useRef, useState, type ReactNode } from 'react' import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { assertNever } from '@deepseek-ai/dsh-util-values' -import type { - ConnectorAccountButton, ConnectorAccountCommand, ConnectorAccountEntry, ConnectorAccountFailure, ConnectorAccountPhase, -} from '../types.ts' +import type { ConnectorAccountButton, ConnectorAccountCommand, ConnectorAccountEntry, ConnectorAccountPhase } from '../types.ts' import css from './ConnectorAccount.module.css' import type { ConnectorAccountKey } from './locales.ts' import { openAuthorizationPage } from './state.ts' -import type { ConnectorAccountFace, ConnectorAccountNotice, ConnectorAccountsState, ConnectorBundleAccountFace } from './types.ts' +import type { ConnectorAccountFace, ConnectorAccountsState, ConnectorBundleAccountFace } from './types.ts' type FaceProps = InjectFace & { t: Translate } type BundleFaceProps = InjectFace & { t: Translate } -type Resolve = (text: LocalizedText) => string -/** The phase a surface shows: the Host's, or `stopped` once this browser's stream failed for good. */ -type ShownPhase = ConnectorAccountPhase | 'stopped' -const TONE: Record = { - checking: 'ongoing', connecting: 'ongoing', connected: 'done', disconnected: 'idle', unavailable: 'warning', stopped: 'warning', +const TONE: Record = { + checking: 'ongoing', connecting: 'ongoing', connected: 'done', disconnected: 'idle', unavailable: 'warning', } -const BADGE_TONE: Record = { - checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', stopped: 'warning', -} - -function shownPhase(entry: ConnectorAccountEntry, stopped: boolean): ShownPhase { - return stopped ? 'stopped' : entry.display.phase +const BADGE_TONE: Record = { + checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', } async function settle(call: Promise>): Promise { @@ -42,8 +33,8 @@ async function settle(call: Promise>): Promise { } /** - * Run a section button's command against the Host: start and cancel call the Remote directly, and open shows the - * operation's authorization page again in this browser. + * Run a button's command against the Host: start and cancel call the Remote directly, and open shows the operation's + * authorization page again in this browser. * @param face - the Remote and the browser state the commands report to. * @returns whether a call this surface made has not answered, and the runner of one account's command. */ @@ -81,156 +72,16 @@ function useAccountCommand( return { busy, run } } -/** What the section shows about one account in this browser. */ -export interface ConnectorAccountSectionProps { - readonly t: Translate - readonly resolveText: Resolve - readonly entry: ConnectorAccountEntry - /** Whether the Host stream is delivering. */ - readonly linked: boolean - /** Whether the Host stream failed for good. */ - readonly stopped: boolean - /** Whether a call the section made has not answered. */ - readonly busy: boolean - readonly onCommand: (command: ConnectorAccountCommand) => void - readonly onRetry: () => void -} - -function describe(t: Translate, failure: ConnectorAccountFailure): string | undefined { - const details = failure.details ?? [] - return details.length === 0 ? undefined : t('failure.details', { details: details.join(' · ') }) -} - -/** - * The account section on a bundle page. - * @param props - the account, the stream state, the command and retry callbacks, and the translators. - * @returns the title, status line, detail, rows, failure, hint, and the confirmation a button asked for. - */ -export function ConnectorAccountSection(props: ConnectorAccountSectionProps): ReactNode { - const { t, resolveText, entry, linked, stopped, busy, onCommand, onRetry } = props - const [confirming, setConfirming] = useState() - const display = entry.display - const phase = shownPhase(entry, stopped) - // Reopening a stopped stream is the one action that does not need the Host stream. - const disabled = busy || (!linked && !stopped) - const button = (item: ConnectorAccountButton): ReactNode => { - const label = resolveText(item.label) - const onClick = item.confirm === undefined ? () => { onCommand(item.command) } : () => { setConfirming(item) } - return - } - const failure = stopped ? undefined : display.failure - const diagnostic = failure === undefined ? undefined : describe(t, failure) - const confirm = confirming?.confirm - return ( -
-

{resolveText(entry.copy.title)}

-
- - {stopped ? t('status.stopped') : resolveText(display.status)} -
- {stopped - ? - : display.buttons.map(button)} -
-
- {stopped - ?

{t('detail.stopped')}

- : display.detail === undefined ? null :

{resolveText(display.detail)}

} - {stopped ? null : display.notes.map((note) => { - const text = resolveText(note.text) - return ( -
- {text} - {note.button === undefined ? null :
{button(note.button)}
} -
- ) - })} - {failure === undefined ? null : ( -

{resolveText(failure.text)}{diagnostic === undefined ? null : <> {diagnostic}}

- )} -

{resolveText(entry.copy.hint)}

- {confirming === undefined || confirm === undefined ? null : ( - { setConfirming(undefined) }} - onConfirm={() => { onCommand(confirming.command) }} /> - )} -
- ) -} - -/** The Plugins page detail the tag sits on: an item page, or a bundle or row page with its package. */ -export type ConnectorAccountBadgeSubject = - | { readonly kind: 'item' } - | { readonly kind: 'bundle' | 'row'; readonly pkg: { readonly name: string; readonly enabled: boolean } } - -/** The tag's phase and text. */ -export interface ConnectorAccountBadgeProps { - readonly phase: ShownPhase - /** The tag's text; absent while nothing is settled. */ - readonly text: string | undefined -} - -/** - * The account tag beside a bundle's title. - * @param props - the account's phase and the tag's text. - * @returns the tag, or null while nothing is settled. - */ -export function ConnectorAccountBadge({ phase, text }: ConnectorAccountBadgeProps): ReactNode { - return text === undefined ? null : {text} -} - -/** The prompt's phase, text, and callbacks. */ -export interface ConnectorAccountActivationProps { - readonly t: Translate - readonly phase: ShownPhase - readonly title: string - readonly body: string - /** The connect button's label. */ - readonly connect: string - readonly onDismiss: () => void - readonly onConnect: () => void -} - -/** - * Guidance after the user switches a bundle on while its account is not connected. - * @param props - the phase, the registrant's text, the dismiss and connect callbacks, and the translator. - * @returns a prompt shown while disconnected; it waits while the account is checking or connecting, which may still end - * disconnected, and dismisses itself once the account is connected or unavailable. - */ -export function ConnectorAccountActivation(props: ConnectorAccountActivationProps): ReactNode { - const { t, phase, title, body, connect, onDismiss, onConnect } = props - const needed = phase === 'disconnected' - useEffect(() => { - if (phase === 'connected' || phase === 'unavailable' || phase === 'stopped') onDismiss() - }, [phase, onDismiss]) - return ( - - - - }> -

{body}

-
- ) -} - -/** A confirmation's text and callbacks, with the translator for the shared buttons. */ -export interface ConnectorAccountConfirmProps { +/** Ask before an action that changes the account outside DSH; the dialog closes before it confirms. */ +function Confirm(props: { readonly t: Translate readonly title: string readonly body: string - /** The confirm button's label. */ readonly label: string readonly onClose: () => void readonly onConfirm: () => void -} - -/** - * Confirm an action that changes the account outside DSH. - * @param props - the question and the close and confirm callbacks. - * @returns a dialog that closes before it confirms. - */ -export function ConnectorAccountConfirm({ t, title, body, label, onClose, onConfirm }: ConnectorAccountConfirmProps): ReactNode { +}): ReactNode { + const { t, title, body, label, onClose, onConfirm } = props return ( @@ -242,41 +93,58 @@ export function ConnectorAccountConfirm({ t, title, body, label, onClose, onConf ) } -/** The latest notice and its dismissal, with both translators. */ -export interface ConnectorAccountToastProps { - readonly t: Translate - readonly resolveText: Resolve - readonly notice: ConnectorAccountNotice | undefined - readonly onDone: () => void -} - /** - * Account outcomes reported outside the Plugins panel's lifetime. - * @param props - the latest notice, its dismissal, and the translators. - * @returns the toast for the notice, or null. - */ -export function ConnectorAccountToast({ t, resolveText, notice, onDone }: ConnectorAccountToastProps): ReactNode { - if (notice === undefined) return null - if (notice.kind === 'action-failed') { - return } onDone={onDone} /> - } - return -} - -/** - * The `plugins.bundle.config` entry of a bundle that owns an account. + * The `plugins.bundle.config` entry: the account section on its bundle's page. * @param props - the bundle's face and the translator. - * @returns the section for the account, or null before the Host lists it. + * @returns the title, status line, buttons, detail, notes, failure, hint, and the confirmation a button asked for, or + * null before the Host lists the account. */ export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode { - const { useConnectorAccounts, account, resolveText, retry, t } = props + const { useConnectorAccounts, account, resolveText, t } = props const entry = useConnectorAccounts(state => state.accounts.get(account)) const linked = useConnectorAccounts(state => state.linked) - const stopped = useConnectorAccounts(state => state.stopped) const { busy, run } = useAccountCommand(props) + const [confirming, setConfirming] = useState() if (entry === undefined) return null - return { run(entry, command) }} onRetry={retry} /> + const { display } = entry + const button = (item: ConnectorAccountButton): ReactNode => { + const label = resolveText(item.label) + const onClick = item.confirm === undefined ? () => { run(entry, item.command) } : () => { setConfirming(item) } + return + } + const details = display.failure?.details ?? [] + const confirm = confirming?.confirm + return ( +
+

{resolveText(entry.copy.title)}

+
+ + {resolveText(display.status)} +
{display.buttons.map(button)}
+
+ {display.detail === undefined ? null :

{resolveText(display.detail)}

} + {display.notes.map((note) => { + const text = resolveText(note.text) + return ( +
+ {text} + {note.button === undefined ? null :
{button(note.button)}
} +
+ ) + })} + {display.failure === undefined ? null : ( +

+ {resolveText(display.failure.text)} + {details.length === 0 ? null : <> {t('failure.details', { details: details.join(' · ') })}} +

+ )} +

{resolveText(entry.copy.hint)}

+ {confirming === undefined || confirm === undefined ? null : ( + { setConfirming(undefined) }} onConfirm={() => { run(entry, confirming.command) }} /> + )} +
+ ) } function accountOf(state: ConnectorAccountsState, packageName: string): ConnectorAccountEntry | undefined { @@ -286,34 +154,35 @@ function accountOf(state: ConnectorAccountsState, packageName: string): Connecto /** * The `plugins.detail.badge` entry shared by every bundle that owns an account. - * @param props - the open detail page's subject, the face, and the translator. - * @returns the tag on the page of an enabled bundle that owns an account, or of one of its rows, or null. + * @param props - the open detail page's subject and the face. + * @returns the display's tag on the page of an enabled bundle that owns an account, or of one of its rows, or null. */ export function ConnectorAccountBadgeEntry(props: FaceProps & Pick, 'subject'>): ReactNode { - const { useConnectorAccounts, resolveText, subject, t } = props - const page: ConnectorAccountBadgeSubject = subject - const packageName = page.kind === 'item' || !page.pkg.enabled ? undefined : page.pkg.name + const { useConnectorAccounts, resolveText, subject } = props + const packageName = subject.kind === 'item' || !subject.pkg.enabled ? undefined : subject.pkg.name const entry = useConnectorAccounts(state => packageName === undefined ? undefined : accountOf(state, packageName)) - const stopped = useConnectorAccounts(state => state.stopped) - if (entry === undefined) return null - const badge = entry.display.badge - const text = stopped ? t('badge.stopped') : badge === undefined ? undefined : resolveText(badge) - return + const badge = entry?.display.badge + return entry === undefined || badge === undefined ? null : {resolveText(badge)} } /** - * The `plugins.bundle.activation` entry of a bundle that owns an account; Connect opens the bundle page and starts the - * display's `connect` command. + * The `plugins.bundle.activation` entry: guidance after the user switches a bundle on while its account is not + * connected. Connect opens the bundle page and starts the display's `connect` command. * @param props - activation callbacks, the bundle's face, and the translator. - * @returns the prompt for the account, or null before the Host lists it. + * @returns a prompt shown while disconnected, or null before the Host lists the account. It waits while the account is + * checking or connecting, which may still end disconnected, and dismisses itself once the account is connected or + * unavailable. */ export function ConnectorAccountActivationEntry( props: BundleFaceProps & Pick, 'onDismiss' | 'onOpenDetails'>, ): ReactNode { const { useConnectorAccounts, account, resolveText, onDismiss, onOpenDetails, t } = props const entry = useConnectorAccounts(state => state.accounts.get(account)) - const stopped = useConnectorAccounts(state => state.stopped) const { run } = useAccountCommand(props) + const phase = entry?.display.phase + useEffect(() => { + if (phase === 'connected' || phase === 'unavailable') onDismiss() + }, [phase, onDismiss]) if (entry === undefined) return null const { activation } = entry.copy const { connect } = entry.display @@ -322,17 +191,25 @@ export function ConnectorAccountActivationEntry( if (connect !== undefined) run(entry, connect) } return ( - + + + + }> +

{resolveText(activation.body)}

+
) } /** - * The `shell.overlay` entry. + * The `shell.overlay` entry: account outcomes reported outside the Plugins panel's lifetime. * @param props - the face and the translator. * @returns the toast for the latest notice, or null. */ export function ConnectorAccountToastEntry({ useConnectorAccounts, resolveText, dismissNotice, t }: FaceProps): ReactNode { const notice = useConnectorAccounts(state => state.notice) - return + if (notice === undefined) return null + return notice.kind === 'action-failed' + ? } onDone={dismissNotice} /> + : } diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts index c76264c8f5..2c15e0ec09 100644 --- a/packages/client/ui-connector-account/src/client/index.ts +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -53,7 +53,6 @@ export function apply(ctx: Context): void { resolveText: text => ctx.locale.resolveText(text), follow: (key, id) => { browser.follow(key, id) }, failed: () => { browser.failed() }, - retry: () => { browser.retry() }, dismissNotice: () => { browser.dismissNotice() }, } ctx.effect(function* () { diff --git a/packages/client/ui-connector-account/src/client/locales.ts b/packages/client/ui-connector-account/src/client/locales.ts index 57e76d24f1..c0a30b7555 100644 --- a/packages/client/ui-connector-account/src/client/locales.ts +++ b/packages/client/ui-connector-account/src/client/locales.ts @@ -8,13 +8,9 @@ export const NS = 'connectorAccount' export const zh = { close: '关闭', 'action.cancel': '取消', - 'action.retry': '重试', 'activation.later': '稍后', 'failure.details': '排障信息:{details}', 'notice.action-failed': '操作未完成,请重试', - 'badge.stopped': '未运行', - 'status.stopped': '账号服务未运行', - 'detail.stopped': '暂时无法读取账号状态,可以重试。', } /** Every key the shared account surfaces translate. */ @@ -24,91 +20,63 @@ export type ConnectorAccountKey = keyof typeof zh export const en: Record = { close: 'Close', 'action.cancel': 'Cancel', - 'action.retry': 'Retry', 'activation.later': 'Later', 'failure.details': 'Diagnostic: {details}', 'notice.action-failed': 'The action did not finish. Try again.', - 'badge.stopped': 'Not running', - 'status.stopped': 'Account service not running', - 'detail.stopped': 'The account status cannot be read right now. Retry to reconnect.', } /** Japanese dictionary. */ export const ja: Record = { close: '閉じる', 'action.cancel': 'キャンセル', - 'action.retry': '再試行', 'activation.later': '後で', 'failure.details': '診断情報:{details}', 'notice.action-failed': '操作が完了しませんでした。もう一度お試しください。', - 'badge.stopped': '未稼働', - 'status.stopped': 'アカウントサービスが稼働していません', - 'detail.stopped': 'アカウントの状態を現在読み取れません。再試行して再接続してください。', } /** Spanish dictionary. */ export const es: Record = { close: 'Cerrar', 'action.cancel': 'Cancelar', - 'action.retry': 'Reintentar', 'activation.later': 'Más tarde', 'failure.details': 'Diagnóstico: {details}', 'notice.action-failed': 'La acción no se completó. Inténtelo de nuevo.', - 'badge.stopped': 'No está en ejecución', - 'status.stopped': 'El servicio de cuentas no está en ejecución', - 'detail.stopped': 'No se puede leer el estado de la cuenta en este momento. Reintente para volver a conectar.', } /** French dictionary. */ export const fr: Record = { close: 'Fermer', 'action.cancel': 'Annuler', - 'action.retry': 'Réessayer', 'activation.later': 'Plus tard', 'failure.details': 'Diagnostic : {details}', 'notice.action-failed': 'L’action n’a pas abouti. Réessayez.', - 'badge.stopped': 'Ne fonctionne pas', - 'status.stopped': 'Le service de comptes ne fonctionne pas', - 'detail.stopped': 'L’état du compte ne peut pas être lu pour le moment. Réessayez pour vous reconnecter.', } /** German dictionary. */ export const de: Record = { close: 'Schließen', 'action.cancel': 'Abbrechen', - 'action.retry': 'Erneut versuchen', 'activation.later': 'Später', 'failure.details': 'Diagnose: {details}', 'notice.action-failed': 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', - 'badge.stopped': 'Läuft nicht', - 'status.stopped': 'Kontodienst läuft nicht', - 'detail.stopped': 'Der Kontostatus kann gerade nicht gelesen werden. Versuchen Sie es erneut, um die Verbindung wiederherzustellen.', } /** Russian dictionary. */ export const ru: Record = { close: 'Закрыть', 'action.cancel': 'Отмена', - 'action.retry': 'Повторить', 'activation.later': 'Позже', 'failure.details': 'Диагностика: {details}', 'notice.action-failed': 'Действие не завершено. Повторите попытку.', - 'badge.stopped': 'Не работает', - 'status.stopped': 'Служба аккаунтов не работает', - 'detail.stopped': 'Сейчас не удаётся прочитать состояние аккаунта. Повторите попытку, чтобы переподключиться.', } /** Portuguese dictionary. */ export const pt: Record = { close: 'Fechar', 'action.cancel': 'Cancelar', - 'action.retry': 'Tentar novamente', 'activation.later': 'Mais tarde', 'failure.details': 'Diagnóstico: {details}', 'notice.action-failed': 'A ação não foi concluída. Tente novamente.', - 'badge.stopped': 'Não está em execução', - 'status.stopped': 'O serviço de contas não está em execução', - 'detail.stopped': 'Não é possível ler o estado da conta agora. Tente novamente para reconectar.', } declare module '@deepseek-ai/dsh-client-ui-slots' { diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts index 2d4954ddb8..332715e431 100644 --- a/packages/client/ui-connector-account/src/client/state.ts +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -28,7 +28,7 @@ export function openAuthorizationPage(url: string | undefined): void { export class BrowserAccounts { /** The accounts, stream state, and notice every surface on the page reads. */ readonly state: SnapshotStore = createSnapshotStore({ - accounts: new Map(), linked: true, stopped: false, notice: undefined, + accounts: new Map(), linked: true, notice: undefined, }) /** @@ -38,15 +38,20 @@ export class BrowserAccounts { private readonly followed = new Map }>() private seq = 0 private disposed = false - private stream!: RemoteStream - private observing!: Promise + private readonly stream: RemoteStream + private readonly observing: Promise /** * @param ctx - the browser context carrying the Remote client. * @param remote - the `connectorAccounts` Remote. */ - constructor(private readonly ctx: Context, private readonly remote: Pick) { - this.subscribe() + constructor(private readonly ctx: Context, remote: Pick) { + this.stream = ctx.remote.$stream({ + name: 'Connector accounts', open: signal => remote.watch(signal), + ended: () => new Error('Connector accounts stream ended'), + carrierFailed: () => { this.patch({ linked: false }) }, + }) + this.observing = this.observe() } /** @@ -72,17 +77,9 @@ export class BrowserAccounts { this.patch({ notice: undefined }) } - /** Reopen the Host stream after it stopped; ignored while it runs, while a reopen is pending, or after disposal. */ - retry(): void { - if (this.disposed || !this.state.getSnapshot().stopped) return - // Clearing `stopped` before the reopen awaits claims it, so a second retry finds nothing to reopen. - this.patch({ stopped: false }) - void this.reopen() - } - /** - * Stop observing the Host; afterwards the page opens no page, reports nothing more, and a pending retry opens no stream. - * Host-owned operations keep running. + * Stop observing the Host; afterwards the page opens no page and reports nothing more. Host-owned operations keep + * running. * @returns after the stream closes. */ async dispose(): Promise { @@ -91,39 +88,26 @@ export class BrowserAccounts { await this.observing } - private subscribe(): void { - this.stream = this.ctx.remote.$stream({ - name: 'Connector accounts', open: signal => this.remote.watch(signal), - ended: () => new Error('Connector accounts stream ended'), - carrierFailed: () => { this.patch({ linked: false }) }, - }) - this.observing = this.observe(this.stream) - } - - private async observe(stream: RemoteStream): Promise { + private async observe(): Promise { try { - for await (const item of stream) { + for await (const item of this.stream) { // An item the stream yielded just before disposal must not reach the disposed page. if (this.disposed) return this.show(item.value.accounts) item.accept() } - } catch { - // A terminal failure, such as a Host without the registry, ends the stream; a disposed page shows nothing. - if (!this.disposed) this.patch({ linked: false, stopped: true }) + } catch (error) { + // A terminal failure, such as a Host without the registry, leaves the buttons disabled until the page reloads. + if (this.disposed) return + this.patch({ linked: false }) + this.ctx.logger.warn('connector accounts stream failed; reload the page to reconnect: %s', error) } } - private async reopen(): Promise { - await this.stream.dispose() - await this.observing - if (!this.disposed) this.subscribe() - } - private show(entries: readonly ConnectorAccountEntry[]): void { const accounts = new Map(entries.map(entry => [entry.key, entry])) for (const key of [...this.followed.keys()]) if (!accounts.has(key)) this.followed.delete(key) - this.patch({ accounts, linked: true, stopped: false }) + this.patch({ accounts, linked: true }) for (const entry of entries) this.track(entry) } diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts index 8ed18a7c81..482363c688 100644 --- a/packages/client/ui-connector-account/src/client/types.ts +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -15,8 +15,6 @@ export interface ConnectorAccountsState { readonly accounts: ReadonlyMap /** Whether the Host stream is delivering. */ readonly linked: boolean - /** Whether the Host stream failed for good; `retry` reopens it. */ - readonly stopped: boolean readonly notice: ConnectorAccountNotice | undefined } @@ -38,8 +36,6 @@ export interface ConnectorAccountFace { readonly follow: (key: string, id: ConnectorOperationId) => void /** Report that a Remote call this browser made did not finish. */ readonly failed: () => void - /** Reopen the Host stream after it stopped. */ - readonly retry: () => void readonly dismissNotice: () => void } diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts index 20481db45e..d01ff8c3f2 100644 --- a/packages/client/ui-connector-account/tests/apply.client.spec.ts +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -98,7 +98,7 @@ async function bench() { it('shows one tag and one notice entry for the page and each bundle\'s section and prompt under the shared dictionary', async () => { const b = await bench() await b.mount() - expect(b.locale.bind(NS)('action.retry')).toBe('Retry') + expect(b.locale.bind(NS)('action.cancel')).toBe('Cancel') expect(b.ctx.slots.entries('plugins.detail.badge').map(item => [item.options.id, item.component])).toEqual([ ['connector-account.badge', ConnectorAccountBadgeEntry], ]) @@ -130,7 +130,6 @@ it('shows one tag and one notice entry for the page and each bundle\'s section a face.failed() expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) face.dismissNotice() - face.retry() expect(face.hooks.connectorAccounts.getSnapshot().notice).toBeUndefined() // A dropped account withdraws its bundle's surfaces, and a bundle whose account changed key shows the new one. @@ -151,6 +150,6 @@ it('withdraws every surface, the dictionaries, and the stream when the plugin un for (const slot of ['plugins.bundle.config', 'plugins.bundle.activation', 'plugins.detail.badge', 'shell.overlay'] as const) { expect(b.ctx.slots.entries(slot)).toEqual([]) } - expect(b.locale.bind(NS)('action.retry')).toBe('action.retry') + expect(b.locale.bind(NS)('action.cancel')).toBe('action.cancel') expect(b.closeStream).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-connector-account/tests/components.client.spec.tsx b/packages/client/ui-connector-account/tests/components.client.spec.tsx index df9a0d0e80..25978b5ac3 100644 --- a/packages/client/ui-connector-account/tests/components.client.spec.tsx +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -1,5 +1,5 @@ // @vitest-environment jsdom -/** The surfaces render each registrant's display from the Host with the shared copy, and buttons call the Remote directly. */ +/** The slot entries render each registrant's display from the Host with the shared copy, and buttons call the Remote directly. */ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' @@ -7,8 +7,7 @@ import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { afterEach, expect, it, onTestFinished, vi } from 'vitest' import { - ConnectorAccountActivation, ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSection, - ConnectorAccountSectionEntry, ConnectorAccountToast, ConnectorAccountToastEntry, + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, } from '../src/client/components.tsx' import { zh } from '../src/client/locales.ts' import type { ConnectorAccountsState } from '../src/client/types.ts' @@ -22,6 +21,7 @@ const t = makeTranslate(zh) const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en const button = (name: string) => screen.getByRole('button', { name }) const disabled = (): boolean[] => screen.getAllByRole('button').map(element => (element as HTMLButtonElement).disabled) +const click = async (name: string) => { await act(async () => { fireEvent.click(button(name)) }) } const DISCONNECTED: ConnectorAccountDisplay = { phase: 'disconnected', status: { en: 'Not connected', zh: '未连接' }, badge: '未连接', @@ -36,122 +36,12 @@ function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial = {}, display?: ConnectorAccountDisplay) { - const onCommand = vi.fn() - const onRetry = vi.fn() - const view = render( - , - ) - return { ...view, onCommand, onRetry } -} - -it('shows the registrant title, status, detail, notes, and hint, and runs each button as its command', () => { - const display: ConnectorAccountDisplay = { - ...DISCONNECTED, detail: '先关联一个应用。', - notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], - } - const { container, onCommand } = section({}, display) - expect(screen.getByText('演示账号')).toBeTruthy() - expect(screen.getByText('未连接')).toBeTruthy() - expect(screen.getByText('先关联一个应用。')).toBeTruthy() - expect(screen.getByText('普通说明')).toBeTruthy() - expect(screen.getByText('与终端共用。')).toBeTruthy() - expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() - fireEvent.click(button('连接演示')) - fireEvent.click(button('更换')) - expect(onCommand.mock.calls).toEqual([[{ kind: 'start', operation: 'connect' }], [{ kind: 'start', operation: 'link-app' }]]) -}) - -it('disables the buttons while a call is pending or the Host stream is down', () => { - const { rerender } = section({ busy: true }) - expect(disabled()).toEqual([true]) - rerender( - , - ) - expect(disabled()).toEqual([true]) -}) - -it('asks before a button that changes the account outside DSH and runs it only after the user accepts', () => { - const display: ConnectorAccountDisplay = { - phase: 'connected', status: '已连接', notes: [], - buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], - } - const { onCommand } = section({}, display) - fireEvent.click(button('退出登录')) - expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() - expect(screen.getByText('终端也会退出。')).toBeTruthy() - fireEvent.click(button(zh['action.cancel'])) - expect(screen.queryByRole('dialog')).toBeNull() - fireEvent.click(button('退出登录')) - fireEvent.click(button('确认退出')) - expect(screen.queryByRole('dialog')).toBeNull() - expect(onCommand.mock.calls).toEqual([[{ kind: 'start', operation: 'sign-out' }]]) -}) - -it.each<[string, ConnectorAccountDisplay['failure'], string]>([ - ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], - ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], - ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], -])('reports %s', (_name, failure, expected) => { - section({}, { ...DISCONNECTED, ...failure === undefined ? {} : { failure } }) - expect(screen.getByRole('alert').textContent).toBe(expected) -}) - -it('explains a stopped stream with the shared copy and reopens it even while offline', () => { - const { container, onRetry } = section({ stopped: true, linked: false }, { ...DISCONNECTED, failure: { text: '失败。' }, notes: [{ text: '说明' }] }) - expect(screen.getByText(zh['status.stopped'])).toBeTruthy() - expect(screen.getByText(zh['detail.stopped'])).toBeTruthy() - expect(screen.queryByRole('alert')).toBeNull() - expect(screen.queryByText('说明')).toBeNull() - expect(container.querySelector('[data-connector-account="stopped"]')).toBeTruthy() - fireEvent.click(button(zh['action.retry'])) - expect(onRetry).toHaveBeenCalledOnce() -}) - -it('prompts to connect only while disconnected, waits while checking or connecting, and steps aside once settled', () => { - const onDismiss = vi.fn() - const onConnect = vi.fn() - const prompt = (phase: 'checking' | 'connecting' | 'disconnected' | 'connected' | 'unavailable' | 'stopped') => - - const { rerender } = render(prompt('checking')) - // An account still connecting after the bundle is switched on may end disconnected. - rerender(prompt('connecting')) - expect(screen.queryByRole('dialog')).toBeNull() - expect(onDismiss).not.toHaveBeenCalled() - rerender(prompt('disconnected')) - expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() - expect(screen.getByText('插件已开启。')).toBeTruthy() - fireEvent.click(button('立即连接')) - expect(onConnect).toHaveBeenCalledOnce() - fireEvent.click(button(zh['activation.later'])) - expect(onDismiss).toHaveBeenCalledOnce() - rerender(prompt('connected')) - expect(onDismiss).toHaveBeenCalledTimes(2) - rerender(prompt('unavailable')) - rerender(prompt('stopped')) - expect(onDismiss).toHaveBeenCalledTimes(4) -}) - -it('shows the latest notice with the registrant text or the shared failure copy', () => { - const onDone = vi.fn() - const toast = (notice: ConnectorAccountsState['notice']) => - - const { rerender } = render(toast(undefined)) - expect(document.body.textContent).toBe('') - rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) - expect(screen.getByText('演示已连接')).toBeTruthy() - rerender(toast({ seq: 2, kind: 'action-failed' })) - expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() -}) - const ok = (value: T): RemoteResult => ({ ok: true, value }) const refused = (): RemoteResult => ({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) as never function face(change: Partial = {}, accounts: readonly ConnectorAccountEntry[] = [entry()]) { const current: ConnectorAccountsState = { - accounts: new Map(accounts.map(item => [item.key, item])), linked: true, stopped: false, notice: undefined, ...change, + accounts: new Map(accounts.map(item => [item.key, item])), linked: true, notice: undefined, ...change, } return { useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), @@ -159,30 +49,75 @@ function face(change: Partial = {}, accounts: readonly C start: vi.fn(async (_key: string, _operation: string) => ok(OP)), cancel: vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ok(undefined)), }, - account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), retry: vi.fn(), dismissNotice: vi.fn(), t, + account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, } } -it('starts an operation through the Remote, follows it, and stays busy until the call answers', async () => { +const sectionOf = (display: ConnectorAccountDisplay, change: Partial = {}) => face(change, [entry(display)]) +const prompt = (props: ReturnType, onDismiss = vi.fn(), onOpenDetails = vi.fn()) => + + +it('shows the registrant title, status, detail, notes, and hint, and starts each button\'s operation through the Remote', async () => { + const props = sectionOf({ + ...DISCONNECTED, detail: '先关联一个应用。', + notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], + }) + const { container } = render() + for (const text of ['演示账号', '未连接', '先关联一个应用。', '普通说明', '与终端共用。']) expect(screen.getByText(text)).toBeTruthy() + expect(container.querySelector('[data-connector-account="disconnected"][data-connector-account-key="@acme/fixture"]')).toBeTruthy() + await click('连接演示') + await click('更换') + expect(props.remote.start.mock.calls).toEqual([[KEY, 'connect'], [KEY, 'link-app']]) + expect(props.follow.mock.calls).toEqual([[KEY, OP], [KEY, OP]]) +}) + +it('disables the buttons while a call is pending or the Host stream is down', async () => { const props = face() const answer = Promise.withResolvers>() props.remote.start.mockReturnValueOnce(answer.promise) render() fireEvent.click(button('连接演示')) - expect(props.remote.start).toHaveBeenCalledWith(KEY, 'connect') expect(disabled()).toEqual([true]) await act(async () => { answer.resolve(ok(OP)) }) - expect(props.follow).toHaveBeenCalledWith(KEY, OP) expect(disabled()).toEqual([false]) expect(props.failed).not.toHaveBeenCalled() + cleanup() + render() + expect(disabled()).toEqual([true]) +}) + +it('asks before a button that changes the account outside DSH and starts it only after the user accepts', async () => { + const props = sectionOf({ + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + }) + render() + fireEvent.click(button('退出登录')) + expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() + expect(screen.getByText('终端也会退出。')).toBeTruthy() + fireEvent.click(button(zh['action.cancel'])) + expect(screen.queryByRole('dialog')).toBeNull() + fireEvent.click(button('退出登录')) + await click('确认退出') + expect(screen.queryByRole('dialog')).toBeNull() + expect(props.remote.start.mock.calls).toEqual([[KEY, 'sign-out']]) +}) + +it.each<[string, ConnectorAccountDisplay['failure'], string]>([ + ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], + ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], + ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], +])('reports %s', (_name, failure, expected) => { + render() + expect(screen.getByRole('alert').textContent).toBe(expected) }) it('reports a start the Host refused or that never answered, without following it', async () => { const props = face() props.remote.start.mockResolvedValueOnce(refused()).mockRejectedValueOnce(new Error('carrier lost')) render() - await act(async () => { fireEvent.click(button('连接演示')) }) - await act(async () => { fireEvent.click(button('连接演示')) }) + await click('连接演示') + await click('连接演示') expect(props.failed).toHaveBeenCalledTimes(2) expect(props.follow).not.toHaveBeenCalled() }) @@ -198,26 +133,23 @@ it('cancels the operation in progress and opens its authorization page again on render() fireEvent.click(button('打开授权页')) expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') - await act(async () => { fireEvent.click(button('取消')) }) + await click('取消') expect(props.remote.cancel).toHaveBeenCalledWith(KEY, OP) // A cancel button with no operation in progress calls nothing. cleanup() - const idle = face({}, [entry(display)]) + const idle = sectionOf(display) render() - await act(async () => { fireEvent.click(button('取消')) }) + await click('取消') expect(idle.remote.cancel).not.toHaveBeenCalled() }) -const prompt = (props: ReturnType, onOpenDetails = vi.fn()) => - - it('renders nothing for a bundle whose account the Host has not listed', () => { render() render(prompt(face({}, []))) expect(document.body.textContent).toBe('') }) -it('tags only the enabled bundle that owns an account, with the Host text or the shared copy once the stream stopped', () => { +it('tags only the enabled bundle that owns an account, with the display\'s tag', () => { const pkg = (name: string, enabled = true) => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] } as const) const page = (name: string, enabled = true): PluginsSubject => ({ kind: 'bundle', pkg: pkg(name, enabled) }) const row: PluginsSubject = { kind: 'row', pkg: pkg(KEY), row: { rowId: 'fixture', moduleName: '@acme/fixture-row', enabled: true } } @@ -226,33 +158,49 @@ it('tags only the enabled bundle that owns an account, with the Host text or the expect(screen.getByText('未连接')).toBeTruthy() rerender(tag(face(), row)) expect(screen.getByText('未连接')).toBeTruthy() - rerender(tag(face({ stopped: true }), page(KEY))) - expect(screen.getByText(zh['badge.stopped'])).toBeTruthy() for (const [props, subject] of [ [face(), page(KEY, false)], [face(), page('@acme/other')], [face(), { kind: 'item', id: 'fixture-item' }], - [face({}, [entry({ phase: 'checking', status: '检查中', buttons: [], notes: [] })]), page(KEY)], + [sectionOf({ phase: 'checking', status: '检查中', buttons: [], notes: [] }), page(KEY)], ] as const) { rerender(tag(props, subject)) expect(document.body.textContent).toBe('') } }) +it('prompts to connect only while disconnected, waits while checking or connecting, and dismisses itself once settled', () => { + const onDismiss = vi.fn() + const at = (phase: ConnectorAccountDisplay['phase']) => prompt(sectionOf({ phase, status: phase, buttons: [], notes: [] }), onDismiss) + const { rerender } = render(at('checking')) + // An account still connecting after the bundle is switched on may end disconnected. + rerender(at('connecting')) + expect(screen.queryByRole('dialog')).toBeNull() + expect(onDismiss).not.toHaveBeenCalled() + rerender(at('disconnected')) + expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() + expect(screen.getByText('插件已开启。')).toBeTruthy() + fireEvent.click(button(zh['activation.later'])) + expect(onDismiss).toHaveBeenCalledOnce() + rerender(at('connected')) + rerender(at('unavailable')) + expect(onDismiss).toHaveBeenCalledTimes(3) +}) + it('connects from the prompt through the operation the display names, or only opens the page', async () => { const onOpenDetails = vi.fn() - const named = face({}, [entry({ ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } })]) - const { rerender } = render(prompt(named, onOpenDetails)) - await act(async () => { fireEvent.click(button('连接演示')) }) + const named = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } }) + const { rerender } = render(prompt(named, vi.fn(), onOpenDetails)) + await click('连接演示') expect(onOpenDetails).toHaveBeenCalledOnce() expect(named.remote.start).toHaveBeenCalledWith(KEY, 'link-app') const bare = face() - rerender(prompt(bare, onOpenDetails)) + rerender(prompt(bare, vi.fn(), onOpenDetails)) fireEvent.click(button('连接演示')) expect(onOpenDetails).toHaveBeenCalledTimes(2) expect(bare.remote.start).not.toHaveBeenCalled() }) it('starts once for a second click before the first call answers', async () => { - const props = face({}, [entry({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } })]) + const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) const answer = Promise.withResolvers>() props.remote.start.mockReturnValueOnce(answer.promise) render(prompt(props)) @@ -263,7 +211,12 @@ it('starts once for a second click before the first call answers', async () => { expect(props.follow).toHaveBeenCalledOnce() }) -it('shows the account notice through the toast entry', () => { - render() +it('shows the latest notice with the registrant text or the shared failure copy', () => { + const toast = (notice: ConnectorAccountsState['notice']) => + const { rerender } = render(toast(undefined)) + expect(document.body.textContent).toBe('') + rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) expect(screen.getByText('演示已连接')).toBeTruthy() + rerender(toast({ seq: 2, kind: 'action-failed' })) + expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() }) diff --git a/packages/client/ui-connector-account/tests/state.client.spec.ts b/packages/client/ui-connector-account/tests/state.client.spec.ts index 490b4dcae3..4c11668ac2 100644 --- a/packages/client/ui-connector-account/tests/state.client.spec.ts +++ b/packages/client/ui-connector-account/tests/state.client.spec.ts @@ -52,7 +52,7 @@ function fixture() { const browser = new BrowserAccounts(ctx, remote) onTestFinished(async () => { await browser.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) return { - browser, remote, open: windowOpen, streams, options: () => options, + ctx, browser, remote, open: windowOpen, streams, options: () => options, state: () => browser.state.getSnapshot(), deliver(view: ConnectorAccountsView) { queue.push(view); wake?.() }, async publish(...entries: ConnectorAccountEntry[]) { @@ -64,12 +64,9 @@ function fixture() { } } -// Every fixture step settles through microtasks, so one macrotask lets a pending reopen finish. -const drain = () => new Promise((resolve) => { setTimeout(resolve, 0) }) - it('mirrors the Host accounts by key and reports carrier loss until the next item', async () => { const b = fixture() - expect(b.state()).toEqual({ accounts: new Map(), linked: true, stopped: false, notice: undefined }) + expect(b.state()).toEqual({ accounts: new Map(), linked: true, notice: undefined }) const open = b.options().open(new AbortController().signal) expect(b.remote.watch).toHaveBeenCalledOnce() expect(open).toBe(b.remote.watch.mock.results[0]?.value) @@ -78,7 +75,7 @@ it('mirrors the Host accounts by key and reports carrier loss until the next ite b.options().carrierFailed?.(new RemoteStreamCarrierError('offline')) expect(b.state().linked).toBe(false) await b.publish(entry(FIXTURE)) - expect(b.state()).toMatchObject({ linked: true, stopped: false }) + expect(b.state().linked).toBe(true) expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) expect(b.options().ended(true).message).toBe('Connector accounts stream ended') }) @@ -135,34 +132,22 @@ it('reports a call that did not finish with a fresh notice each time', () => { expect(b.state().notice).toEqual({ seq: 2, kind: 'action-failed' }) }) -it('stops after a terminal stream failure and reopens on retry', async () => { +it('keeps the buttons disabled and logs a terminal stream failure, opening no second stream', async () => { const b = fixture() + const warn = vi.spyOn(b.ctx.logger, 'warn').mockImplementation(() => {}) await b.publish(entry(FIXTURE)) - b.browser.retry() - expect(b.streams).toHaveLength(1) b.fail(new Error('Host without the registry')) - await vi.waitFor(() => { expect(b.state().stopped).toBe(true) }) - expect(b.state().linked).toBe(false) - b.browser.retry() - b.browser.retry() - await drain() - expect(b.streams).toHaveLength(2) - expect(b.streams[0]?.dispose).toHaveBeenCalledOnce() - await b.publish(entry(FIXTURE)) - expect(b.state()).toMatchObject({ linked: true, stopped: false }) + await vi.waitFor(() => { expect(b.state().linked).toBe(false) }) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('connector accounts stream failed'), expect.any(Error)) + expect(b.streams).toHaveLength(1) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE]) }) -it('opens nothing and reports nothing after disposal, and a retry pending at disposal opens no stream', async () => { +it('opens nothing and reports nothing after disposal', async () => { const b = fixture() - b.fail(new Error('Host without the registry')) - await vi.waitFor(() => { expect(b.state().stopped).toBe(true) }) - b.browser.retry() await b.browser.dispose() - await drain() - expect(b.streams).toHaveLength(1) b.browser.follow(FIXTURE, OP) b.browser.failed() - b.browser.retry() expect(b.state().notice).toBeUndefined() }) @@ -171,7 +156,7 @@ it('shows nothing for a stream that fails while the page disposes it', async () const disposing = b.browser.dispose() b.fail(new Error('carrier lost')) await disposing - expect(b.state()).toMatchObject({ linked: true, stopped: false }) + expect(b.state().linked).toBe(true) }) it('ignores an item the stream yielded just before disposal', async () => {