From a8f3badfeef6470aabfd8b43615fafe9c3bd4155 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Fri, 6 Nov 2026 19:21:03 +0800 Subject: [PATCH 01/13] feat(connector-account): add one Host registry and Plugins page surfaces for connector accounts `@deepseek-ai/dsh-client-ui-connector-account` provides `ctx.connectorAccounts`, where CLI app plugins and MCP connectors register an account with its source, page operations, copy, and Host-side presentation, and the `connectorAccounts` Remote (`watch`, `start`, `cancel`). The browser half follows every account through one stream and renders each bundle's section, title tag, activation prompt, confirmation, and notice from the Host display; it opens authorization pages and reports notices only for the operations this browser started. `dsh-api-remotes` mounts the generated Remote, `dsh-web-app` loads the package, LiveShare classifies the three endpoints as owner-only, and the client test runtime answers `connectorAccounts/watch` with no accounts. --- ...11-06-connector-account-registry.i18n.yaml | 19 + .../2026-11-06-connector-account-registry.md | 42 +++ ...026-11-06-connector-account-registry.zh.md | 42 +++ docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 4 + docs/capability-seams.zh.md | 4 + docs/config-catalog.md | 1 + docs/config-catalog.zh.md | 1 + docs/module-graph.md | 2 + docs/module-graph.zh.md | 2 + docs/subsystems/boot.md | 44 +++ docs/subsystems/boot.zh.md | 44 +++ packages/api/remotes/README.i18n.yaml | 4 +- packages/api/remotes/README.md | 2 +- packages/api/remotes/README.zh.md | 2 +- packages/api/remotes/package.json | 1 + packages/api/remotes/src/client/index.ts | 3 + packages/bundle/web-app/cordis.patch.yml | 5 + packages/bundle/web-app/package.json | 1 + packages/client/README.i18n.yaml | 4 +- packages/client/README.md | 1 + packages/client/README.zh.md | 1 + .../ui-connector-account/README.i18n.yaml | 49 +++ .../client/ui-connector-account/README.md | 138 +++++++ .../client/ui-connector-account/README.zh.md | 138 +++++++ .../ui-connector-account/locale/de.json | 6 + .../ui-connector-account/locale/en.json | 6 + .../ui-connector-account/locale/es.json | 6 + .../ui-connector-account/locale/fr.json | 6 + .../ui-connector-account/locale/ja.json | 6 + .../ui-connector-account/locale/pt.json | 6 + .../ui-connector-account/locale/ru.json | 6 + .../ui-connector-account/locale/zh.json | 6 + .../client/ui-connector-account/package.json | 96 +++++ .../src/client/ConnectorAccount.module.css | 51 +++ .../src/client/components.tsx | 337 ++++++++++++++++++ .../ui-connector-account/src/client/index.ts | 90 +++++ .../src/client/locales.ts | 118 ++++++ .../ui-connector-account/src/client/state.ts | 157 ++++++++ .../ui-connector-account/src/client/types.ts | 50 +++ .../ui-connector-account/src/css-modules.d.ts | 6 + .../client/ui-connector-account/src/index.ts | 163 +++++++++ .../client/ui-connector-account/src/types.ts | 164 +++++++++ .../tests/apply.client.spec.ts | 156 ++++++++ .../tests/components.client.spec.tsx | 264 ++++++++++++++ .../tests/registry.host.spec.ts | 166 +++++++++ .../tests/state.client.spec.ts | 194 ++++++++++ .../ui-connector-account/tsconfig.client.json | 57 +++ .../ui-connector-account/tsconfig.host.json | 26 ++ .../client/ui-connector-account/tsconfig.json | 11 + .../ui-connector-account/tsdown.config.ts | 3 + .../liveshare/src/endpoint-classification.ts | 3 + .../src/client/slot-catalog.ts | 7 +- .../extensions/tool-cordis/src/api-catalog.ts | 110 ++++++ .../skills/dsh-doc/references/packages.md | 1 + .../src/assembly/remote-default-responses.ts | 2 + pnpm-lock.yaml | 67 ++++ scripts/gen-cordis-catalog.ts | 5 + scripts/gen-doc-graphs.ts | 7 + .../verify-package-readme-model-experience.ts | 1 + tsconfig.base.json | 2 + tsconfig.client.json | 1 + tsconfig.host.json | 1 + 63 files changed, 2913 insertions(+), 9 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md create mode 100644 .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md create mode 100644 packages/client/ui-connector-account/README.i18n.yaml create mode 100644 packages/client/ui-connector-account/README.md create mode 100644 packages/client/ui-connector-account/README.zh.md create mode 100644 packages/client/ui-connector-account/locale/de.json create mode 100644 packages/client/ui-connector-account/locale/en.json create mode 100644 packages/client/ui-connector-account/locale/es.json create mode 100644 packages/client/ui-connector-account/locale/fr.json create mode 100644 packages/client/ui-connector-account/locale/ja.json create mode 100644 packages/client/ui-connector-account/locale/pt.json create mode 100644 packages/client/ui-connector-account/locale/ru.json create mode 100644 packages/client/ui-connector-account/locale/zh.json create mode 100644 packages/client/ui-connector-account/package.json create mode 100644 packages/client/ui-connector-account/src/client/ConnectorAccount.module.css create mode 100644 packages/client/ui-connector-account/src/client/components.tsx create mode 100644 packages/client/ui-connector-account/src/client/index.ts create mode 100644 packages/client/ui-connector-account/src/client/locales.ts create mode 100644 packages/client/ui-connector-account/src/client/state.ts create mode 100644 packages/client/ui-connector-account/src/client/types.ts create mode 100644 packages/client/ui-connector-account/src/css-modules.d.ts create mode 100644 packages/client/ui-connector-account/src/index.ts create mode 100644 packages/client/ui-connector-account/src/types.ts create mode 100644 packages/client/ui-connector-account/tests/apply.client.spec.ts create mode 100644 packages/client/ui-connector-account/tests/components.client.spec.tsx create mode 100644 packages/client/ui-connector-account/tests/registry.host.spec.ts create mode 100644 packages/client/ui-connector-account/tests/state.client.spec.ts create mode 100644 packages/client/ui-connector-account/tsconfig.client.json create mode 100644 packages/client/ui-connector-account/tsconfig.host.json create mode 100644 packages/client/ui-connector-account/tsconfig.json create mode 100644 packages/client/ui-connector-account/tsdown.config.ts diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml new file mode 100644 index 0000000000..121a9d669b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-06-connector-account-registry.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts: + en: 3950421fb526f6b7 + zh: 47c5f6cc4b735058 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/problem: + en: 2a7b59cd509a0b9a + zh: 38130ce17829342d +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/decision: + en: d96b43106a1ba837 + zh: 97bc8f9436ec07d0 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/alternatives-considered: + en: ee0aa3f9ea40ef15 + zh: fded69a6dcc8ca87 +/agent-note-one-host-registry-and-one-browser-half-for-connector-accounts/consequences: + en: 5228f32becfbdec3 + zh: 013f1073e70d46f7 diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md new file mode 100644 index 0000000000..93138b065e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.md @@ -0,0 +1,42 @@ +# Agent Note: One Host registry and one browser half for connector accounts + +Status: implemented + +English | [中文](2026-11-06-connector-account-registry.zh.md) + +## Problem + +Connector plugins show an account section on the Plugins page. CLI app plugins keep the account in their vendor CLI; MCP connectors keep an OAuth grant through the MCP manager. Both kinds need the same surfaces: a bundle's section, title tag, and activation prompt, a confirmation before an action that changes the account outside DSH, and a notice in the browser that started the operation. A client plugin cannot share runtime code with another feature plugin ([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) rule 3), so one browser half per connector kind duplicates the same code and lets the copies drift. When the browser decides an account's state or relays an identifier from one Remote to another, the Host can no longer run the flow without the browser. + +## Decision + +[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.md) provides one Host registry, `ctx.connectorAccounts`, one `connectorAccounts` Remote, and one browser half for every connector kind. + +| Part | Contract | +|---|---| +| Registration | `register({ key, packageName?, source, operations, copy, present })` returns the disposer that withdraws the account | +| Key | Unique among registered accounts and independent of the package, so an account that no bundle owns, such as a server configured in Settings, registers too | +| Package | Decides which bundle page carries the section and tag; a package carries at most one account | +| Source | The registrant's account: `snapshot`, `observe`, `refresh`, `start`, and `cancel` | +| Display | `present(view)` on the Host gives the phase, status text, title tag, buttons and their commands, confirmations, failure, and the operation the activation prompt starts | +| Remote | `watch`, plus `start(key, operation)` and `cancel(key, id)`, which route by key to the account's source | + +The Host decides everything except opening the authorization page. The browser never learns how an account connects: it receives only the display, the operation in progress with its authorization page, and the latest result with its success text. The browser half keeps only what belongs to one browser: the operations it started, so their authorization pages open and their success is reported only there; the latest notice; and whether its stream is delivering. Buttons call `start` and `cancel` on the Remote themselves, and each surface keeps its own pending state. + +The page registers one title tag entry and one notice entry. It also registers a section and an activation prompt for each account that names a package, because those two slots are keyed by package. + +## Alternatives considered + +**Two registries behind one browser half.** Rejected: the browser would follow both Remotes and choose which one each button calls, which relays between Host services again, and the two Host registries would hold the same code. + +**One browser half per connector kind.** Rejected: client plugins cannot import each other's values, so the shared surfaces would be written twice and diverge. + +**Share the browser half through `PLATFORM_MODULES` or a browser-side service.** Rejected: the module table is reserved for shell-seeded and static infrastructure libraries, and a browser-side service would keep the registrations in the browser, which only repeat what the Host knows. + +**Let the browser derive an account's phase and actions from the registrant's raw state.** Rejected: the rules for which actions apply would live where the Host cannot test or run them, and the browser would need the registrant's own Remote. + +## Consequences + +The registry and browser half exist once. A new connector kind writes a source and `present` on the Host and needs no browser code. The account rules live beside the services that own them, and the Host can run every operation without a browser. + +Registrants map their account states onto five phases (checking, connecting, connected, disconnected, unavailable); a state outside them shows through its status text and detail. The Web and Desktop compositions load the registry whether or not a connector plugin is installed. An authorization page that opens after the start call answers can be blocked by the browser; the section's open button shows it again. diff --git a/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md new file mode 100644 index 0000000000..e2c7a56b41 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-06-connector-account-registry.zh.md @@ -0,0 +1,42 @@ +# Agent Note:连接器账号使用一个 Host 注册表和一个浏览器一半 + +Status: implemented + +[English](2026-11-06-connector-account-registry.md) | 中文 + +## 问题 + +连接器插件会在插件页显示账号区块。CLI 应用插件的账号保存在厂商 CLI 中;MCP 连接器通过 MCP 管理器保存 OAuth 授权。两类插件需要同样的界面:插件包的区块、标题旁标签和开启引导,在会改变 DSH 之外账号状态的操作前确认,以及只在发起操作的浏览器中显示的提示。客户端插件不能与其他功能插件共享运行时代码([packages/client/AGENTS.md](../../../../packages/client/AGENTS.md) 第 3 条),因此每类连接器各有一个浏览器一半,就会把同样的代码写两遍,副本还会逐渐不一致。如果由浏览器决定账号状态,或在两个 Remote 之间转发标识,Host 就无法在没有浏览器的情况下完成流程。 + +## 决定 + +[`@deepseek-ai/dsh-client-ui-connector-account`](../../../../packages/client/ui-connector-account/README.zh.md) 为所有连接器类型提供一个 Host 注册表 `ctx.connectorAccounts`、一个 `connectorAccounts` Remote 和一个浏览器一半。 + +| 部分 | 约定 | +|---|---| +| 注册 | `register({ key, packageName?, source, operations, copy, present })` 返回撤下账号的销毁函数 | +| 键 | 在已注册账号中唯一,且与包无关,因此没有插件包承载的账号(如在 Settings 中配置的服务器)也能注册 | +| 包 | 决定由哪个插件包页面承载区块和标签;一个包最多承载一个账号 | +| 来源 | 注册方的账号:`snapshot`、`observe`、`refresh`、`start` 和 `cancel` | +| 展示 | Host 上的 `present(view)` 给出阶段、状态文字、标题旁标签、按钮及其命令、确认、失败信息,以及开启引导启动的操作 | +| Remote | `watch`,以及按键路由到账号来源的 `start(key, operation)` 和 `cancel(key, id)` | + +除了打开授权页,其余都由 Host 决定。浏览器不知道账号如何连接:它只收到展示内容、进行中的操作及其授权页,以及带成功文本的最新结果。浏览器一半只保存属于本浏览器的东西:它发起的操作(授权页只在这里打开,成功只在这里报告)、最新提示,以及它的流是否在推送。按钮自己调用 Remote 的 `start` 和 `cancel`,每个界面自己保存未完成状态。 + +页面只注册一个标题旁标签条目和一个提示条目;对每个带包名的账号,再注册一个区块和一个开启引导,因为这两个插槽以包为键。 + +## 考虑过的替代方案 + +**一个浏览器一半背后有两个注册表。** 否决:浏览器要同时跟随两个 Remote,并为每个按钮选择调用哪一个,这又是在 Host 服务之间转发;两个 Host 注册表的代码也会相同。 + +**每类连接器各有一个浏览器一半。** 否决:客户端插件不能导入彼此的值,共用界面就要写两遍,并逐渐不一致。 + +**通过 `PLATFORM_MODULES` 或浏览器端服务共享浏览器一半。** 否决:模块表只留给由 shell 预置的基础设施和静态库;浏览器端服务会把注册留在浏览器中,而这些注册只是重复 Host 已知的信息。 + +**由浏览器根据注册方的原始状态推算账号阶段和操作。** 否决:哪些操作可用的规则会放在 Host 无法测试和执行的地方,浏览器还需要注册方自己的 Remote。 + +## 后果 + +注册表和浏览器一半只有一份。新的连接器类型只需在 Host 上编写来源和 `present`,不需要浏览器代码。账号规则与拥有它们的服务在一起,Host 不依赖浏览器就能执行每个操作。 + +注册方需要把账号状态映射到五个阶段(检查中、连接中、已连接、未连接、不可用);超出这些阶段的状态通过状态文字和说明表达。无论是否安装了连接器插件,Web 与桌面端组合都会加载注册表。启动调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。 diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 77f025f1e9..38090bd827 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: b76743a3ff14d2f4 - zh: 82431aa3ded14a89 + en: b3be76b595765ee3 + zh: 85de5f625a7a15a6 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 145a4f5317..b4fcad0d21 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -28,6 +28,8 @@ flowchart LR pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"] + pkg_client_ui_connector_account["client-ui-connector-account"] + svc_connectorAccounts["ctx.connectorAccounts
Connector accounts on the Plugins page"] pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] @@ -344,6 +346,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics + pkg_client_ui_connector_account --> svc_connectorAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands @@ -659,6 +662,7 @@ flowchart LR | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | Owns module and exact configuration watchers; application mutations share its queue and automatic reloads await the application file lock. | | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | Races public registry responses on the Host; the Client owns the initial registry recommendation. | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. | +| `ctx.connectorAccounts` | `service` | [`client-ui-connector-account`](../packages/client/ui-connector-account) | - | - | - | Holds the accounts CLI app plugins and MCP connectors register and serves their Host-computed displays to the Plugins page through one Remote; authorization pages and notices stay in the browser that started the operation. | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | Fetches and validates the index sources the user configures; installation goes through the plugin manager. | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr. | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 5effa1f8c4..57543c3bd5 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -30,6 +30,8 @@ flowchart LR pkg_plugin_manager["plugin-manager"] svc_pluginManager["ctx.pluginManager
Current-profile plugin and bundle management"] pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"] + pkg_client_ui_connector_account["client-ui-connector-account"] + svc_connectorAccounts["ctx.connectorAccounts
Connector accounts on the Plugins page"] pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] @@ -346,6 +348,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics + pkg_client_ui_connector_account --> svc_connectorAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands @@ -661,6 +664,7 @@ flowchart LR | `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | 负责模块和精确配置监听;应用修改共用其队列,自动重载等待应用文件锁。 | | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | 在 Host 上并发比较公共安装源响应;初始安装源推荐由 Client 负责。 | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 | +| `ctx.connectorAccounts` | `service` | [`client-ui-connector-account`](../packages/client/ui-connector-account) | - | - | - | 保存 CLI 应用插件和 MCP 连接器注册的账号,并通过一个 Remote 把 Host 算好的展示内容提供给插件页;授权页和提示只出现在发起操作的浏览器中。 | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | 获取并校验用户配置的索引源;安装通过插件管理器完成。 | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | dsh launcher 提供纯数据形式的 profile 位置与组合输入;重载调度由 dsh-hmr 负责。 | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 负责浏览器认证与共享 HTTP 请求分发;API 适配器注册端点和流。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 6c75efde1d..3a24364ee1 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -5022,6 +5022,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index c7a7ba3c7a..9535e76458 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -5024,6 +5024,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-connector-account` | — | [`packages/client/ui-connector-account/src/index.ts`](../packages/client/ui-connector-account/src/index.ts) | | `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 2e73bd13bc..e63ca7d1c6 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -166,6 +166,7 @@ flowchart TD pkg_client_ui_brand_official["client-ui-brand-official"] pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_connector_account["client-ui-connector-account"] pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -1586,6 +1587,7 @@ flowchart TD | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — | | [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 1b697fe591..fb305c3557 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -168,6 +168,7 @@ flowchart TD pkg_client_ui_brand_official["client-ui-brand-official"] pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_connector_account["client-ui-connector-account"] pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -1588,6 +1589,7 @@ flowchart TD | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-connector-account`](../packages/client/ui-connector-account) | `client` | — | | [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 6780e92c43..c8f36d14e2 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -143,6 +143,50 @@ async edit( entry: Entry, change: (current: Record, inherited: Source: [`packages/boot/config-editor/src/index.ts`](../../packages/boot/config-editor/src/index.ts) + + +### `ctx.connectorAccounts` — `ConnectorAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ +register(registration: ConnectorAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ +@Remote start(key: string, operation: string): ConnectorOperationId + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ +@Remote cancel(key: string, id: ConnectorOperationId): Promise +``` + +Source: [`packages/client/ui-connector-account/src/index.ts`](../../packages/client/ui-connector-account/src/index.ts) + ### `ctx.headlessStartup` — `HeadlessStartupValues` diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index 915b6e8112..ab6383e0b3 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -143,6 +143,50 @@ async edit( entry: Entry, change: (current: Record, inherited: Source: [`packages/boot/config-editor/src/index.ts`](../../packages/boot/config-editor/src/index.ts) + + +### `ctx.connectorAccounts` — `ConnectorAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ +register(registration: ConnectorAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ +@Remote start(key: string, operation: string): ConnectorOperationId + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ +@Remote cancel(key: string, id: ConnectorOperationId): Promise +``` + +Source: [`packages/client/ui-connector-account/src/index.ts`](../../packages/client/ui-connector-account/src/index.ts) + ### `ctx.headlessStartup` — `HeadlessStartupValues` diff --git a/packages/api/remotes/README.i18n.yaml b/packages/api/remotes/README.i18n.yaml index 4178adfa26..b05bc795e0 100644 --- a/packages/api/remotes/README.i18n.yaml +++ b/packages/api/remotes/README.i18n.yaml @@ -15,8 +15,8 @@ en: a7a78c6d1aeebeb3 zh: 4bb69f32d8b05ba3 /deepseek-ai-dsh-api-remotes/use-this-package: - en: 5e5770cc1cbf49db - zh: b9ee3c309d0cd93c + en: d8622091b217f050 + zh: c36cb87f10e7802a /deepseek-ai-dsh-api-remotes/forwarded-host-events: en: 1dea001229f8c06a zh: 3acb1fa1c5d24f8c diff --git a/packages/api/remotes/README.md b/packages/api/remotes/README.md index 71e5dc385f..a01a776f3e 100644 --- a/packages/api/remotes/README.md +++ b/packages/api/remotes/README.md @@ -29,7 +29,7 @@ Two-sided BFF for Host Remote capabilities selected by this application. The Hos [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.md) owns Agent and Session identity policy, including the Typert lookup resolvers used by other namespaces. This package selects and mounts that generated Session contribution without a direct runtime dependency on `@deepseek-ai/dsh-session`; activation policy stays with Session Controller. -The Client assembly mounts Office conversion, Commands, Agent Teams, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, message feedback, permission presets, Session Controller, subagents, web provider list, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. +The Client assembly mounts Office conversion, Commands, Agent Teams, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, connector accounts, message feedback, permission presets, Session Controller, subagents, web provider list, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. This facade is also the front door for the wire type vocabulary a Client package names. It re-exports, type-only, the Remote failure vocabulary (`RemoteResult`, `RemoteFailure`, `RemoteErrorCode`, `RemoteErrorDetailsMap`), the Host facts (`RemoteHostFacts`), and each selected domain's client-safe payload types, so a Client feature package imports one specifier instead of reaching into `dsh-typert-protocol`, the Gateway, or an owner's Host entry. Two kinds of package deliberately skip this door: the API-layer packages this assembly itself selects — importing it back would close a dependency cycle — and their tests, which take the failure vocabulary from `dsh-typert-protocol` directly. A UI package's tests instead take the `RemoteError` constructor from [`dsh-client-test-runtime`](../../test-support/client-runtime/README.md). diff --git a/packages/api/remotes/README.zh.md b/packages/api/remotes/README.zh.md index 5bef7cb29c..cc3c407f49 100644 --- a/packages/api/remotes/README.zh.md +++ b/packages/api/remotes/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.zh.md) 拥有 agent(智能体)与会话身份策略,包括供其他 namespace 使用的 Typert lookup 解析器。本包选择并挂载生成的会话 contribution,无需直接依赖 `@deepseek-ai/dsh-session` 的运行时;激活策略由会话控制器负责。 -Client 组合挂载 Office 转换、Commands、Agent Teams、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、消息反馈、权限预设、会话控制器、subagents、Web 提供方列表和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 +Client 组合挂载 Office 转换、Commands、Agent Teams、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、连接器账号、消息反馈、权限预设、会话控制器、subagents、Web 提供方列表和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 本 facade 同时是 Client 包指称 wire 类型词汇的正门。它以 type-only 方式转出 Remote 失败词汇(`RemoteResult`、`RemoteFailure`、`RemoteErrorCode`、`RemoteErrorDetailsMap`)、Host 事实(`RemoteHostFacts`),以及各已选领域对 Client 安全的载荷类型,因此 Client 功能包只 import 一个 specifier,不必伸手进 `dsh-typert-protocol`、Gateway 或某个拥有方的 Host 入口。有两类包刻意不走这道门:本装配自己选中的 API 层包——反向 import 会形成依赖环——以及它们的测试,后者直接从 `dsh-typert-protocol` 取失败词汇。UI 包的测试则从 [`dsh-client-test-runtime`](../../test-support/client-runtime/README.zh.md) 取 `RemoteError` 构造器。 diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index 25718e223b..ffc73c917b 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -98,6 +98,7 @@ "@deepseek-ai/dsh-plugin-manager": "workspace:*", "@deepseek-ai/dsh-mcp-manager": "workspace:*", "@deepseek-ai/dsh-plugin-market": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", "@deepseek-ai/dsh-office-kit": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 5d91957c0a..ade29eff4e 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -19,6 +19,7 @@ import pluginManagerRemote from '@deepseek-ai/dsh-plugin-manager/remote' import mcpManagerRemote from '@deepseek-ai/dsh-mcp-manager/remote' import toolResultsRemote from '@deepseek-ai/dsh-client-ui-trajectory/remote' import pluginRegistryProbeRemote from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' +import connectorAccountsRemote from '@deepseek-ai/dsh-client-ui-connector-account/remote' import pluginMarketRemote from '@deepseek-ai/dsh-plugin-market/remote' import pluginInventoryRemote from '@deepseek-ai/dsh-host-plugin-inventory/remote' import messageFeedbackRemote from '@deepseek-ai/dsh-message-feedback/remote' @@ -48,6 +49,7 @@ export type { McpManagedServerStatus, McpManagedServerView } from '@deepseek-ai/ export type {} from '@deepseek-ai/dsh-plugin-manager/remote' export type {} from '@deepseek-ai/dsh-mcp-manager/remote' export type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/remote' +export type {} from '@deepseek-ai/dsh-client-ui-connector-account/remote' export type {} from '@deepseek-ai/dsh-client-ui-trajectory/remote' export type {} from '@deepseek-ai/dsh-plugin-market/remote' export type { @@ -200,6 +202,7 @@ export async function apply(ctx: Context): Promise<() => Promise> { productAnalyticsRemote, agentPresetsRemote, commandsRemote, agentTeamsRemote, settingsControllerRemote, accountRemote, goalsRemote, llmRemote, dynamicRemote, scheduleRemote, pluginInventoryRemote, pluginManagerRemote, mcpManagerRemote, pluginMarketRemote, pluginRegistryProbeRemote, + connectorAccountsRemote, toolResultsRemote, messageFeedbackRemote, sessionFeedbackRemote, fileUploadsRemote, sessionReferencesRemote, diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index e842d8e3e1..fc7b384795 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -341,6 +341,11 @@ - id: ui-plugin-manager name: '@deepseek-ai/dsh-client-ui-plugin-manager' + # Connector account sections on the Plugins page; CLI app plugins and MCP + # connectors register their accounts with `ctx.connectorAccounts`. + - id: ui-connector-account + name: '@deepseek-ai/dsh-client-ui-connector-account' + # Read-only Plugin list tab in the Settings Plugins section; the built-in # bundles the sidebar page leaves out are inspected here. - id: ui-settings-plugin-inventory diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index 2858130d13..82ce2dd4a3 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -86,6 +86,7 @@ "@deepseek-ai/dsh-client-ui-brand-official": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", "@deepseek-ai/dsh-client-ui-commands": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-cordis": "workspace:*", diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index f77d3835d7..54854f5f19 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: 2165938f26300774 - zh: 5f739534a8509545 + en: affd6d8506276e34 + zh: 92730ec91d83d609 /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index 3047a181c1..6edf512eb4 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -83,6 +83,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-settings-subagent/`](ui-settings-subagent/README.md) | Provides the Subagent settings page on the Plugins page | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.md) | Provides the web search and fetch settings page on the Plugins page | — | | [`ui-plugin-manager/`](ui-plugin-manager/README.md) | Contributes the sidebar Plugins panel: install, enable, disable, retry, and compose installed packages | — | +| [`ui-connector-account/`](ui-connector-account/README.md) | Holds the accounts connector plugins register on the Host and shows each bundle's account section, tag, activation prompt, confirmations, and notices on the Plugins page | `ctx.connectorAccounts` | | [`ui-entry-customization/`](ui-entry-customization/README.md) | Adds region-local More menus that pin or unpin plugin launchers and start a plugin draft | — | | [`ui-plugin-market/`](ui-plugin-market/README.md) | Contributes the Discover tab to the Plugins page: browse market indexes and install their bundles | — | | [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.md) | Contributes the read-only Host Loader inventory tab to Plugins settings | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index e327a717d9..635750069e 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -83,6 +83,7 @@ kind: "package-group" | [`ui-settings-subagent/`](ui-settings-subagent/README.zh.md) | 在插件页提供子智能体设置页 | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.zh.md) | 在插件页提供网页搜索与获取设置页 | — | | [`ui-plugin-manager/`](ui-plugin-manager/README.zh.md) | 贡献侧栏的“插件”面板:安装、启用、停用、重试与组合已安装的包 | — | +| [`ui-connector-account/`](ui-connector-account/README.zh.md) | 保存连接器插件在 Host 上注册的账号,并在插件页显示每个插件包的账号区块、标签、开启引导、确认和提示 | `ctx.connectorAccounts` | | [`ui-entry-customization/`](ui-entry-customization/README.zh.md) | 添加分区域的“更多”菜单,固定或收起插件入口,并开始创建插件的草稿 | — | | [`ui-plugin-market/`](ui-plugin-market/README.zh.md) | 为“插件”页面贡献“发现”标签页:浏览市场索引并安装其中的组合包 | — | | [`ui-settings-plugin-inventory/`](ui-settings-plugin-inventory/README.zh.md) | 向「插件」设置贡献只读的 Host Loader 清单标签页 | — | diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml new file mode 100644 index 0000000000..347d021162 --- /dev/null +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -0,0 +1,49 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-connector-account/README.md +/: + en: f09638e4097c52fb + zh: 2fb344b05a189ad0 +/deepseek-ai-dsh-client-ui-connector-account: + en: bdb528546ec26353 + zh: 0dd55dbc0c8e837a +/deepseek-ai-dsh-client-ui-connector-account/summary: + en: b25fc16fb18a63c1 + zh: 4508e8a44745b08d +/deepseek-ai-dsh-client-ui-connector-account/table-of-contents: + en: d152484eb41ac6b4 + zh: 5b6bd00fce5371c3 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package: + en: 9d8d49a0b1b3ce24 + zh: 8eba3710036afa00 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/register-an-account: + en: e618281ea7721daf + zh: a5d5f5e307ea3435 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/present-the-section: + en: 73ca134d685b5872 + zh: 05b929fd28dc955e +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: + en: a9e64f316efcac3e + zh: d059d31b65573bf5 +/deepseek-ai-dsh-client-ui-connector-account/use-this-package/shared-copy: + en: f88db8d50a68a0ca + zh: 6169fd1ffc9c79a0 +/deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: + en: da424b56f995bef5 + zh: 298fc8e50149fea5 +/deepseek-ai-dsh-client-ui-connector-account/further-exploration: + en: 029949903a73d283 + zh: 6f9a8c2f7620de69 +/deepseek-ai-dsh-client-ui-connector-account/model-experience: + en: bdbc56a07884f8d6 + zh: 22ca2ee613472c0b +/deepseek-ai-dsh-client-ui-connector-account/model-experience/kv-cache-effect: + en: 4cd0965a7997970e + zh: 690e5a9d945f7f6e +/deepseek-ai-dsh-client-ui-connector-account/known-limitations-and-deferred-work: + en: d2c5f54b80b86b15 + zh: 8b637f97ac1d0223 +/deepseek-ai-dsh-client-ui-connector-account/known-limitations-and-deferred-work/dev-note: + en: 2ab3c4acae06850c + zh: bd2093ba1fdd6860 diff --git a/packages/client/ui-connector-account/README.md b/packages/client/ui-connector-account/README.md new file mode 100644 index 0000000000..1013fb4f48 --- /dev/null +++ b/packages/client/ui-connector-account/README.md @@ -0,0 +1,138 @@ +--- +description: "Register a connector plugin's account on the Host with `ctx.connectorAccounts` and show its section, title tag, activation prompt, confirmations, and notices on the Plugins page through one `connectorAccounts` Remote, with the registrant's own text and the shared copy of this package." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-connector-account + +English | [中文](README.zh.md) + +## Summary + +Connector plugins register their account on the Host with `ctx.connectorAccounts` to show it on the Plugins page: CLI app plugins register the account their vendor CLI keeps, and MCP connectors their OAuth server's account. The Host decides what the page shows and does: each registrant maps its account to a display, and the registry starts or cancels only the operations the account lists. The browser half renders each bundle's section, title tag, and activation prompt, and opens authorization pages and reports notices only in the browser that started the operation. The Web and Desktop compositions load both halves through [`dsh-web-app`](../../bundle/web-app/README.md). + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +A registrant's Host row registers its account once; the registrant ships no browser code for the account. + +### Register an account + +The registrant's Host row registers its account source while the registry runs, so a composition without the registry, such as a headless profile, skips the registration: + +```ts ignore-check +import type {} from '@deepseek-ai/dsh-client-ui-connector-account' + +export function apply(ctx: Context): void { + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['connectorAccounts'], (scope) => { + scope.effect(() => scope.connectorAccounts.register({ + key: '@acme/cli', packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) +} +``` + +- `key` identifies the account in the Remote; the page passes it back to start and cancel operations. A second registration with the same key throws. +- `packageName` is the npm package whose bundle page carries the section and tag; a package carries at most one account. An account without one, such as a server configured in Settings, appears on no bundle page. +- `source` is the account: its current view, change observation, a check, and starting and cancelling operations. +- `operations` lists the kinds a page button may start, each with the optional text its success reports in the browser that started it; the registry rejects any other kind. +- `copy` holds the section title, the hint under it, and the activation prompt's title, body, and Connect label. + +The registrant imports the registry's types with `import type` from the package root or `./types`. The returned disposer withdraws the account from every page. + +### Present the section + +`present(view)` maps the account view to a `ConnectorAccountDisplay`: the phase, the status line, the optional title tag, buttons, the operation Connect starts in the activation prompt, detail, notes, and failure with its untranslated diagnostic items. The registry calls it for every stream on each change, so it only maps the view. Every string is `LocalizedText`, which each browser resolves in its active language. A button carries a command: `start` with one of the registered operation kinds, `cancel` for the operation in progress, which the source ignores in a phase that is not cancellable, or `open` to reopen its authorization page. A button with `confirm` asks first and runs only after the user accepts. + +| Surface | Behavior | +|---|---| +| 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 | +| 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. + +### 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. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +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. + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | The `ctx.connectorAccounts` registry and its Remote | +| [`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/locales.ts`](src/client/locales.ts) | The shared dictionary | +| [`src/client/types.ts`](src/client/types.ts) | Browser state, notice, Remote, and face types | + +
+ +----- + + +## Further Exploration + +- [Plugin manager page](../ui-plugin-manager/README.md) — the Plugins page and its bundle slots. +- [Client package map](../README.md) — adjacent browser UI packages. + +----- + + +## Model Experience + +None, as the registry and its surfaces are Plugins page UI and add no model input. Each registrant documents the tools and skills its account enables. + +#### KV Cache effect + +None; registering or removing an account changes no model-visible text. + +## Known Limitations and Deferred Work + + + +- The five display phases are fixed; a registrant maps any further account state onto one of them. +- A registrant whose Host row fails to load shows no account section; the Plugins page still lists the bundle with its load failure. +- Each browser that loads the Web app starts a check of every idle account. +- The Web and Desktop compositions load the registry whether or not a connector plugin is installed. +- An authorization page that opens after the call answers can be blocked by the browser; the section's open button shows it again. + + +### Dev Note + +
+Working context for maintainers — click to expand + +Host specs drive the registry with fake account sources. Client specs drive `BrowserAccounts` with a fake Remote stream, render the surfaces with the Chinese dictionary and a fake Remote, and mount the browser half against a real slot registry and locale runtime. + +
diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md new file mode 100644 index 0000000000..a32ed876b2 --- /dev/null +++ b/packages/client/ui-connector-account/README.zh.md @@ -0,0 +1,138 @@ +--- +description: "通过 `ctx.connectorAccounts` 在 Host 上注册连接器插件的账号,并经由一个 `connectorAccounts` Remote 在插件页显示其区块、标题旁标签、开启引导、确认和提示,文案来自注册方自己的文本和本包的共用文案。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-connector-account + +[English](README.md) | 中文 + +## 概述 + +连接器插件在 Host 上通过 `ctx.connectorAccounts` 注册账号,在插件页显示账号:CLI 应用插件注册其厂商 CLI 保存的账号,MCP 连接器注册其 OAuth 服务器的账号。页面显示什么、能做什么由 Host 决定:每个注册方把自己的账号映射为展示内容,注册表只启动或取消该账号列出的操作。浏览器一半渲染每个插件包的区块、标题旁标签和开启引导,并且只在发起操作的浏览器中打开授权页、报告提示。Web 与桌面端组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 加载这两半。 + +## 目录 + +- [使用此包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [延伸阅读](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与后续工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用此包 + +注册方的 Host 行注册一次账号;注册方不为账号提供任何浏览器代码。 + +### 注册账号 + +注册方的 Host 行在注册表运行时注册其账号来源,因此没有注册表的组合(如 headless profile)会跳过注册: + +```ts ignore-check +import type {} from '@deepseek-ai/dsh-client-ui-connector-account' + +export function apply(ctx: Context): void { + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['connectorAccounts'], (scope) => { + scope.effect(() => scope.connectorAccounts.register({ + key: '@acme/cli', packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) +} +``` + +- `key` 在 Remote 中标识该账号;页面启动和取消操作时把它传回。用同一个键再次注册会抛出异常。 +- `packageName` 是其插件包页面承载区块和标签的 npm 包;一个包最多承载一个账号。没有包名的账号(如在 Settings 中配置的服务器)不出现在任何插件包页面上。 +- `source` 是账号:其当前视图、变化观察、检查,以及启动和取消操作。 +- `operations` 列出页面按钮可以启动的操作类型,每项可带该操作成功时在发起它的浏览器中报告的文本;注册表拒绝其他类型。 +- `copy` 包含区块标题、区块下方的提示,以及开启引导的标题、正文和连接按钮文案。 + +注册方用 `import type` 从包根或 `./types` 导入注册表的类型。返回的销毁函数会把账号从所有页面撤下。 + +### 展示区块 + +`present(view)` 把账号视图映射为 `ConnectorAccountDisplay`:阶段、状态行、可选的标题旁标签、按钮、开启引导中“连接”启动的操作、说明、附加行,以及带不翻译诊断项的失败信息。注册表在每次变化时为每条流调用它,因此它只做视图映射。所有文案都是 `LocalizedText`,由各浏览器按当前语言解析。按钮携带一个命令:`start` 启动某个已注册的操作类型,`cancel` 取消进行中的操作(处于不可取消的阶段时来源会忽略),`open` 重新打开其授权页。带 `confirm` 的按钮会先询问,用户确认后才执行。 + +| 界面 | 行为 | +|---|---| +| 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮不可用。失败时先显示注册方的文案,再显示其诊断项 | +| 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。阶段确定为其他值后自动关闭 | +| 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | + +### 跟随操作 + +每个浏览器在 Web 应用加载时打开一条流,Host 为每条新流检查每个没有在运行操作的账号;流打开期间注册的账号会立即检查。浏览器跟随其最近一次启动返回的操作,从返回时起,直到流推送该操作的结果。被跟随的操作提供的每个页面只在新标签页中打开一次,只打开 HTTPS 页面或回环地址上的 HTTP 页面;其他浏览器显示同样的区块,但不打开页面,也不报告提示。第一次调用返回前的第二次点击不会启动任何操作。流永久失败时,区块显示账号服务未运行,并提供“重试”;无论按多少次,都只重新打开流一次。卸载浏览器一半会关闭流;Host 持有的操作继续运行。 + +### 共用文案 + +`connectorAccount` 字典包含所有账号共用的文案:关闭、取消、重试、稍后、排障信息标签、失败提示,以及未运行时的状态、标签和说明。其余文案都来自注册方。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +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 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | `ctx.connectorAccounts` 注册表及其 Remote | +| [`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/locales.ts`](src/client/locales.ts) | 共用字典 | +| [`src/client/types.ts`](src/client/types.ts) | 浏览器状态、提示、Remote 和 face 类型 | + +
+ +----- + + +## 延伸阅读 + +- [插件管理页](../ui-plugin-manager/README.zh.md)——插件页及其插件包插槽。 +- [客户端包地图](../README.zh.md)——相邻的浏览器 UI 包。 + +----- + + +## 模型体验 + +无,注册表及其界面属于插件页 UI,不增加模型输入。各注册方自行说明其账号启用的工具和技能。 + +#### KV Cache 影响 + +无;注册或移除账号不改变任何模型可见文本。 + +## 已知限制与后续工作 + + + +- 五个显示阶段固定不变;注册方需把其他账号状态映射到其中之一。 +- Host 行加载失败的注册方不显示账号区块;插件页仍会列出该插件包及其加载失败。 +- 每个加载 Web 应用的浏览器都会触发一次对所有空闲账号的检查。 +- 无论是否安装了连接器插件,Web 与桌面端组合都会加载注册表。 +- 调用返回后才打开的授权页可能被浏览器拦截;区块中的打开按钮可以再次打开它。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +Host 测试用假的账号来源驱动注册表。客户端测试用假的 Remote 流驱动 `BrowserAccounts`,用中文字典和假的 Remote 渲染各界面,并在真实的插槽注册表和 locale 运行时上挂载浏览器一半。 + +
diff --git a/packages/client/ui-connector-account/locale/de.json b/packages/client/ui-connector-account/locale/de.json new file mode 100644 index 0000000000..98f0f64dea --- /dev/null +++ b/packages/client/ui-connector-account/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connector-Kontoverbindung", + "description": "Kontobereich, Titel-Tag, Aktivierungshinweis und Benachrichtigungen auf der Seite „Plugins“ für Connector-Plugins." + } +} diff --git a/packages/client/ui-connector-account/locale/en.json b/packages/client/ui-connector-account/locale/en.json new file mode 100644 index 0000000000..f0d6ca2f20 --- /dev/null +++ b/packages/client/ui-connector-account/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connector account connection", + "description": "Account section, title tag, activation prompt, and notices on the Plugins page for connector plugins." + } +} diff --git a/packages/client/ui-connector-account/locale/es.json b/packages/client/ui-connector-account/locale/es.json new file mode 100644 index 0000000000..90e3835555 --- /dev/null +++ b/packages/client/ui-connector-account/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Conexión de cuenta de conectores", + "description": "Sección de cuenta, etiqueta del título, aviso de activación y notificaciones en la página Complementos para los complementos de conectores." + } +} diff --git a/packages/client/ui-connector-account/locale/fr.json b/packages/client/ui-connector-account/locale/fr.json new file mode 100644 index 0000000000..6aa61577ee --- /dev/null +++ b/packages/client/ui-connector-account/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Connexion de compte de connecteur", + "description": "Section de compte, étiquette de titre, invite d’activation et notifications sur la page Plugins pour les plugins de connecteur." + } +} diff --git a/packages/client/ui-connector-account/locale/ja.json b/packages/client/ui-connector-account/locale/ja.json new file mode 100644 index 0000000000..d8a18a8135 --- /dev/null +++ b/packages/client/ui-connector-account/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "コネクターアカウント接続", + "description": "コネクタープラグイン向けに、「プラグイン」ページでのアカウントセクション、タイトルタグ、有効化時の案内、通知を提供します。" + } +} diff --git a/packages/client/ui-connector-account/locale/pt.json b/packages/client/ui-connector-account/locale/pt.json new file mode 100644 index 0000000000..abec0eafe9 --- /dev/null +++ b/packages/client/ui-connector-account/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Conexão de conta de conector", + "description": "Seção da conta, etiqueta do título, aviso de ativação e notificações na página Plug-ins para plugins de conector." + } +} diff --git a/packages/client/ui-connector-account/locale/ru.json b/packages/client/ui-connector-account/locale/ru.json new file mode 100644 index 0000000000..be0914f34b --- /dev/null +++ b/packages/client/ui-connector-account/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Подключение аккаунта коннектора", + "description": "Раздел аккаунта, метка у заголовка, подсказка при включении и уведомления на странице «Плагины» для плагинов-коннекторов." + } +} diff --git a/packages/client/ui-connector-account/locale/zh.json b/packages/client/ui-connector-account/locale/zh.json new file mode 100644 index 0000000000..af4aade6f6 --- /dev/null +++ b/packages/client/ui-connector-account/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "连接器账号连接", + "description": "在插件页为连接器插件提供账号区块、标题标签、开启引导与提示。" + } +} diff --git a/packages/client/ui-connector-account/package.json b/packages/client/ui-connector-account/package.json new file mode 100644 index 0000000000..a571731e29 --- /dev/null +++ b/packages/client/ui-connector-account/package.json @@ -0,0 +1,96 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-connector-account", + "description": "Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-connector-account" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./types": { + "types": "./lib/types/types.d.ts" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + }, + "./locale/*.json": "./locale/*.json" + }, + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-layout", + "@deepseek-ai/dsh-client-ui-plugin-manager" + ], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "zod": "4.6.6" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-layout": "workspace:*", + "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-package-manifest": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", + "@testing-library/react": "^16.3.3", + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts", + "lib/typert.remote-client.d.ts.map", + "src" + ] +} diff --git a/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css new file mode 100644 index 0000000000..c15f495d50 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css @@ -0,0 +1,51 @@ +.section { + display: flex; + flex-direction: column; + gap: 8px; +} + +.title { + margin: 0 0 4px; + font-size: 14px; + line-height: 20px; + font-weight: 500; +} + +.status { + display: flex; + align-items: center; + gap: 8px; + min-height: 28px; +} + +.label { + font-size: 13px; + line-height: 20px; + color: var(--dsw-alias-label-primary); +} + +.actions { + display: flex; + gap: 8px; + margin-left: auto; +} + +.detail, +.hint, +.failure { + margin: 0; + font-size: 13px; + line-height: 20px; +} + +.detail { + color: var(--dsw-alias-label-secondary); +} + +.hint { + color: var(--dsw-alias-label-tertiary); +} + +.failure { + color: var(--dsw-alias-state-error-primary); +} diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx new file mode 100644 index 0000000000..93bc807582 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -0,0 +1,337 @@ +/** + * 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. + */ +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 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' + +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 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 +} + +async function settle(call: Promise>): Promise { + const result = await call + if (!result.ok) throw new Error(result.error.message) + return result.value +} + +/** + * 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. + * @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. + */ +function useAccountCommand( + face: Pick, +): { readonly busy: boolean; readonly run: (entry: ConnectorAccountEntry, command: ConnectorAccountCommand) => void } { + const [busy, setBusy] = useState(false) + // A second click before the re-render still finds the first call pending. + const pending = useRef(false) + const call = (operation: () => Promise): void => { + if (pending.current) return + pending.current = true + setBusy(true) + // The Host keeps the diagnostic; the page reports one retryable outcome. + void operation().catch(() => { face.failed() }).finally(() => { pending.current = false; setBusy(false) }) + } + const run = (entry: ConnectorAccountEntry, command: ConnectorAccountCommand): void => { + const { key } = entry + switch (command.kind) { + case 'start': + call(async () => { face.follow(key, await settle(face.remote.start(key, command.operation))) }) + return + case 'cancel': { + const operation = entry.operation + if (operation !== undefined) call(async () => { await settle(face.remote.cancel(key, operation.id)) }) + return + } + case 'open': + openAuthorizationPage(entry.operation?.authorizationUrl) + return + /* v8 ignore next -- closed command union */ + default: assertNever(command) + } + } + 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 dismisses itself once the phase settles elsewhere. + */ +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]) + return ( + + + + }> +

{body}

+
+ ) +} + +/** A confirmation's text and callbacks, with the translator for the shared buttons. */ +export interface ConnectorAccountConfirmProps { + 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 { + return ( + + + + }> +

{body}

+
+ ) +} + +/** 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. + * @param props - the bundle's face and the translator. + * @returns the section for the account, or null before the Host lists it. + */ +export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode { + const { useConnectorAccounts, account, resolveText, retry, 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) + if (entry === undefined) return null + return { run(entry, command) }} onRetry={retry} /> +} + +function accountOf(state: ConnectorAccountsState, packageName: string): ConnectorAccountEntry | undefined { + for (const entry of state.accounts.values()) if (entry.packageName === packageName) return entry + return undefined +} + +/** + * 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. + */ +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 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 +} + +/** + * The `plugins.bundle.activation` entry of a bundle that owns an account; 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. + */ +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) + if (entry === undefined) return null + const { activation } = entry.copy + const { connect } = entry.display + const onConnect = (): void => { + onOpenDetails() + if (connect !== undefined) run(entry, connect) + } + return ( + + ) +} + +/** + * The `shell.overlay` entry. + * @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 +} diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts new file mode 100644 index 0000000000..c76264c8f5 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -0,0 +1,90 @@ +/** + * Connector account surfaces, browser half: follows the accounts CLI app plugins and MCP connectors register on the Host, + * and shows each bundle's section, title tag, and activation prompt on its Plugins page, with the notices of the + * operations this browser started. The surfaces read the shared copy from this package's dictionary and each + * registrant's text from the Host. + */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from './components.tsx' +import { de, en, es, fr, ja, NS, pt, ru, zh } from './locales.ts' +import { BrowserAccounts } from './state.ts' +import type { ConnectorAccountFace } from './types.ts' + +export type { ConnectorAccountKey } from './locales.ts' +export type { + ConnectorAccountFace, ConnectorAccountNotice, ConnectorAccountsState, ConnectorBundleAccountFace, +} from './types.ts' + +/** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ +export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] + +function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { + const bundle = { ...face, account } + const dispose = ctx.effect(function* () { + yield ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ + name: 'plugins.bundle.config', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountSectionEntry)) + yield ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ + name: 'plugins.bundle.activation', key: packageName, locale: NS, inject: () => bundle, + }, ConnectorAccountActivationEntry)) + }, `connector-account: ${packageName}`) + return () => void dispose() +} + +/** + * Show the registered connector accounts for one plugin lifetime: one tag and one notice entry for the page, and a + * section and activation prompt for each bundle that owns an account. + * @param ctx - the browser plugin context. + */ +export function apply(ctx: Context): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'connector-account: dictionaries') + const browser = new BrowserAccounts(ctx, ctx.remote.connectorAccounts) + ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') + const face: ConnectorAccountFace = { + hooks: { connectorAccounts: browser.state }, + remote: ctx.remote.connectorAccounts, + 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* () { + yield ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ + name: 'plugins.detail.badge', id: 'connector-account.badge', locale: NS, inject: () => face, + }, ConnectorAccountBadgeEntry)) + yield ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: 'connector-account.notice', locale: NS, inject: () => face, + }, ConnectorAccountToastEntry)) + }, 'connector-account: page surfaces') + ctx.effect(() => { + const shown = new Map void }>() + const sync = (): void => { + const owned = new Map() + for (const entry of browser.state.getSnapshot().accounts.values()) { + if (entry.packageName !== undefined) owned.set(entry.packageName, entry.key) + } + for (const [packageName, surfaces] of shown) { + if (owned.get(packageName) === surfaces.account) continue + surfaces.withdraw() + shown.delete(packageName) + } + for (const [packageName, account] of owned) { + if (!shown.has(packageName)) shown.set(packageName, { account, withdraw: registerBundle(ctx, face, packageName, account) }) + } + } + sync() + const stop = browser.state.subscribe(sync) + return () => { + stop() + for (const surfaces of shown.values()) surfaces.withdraw() + } + }, 'connector-account: bundle surfaces') +} diff --git a/packages/client/ui-connector-account/src/client/locales.ts b/packages/client/ui-connector-account/src/client/locales.ts new file mode 100644 index 0000000000..57e76d24f1 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/locales.ts @@ -0,0 +1,118 @@ +/** Locale-owned copy the connector account surfaces share; each registrant's own text arrives from the Host. */ +import type {} from '@deepseek-ai/dsh-client-ui-slots' + +/** Dictionary namespace of the shared account copy. */ +export const NS = 'connectorAccount' + +/** Chinese dictionary and key source. */ +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. */ +export type ConnectorAccountKey = keyof typeof zh + +/** English dictionary. */ +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' { + interface LocaleNamespaceMap { + connectorAccount: ConnectorAccountKey + } +} diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts new file mode 100644 index 0000000000..2d4954ddb8 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -0,0 +1,157 @@ +/** + * The page's one subscription to the registered accounts, and what only this browser knows about them: the operations + * it started, whose authorization pages open here, and the notice to show. + */ +import type { Context } from '@deepseek-ai/cordis' +import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' +import type { ConnectorAccountNotice, ConnectorAccountsRemote, ConnectorAccountsState } from './types.ts' + +const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']) + +/** + * Open an authorization page in a new tab when it is HTTPS, or HTTP on a loopback address such as a local + * authorization server. + * @param url - the page an operation waits on; other values open nothing. + */ +export function openAuthorizationPage(url: string | undefined): void { + if (url === undefined || !URL.canParse(url)) return + const parsed = new URL(url) + if (parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOOPBACK_HOSTS.has(parsed.hostname))) { + window.open(url, '_blank', 'noopener,noreferrer') + } +} + +/** One Host subscription per browser, shared by every account surface on the page. */ +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, + }) + + /** + * The operation each account's latest start in this browser returned, with the pages already opened for it. It lasts + * until the stream delivers its result or the account leaves. + */ + private readonly followed = new Map }>() + private seq = 0 + private disposed = false + private stream!: RemoteStream + private 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() + } + + /** + * Follow an operation this browser started, replacing the account's previous one. + * @param key - the account key. + * @param id - the operation the Host started. + */ + follow(key: string, id: ConnectorOperationId): void { + if (this.disposed) return + this.followed.set(key, { id, opened: new Set() }) + // The stream may have delivered the operation before the start call answered. + const entry = this.state.getSnapshot().accounts.get(key) + if (entry !== undefined) this.track(entry) + } + + /** Report that a Remote call this browser made did not finish; the Host keeps the diagnostic. */ + failed(): void { + this.notify({ kind: 'action-failed' }) + } + + /** Clear the notice once it has been shown. */ + dismissNotice(): void { + 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. + * @returns after the stream closes. + */ + async dispose(): Promise { + this.disposed = true + await this.stream.dispose() + 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 { + try { + for await (const item of 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 }) + } + } + + 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 }) + for (const entry of entries) this.track(entry) + } + + /** Open each new page of the account's followed operation once, and report its success once its result arrives. */ + private track(entry: ConnectorAccountEntry): void { + const followed = this.followed.get(entry.key) + if (followed === undefined) return + const url = entry.operation?.id === followed.id ? entry.operation.authorizationUrl : undefined + if (url !== undefined && !followed.opened.has(url)) { + followed.opened.add(url) + openAuthorizationPage(url) + } + const result = entry.result + if (result?.id !== followed.id) return + this.followed.delete(entry.key) + if (result.notice !== undefined) this.notify({ kind: 'succeeded', text: result.notice }) + } + + private notify( + notice: { readonly kind: 'succeeded'; readonly text: LocalizedText } | { readonly kind: 'action-failed' }, + ): void { + if (this.disposed) return + this.seq += 1 + const next: ConnectorAccountNotice = { ...notice, seq: this.seq } + this.patch({ notice: next }) + } + + private patch(change: Partial): void { + this.state.set({ ...this.state.getSnapshot(), ...change }) + } +} diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts new file mode 100644 index 0000000000..8ed18a7c81 --- /dev/null +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -0,0 +1,50 @@ +/** Browser-side state and face of the accounts the Plugins page shows. */ +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' + +/** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ +export type ConnectorAccountNotice = + | { readonly seq: number; readonly kind: 'succeeded'; readonly text: LocalizedText } + | { readonly seq: number; readonly kind: 'action-failed' } + +/** What this browser shows: the Host's accounts, the stream state, and the latest notice. */ +export interface ConnectorAccountsState { + /** Registered accounts by key, as the Host last published them. */ + 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 +} + +/** The `connectorAccounts` Remote methods the page uses. */ +export interface ConnectorAccountsRemote { + watch(signal: AbortSignal): AsyncIterable + start(key: string, operation: string): Promise> + cancel(key: string, id: ConnectorOperationId): Promise> +} + +/** The face every surface entry injects. */ +export interface ConnectorAccountFace { + hooks: { connectorAccounts: HostObservable } + /** The Remote the buttons call directly. */ + readonly remote: Pick + /** Pick the active language's entry of a registrant's text. */ + readonly resolveText: (text: LocalizedText) => string + /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ + 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 +} + +/** The face of a bundle's own surfaces, which show the bundle's account. */ +export interface ConnectorBundleAccountFace extends ConnectorAccountFace { + /** The key of the account the bundle owns. */ + readonly account: string +} diff --git a/packages/client/ui-connector-account/src/css-modules.d.ts b/packages/client/ui-connector-account/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-connector-account/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-connector-account/src/index.ts b/packages/client/ui-connector-account/src/index.ts new file mode 100644 index 0000000000..691e56d90a --- /dev/null +++ b/packages/client/ui-connector-account/src/index.ts @@ -0,0 +1,163 @@ +/** + * Connector account surfaces, Host half. CLI app plugins and MCP connectors register their accounts with + * `ctx.connectorAccounts`; the Plugins page follows every registered account through the `connectorAccounts` Remote and + * starts or cancels operations through it, so the browser never learns how an account connects. + * @module @deepseek-ai/dsh-client-ui-connector-account + */ + +import type { Context } from '@deepseek-ai/cordis' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import type { + AnyConnectorAccountView, ConnectorAccountEntry, ConnectorAccountRegistration, ConnectorAccountsView, ConnectorOperationId, +} from './types.ts' + +export type * from './types.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Connector accounts on the Plugins page. */ + connectorAccounts: ConnectorAccounts + } +} + +interface Registered { + readonly packageName: string | undefined + readonly entry: () => ConnectorAccountEntry + readonly refresh: () => void + readonly start: (operation: string) => ConnectorOperationId + readonly cancel: (id: ConnectorOperationId) => Promise +} + +function registeredOf(registration: ConnectorAccountRegistration): Registered { + const { key, packageName, source, operations, copy, present } = registration + return { + packageName, + entry: () => { + const view = source.snapshot() + const { operation, result } = view + const notice = result?.outcome === 'succeeded' ? operations.find(candidate => candidate.kind === result.kind)?.notice : undefined + return { + key, ...packageName === undefined ? {} : { packageName }, copy, display: present(view), + ...operation === undefined ? {} : { + operation: { + id: operation.id, ...operation.authorizationUrl === undefined ? {} : { authorizationUrl: operation.authorizationUrl }, + }, + }, + ...result === undefined ? {} : { result: { id: result.id, ...notice === undefined ? {} : { notice } } }, + } + }, + refresh: () => { source.refresh() }, + start: (operation) => { + const kind = operations.find(candidate => candidate.kind === operation)?.kind + if (kind === undefined) throw new Error(`connectorAccounts: ${key} has no page operation ${operation}`) + return source.start(kind) + }, + cancel: id => source.cancel(id), + } +} + +/** Holds the registered accounts and serves them to the Plugins page. */ +export default class ConnectorAccounts extends TypertRemoteService { + private readonly accounts = new Map() + private readonly listeners = new Set<() => void>() + private readonly lifetime = new AbortController() + private subscribers = 0 + + /** @param ctx - the Host context the registry serves the page from. */ + constructor(ctx: Context) { + super(ctx, 'connectorAccounts') + ctx.effect(() => () => { this.lifetime.abort(new Error('connectorAccounts: registry disposed')) }) + } + + /** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the account key, its bundle package, the account source, the page operations, and the + * presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the key or the package. + */ + register(registration: ConnectorAccountRegistration): () => void { + const { key, packageName } = registration + if (this.accounts.has(key)) throw new Error(`connectorAccounts: ${key} is already registered`) + if (packageName !== undefined && [...this.accounts.values()].some(account => account.packageName === packageName)) { + throw new Error(`connectorAccounts: ${packageName} already has an account`) + } + this.accounts.set(key, registeredOf(registration)) + const stop = registration.source.observe(() => { this.changed() }) + // A page that already follows the accounts checks a newly registered one, as it checks each account it subscribes to. + if (this.subscribers > 0) registration.source.refresh() + this.changed() + let active = true + return () => { + if (!active) return + active = false + stop() + this.accounts.delete(key) + this.changed() + } + } + + /** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ + @Remote({ mode: 'stream' }) + async *watch(signal: AbortSignal): AsyncIterable { + const combined = AbortSignal.any([signal, this.lifetime.signal]) + let wake = Promise.withResolvers() + let changed = true + const notify = (): void => { changed = true; wake.resolve() } + this.listeners.add(notify) + combined.addEventListener('abort', notify, { once: true }) + this.subscribers += 1 + try { + for (const account of this.accounts.values()) account.refresh() + for (;;) { + if (!changed) await wake.promise + if (combined.aborted) break + wake = Promise.withResolvers() + changed = false + yield { accounts: [...this.accounts.values()].map(account => account.entry()) } + } + } finally { + this.subscribers -= 1 + this.listeners.delete(notify) + combined.removeEventListener('abort', notify) + } + } + + /** + * Start one of the operations the account registered as page actions. + * @param key - the account key. + * @param operation - the operation kind. + * @returns the operation identity. + * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. + */ + @Remote + start(key: string, operation: string): ConnectorOperationId { + return this.account(key).start(operation) + } + + /** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param key - the account key. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown account. + */ + @Remote + cancel(key: string, id: ConnectorOperationId): Promise { + return this.account(key).cancel(id) + } + + private account(key: string): Registered { + const account = this.accounts.get(key) + if (account === undefined) throw new Error(`connectorAccounts: ${key} is not registered`) + return account + } + + private changed(): void { + for (const notify of this.listeners) notify() + } +} diff --git a/packages/client/ui-connector-account/src/types.ts b/packages/client/ui-connector-account/src/types.ts new file mode 100644 index 0000000000..a04cbf4a1d --- /dev/null +++ b/packages/client/ui-connector-account/src/types.ts @@ -0,0 +1,164 @@ +/** + * Credential-free account views of connector plugins, and what the Plugins page receives about them. Each registrant + * supplies its own account, operation, phase, and failure types and maps its views to the page's display, so CLI app + * plugins and MCP connectors share one registry and one page. + */ + +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' + +/** Identifies one Host-owned account operation across the browsers that show the account. */ +export type ConnectorOperationId = Branded<'ConnectorOperationId'> + +/** The account operation in progress; `Phase` names the registrant's own steps. */ +export interface ConnectorOperation { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly phase: Phase + /** Whether the source cancels the operation in its current phase. */ + readonly cancellable: boolean + /** The page the user authorizes in, while the operation waits for one; only the browser that started it opens it. */ + readonly authorizationUrl?: string +} + +/** The most recent finished operation, kept until another one starts. */ +export interface ConnectorOperationResult { + readonly id: ConnectorOperationId + readonly kind: Kind + readonly outcome: 'succeeded' | 'cancelled' | 'failed' + /** The registrant's classified failure, for its own presentation; does not imply rollback or a safe retry. */ + readonly failure?: Failure +} + +/** The complete account view; observers reread it after each change. */ +export interface ConnectorAccountView { + /** The account as the source last published it. */ + readonly account: Account + readonly operation?: ConnectorOperation + readonly result?: ConnectorOperationResult +} + +/** Any registrant's account view. */ +export type AnyConnectorAccountView = ConnectorAccountView + +/** The operation kinds a view reports. */ +export type ConnectorOperationKindOf = NonNullable['kind'] + +/** What the Plugins page shows about an account; each registrant maps its own account states onto these phases. */ +export type ConnectorAccountPhase = 'checking' | 'connecting' | 'connected' | 'disconnected' | 'unavailable' + +/** What a section button does. */ +export type ConnectorAccountCommand = + /** Start one of the operations the account registered as page actions. */ + | { readonly kind: 'start'; readonly operation: string } + /** Cancel the operation in progress when it is cancellable. */ + | { readonly kind: 'cancel' } + /** Open the current operation's authorization page again in this browser. */ + | { readonly kind: 'open' } + +/** The question a button asks before it runs. */ +export interface ConnectorAccountConfirmation { + readonly title: LocalizedText + readonly body: LocalizedText + /** The confirm button's label. */ + readonly label: LocalizedText +} + +/** One button in the section. */ +export interface ConnectorAccountButton { + readonly label: LocalizedText + readonly command: ConnectorAccountCommand + /** Defaults to an outline button. */ + readonly variant?: 'primary' | 'ghost' + /** Ask first, for an action that changes the account outside DSH, such as signing out. */ + readonly confirm?: ConnectorAccountConfirmation +} + +/** One extra row under the status line, such as the linked app, with an optional button. */ +export interface ConnectorAccountNote { + readonly text: LocalizedText + readonly button?: ConnectorAccountButton +} + +/** A failed operation as the section reports it. */ +export interface ConnectorAccountFailure { + /** The registrant's recovery guidance. */ + readonly text: LocalizedText + /** Untranslated diagnostic items shown after the guidance in order. */ + readonly details?: readonly string[] +} + +/** What the section shows for the current view; every text carries each shipped language. */ +export interface ConnectorAccountDisplay { + readonly phase: ConnectorAccountPhase + readonly status: LocalizedText + /** The tag beside the bundle title; absent while nothing is settled. */ + readonly badge?: LocalizedText + readonly buttons: readonly ConnectorAccountButton[] + /** What Connect in the activation prompt starts after opening the bundle page; absent, Connect only opens the page. */ + readonly connect?: Extract + readonly detail?: LocalizedText + readonly notes: readonly ConnectorAccountNote[] + readonly failure?: ConnectorAccountFailure +} + +/** The section's fixed text that names the service or uses its wording. */ +export interface ConnectorAccountCopy { + readonly title: LocalizedText + /** The line under the section, such as where the account is shared or authorized. */ + readonly hint: LocalizedText + /** The prompt after the bundle is switched on while the account is disconnected. */ + readonly activation: { readonly title: LocalizedText; readonly body: LocalizedText; readonly connect: LocalizedText } +} + +/** One registered account as the Plugins page receives it. */ +export interface ConnectorAccountEntry { + /** The registrant's stable account key, which the page passes back to start and cancel operations. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; absent for an account no bundle owns. */ + readonly packageName?: string + readonly copy: ConnectorAccountCopy + readonly display: ConnectorAccountDisplay + /** The operation in progress, which a browser follows when it started it. */ + readonly operation?: { readonly id: ConnectorOperationId; readonly authorizationUrl?: string } + /** The most recent finished operation, with the registrant's text when it succeeded. */ + readonly result?: { readonly id: ConnectorOperationId; readonly notice?: LocalizedText } +} + +/** Every registered account, as each change publishes it. */ +export interface ConnectorAccountsView { + readonly accounts: readonly ConnectorAccountEntry[] +} + +/** The account a registration exposes to the page. */ +export interface ConnectorAccountSource { + snapshot(): View + /** @returns a disposer; the listener runs after each change without starting a check. */ + observe(listener: () => void): () => void + /** Start a check unless an operation runs; a source whose view is always current does nothing. */ + refresh(): void + /** @returns the started operation's identity. */ + start(kind: ConnectorOperationKindOf): ConnectorOperationId + /** @returns after the named operation settles, or at once when it is not cancellable. */ + cancel(id: ConnectorOperationId): Promise +} + +/** One operation a page button may start, with the text its success reports in the browser that started it. */ +export interface ConnectorAccountOperation { + readonly kind: Kind + readonly notice?: LocalizedText +} + +/** One connector account, registered with the Host's `ctx.connectorAccounts`. */ +export interface ConnectorAccountRegistration { + /** Stable key, unique among registered accounts, such as the bundle's package name. */ + readonly key: string + /** npm package whose bundle page carries the section and tag; at most one account per package. */ + readonly packageName?: string + readonly source: ConnectorAccountSource + /** The operations a page button may start; the registry rejects any other. */ + readonly operations: readonly ConnectorAccountOperation>[] + readonly copy: ConnectorAccountCopy + /** Map the current view to what the section shows; called on each change for each subscriber. */ + readonly present: (view: View) => ConnectorAccountDisplay +} diff --git a/packages/client/ui-connector-account/tests/apply.client.spec.ts b/packages/client/ui-connector-account/tests/apply.client.spec.ts new file mode 100644 index 0000000000..20481db45e --- /dev/null +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -0,0 +1,156 @@ +/** + * The browser plugin shows one tag and one notice entry for the page, and a section and activation prompt for each bundle + * that owns an account, withdrawing them with the account or the plugin. + */ +import assert from 'node:assert/strict' +import { Context, Service } from '@deepseek-ai/cordis' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import { + ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, +} from '../src/client/components.tsx' +import { NS } from '../src/client/locales.ts' +import { apply, inject } from '../src/client/index.ts' +import type { ConnectorAccountFace, ConnectorBundleAccountFace } from '../src/client/types.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const FIXTURE = '@acme/fixture' +const OTHER = '@acme/other' +const OP = 'op-1' as ConnectorOperationId + +function isFace(value: Record): asserts value is Record & ConnectorAccountFace { + assert(typeof value.resolveText === 'function' && typeof value.follow === 'function' && typeof value.remote === 'object') + assert(typeof value.hooks === 'object' && value.hooks !== null) +} + +/** Read the face a slot entry injects. */ +function faceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorAccountFace { + assert(item.inject !== undefined) + const face = item.inject() + isFace(face) + return face +} + +function bundleFaceOf(item: { readonly inject?: (() => Record) | undefined }): ConnectorBundleAccountFace { + const face = faceOf(item) + assert('account' in face && typeof face.account === 'string') + return face as ConnectorBundleAccountFace +} + +function entry(key: string, packageName: string | null = key): ConnectorAccountEntry { + return { + key, ...packageName === null ? {} : { packageName }, + copy: { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } }, + display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, + } +} + +async function bench() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, accepted = 0 + const closeStream = vi.fn(async () => { closed = true; wake?.() }) + const start = vi.fn(async (_key: string, _operation: string): Promise> => ({ ok: true, value: OP })) + class Remote extends Service { + constructor() { super(ctx, 'remote') } + $stream() { + return { + async *[Symbol.asyncIterator]() { + for (;;) { + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: closeStream, + } + } + } + new Remote() + ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel: vi.fn() }) + const locale = new LocaleRuntime(ctx) + ctx.provide('locale', locale) + await ctx.plugin(SlotRegistry) + ctx.slots.register({ name: 'root', children: { + 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, + 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, + 'plugins.detail.badge': { kind: 'list', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + } } as never, () => null) + const bundles = (slot: 'plugins.bundle.config' | 'plugins.bundle.activation') => + ctx.slots.entries(slot).map(item => [item.options.key, bundleFaceOf(item).account]) + return { + ctx, locale, start, closeStream, bundles, + mount: () => ctx.plugin({ inject: [...inject], apply }), + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + queue.push({ accounts: entries }) + wake?.() + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + } +} + +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.ctx.slots.entries('plugins.detail.badge').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.badge', ConnectorAccountBadgeEntry], + ]) + expect(b.ctx.slots.entries('shell.overlay').map(item => [item.options.id, item.component])).toEqual([ + ['connector-account.notice', ConnectorAccountToastEntry], + ]) + expect(b.bundles('plugins.bundle.config')).toEqual([]) + + // An account no bundle owns gets no bundle surfaces. + await b.publish(entry(FIXTURE), entry(OTHER), entry('mcp:custom', null)) + expect(b.bundles('plugins.bundle.config')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[FIXTURE, FIXTURE], [OTHER, OTHER]]) + const [section] = b.ctx.slots.entries('plugins.bundle.config') + assert(section !== undefined) + expect(section).toMatchObject({ locale: NS, component: ConnectorAccountSectionEntry }) + expect(b.ctx.slots.entries('plugins.bundle.activation')[0]).toMatchObject({ locale: NS, component: ConnectorAccountActivationEntry }) + const face = bundleFaceOf(section) + const [badge] = b.ctx.slots.entries('plugins.detail.badge') + assert(badge !== undefined) + const [toast] = b.ctx.slots.entries('shell.overlay') + assert(toast !== undefined) + expect(faceOf(badge).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) + expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) + expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') + await face.remote.start(FIXTURE, 'connect') + expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') + face.follow(FIXTURE, OP) + 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. + await b.publish(entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, OTHER]]) + await b.publish(entry('mcp:other', OTHER)) + expect(b.bundles('plugins.bundle.config')).toEqual([[OTHER, 'mcp:other']]) + expect(b.bundles('plugins.bundle.activation')).toEqual([[OTHER, 'mcp:other']]) +}) + +it('withdraws every surface, the dictionaries, and the stream when the plugin unloads', async () => { + const b = await bench() + const fiber = b.mount() + await fiber + await b.publish(entry(FIXTURE), entry(OTHER)) + expect(b.bundles('plugins.bundle.config')).toHaveLength(2) + await fiber.dispose() + 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.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 new file mode 100644 index 0000000000..c84907ffed --- /dev/null +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -0,0 +1,264 @@ +// @vitest-environment jsdom +/** The surfaces 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' +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, +} from '../src/client/components.tsx' +import { zh } from '../src/client/locales.ts' +import type { ConnectorAccountsState } from '../src/client/types.ts' +import type { ConnectorAccountDisplay, ConnectorAccountEntry, ConnectorOperationId } from '../src/types.ts' + +afterEach(cleanup) + +const KEY = '@acme/fixture' +const OP = 'op-1' as ConnectorOperationId +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 DISCONNECTED: ConnectorAccountDisplay = { + phase: 'disconnected', status: { en: 'Not connected', zh: '未连接' }, badge: '未连接', + buttons: [{ label: '连接演示', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [], +} + +function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial = {}): ConnectorAccountEntry { + return { + key: KEY, packageName: KEY, display, + copy: { title: { en: 'Fixture account', zh: '演示账号' }, hint: '与终端共用。', activation: { title: '连接演示', body: '插件已开启。', connect: '连接演示' } }, + ...extra, + } +} + +function section(change: Partial<{ linked: boolean; stopped: boolean; busy: boolean }> = {}, 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 and steps aside once the phase settles elsewhere', () => { + const onDismiss = vi.fn() + const onConnect = vi.fn() + const prompt = (phase: 'checking' | 'disconnected' | 'connected') => + + const { rerender } = render(prompt('checking')) + 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) +}) + +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, + } + return { + useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), + remote: { + 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, + } +} + +it('starts an operation through the Remote, follows it, and stays busy until the call answers', 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() +}) + +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('连接演示')) }) + expect(props.failed).toHaveBeenCalledTimes(2) + expect(props.follow).not.toHaveBeenCalled() +}) + +it('cancels the operation in progress and opens its authorization page again on request', async () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + const display: ConnectorAccountDisplay = { + phase: 'connecting', status: '等待浏览器', notes: [], + buttons: [{ label: '打开授权页', command: { kind: 'open' } }, { label: '取消', command: { kind: 'cancel' }, variant: 'ghost' }], + } + const props = face({}, [entry(display, { operation: { id: OP, authorizationUrl: 'https://example.com/a' } })]) + render() + fireEvent.click(button('打开授权页')) + expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') + await act(async () => { fireEvent.click(button('取消')) }) + expect(props.remote.cancel).toHaveBeenCalledWith(KEY, OP) + // A cancel button with no operation in progress calls nothing. + cleanup() + const idle = face({}, [entry(display)]) + render() + await act(async () => { fireEvent.click(button('取消')) }) + 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', () => { + 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 } } + const tag = (props: ReturnType, subject: PluginsSubject) => + const { rerender } = render(tag(face(), page(KEY))) + 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)], + ] as const) { + rerender(tag(props, subject)) + expect(document.body.textContent).toBe('') + } +}) + +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('连接演示')) }) + expect(onOpenDetails).toHaveBeenCalledOnce() + expect(named.remote.start).toHaveBeenCalledWith(KEY, 'link-app') + const bare = face() + rerender(prompt(bare, 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 answer = Promise.withResolvers>() + props.remote.start.mockReturnValueOnce(answer.promise) + render(prompt(props)) + fireEvent.click(button('连接演示')) + fireEvent.click(button('连接演示')) + await act(async () => { answer.resolve(ok(OP)) }) + expect(props.remote.start).toHaveBeenCalledOnce() + expect(props.follow).toHaveBeenCalledOnce() +}) + +it('shows the account notice through the toast entry', () => { + render() + expect(screen.getByText('演示已连接')).toBeTruthy() +}) diff --git a/packages/client/ui-connector-account/tests/registry.host.spec.ts b/packages/client/ui-connector-account/tests/registry.host.spec.ts new file mode 100644 index 0000000000..f5062b9596 --- /dev/null +++ b/packages/client/ui-connector-account/tests/registry.host.spec.ts @@ -0,0 +1,166 @@ +/** The registry serves every registered account to the Plugins page and routes page operations to the account that owns them. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, onTestFinished, vi } from 'vitest' +import ConnectorAccounts from '../src/index.ts' +import type { + ConnectorAccountDisplay, ConnectorAccountRegistration, ConnectorAccountSource, ConnectorAccountsView, ConnectorAccountView, + ConnectorOperationId, +} from '../src/types.ts' + +type View = ConnectorAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> + +const OP = 'op-1' as ConnectorOperationId +const COPY = { + title: { en: 'Fixture account', zh: '演示账号' }, + hint: 'Shared with the terminal.', + activation: { title: 'Connect Fixture', body: 'The plugin is on.', connect: 'Connect' }, +} + +function source(initial: View = { account: { state: 'out' } }) { + let view = initial + const listeners = new Set<() => void>() + const fake = { + snapshot: () => view, + observe: vi.fn((listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }), + refresh: vi.fn(), + start: vi.fn((_kind: 'check' | 'connect') => OP), + cancel: vi.fn(async (_id: ConnectorOperationId) => {}), + } satisfies ConnectorAccountSource + return { fake, listeners, publish: (next: View) => { view = next; for (const listener of listeners) listener() } } +} + +function display(view: View): ConnectorAccountDisplay { + return view.account.state === 'in' + ? { phase: 'connected', status: 'Connected', badge: 'Connected', buttons: [], notes: [] } + : { phase: 'disconnected', status: 'Not connected', buttons: [{ label: 'Connect', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [] } +} + +/** A registration whose bundle package defaults to its key; `null` registers an account no bundle owns. */ +function registration(key: string, account = source(), packageName: string | null = key): ConnectorAccountRegistration { + return { + key, ...packageName === null ? {} : { packageName }, source: account.fake, copy: COPY, present: display, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Fixture connected', zh: '演示已连接' } }], + } +} + +async function registry() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(ConnectorAccounts) + return ctx +} + +/** Read the stream until a view satisfies the predicate. */ +async function until( + stream: AsyncIterator, predicate: (view: ConnectorAccountsView) => boolean, +): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('stream ended') + if (predicate(next.value)) return next.value + } +} + +it('publishes each account with its key, package, copy, display, operation, and result, and checks it for each new subscriber', async () => { + const ctx = await registry() + const account = source() + const withdraw = ctx.connectorAccounts.register(registration('@acme/fixture', account)) + expect(account.fake.refresh).not.toHaveBeenCalled() + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + const first = await until(stream, () => true) + expect(account.fake.refresh).toHaveBeenCalledOnce() + expect(first.accounts).toEqual([ + { key: '@acme/fixture', packageName: '@acme/fixture', copy: COPY, display: display({ account: { state: 'out' } }) }, + ]) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: true, authorizationUrl: 'https://example.com/a' } }) + const waiting = await until(stream, view => view.accounts[0]?.operation !== undefined) + expect(waiting.accounts[0]?.operation).toEqual({ id: OP, authorizationUrl: 'https://example.com/a' }) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: false } }) + const checking = await until(stream, (view) => { + const operation = view.accounts[0]?.operation + return operation !== undefined && operation.authorizationUrl === undefined + }) + expect(checking.accounts[0]?.operation).toEqual({ id: OP }) + + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) + const connected = await until(stream, view => view.accounts[0]?.result !== undefined) + expect(connected.accounts[0]).toMatchObject({ + display: { phase: 'connected' }, result: { id: OP, notice: { en: 'Fixture connected', zh: '演示已连接' } }, + }) + + // Only a success reports a notice, and only for an operation that registered one. + account.publish({ account: { state: 'out' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'disconnected')).accounts[0]?.result).toEqual({ id: OP }) + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'connected')).accounts[0]?.result).toEqual({ id: OP }) + + withdraw() + expect((await until(stream, view => view.accounts.length === 0)).accounts).toEqual([]) + withdraw() + expect(account.listeners.size).toBe(0) + controller.abort() + expect((await stream.next()).done).toBe(true) +}) + +it('publishes an account that no bundle owns without a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('mcp:custom', source(), null)) + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + const [entry] = (await until(stream, () => true)).accounts + expect(entry).toEqual({ key: 'mcp:custom', copy: COPY, display: display({ account: { state: 'out' } }) }) +}) + +it('checks an account registered while the page follows, and none registered while nobody follows', async () => { + const ctx = await registry() + const idle = source() + ctx.connectorAccounts.register(registration('@acme/idle', idle)) + const controller = new AbortController() + const stream = ctx.connectorAccounts.watch(controller.signal)[Symbol.asyncIterator]() + await until(stream, view => view.accounts.length === 1) + const late = source() + ctx.connectorAccounts.register(registration('@acme/late', late)) + expect(late.fake.refresh).toHaveBeenCalledOnce() + expect((await until(stream, view => view.accounts.length === 2)).accounts.map(entry => entry.key)).toEqual(['@acme/idle', '@acme/late']) + controller.abort() + await stream.next() + const after = source() + ctx.connectorAccounts.register(registration('@acme/after', after)) + expect(after.fake.refresh).not.toHaveBeenCalled() +}) + +it('starts only the operations an account registered and cancels through its source', async () => { + const ctx = await registry() + const account = source() + ctx.connectorAccounts.register(registration('@acme/fixture', account)) + expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).toBe(OP) + expect(account.fake.start).toHaveBeenCalledWith('connect') + expect(() => ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).toThrow('@acme/fixture has no page operation sign-out') + expect(() => ctx.connectorAccounts.start('@acme/other', 'connect')).toThrow('@acme/other is not registered') + await ctx.connectorAccounts.cancel('@acme/fixture', OP) + expect(account.fake.cancel).toHaveBeenCalledWith(OP) + expect(() => ctx.connectorAccounts.cancel('@acme/other', OP)).toThrow('@acme/other is not registered') +}) + +it('refuses a second account for a key or for a package', async () => { + const ctx = await registry() + ctx.connectorAccounts.register(registration('@acme/fixture')) + expect(() => ctx.connectorAccounts.register(registration('@acme/fixture'))).toThrow('@acme/fixture is already registered') + expect(() => ctx.connectorAccounts.register(registration('mcp:fixture', source(), '@acme/fixture'))) + .toThrow('@acme/fixture already has an account') + expect(() => ctx.connectorAccounts.register(registration('mcp:custom', source(), null))).not.toThrow() +}) + +it('ends every stream when the registry unloads', async () => { + const ctx = new Context() + const fiber = ctx.plugin(ConnectorAccounts) + await fiber + const stream = ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + await until(stream, () => true) + const pending = stream.next() + await fiber.dispose() + expect((await pending).done).toBe(true) + await ctx.fiber.dispose() +}) diff --git a/packages/client/ui-connector-account/tests/state.client.spec.ts b/packages/client/ui-connector-account/tests/state.client.spec.ts new file mode 100644 index 0000000000..490b4dcae3 --- /dev/null +++ b/packages/client/ui-connector-account/tests/state.client.spec.ts @@ -0,0 +1,194 @@ +// @vitest-environment jsdom +/** The browser follows every registered account through one Host stream and keeps only what this browser started. */ +import { Context } from '@deepseek-ai/cordis' +import { RemoteStreamCarrierError, type RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' +import { expect, it, onTestFinished, vi } from 'vitest' +import { BrowserAccounts, openAuthorizationPage } from '../src/client/state.ts' +import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../src/types.ts' + +const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId +const FIXTURE = '@acme/fixture' +const OTHER = 'mcp:other' +const COPY = { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } } + +function entry(key: string, extra: Partial = {}): ConnectorAccountEntry { + return { key, copy: COPY, display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, ...extra } +} + +const waiting = (url?: string, id = OP): Partial => + ({ operation: { id, ...url === undefined ? {} : { authorizationUrl: url } } }) + +function fixture() { + const queue: ConnectorAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 + let options!: RemoteStreamOptions + const open = () => ({ + async *[Symbol.asyncIterator]() { + for (;;) { + if (failure !== undefined) throw failure + // A queued item still arrives after close, as an item the stream yielded just before disposal does. + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: vi.fn(async () => { closed = true; wake?.() }), + }) + const streams: Array> = [] + const remote = { watch: vi.fn() } + const ctx = new Context() + ctx.provide('remote', { + $stream: (value: typeof options) => { + options = value + closed = false + failure = undefined + streams.push(open()) + return streams.at(-1) + }, + }) + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + 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, + state: () => browser.state.getSnapshot(), + deliver(view: ConnectorAccountsView) { queue.push(view); wake?.() }, + async publish(...entries: ConnectorAccountEntry[]) { + const target = accepted + 1 + this.deliver({ accounts: entries }) + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + fail(error: Error) { failure = error; wake?.() }, + } +} + +// 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 }) + const open = b.options().open(new AbortController().signal) + expect(b.remote.watch).toHaveBeenCalledOnce() + expect(open).toBe(b.remote.watch.mock.results[0]?.value) + await b.publish(entry(FIXTURE), entry(OTHER)) + expect([...b.state().accounts.keys()]).toEqual([FIXTURE, OTHER]) + 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().accounts.keys()]).toEqual([FIXTURE]) + expect(b.options().ended(true).message).toBe('Connector accounts stream ended') +}) + +it('opens each new authorization page of an operation this browser started once, and no other account\'s', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, waiting('https://example.com/a')), entry(OTHER, waiting('https://example.com/other'))) + expect(b.open.mock.calls).toEqual([['https://example.com/a', '_blank', 'noopener,noreferrer']]) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + await b.publish(entry(FIXTURE, waiting('http://127.0.0.1:8123/authorize'))) + // Another browser's operation on the same account opens nothing here. + await b.publish(entry(FIXTURE, waiting('https://example.com/b', NEXT))) + expect(b.open.mock.calls.map(([url]) => url)).toEqual(['https://example.com/a', 'http://127.0.0.1:8123/authorize']) +}) + +it('opens the page at once when the stream delivered the operation before the start call answered', async () => { + const b = fixture() + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() + b.browser.follow(FIXTURE, OP) + expect(b.open).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') +}) + +it('reports the success of an operation this browser started once, and stops following it', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(FIXTURE, { result: { id: NEXT, notice: 'Other browser connected' } })) + expect(b.state().notice).toBeUndefined() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toEqual({ seq: 1, kind: 'succeeded', text: 'Fixture connected' }) + b.browser.dismissNotice() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Fixture connected' } })) + expect(b.state().notice).toBeUndefined() + + // A result without the registrant's text, or a cancelled or failed one, reports nothing. + b.browser.follow(FIXTURE, NEXT) + await b.publish(entry(FIXTURE, { result: { id: NEXT } })) + expect(b.state().notice).toBeUndefined() +}) + +it('forgets the operation of an account the Host withdrew', async () => { + const b = fixture() + b.browser.follow(FIXTURE, OP) + await b.publish(entry(OTHER)) + await b.publish(entry(FIXTURE, waiting('https://example.com/a'))) + expect(b.open).not.toHaveBeenCalled() +}) + +it('reports a call that did not finish with a fresh notice each time', () => { + const b = fixture() + b.browser.failed() + b.browser.failed() + expect(b.state().notice).toEqual({ seq: 2, kind: 'action-failed' }) +}) + +it('stops after a terminal stream failure and reopens on retry', async () => { + const b = fixture() + 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 }) +}) + +it('opens nothing and reports nothing after disposal, and a retry pending at disposal opens no stream', 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() +}) + +it('shows nothing for a stream that fails while the page disposes it', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.fail(new Error('carrier lost')) + await disposing + expect(b.state()).toMatchObject({ linked: true, stopped: false }) +}) + +it('ignores an item the stream yielded just before disposal', async () => { + const b = fixture() + const disposing = b.browser.dispose() + b.deliver({ accounts: [entry(FIXTURE)] }) + await disposing + expect(b.state().accounts.size).toBe(0) +}) + +it('opens only HTTPS pages and HTTP pages on loopback addresses', () => { + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + onTestFinished(() => { windowOpen.mockRestore() }) + for (const url of [undefined, 'not a url', 'http://example.com/a', 'javascript:alert(1)']) openAuthorizationPage(url) + expect(windowOpen).not.toHaveBeenCalled() + for (const url of ['https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a']) openAuthorizationPage(url) + expect(windowOpen.mock.calls.map(([url]) => url)).toEqual([ + 'https://example.com/a', 'http://localhost:1/a', 'http://[::1]:1/a', 'http://127.0.0.1:1/a', + ]) +}) diff --git a/packages/client/ui-connector-account/tsconfig.client.json b/packages/client/ui-connector-account/tsconfig.client.json new file mode 100644 index 0000000000..115af386fd --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.client.json @@ -0,0 +1,57 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/css-modules.d.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-layout" + }, + { + "path": "../ui-plugin-manager/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + }, + { + "path": "../../util/values" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.host.json b/packages/client/ui-connector-account/tsconfig.host.json new file mode 100644 index 0000000000..564ba19f3b --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.host.json @@ -0,0 +1,26 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "files": [ + "src/index.ts", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/package-manifest" + } + ] +} diff --git a/packages/client/ui-connector-account/tsconfig.json b/packages/client/ui-connector-account/tsconfig.json new file mode 100644 index 0000000000..2eca820546 --- /dev/null +++ b/packages/client/ui-connector-account/tsconfig.json @@ -0,0 +1,11 @@ +{ + "files": [], + "references": [ + { + "path": "./tsconfig.host.json" + }, + { + "path": "./tsconfig.client.json" + } + ] +} diff --git a/packages/client/ui-connector-account/tsdown.config.ts b/packages/client/ui-connector-account/tsdown.config.ts new file mode 100644 index 0000000000..620261533c --- /dev/null +++ b/packages/client/ui-connector-account/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/experimental/liveshare/src/endpoint-classification.ts b/packages/experimental/liveshare/src/endpoint-classification.ts index a868012bd6..f6d4651fcc 100644 --- a/packages/experimental/liveshare/src/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/endpoint-classification.ts @@ -163,6 +163,9 @@ export const VIEWER_ENDPOINT_CLASSES = { 'productAnalytics/report': 'owner-only', // owner product analytics 'productAnalytics/watchPolicy': 'owner-only', // owner product analytics 'pluginRegistryProbe/fastest': 'owner-only', // owner plugin registry probe + 'connectorAccounts/cancel': 'owner-only', // owner connector accounts on the Plugins page + 'connectorAccounts/start': 'owner-only', // owner connector accounts on the Plugins page + 'connectorAccounts/watch': 'owner-only', // owner connector accounts on the Plugins page 'sessionReferenceResolver/candidates': 'owner-only', // owner composer reference resolution 'officeKit/generation': 'owner-only', // owner document export 'officeKit/render': 'owner-only', // owner document export diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 41f4010684..3f81339648 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -2831,6 +2831,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ slotInject: '', declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', occupants: [ + 'client-ui-connector-account ConnectorAccountActivationEntry', 'experimental-client-ui-voice-input VoiceSetupPrompt key \'@deepseek-ai/dsh-experimental-voice-input-bundle\'', 'cua PermissionSetup key \'@deepseek-ai/dsh-cua-bundle\'', ], @@ -2875,6 +2876,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ slotInject: '', declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', occupants: [ + 'client-ui-connector-account ConnectorAccountSectionEntry', 'experimental-client-ui-cot-translation TranslationSettings key \'@deepseek-ai/dsh-experimental-cot-translation-bundle\'', 'experimental-client-ui-voice-input VoicePreparation key \'@deepseek-ai/dsh-experimental-voice-input-bundle\'', 'cua PermissionPanel key \'@deepseek-ai/dsh-cua-bundle\'', @@ -2984,7 +2986,9 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ hookContext: '', slotInject: '', declaredBy: 'an entry in \'main\' (client-ui-plugin-manager), so it exists while that entry is mounted', - occupants: [], + occupants: [ + 'client-ui-connector-account ConnectorAccountBadgeEntry id \'connector-account.badge\'', + ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'plugins.detail.badge\', () => ctx.slots.register(\n { name: \'plugins.detail.badge\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-plugin-manager/src/client/slot-contract.ts:178', @@ -4052,6 +4056,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [ 'client-ui-agent-team TeamDisableConfirmation id \'agent-team.disable\'', 'client-ui-chat QuotaNoticeHost id \'chat.quota-notice\'', + 'client-ui-connector-account ConnectorAccountToastEntry id \'connector-account.notice\'', 'client-ui-context-menu MenuOverlay id \'context-menu\'', 'client-ui-file-drag FileDragFeedback id \'file-drag.feedback\'', 'client-ui-open-in-app OpenInAppToast id \'open-in-app.toast\'', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 0ac2e9e122..7dab041b4e 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -812,6 +812,40 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'connectorAccounts', + summary: 'Holds the registered accounts and serves them to the Plugins page.', + description: 'Holds the registered accounts and serves them to the Plugins page.', + methods: [ + { + signature: 'register(registration: ConnectorAccountRegistration): () => void', + description: 'Show one account on the Plugins page for as long as the returned disposer has not run.', + parameters: [{ name: 'registration', description: 'the account key, its bundle package, the account source, the page operations, and the presentation.' }], + returns: 'an idempotent disposer that withdraws the account.', + throws: ['when another account already uses the key or the package.'], + }, + { + signature: '@Remote({ mode: \'stream\' }) async *watch(signal: AbortSignal): AsyncIterable', + description: 'Follow every registered account; each new subscriber starts a check of each account that runs no operation.', + parameters: [{ name: 'signal', description: 'the Client\'s observation lifetime; disposal also ends the stream.' }], + returns: 'the current accounts, then each changed set, coalescing changes that arrive before the next read.', + }, + { + signature: '@Remote start(key: string, operation: string): ConnectorOperationId', + description: 'Start one of the operations the account registered as page actions.', + parameters: [{ name: 'key', description: 'the account key.' }, { name: 'operation', description: 'the operation kind.' }], + returns: 'the operation identity.', + throws: ['for an unknown account or operation, or whatever the account\'s source refuses, such as a second operation.'], + }, + { + signature: '@Remote cancel(key: string, id: ConnectorOperationId): Promise', + description: 'Cancel one operation while its phase is cancellable, and wait for it to settle.', + parameters: [{ name: 'key', description: 'the account key.' }, { name: 'id', description: 'the operation to cancel; a finished one or a phase that is not cancellable is ignored.' }], + returns: 'after the operation settles, or at once when nothing is cancelled.', + throws: ['for an unknown account.'], + }, + ], + }, { key: 'cotTranslation', summary: 'Optional reasoning translation delegates Session-bound storage to the translator.', @@ -5754,6 +5788,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AnonymousTranslationSpec', declaration: 'export interface AnonymousTranslationSpec extends TranslationSpecFields {\n readonly provider: AnonymousTranslationProvider;\n}', }, + { + name: 'AnyConnectorAccountView', + declaration: 'export type AnyConnectorAccountView = ConnectorAccountView;', + }, { name: 'AnyHook', declaration: 'export type AnyHook = ModHook;', @@ -6178,6 +6216,78 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ConnectionTrustRequest', declaration: 'export interface ConnectionTrustRequest {\n readonly headers: Headers | Readonly>;\n}', }, + { + name: 'ConnectorAccountButton', + declaration: 'export interface ConnectorAccountButton {\n readonly label: LocalizedText;\n readonly command: ConnectorAccountCommand;\n readonly variant?: \'primary\' | \'ghost\';\n readonly confirm?: ConnectorAccountConfirmation;\n}', + }, + { + name: 'ConnectorAccountCommand', + declaration: 'export type ConnectorAccountCommand = {\n readonly kind: \'start\';\n readonly operation: string;\n} | {\n readonly kind: \'cancel\';\n} | {\n readonly kind: \'open\';\n};', + }, + { + name: 'ConnectorAccountConfirmation', + declaration: 'export interface ConnectorAccountConfirmation {\n readonly title: LocalizedText;\n readonly body: LocalizedText;\n readonly label: LocalizedText;\n}', + }, + { + name: 'ConnectorAccountCopy', + declaration: 'export interface ConnectorAccountCopy {\n readonly title: LocalizedText;\n readonly hint: LocalizedText;\n readonly activation: {\n readonly title: LocalizedText;\n readonly body: LocalizedText;\n readonly connect: LocalizedText;\n };\n}', + }, + { + name: 'ConnectorAccountDisplay', + declaration: 'export interface ConnectorAccountDisplay {\n readonly phase: ConnectorAccountPhase;\n readonly status: LocalizedText;\n readonly badge?: LocalizedText;\n readonly buttons: readonly ConnectorAccountButton[];\n readonly connect?: Extract;\n readonly detail?: LocalizedText;\n readonly notes: readonly ConnectorAccountNote[];\n readonly failure?: ConnectorAccountFailure;\n}', + }, + { + name: 'ConnectorAccountEntry', + declaration: 'export interface ConnectorAccountEntry {\n readonly key: string;\n readonly packageName?: string;\n readonly copy: ConnectorAccountCopy;\n readonly display: ConnectorAccountDisplay;\n readonly operation?: {\n readonly id: ConnectorOperationId;\n readonly authorizationUrl?: string;\n };\n readonly result?: {\n readonly id: ConnectorOperationId;\n readonly notice?: LocalizedText;\n };\n}', + }, + { + name: 'ConnectorAccountFailure', + declaration: 'export interface ConnectorAccountFailure {\n readonly text: LocalizedText;\n readonly details?: readonly string[];\n}', + }, + { + name: 'ConnectorAccountNote', + declaration: 'export interface ConnectorAccountNote {\n readonly text: LocalizedText;\n readonly button?: ConnectorAccountButton;\n}', + }, + { + name: 'ConnectorAccountOperation', + declaration: 'export interface ConnectorAccountOperation {\n readonly kind: Kind;\n readonly notice?: LocalizedText;\n}', + }, + { + name: 'ConnectorAccountPhase', + declaration: 'export type ConnectorAccountPhase = \'checking\' | \'connecting\' | \'connected\' | \'disconnected\' | \'unavailable\';', + }, + { + name: 'ConnectorAccountRegistration', + declaration: 'export interface ConnectorAccountRegistration {\n readonly key: string;\n readonly packageName?: string;\n readonly source: ConnectorAccountSource;\n readonly operations: readonly ConnectorAccountOperation>[];\n readonly copy: ConnectorAccountCopy;\n readonly present: (view: View) => ConnectorAccountDisplay;\n}', + }, + { + name: 'ConnectorAccountSource', + declaration: 'export interface ConnectorAccountSource {\n snapshot(): View;\n observe(listener: () => void): () => void;\n refresh(): void;\n start(kind: ConnectorOperationKindOf): ConnectorOperationId;\n cancel(id: ConnectorOperationId): Promise;\n}', + }, + { + name: 'ConnectorAccountsView', + declaration: 'export interface ConnectorAccountsView {\n readonly accounts: readonly ConnectorAccountEntry[];\n}', + }, + { + name: 'ConnectorAccountView', + declaration: 'export interface ConnectorAccountView {\n readonly account: Account;\n readonly operation?: ConnectorOperation;\n readonly result?: ConnectorOperationResult;\n}', + }, + { + name: 'ConnectorOperation', + declaration: 'export interface ConnectorOperation {\n readonly id: ConnectorOperationId;\n readonly kind: Kind;\n readonly phase: Phase;\n readonly cancellable: boolean;\n readonly authorizationUrl?: string;\n}', + }, + { + name: 'ConnectorOperationId', + declaration: 'export type ConnectorOperationId = Branded<\'ConnectorOperationId\'>;', + }, + { + name: 'ConnectorOperationKindOf', + declaration: 'export type ConnectorOperationKindOf = NonNullable[\'kind\'];', + }, + { + name: 'ConnectorOperationResult', + declaration: 'export interface ConnectorOperationResult {\n readonly id: ConnectorOperationId;\n readonly kind: Kind;\n readonly outcome: \'succeeded\' | \'cancelled\' | \'failed\';\n readonly failure?: Failure;\n}', + }, { name: 'ContentBlockMap', declaration: 'export interface ContentBlockMap {\n \'text\': TextBlock;\n \'reasoning\': ReasoningBlock;\n \'image\': ImageBlock;\n \'file\': FileBlock;\n \'tool-call\': ToolCallBlock;\n \'tool-addition\': ToolAdditionBlock;\n \'tool-removal\': ToolRemovalBlock;\n}', diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 489d3c98ce..4e85565b18 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -74,6 +74,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-client-ui-brand-official` | no | Official DeepSeek Harness brand artwork and click-triggered home background | | `@deepseek-ai/dsh-client-ui-chat` | no | Chat Conversation target, node definitions, renderers, and details surface | | `@deepseek-ai/dsh-client-ui-commands` | no | Client command surface: global directory cache, '/' source, three command UI kinds, popupSelect registry | +| `@deepseek-ai/dsh-client-ui-connector-account` | no | Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote | | `@deepseek-ai/dsh-client-ui-context-menu` | no | Typed, plugin-extensible context menus with captured targets and shared Web presentation | | `@deepseek-ai/dsh-client-ui-conversation` | no | Target-neutral Conversation assembly, shell, composer, queue, and view navigation | | `@deepseek-ai/dsh-client-ui-deliverables` | no | Changed-files card with per-file comparison tabs, delivery cards, and clickable final-response file references for Web | diff --git a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts index f43eae5217..faa5009098 100644 --- a/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts +++ b/packages/test-support/client-runtime/src/assembly/remote-default-responses.ts @@ -60,5 +60,7 @@ export const remoteDefaultResponses: RemoteTable = { 'remoteAccess/follow': openStream([{ type: 'baseline', owner: true }]), // ui-sidebar-terminal header entry `agent-terminals`: the displayed Session's terminal roster, then open. 'terminal/watch': openStream([[]]), + // ui-connector-account `apply`: the registered connector accounts, none in a default composition, then open. + 'connectorAccounts/watch': openStream([{ accounts: [] }]), }, } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b48c3c87c1..b8e66b0ebf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1482,6 +1482,9 @@ importers: '@deepseek-ai/dsh-client-product-analytics': specifier: workspace:* version: link:../../client/product-analytics + '@deepseek-ai/dsh-client-ui-connector-account': + specifier: workspace:* + version: link:../../client/ui-connector-account '@deepseek-ai/dsh-client-ui-plugin-manager': specifier: workspace:* version: link:../../client/ui-plugin-manager @@ -2992,6 +2995,9 @@ importers: '@deepseek-ai/dsh-client-ui-commands': specifier: workspace:* version: link:../../client/ui-commands + '@deepseek-ai/dsh-client-ui-connector-account': + specifier: workspace:* + version: link:../../client/ui-connector-account '@deepseek-ai/dsh-client-ui-context-menu': specifier: workspace:* version: link:../../client/ui-context-menu @@ -4184,6 +4190,67 @@ importers: specifier: ^18.2.0 version: 18.3.1 + packages/client/ui-connector-account: + dependencies: + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + zod: + specifier: 4.6.6 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:* + version: link:../../api/gateway + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:* + version: link:../../api/remotes + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand + '@deepseek-ai/dsh-client-locale': + specifier: workspace:* + version: link:../locale + '@deepseek-ai/dsh-client-store': + specifier: workspace:* + version: link:../store + '@deepseek-ai/dsh-client-test-runtime': + specifier: workspace:* + version: link:../../test-support/client-runtime + '@deepseek-ai/dsh-client-ui-layout': + specifier: workspace:* + version: link:../ui-layout + '@deepseek-ai/dsh-client-ui-plugin-manager': + specifier: workspace:* + version: link:../ui-plugin-manager + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:* + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-renderer': + specifier: workspace:* + version: link:../ui-renderer + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:* + version: link:../ui-slots + '@deepseek-ai/dsh-package-manifest': + specifier: workspace:* + version: link:../../util/package-manifest + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + '@testing-library/react': + specifier: ^16.3.3 + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: + specifier: ^18.2.0 + version: 18.3.1 + react-dom: + specifier: ^18.2.0 + version: 18.3.1(react@18.3.1) + packages/client/ui-context-menu: devDependencies: '@deepseek-ai/cordis': diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 9e5119387d..4086cfb588 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -63,6 +63,7 @@ export const SERVICE_PAGE: Record = { actionCards: 'boot.md', pluginRecommendations: 'boot.md', pluginMarket: 'boot.md', + connectorAccounts: 'boot.md', pluginRegistryProbe: 'boot.md', configEditor: 'boot.md', profileContext: 'boot.md', @@ -1009,6 +1010,10 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet = new Set([ /** Project types deliberately documented outside the subsystems catalog. */ export const TYPE_LINK_EXEMPTIONS: Readonly> = { + AnyConnectorAccountView: 'generic connector account view is owned by packages/client/ui-connector-account/README.md', + ConnectorAccountRegistration: 'Plugins page account registration is owned by packages/client/ui-connector-account/README.md', + ConnectorAccountsView: 'registered account stream item is owned by packages/client/ui-connector-account/README.md', + ConnectorOperationId: 'account operation id is owned by packages/client/ui-connector-account/README.md', ActionCardDecision: 'packages/experimental/action-cards/README.md', ActionCardKind: 'packages/experimental/action-cards/README.md', ActionCardResult: 'packages/experimental/action-cards/README.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 6643bd5b44..f37c4165b3 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -170,6 +170,13 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['plugin-manager', 'ui-settings-plugin-inventory'], note: 'Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers.', }, + { + key: 'connectorAccounts', + pkg: 'client-ui-connector-account', + title: 'Connector accounts on the Plugins page', + mode: 'service', + note: 'Holds the accounts CLI app plugins and MCP connectors register and serves their Host-computed displays to the Plugins page through one Remote; authorization pages and notices stay in the browser that started the operation.', + }, { key: 'pluginMarket', pkg: 'plugin-market', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index d5001cd021..1438911741 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -150,6 +150,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-brand-official': { kind: 'none', reason: 'Browser-side presentation occupants; registers nothing model-facing.' }, 'packages/client/ui-approval': { kind: 'none', reason: 'Browser-side approval presentation; registers nothing model-facing.' }, 'packages/client/ui-chat': { kind: 'none', reason: 'Browser-side Chat presentation; registers nothing model-facing.' }, + 'packages/client/ui-connector-account': { kind: 'none', reason: 'Plugins page account surfaces over Host-registered accounts; each registrant documents the tools and skills its account enables.' }, 'packages/client/ui-message-feedback': { kind: 'none', reason: 'Browser-side controls over log-only message feedback; ratings and notes never enter model context or change model-input tokens.' }, 'packages/client/ui-tool': { kind: 'none', reason: 'Browser-side Tool presentation layer; renders logged calls without changing model context.' }, 'packages/client/ui-schedule': { kind: 'none', reason: 'Browser-side catalog, editing, and deletion of Host Schedule records; dsh-schedule owns storage and delivery, and dsh-tool-schedule contributes the model-facing tools in a preset that mounts it.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 2121904985..adbdc839ee 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -323,6 +323,8 @@ "@deepseek-ai/dsh-client-ui-input-trigger": ["./packages/client/ui-input-trigger/src"], "@deepseek-ai/dsh-client-ui-reference": ["./packages/client/ui-reference/src"], "@deepseek-ai/dsh-client-ui-commands": ["./packages/client/ui-commands/src"], + "@deepseek-ai/dsh-client-ui-connector-account": ["./packages/client/ui-connector-account/src"], + "@deepseek-ai/dsh-client-ui-connector-account/types": ["./packages/client/ui-connector-account/src/types.ts"], "@deepseek-ai/dsh-client-ui-model-selection": ["./packages/client/ui-model-selection/src"], "@deepseek-ai/dsh-client-ui-goal": ["./packages/client/ui-goal/src"], "@deepseek-ai/dsh-client-ui-message-feedback": ["./packages/client/ui-message-feedback/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index f15b78502b..a6da608953 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -142,6 +142,7 @@ { "path": "./packages/client/ui-directory-picker-native" }, { "path": "./packages/client/ui-goal" }, { "path": "./packages/client/ui-message-feedback" }, + { "path": "./packages/client/ui-connector-account/tsconfig.client.json" }, { "path": "./packages/client/ui-model-selection" }, { "path": "./packages/client/ui-agent-preset" }, { "path": "./packages/client/ui-permission-presets" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index c926055be3..f4d9239e0e 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -305,6 +305,7 @@ { "path": "./packages/client/ui-theme/tsconfig.host.json" }, { "path": "./packages/client/ui-chat/tsconfig.host.json" }, { "path": "./packages/client/ui-conversation/tsconfig.host.json" }, + { "path": "./packages/client/ui-connector-account/tsconfig.host.json" }, { "path": "./packages/client/ui-settings/tsconfig.host.json" }, { "path": "./packages/client/ui-settings-general/tsconfig.host.json" }, From fadd1c28582a362f2d63034fe839dba435ba0226 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sun, 8 Nov 2026 04:15:16 +0800 Subject: [PATCH 02/13] feat(connector-account): let an account source start its operation asynchronously An MCP server's authorization starts only after the previous attempt's cleanup settles, so its source learns the operation identity after an await. `ConnectorAccountSource.start` may now return a Promise, and the registry's `start` answers once the source has the identity. --- docs/subsystems/boot.md | 4 ++-- docs/subsystems/boot.zh.md | 4 ++-- packages/client/ui-connector-account/src/index.ts | 8 ++++---- packages/client/ui-connector-account/src/types.ts | 4 ++-- .../ui-connector-account/tests/registry.host.spec.ts | 12 ++++++++---- packages/extensions/tool-cordis/src/api-catalog.ts | 6 +++--- 6 files changed, 21 insertions(+), 17 deletions(-) diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index c8f36d14e2..5c131881f7 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -170,10 +170,10 @@ register(registration: ConnectorAccountReg * Start one of the operations the account registered as page actions. * @param key - the account key. * @param operation - the operation kind. - * @returns the operation identity. + * @returns the operation identity once the account's source has started it. * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. */ -@Remote start(key: string, operation: string): ConnectorOperationId +@Remote async start(key: string, operation: string): Promise /** * Cancel one operation while its phase is cancellable, and wait for it to settle. diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index ab6383e0b3..0a48541725 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -170,10 +170,10 @@ register(registration: ConnectorAccountReg * Start one of the operations the account registered as page actions. * @param key - the account key. * @param operation - the operation kind. - * @returns the operation identity. + * @returns the operation identity once the account's source has started it. * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. */ -@Remote start(key: string, operation: string): ConnectorOperationId +@Remote async start(key: string, operation: string): Promise /** * Cancel one operation while its phase is cancellable, and wait for it to settle. diff --git a/packages/client/ui-connector-account/src/index.ts b/packages/client/ui-connector-account/src/index.ts index 691e56d90a..aa7ec1d6d4 100644 --- a/packages/client/ui-connector-account/src/index.ts +++ b/packages/client/ui-connector-account/src/index.ts @@ -24,7 +24,7 @@ interface Registered { readonly packageName: string | undefined readonly entry: () => ConnectorAccountEntry readonly refresh: () => void - readonly start: (operation: string) => ConnectorOperationId + readonly start: (operation: string) => ConnectorOperationId | Promise readonly cancel: (id: ConnectorOperationId) => Promise } @@ -131,12 +131,12 @@ export default class ConnectorAccounts extends TypertRemoteService { * Start one of the operations the account registered as page actions. * @param key - the account key. * @param operation - the operation kind. - * @returns the operation identity. + * @returns the operation identity once the account's source has started it. * @throws for an unknown account or operation, or whatever the account's source refuses, such as a second operation. */ @Remote - start(key: string, operation: string): ConnectorOperationId { - return this.account(key).start(operation) + async start(key: string, operation: string): Promise { + return await this.account(key).start(operation) } /** diff --git a/packages/client/ui-connector-account/src/types.ts b/packages/client/ui-connector-account/src/types.ts index a04cbf4a1d..debd04d302 100644 --- a/packages/client/ui-connector-account/src/types.ts +++ b/packages/client/ui-connector-account/src/types.ts @@ -137,8 +137,8 @@ export interface ConnectorAccountSource { observe(listener: () => void): () => void /** Start a check unless an operation runs; a source whose view is always current does nothing. */ refresh(): void - /** @returns the started operation's identity. */ - start(kind: ConnectorOperationKindOf): ConnectorOperationId + /** @returns the started operation's identity, at once or after the source has started the operation. */ + start(kind: ConnectorOperationKindOf): ConnectorOperationId | Promise /** @returns after the named operation settles, or at once when it is not cancellable. */ cancel(id: ConnectorOperationId): Promise } diff --git a/packages/client/ui-connector-account/tests/registry.host.spec.ts b/packages/client/ui-connector-account/tests/registry.host.spec.ts index f5062b9596..ee8e24276f 100644 --- a/packages/client/ui-connector-account/tests/registry.host.spec.ts +++ b/packages/client/ui-connector-account/tests/registry.host.spec.ts @@ -10,6 +10,7 @@ import type { type View = ConnectorAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> const OP = 'op-1' as ConnectorOperationId +const NEXT = 'op-2' as ConnectorOperationId const COPY = { title: { en: 'Fixture account', zh: '演示账号' }, hint: 'Shared with the terminal.', @@ -23,7 +24,7 @@ function source(initial: View = { account: { state: 'out' } }) { snapshot: () => view, observe: vi.fn((listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }), refresh: vi.fn(), - start: vi.fn((_kind: 'check' | 'connect') => OP), + start: vi.fn((_kind: 'check' | 'connect'): ConnectorOperationId | Promise => OP), cancel: vi.fn(async (_id: ConnectorOperationId) => {}), } satisfies ConnectorAccountSource return { fake, listeners, publish: (next: View) => { view = next; for (const listener of listeners) listener() } } @@ -135,10 +136,13 @@ it('starts only the operations an account registered and cancels through its sou const ctx = await registry() const account = source() ctx.connectorAccounts.register(registration('@acme/fixture', account)) - expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).toBe(OP) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(OP) expect(account.fake.start).toHaveBeenCalledWith('connect') - expect(() => ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).toThrow('@acme/fixture has no page operation sign-out') - expect(() => ctx.connectorAccounts.start('@acme/other', 'connect')).toThrow('@acme/other is not registered') + // A source that starts its operation asynchronously answers once it has the identity. + account.fake.start.mockImplementationOnce(async () => NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'connect')).resolves.toBe(NEXT) + await expect(ctx.connectorAccounts.start('@acme/fixture', 'sign-out')).rejects.toThrow('@acme/fixture has no page operation sign-out') + await expect(ctx.connectorAccounts.start('@acme/other', 'connect')).rejects.toThrow('@acme/other is not registered') await ctx.connectorAccounts.cancel('@acme/fixture', OP) expect(account.fake.cancel).toHaveBeenCalledWith(OP) expect(() => ctx.connectorAccounts.cancel('@acme/other', OP)).toThrow('@acme/other is not registered') diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 7dab041b4e..ca4b751e86 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -831,10 +831,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the current accounts, then each changed set, coalescing changes that arrive before the next read.', }, { - signature: '@Remote start(key: string, operation: string): ConnectorOperationId', + signature: '@Remote async start(key: string, operation: string): Promise', description: 'Start one of the operations the account registered as page actions.', parameters: [{ name: 'key', description: 'the account key.' }, { name: 'operation', description: 'the operation kind.' }], - returns: 'the operation identity.', + returns: 'the operation identity once the account\'s source has started it.', throws: ['for an unknown account or operation, or whatever the account\'s source refuses, such as a second operation.'], }, { @@ -6262,7 +6262,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ConnectorAccountSource', - declaration: 'export interface ConnectorAccountSource {\n snapshot(): View;\n observe(listener: () => void): () => void;\n refresh(): void;\n start(kind: ConnectorOperationKindOf): ConnectorOperationId;\n cancel(id: ConnectorOperationId): Promise;\n}', + declaration: 'export interface ConnectorAccountSource {\n snapshot(): View;\n observe(listener: () => void): () => void;\n refresh(): void;\n start(kind: ConnectorOperationKindOf): ConnectorOperationId | Promise;\n cancel(id: ConnectorOperationId): Promise;\n}', }, { name: 'ConnectorAccountsView', From fcf5908ff7cf1fe748e92c6c5d60bde69eb6246d Mon Sep 17 00:00:00 2001 From: gengruilin Date: Sun, 8 Nov 2026 04:36:33 +0800 Subject: [PATCH 03/13] 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 04/13] 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 () => { From a5859c3fc4e4a62a35094af0237580fa13ef01a3 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Mon, 9 Nov 2026 14:21:58 +0800 Subject: [PATCH 05/13] fix(connector-account): inject Host callbacks, gate dialogs on the stream, and wrap narrow rows The surfaces receive `start` and `cancel` callbacks that unwrap the Remote result in the apply closure instead of the Remote itself, as the client inject rule requires. An open confirmation disables its button under the same conditions as the section's buttons, and the activation prompt's Connect is disabled while the Host stream is down. The status row and its buttons wrap, so a long status or long button labels stay inside a narrow panel. --- .../ui-connector-account/README.i18n.yaml | 8 +-- .../client/ui-connector-account/README.md | 6 +- .../client/ui-connector-account/README.zh.md | 6 +- .../src/client/ConnectorAccount.module.css | 5 ++ .../src/client/components.tsx | 50 +++++++------- .../ui-connector-account/src/client/index.ts | 14 +++- .../ui-connector-account/src/client/types.ts | 9 ++- .../tests/apply.client.spec.ts | 17 +++-- .../tests/components.client.spec.tsx | 65 ++++++++++++------- 9 files changed, 111 insertions(+), 69 deletions(-) diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml index 63dcb56e37..64303c4159 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: f2bb2f05e2e122a4 - zh: f3dc9945b3f30736 + en: fcbc46fc932ed5c8 + zh: 2f1cce21453bced6 /deepseek-ai-dsh-client-ui-connector-account/use-this-package/following-operations: en: 0f6140d7ed6427b9 zh: feadef500ee4fd98 @@ -30,8 +30,8 @@ en: 353a48db7e7dd0f7 zh: 653f3d983d3fd572 /deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: - en: 890bd2109a5b5c4f - zh: f4373b71cb4f2018 + en: 8c16bb36ce00d4cc + zh: d52d2a6f2beacf21 /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 9f1ac26602..1226880ada 100644 --- a/packages/client/ui-connector-account/README.md +++ b/packages/client/ui-connector-account/README.md @@ -61,9 +61,9 @@ The registrant imports the registry's types with `import type` from the package | Surface | Behavior | |---|---| -| 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 | +| Section | Title, status, buttons, detail, notes, failure, and hint. Buttons, including a confirmation's, 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 or unavailable | +| 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, and is disabled while the Host stream is down. 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 @@ -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, 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 surfaces receive `start` and `cancel` callbacks that call the Remote and reject when the Host refuses or the call does not answer; the buttons await them 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 | |---|---| diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md index 5c00f7a229..845d244b47 100644 --- a/packages/client/ui-connector-account/README.zh.md +++ b/packages/client/ui-connector-account/README.zh.md @@ -61,9 +61,9 @@ export function apply(ctx: Context): void { | 界面 | 行为 | |---|---| -| 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮不可用。失败时先显示注册方的文案,再显示其诊断项 | +| 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。区块发起的调用未返回,或 Host 流中断时,按钮(包括确认框的按钮)不可用。失败时先显示注册方的文案,再显示其诊断项 | | 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | -| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。账号检查中或连接中时继续等待,已连接或不可用时自动关闭 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作;Host 流中断时它不可用。账号检查中或连接中时继续等待,已连接或不可用时自动关闭 | | 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | ### 跟随操作 @@ -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` 命名空间。各界面收到 `start` 和 `cancel` 两个回调:它们调用 Remote,在 Host 拒绝或调用没有回应时 reject;按钮等待回调结果,并把启动的操作报告给 `BrowserAccounts`。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 | 文件 | 职责 | |---|---| diff --git a/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css index c15f495d50..0ad221ae6f 100644 --- a/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css +++ b/packages/client/ui-connector-account/src/client/ConnectorAccount.module.css @@ -13,12 +13,16 @@ .status { display: flex; + flex-wrap: wrap; align-items: center; gap: 8px; min-height: 28px; } .label { + flex: 1 1 auto; + min-width: 0; + overflow-wrap: anywhere; font-size: 13px; line-height: 20px; color: var(--dsw-alias-label-primary); @@ -26,6 +30,7 @@ .actions { display: flex; + flex-wrap: wrap; gap: 8px; margin-left: auto; } diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx index e0293d02b2..483d8924ff 100644 --- a/packages/client/ui-connector-account/src/client/components.tsx +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -1,13 +1,12 @@ /** * 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. + * this browser's state and calls the Host through the injected callbacks. */ 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 { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { assertNever } from '@deepseek-ai/dsh-util-values' import type { ConnectorAccountButton, ConnectorAccountCommand, ConnectorAccountEntry, ConnectorAccountPhase } from '../types.ts' import css from './ConnectorAccount.module.css' @@ -26,21 +25,21 @@ const BADGE_TONE: Record = { checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', } -async function settle(call: Promise>): Promise { - const result = await call - if (!result.ok) throw new Error(result.error.message) - return result.value -} - /** - * 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. + * Run a button's command against the Host: start and cancel call the face's callbacks, and open shows the + * operation's authorization page again in this browser. + * @param face - the Host callbacks and the browser state the commands read and report to. + * @returns whether a call this surface made has not answered, whether the Host stream is delivering, and the runner of + * one account's command. */ function useAccountCommand( - face: Pick, -): { readonly busy: boolean; readonly run: (entry: ConnectorAccountEntry, command: ConnectorAccountCommand) => void } { + face: Pick, +): { + readonly busy: boolean + readonly linked: boolean + readonly run: (entry: ConnectorAccountEntry, command: ConnectorAccountCommand) => void +} { + const linked = face.useConnectorAccounts(state => state.linked) const [busy, setBusy] = useState(false) // A second click before the re-render still finds the first call pending. const pending = useRef(false) @@ -55,11 +54,11 @@ function useAccountCommand( const { key } = entry switch (command.kind) { case 'start': - call(async () => { face.follow(key, await settle(face.remote.start(key, command.operation))) }) + call(async () => { face.follow(key, await face.start(key, command.operation)) }) return case 'cancel': { const operation = entry.operation - if (operation !== undefined) call(async () => { await settle(face.remote.cancel(key, operation.id)) }) + if (operation !== undefined) call(async () => { await face.cancel(key, operation.id) }) return } case 'open': @@ -69,7 +68,7 @@ function useAccountCommand( default: assertNever(command) } } - return { busy, run } + return { busy, linked, run } } /** Ask before an action that changes the account outside DSH; the dialog closes before it confirms. */ @@ -78,15 +77,16 @@ function Confirm(props: { readonly title: string readonly body: string readonly label: string + readonly disabled: boolean readonly onClose: () => void readonly onConfirm: () => void }): ReactNode { - const { t, title, body, label, onClose, onConfirm } = props + const { t, title, body, label, disabled, onClose, onConfirm } = props return ( - + }>

{body}

@@ -102,15 +102,15 @@ function Confirm(props: { export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode { const { useConnectorAccounts, account, resolveText, t } = props const entry = useConnectorAccounts(state => state.accounts.get(account)) - const linked = useConnectorAccounts(state => state.linked) - const { busy, run } = useAccountCommand(props) + const { busy, linked, run } = useAccountCommand(props) + const disabled = busy || !linked const [confirming, setConfirming] = useState() if (entry === undefined) return null 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 + return } const details = display.failure?.details ?? [] const confirm = confirming?.confirm @@ -141,7 +141,7 @@ export function ConnectorAccountSectionEntry(props: BundleFaceProps): ReactNode

{resolveText(entry.copy.hint)}

{confirming === undefined || confirm === undefined ? null : ( { setConfirming(undefined) }} onConfirm={() => { run(entry, confirming.command) }} /> + disabled={disabled} onClose={() => { setConfirming(undefined) }} onConfirm={() => { run(entry, confirming.command) }} /> )} ) @@ -178,7 +178,7 @@ export function ConnectorAccountActivationEntry( ): ReactNode { const { useConnectorAccounts, account, resolveText, onDismiss, onOpenDetails, t } = props const entry = useConnectorAccounts(state => state.accounts.get(account)) - const { run } = useAccountCommand(props) + const { linked, run } = useAccountCommand(props) const phase = entry?.display.phase useEffect(() => { if (phase === 'connected' || phase === 'unavailable') onDismiss() @@ -194,7 +194,7 @@ export function ConnectorAccountActivationEntry( - + }>

{resolveText(activation.body)}

diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts index 2c15e0ec09..d0e9f7cb05 100644 --- a/packages/client/ui-connector-account/src/client/index.ts +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -10,6 +10,7 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, } from './components.tsx' @@ -25,6 +26,13 @@ export type { /** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] +/** The value of a Remote call, or a rejection with the Host's message when the Host refused it. */ +async function settle(call: Promise>): Promise { + const result = await call + if (!result.ok) throw new Error(result.error.message) + return result.value +} + function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { const bundle = { ...face, account } const dispose = ctx.effect(function* () { @@ -45,11 +53,13 @@ function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: s */ export function apply(ctx: Context): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'connector-account: dictionaries') - const browser = new BrowserAccounts(ctx, ctx.remote.connectorAccounts) + const remote = ctx.remote.connectorAccounts + const browser = new BrowserAccounts(ctx, remote) ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') const face: ConnectorAccountFace = { hooks: { connectorAccounts: browser.state }, - remote: ctx.remote.connectorAccounts, + start: (key, operation) => settle(remote.start(key, operation)), + cancel: (key, id) => settle(remote.cancel(key, id)), resolveText: text => ctx.locale.resolveText(text), follow: (key, id) => { browser.follow(key, id) }, failed: () => { browser.failed() }, diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts index 482363c688..89a7a333b0 100644 --- a/packages/client/ui-connector-account/src/client/types.ts +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -28,8 +28,13 @@ export interface ConnectorAccountsRemote { /** The face every surface entry injects. */ export interface ConnectorAccountFace { hooks: { connectorAccounts: HostObservable } - /** The Remote the buttons call directly. */ - readonly remote: Pick + /** + * Start an operation of an account on the Host. Resolves to the operation the Host started, and rejects when the Host + * refuses or the call does not answer. + */ + readonly start: (key: string, operation: string) => Promise + /** Cancel an account's operation on the Host; rejects like `start`. */ + readonly cancel: (key: string, id: ConnectorOperationId) => Promise /** Pick the active language's entry of a registrant's text. */ readonly resolveText: (text: LocalizedText) => string /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ 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 d01ff8c3f2..6c6ad38b68 100644 --- a/packages/client/ui-connector-account/tests/apply.client.spec.ts +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -6,7 +6,7 @@ import assert from 'node:assert/strict' import { Context, Service } from '@deepseek-ai/cordis' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { expect, it, onTestFinished, vi } from 'vitest' import { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, @@ -21,7 +21,8 @@ const OTHER = '@acme/other' const OP = 'op-1' as ConnectorOperationId function isFace(value: Record): asserts value is Record & ConnectorAccountFace { - assert(typeof value.resolveText === 'function' && typeof value.follow === 'function' && typeof value.remote === 'object') + assert(typeof value.resolveText === 'function' && typeof value.follow === 'function') + assert(typeof value.start === 'function' && typeof value.cancel === 'function') assert(typeof value.hooks === 'object' && value.hooks !== null) } @@ -54,6 +55,7 @@ async function bench() { let wake: (() => void) | undefined, closed = false, accepted = 0 const closeStream = vi.fn(async () => { closed = true; wake?.() }) const start = vi.fn(async (_key: string, _operation: string): Promise> => ({ ok: true, value: OP })) + const cancel = vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ({ ok: true, value: undefined })) class Remote extends Service { constructor() { super(ctx, 'remote') } $stream() { @@ -71,7 +73,7 @@ async function bench() { } } new Remote() - ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel: vi.fn() }) + ctx.provide('remote.connectorAccounts', { watch: vi.fn(), start, cancel }) const locale = new LocaleRuntime(ctx) ctx.provide('locale', locale) await ctx.plugin(SlotRegistry) @@ -84,7 +86,7 @@ async function bench() { const bundles = (slot: 'plugins.bundle.config' | 'plugins.bundle.activation') => ctx.slots.entries(slot).map(item => [item.options.key, bundleFaceOf(item).account]) return { - ctx, locale, start, closeStream, bundles, + ctx, locale, start, cancel, closeStream, bundles, mount: () => ctx.plugin({ inject: [...inject], apply }), async publish(...entries: ConnectorAccountEntry[]) { const target = accepted + 1 @@ -124,8 +126,13 @@ it('shows one tag and one notice entry for the page and each bundle\'s section a expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') - await face.remote.start(FIXTURE, 'connect') + expect(await face.start(FIXTURE, 'connect')).toBe(OP) expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') + await face.cancel(FIXTURE, OP) + expect(b.cancel).toHaveBeenCalledWith(FIXTURE, OP) + // A refusal reaches the buttons as a rejection with the Host's message. + b.start.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } as never) + await expect(face.start(FIXTURE, 'connect')).rejects.toThrow('offline') face.follow(FIXTURE, OP) face.failed() expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) 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 25978b5ac3..222db693f6 100644 --- a/packages/client/ui-connector-account/tests/components.client.spec.tsx +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -1,10 +1,9 @@ // @vitest-environment jsdom -/** The slot entries 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 Host callbacks. */ 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' 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 { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, @@ -36,19 +35,14 @@ function entry(display: ConnectorAccountDisplay = DISCONNECTED, extra: Partial(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, notice: undefined, ...change, } return { useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), - remote: { - start: vi.fn(async (_key: string, _operation: string) => ok(OP)), - cancel: vi.fn(async (_key: string, _id: ConnectorOperationId): Promise> => ok(undefined)), - }, + start: vi.fn(async (_key: string, _operation: string) => OP), + cancel: vi.fn(async (_key: string, _id: ConnectorOperationId) => {}), account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, } } @@ -57,7 +51,7 @@ const sectionOf = (display: ConnectorAccountDisplay, change: Partial, 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 () => { +it('shows the registrant title, status, detail, notes, and hint, and starts each button\'s operation on the Host', async () => { const props = sectionOf({ ...DISCONNECTED, detail: '先关联一个应用。', notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], @@ -67,18 +61,18 @@ it('shows the registrant title, status, detail, notes, and hint, and starts each 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.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) + const answer = Promise.withResolvers() + props.start.mockReturnValueOnce(answer.promise) render() fireEvent.click(button('连接演示')) expect(disabled()).toEqual([true]) - await act(async () => { answer.resolve(ok(OP)) }) + await act(async () => { answer.resolve(OP) }) expect(disabled()).toEqual([false]) expect(props.failed).not.toHaveBeenCalled() cleanup() @@ -100,7 +94,28 @@ it('asks before a button that changes the account outside DSH and starts it only fireEvent.click(button('退出登录')) await click('确认退出') expect(screen.queryByRole('dialog')).toBeNull() - expect(props.remote.start.mock.calls).toEqual([[KEY, 'sign-out']]) + expect(props.start.mock.calls).toEqual([[KEY, 'sign-out']]) +}) + +it('disables an open confirmation and the activation prompt\'s Connect while the Host stream is down', () => { + const display: ConnectorAccountDisplay = { + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + } + const { rerender } = render() + fireEvent.click(button('退出登录')) + // The stream drops while the confirmation is open. + const down = sectionOf(display, { linked: false }) + rerender() + fireEvent.click(button('确认退出')) + expect((button('确认退出') as HTMLButtonElement).disabled).toBe(true) + expect(down.start).not.toHaveBeenCalled() + cleanup() + const offline = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }, { linked: false }) + render(prompt(offline)) + fireEvent.click(button('连接演示')) + expect((button('连接演示') as HTMLButtonElement).disabled).toBe(true) + expect(offline.start).not.toHaveBeenCalled() }) it.each<[string, ConnectorAccountDisplay['failure'], string]>([ @@ -112,9 +127,9 @@ it.each<[string, ConnectorAccountDisplay['failure'], string]>([ expect(screen.getByRole('alert').textContent).toBe(expected) }) -it('reports a start the Host refused or that never answered, without following it', async () => { +it('reports a start that the Host refused or that never answered, without following it', async () => { const props = face() - props.remote.start.mockResolvedValueOnce(refused()).mockRejectedValueOnce(new Error('carrier lost')) + props.start.mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce(new Error('carrier lost')) render() await click('连接演示') await click('连接演示') @@ -134,13 +149,13 @@ it('cancels the operation in progress and opens its authorization page again on fireEvent.click(button('打开授权页')) expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') await click('取消') - expect(props.remote.cancel).toHaveBeenCalledWith(KEY, OP) + expect(props.cancel).toHaveBeenCalledWith(KEY, OP) // A cancel button with no operation in progress calls nothing. cleanup() const idle = sectionOf(display) render() await click('取消') - expect(idle.remote.cancel).not.toHaveBeenCalled() + expect(idle.cancel).not.toHaveBeenCalled() }) it('renders nothing for a bundle whose account the Host has not listed', () => { @@ -191,23 +206,23 @@ it('connects from the prompt through the operation the display names, or only op const { rerender } = render(prompt(named, vi.fn(), onOpenDetails)) await click('连接演示') expect(onOpenDetails).toHaveBeenCalledOnce() - expect(named.remote.start).toHaveBeenCalledWith(KEY, 'link-app') + expect(named.start).toHaveBeenCalledWith(KEY, 'link-app') const bare = face() rerender(prompt(bare, vi.fn(), onOpenDetails)) fireEvent.click(button('连接演示')) expect(onOpenDetails).toHaveBeenCalledTimes(2) - expect(bare.remote.start).not.toHaveBeenCalled() + expect(bare.start).not.toHaveBeenCalled() }) it('starts once for a second click before the first call answers', async () => { const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) - const answer = Promise.withResolvers>() - props.remote.start.mockReturnValueOnce(answer.promise) + const answer = Promise.withResolvers() + props.start.mockReturnValueOnce(answer.promise) render(prompt(props)) fireEvent.click(button('连接演示')) fireEvent.click(button('连接演示')) - await act(async () => { answer.resolve(ok(OP)) }) - expect(props.remote.start).toHaveBeenCalledOnce() + await act(async () => { answer.resolve(OP) }) + expect(props.start).toHaveBeenCalledOnce() expect(props.follow).toHaveBeenCalledOnce() }) From df7a21330c4bb2d1af021c1eaeb4b2f860f26141 Mon Sep 17 00:00:00 2001 From: mektpoy Date: Fri, 13 Nov 2026 17:15:52 +0800 Subject: [PATCH 06/13] fix(client): keep draft attachments across session switches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 切到另一个会话再切回时,附件栏被清空而文字保留(#5070):会话 scope 销毁时 会释放退役输入框持有的全部附件并回收图片预览。 - ConversationController 记录每个草稿附件所属的会话;退役的输入框只在发送在途 或会话已删除时释放附件,其余情况保留登记,下一个输入框按顺序接回。 - 切走期间上传照常进行,失败的上传切回后仍可原位重试。 - 没有挂载输入框时被删除的会话,由 hub 的会话目录监听释放其附件。 - 刷新不恢复附件:pagehide 时为仍持有附件的会话写标记,重新挂载且没有已登记附件时 提示「部分草稿附件已失效,请重新添加」;往返缓存恢复时清除标记。 --- ...achments-across-session-switches.i18n.yaml | 19 ++ ...aft-attachments-across-session-switches.md | 25 ++ ...-attachments-across-session-switches.zh.md | 25 ++ .../draft-attachment-session-switch.e2e.ts | 99 +++++++ apps/web/tsconfig.json | 1 + .../client/ui-conversation/README.i18n.yaml | 8 +- packages/client/ui-conversation/README.md | 3 +- packages/client/ui-conversation/README.zh.md | 3 +- .../ui-conversation/src/client/input/hub.ts | 99 ++++++- .../ui-conversation/src/client/locales.ts | 8 + .../ui-conversation/src/client/service.ts | 58 ++++ .../draft-attachment-retention.client.spec.ts | 260 ++++++++++++++++++ .../service-orchestration.client.spec.ts | 9 +- tsconfig.host.json | 1 + 14 files changed, 608 insertions(+), 10 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml create mode 100644 .agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md create mode 100644 .agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md create mode 100644 apps/web/tests/draft-attachment-session-switch.e2e.ts create mode 100644 packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml new file mode 100644 index 0000000000..c3f436a8db --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-13-draft-attachments-across-session-switches.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md +/agent-note-draft-attachments-across-session-switches: + en: 2a1645c8c80d6dff + zh: 59277c3754231479 +/agent-note-draft-attachments-across-session-switches/problem: + en: 46a55e2fd42657ca + zh: da1033d096f2fa56 +/agent-note-draft-attachments-across-session-switches/decision: + en: 4fa08f8abfda5e6e + zh: 53775fc23322f1c0 +/agent-note-draft-attachments-across-session-switches/alternatives-considered: + en: 2c43ad479f4a3577 + zh: 07743f45870eb0fe +/agent-note-draft-attachments-across-session-switches/consequences: + en: 6ac6defa552ea040 + zh: aa64a3c3e54dbebc diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md new file mode 100644 index 0000000000..8fc611469c --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md @@ -0,0 +1,25 @@ +# Agent Note: Draft attachments across Session switches + +Status: implemented + +English | [中文](2026-11-13-draft-attachments-across-session-switches.zh.md) + +## Problem + +Switching to another Session and back emptied the composer's attachment rail while its text survived ([#5070](https://github.com/deepseek-harness/deepseek-harness/issues/5070)). The Session scope disposer released every attachment the retiring composer held and revoked image previews, and nothing could rebuild them. + +## Decision + +**The Conversation service keeps every draft attachment across a switch.** `ConversationController` records which Session owns each draft attachment. A retiring composer releases its attachments only when a send is still in flight or its Session was removed; otherwise they stay registered, an active upload keeps running, a failed upload keeps its in-place retry, and the Session's next composer re-adopts them in rail order. A Session removed while no composer is mounted releases its attachments through the hub's catalog watch. Picked and dropped files hold only a browser file handle; a pasted image keeps its bytes in memory until it is sent or removed or its Session is removed. + +**A reload reports discarded attachments instead of restoring them.** On `pagehide`, the input hub marks each Session that still owns draft attachments in browser storage; a back-forward cache restore clears the marks. A composer mounted with a mark and no registered attachments shows the "add them again" notice. + +## Alternatives considered + +**Restoring attachments after a reload from durable browser references and a Host `restore` Remote.** It would bring uploaded files and images back after a page reload, but it needs a Host Remote with its Liveshare and catalog classifications, a persisted browser format, a send gate during restoration, and an image byte payload. Desktop, where most users work, gains little: its Host binds a new port on every launch, so its storage origin, and with it every saved reference, does not survive an application restart. + +**Releasing settled attachments on a switch and restoring them from the Host on return.** It would save the memory of pasted images while a Session is not shown, but every return needs a Host round trip, fails on a weak network, and allocates the same bytes again. + +## Consequences + +Switching never touches the Host, so a weak network cannot lose a draft attachment there. A reload or crash still discards attachments; a crash writes no mark and so shows no notice. diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md new file mode 100644 index 0000000000..717f12a13e --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md @@ -0,0 +1,25 @@ +# Agent Note:草稿附件跨会话切换 + +Status: implemented + +[English](2026-11-13-draft-attachments-across-session-switches.md) | 中文 + +## 问题 + +切到另一个会话再切回时,输入框的附件栏被清空,文字却还在([#5070](https://github.com/deepseek-harness/deepseek-harness/issues/5070))。会话 scope 销毁时会释放退役输入框持有的全部附件并回收图片预览,之后没有任何途径能重建它们。 + +## 决策 + +**Conversation 服务在切换期间保留全部草稿附件。** `ConversationController` 记录每个草稿附件属于哪个会话。退役的输入框只在发送仍在途或其会话已被删除时释放附件;其他情况下附件继续登记,进行中的上传继续进行,失败的上传保留原位重试,会话下一次挂载的输入框按附件栏顺序接回它们。没有挂载输入框时被删除的会话,由 hub 的会话目录监听释放其附件。选择或拖入的文件只占一个浏览器文件句柄;粘贴的图片会把字节保留在内存中,直到发送、移除或其会话被删除。 + +**刷新时提示被丢弃的附件,而不恢复它们。** `pagehide` 时,输入 hub 在浏览器存储中为每个仍持有草稿附件的会话写一个标记;往返缓存恢复页面时清除这些标记。挂载时有标记且没有已登记附件的输入框,会显示「请重新添加」提示。 + +## 考虑过的替代方案 + +**刷新后通过浏览器 durable 引用与 Host `restore` Remote 恢复附件。** 它能在页面刷新后找回已上传的文件和图片,但需要新增一个 Host Remote 及其 Liveshare 与目录分类、一种浏览器持久化格式、恢复期间的发送拦截和图片字节载荷。主要用户所在的桌面端收益很小:桌面端 Host 每次启动都绑定新端口,存储 origin 连同所有已存引用都无法跨应用重启保留。 + +**切换时释放已结算附件,切回时由 Host 恢复。** 它能在会话不显示期间省下粘贴图片的内存,但每次切回都需要一次 Host 往返,弱网下会失败,并且之后还要再分配同样的字节。 + +## 影响 + +切换会话从不访问 Host,因此弱网不会让草稿附件在切换中丢失。刷新或崩溃仍会丢弃附件;崩溃时不会写标记,因此没有提示。 diff --git a/apps/web/tests/draft-attachment-session-switch.e2e.ts b/apps/web/tests/draft-attachment-session-switch.e2e.ts new file mode 100644 index 0000000000..3fff0f980b --- /dev/null +++ b/apps/web/tests/draft-attachment-session-switch.e2e.ts @@ -0,0 +1,99 @@ +// Web e2e scenario: a composer draft's pasted image survives a sidebar session +// switch. The reported defect spans the whole chain — sidebar row click, Session +// scope retirement, the input shell's teardown, and the rail's rebuild — so only +// the real composition can pin it. Units cover each link separately (hub/shell/ +// service specs); this covers the assembled path and the rail the user sees. +// +// Zero model calls: a seeded session is non-blank (so the sidebar can create a +// second one instead of reusing it) and the scenario never submits. +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { + launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const MODE = webSnapshotMode() +const SEED_ID = 'draft-attachment-switch-a' +const PEER_ID = 'draft-attachment-switch-b' +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url)) +const PNG = fileURLToPath(new URL('../../../snapshots/session/read-image/workspace/red.png', import.meta.url)) +const DRAFT_TEXT = 'draft text that survives the switch' + +/** The composer's pending-attachment rail, present only while it holds items. */ +const RAIL = '[role="group"][aria-label="Pending attachments"]' + +/** + * Paste one real PNG into the composer through a genuine clipboard event, the + * same intake a user's screenshot paste performs. + * @param page - page holding the composer. + * @param bytes - PNG bytes. + */ +async function pasteImage(page: Page, bytes: Uint8Array): Promise { + await page.locator('[data-composer-input]').first().evaluate((surface, data) => { + const transfer = new DataTransfer() + transfer.items.add(new File([new Uint8Array(data)], 'draft.png', { type: 'image/png' })) + surface.dispatchEvent(new ClipboardEvent('paste', { + clipboardData: transfer, bubbles: true, cancelable: true, + })) + }, [...bytes]) +} + +describe.skipIf(MODE === 'record')('web e2e: draft attachment across a session switch', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + const log = await readFile(FIXTURE, 'utf8') + await seedSession(scaffold, log, SEED_ID) + await seedSession(scaffold, log, PEER_ID) + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + // Expand the workspace group and open the seeded session. + const groupRow = page.locator('[role="treeitem"]').first() + await groupRow.waitFor({ timeout: 15_000 }) + await groupRow.click() + const sessionRow = page.locator(`[data-row-key="session:${SEED_ID}"]`) + await sessionRow.waitFor({ timeout: 15_000 }) + await sessionRow.click() + await page.locator('[data-composer-input]').first().waitFor({ timeout: 15_000 }) + }) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('keeps the pasted image and the typed draft when the sidebar leaves and returns', async () => { + onTestFailed(() => saveFailureShot(page, 'draft-attachment-session-switch')) + // (a) paste an image, then type text into the seeded session's composer. + await pasteImage(page, await readFile(PNG)) + await expect.poll(() => page.locator(`${RAIL} img`).count(), { timeout: 15_000 }).toBe(1) + await page.locator('[data-composer-input]').first().click() + await page.keyboard.type(DRAFT_TEXT, { delay: 5 }) + await expect.poll(() => page.locator(RAIL).locator('img').count(), { timeout: 10_000 }).toBe(1) + + // (b) leave through the sidebar: switching to another session retires this + // one's Session scope. + await page.locator(`[data-row-key="session:${PEER_ID}"]`).click() + await expect.poll(() => page.locator(RAIL).count(), { timeout: 15_000 }).toBe(0) + + // (c) return: the rebuilt composer must show the image AND the text. + await page.locator(`[data-row-key="session:${SEED_ID}"]`).click() + await expect.poll(() => page.locator(`${RAIL} img`).count(), { timeout: 15_000 }).toBe(1) + await expect.poll( + () => page.locator('[data-composer-input]').first().innerText(), + { timeout: 10_000 }, + ).toContain(DRAFT_TEXT) + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 4b9010be09..02033a002f 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -184,6 +184,7 @@ "tests/present-after-closing-reply.e2e.ts", "tests/autolink-cjk-punctuation.e2e.ts", "tests/composer-draft-scroll.e2e.ts", + "tests/draft-attachment-session-switch.e2e.ts", "tests/composer-focus.e2e.ts", "tests/composer-placeholder.e2e.ts", "tests/context-meter.e2e.ts", diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 83044eef74..89ea06d3e0 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: dcbdef97e4532896 - zh: 23d6840c89f66bab + en: 4919c08c24d2453b + zh: 45566252950a1ed1 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 @@ -42,8 +42,8 @@ en: f8621bbc481c26ae zh: 5be844989dc80803 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work: - en: c8323c1986c1be46 - zh: 6151492c67d4cb88 + en: c65789c64093eb47 + zh: b58cccbeea767849 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 24077e4a55..528c8e368c 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -100,7 +100,7 @@ The composer reads its Session's access answers through the Session-scope `useAc `SessionInputShell` owns one Lexical editor per Session through its private [DraftEditorRuntime](src/client/input/editor/runtime.ts), while retaining submission, attachment selection, and recovery decisions. [DraftEditor](src/client/input/editor/DraftEditor.tsx) renders the borrowed editor; InputBar retains its Hooks and refs and installs DOM behavior through [view-binding](src/client/input/editor/view-binding.ts). Editor-facing types live in [draft-editor.ts](src/client/contract/draft-editor.ts), with shared input and submission types in [input.ts](src/client/contract/input.ts). Background editor updates retain the draft selection without changing the document selection or reclaiming focus from another control; explicit Composer focus restores its selection. This separation does not support simultaneous editable roots for one Session; [the two-stage isolation proposal](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.md) defines the remaining work. -Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. +Drafts retain plain text and file, folder, and Session reference chips across Session switching and reload. Public input methods accept text; internal restoration and Workspace transfer preserve structured references. The input model imports saved content before its first published read; React only mounts that editor and binds the existing Conversation store writer. The original storage key accepts legacy strings and writes semantic snapshots without runtime node IDs. A pending skill catalog does not block editing: slash names remain ordinary text until a matching catalog entry arrives. Arrival rematches the current text without changing chips, selection, or Undo history. Browser-owned attachment File objects are not persisted by this mechanism; the Conversation service keeps them registered across Session switches, so a returning composer re-adopts them. The [draft initialization decision](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md) defines ownership and restoration. A claimed command is one atomic chip at the start of the draft, and the claim lasts exactly as long as that chip. Deleting the arguments and separator keeps the claim. At the chip's edge, the first Backspace or Delete selects the whole chip and the next one removes it and releases the claim, leaving the arguments as plain text; any other key, a click, or a caret move clears the selection. Text or a line break inserted before the chip turns it back into its literal token and releases the claim, and undo restores a deleted chip together with its claim. The persisted draft records the chip's token, so a reload rebuilds the chip once the command catalog resolves the claim; editing the draft first keeps the literal token, which Enter still submits as the command. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. @@ -225,6 +225,7 @@ Serialization of the empty retry message depends on the adapter. Prefix reuse de - **Factory occurrences inherit their render-position Session** — `conversation.content` does not accept an independently addressed Session; that requires a separate Session-provider capability. - **Manual continuation uses a fixed product allowlist** — the supported failure codes are independent of the provider's configurable `retryableCodes`; changing automatic retry policy does not expand or reduce this action. `STREAM_CLOSED` permits an explicit new user turn even when the default policy does not retry it. That code can also identify a protocol violation, so another request is not guaranteed to recover. - **Composer backdrop blur is verified only in Chromium** — with `will-change: transform` on the docked composer, descendant `backdrop-filter` still samples the transcript in Chromium; WebKit behavior has not been verified. +- **A reload discards draft attachments** — only switching between Sessions keeps them; after a reload the reopened composer reports the loss and asks the user to add them again, and a crash leaves no notice. While a Session is not shown, a pasted image keeps its bytes in memory ([decision](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md)). - **Document file drops are not routed** — every mounted attachment view handles a document-level file drop, so with a continuable subagent chat open in the right Sidebar one drop adds the files to both composers; only window pastes pass through the single paste route. - **A failing Definition costs a full replay per publication** — after an incremental flush fails, the assembler replays the complete loaded window to keep the views correct. A Definition that fails on every update therefore replays the whole window on each publication until its owner fixes it ([window update paths](../../../docs/subsystems/conversation.md#window-update-paths)). diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index a2d6b994cb..c43343c7be 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -100,7 +100,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 `SessionInputShell` 通过私有 [DraftEditorRuntime](src/client/input/editor/runtime.ts) 为每个 Session 持有一个 Lexical editor,同时保留提交、附件选择和恢复决策。[DraftEditor](src/client/input/editor/DraftEditor.tsx) 呈现借用的 editor;InputBar 保留钩子与 refs,并通过 [view-binding](src/client/input/editor/view-binding.ts) 安装 DOM 行为。编辑器类型位于 [draft-editor.ts](src/client/contract/draft-editor.ts),共享输入和提交类型位于 [input.ts](src/client/contract/input.ts)。编辑器后台更新会保留草稿选区,不修改文档选区或从其他控件夺回焦点;显式聚焦 Composer 时恢复其选区。这一拆分不支持同一 Session 同时挂载多个可编辑 root;[两阶段隔离提案](../../../.agents/notes/proposed/architecture/2026-09-14-composer-model-and-draft-editor.zh.md) 定义剩余工作。 -草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 +草稿中的普通文字及文件、目录、Session 引用胶囊在切换 Session 和刷新后保留。公开输入方法接受文本;内部恢复和工作区携带保留结构化引用。输入模型在首次对外读取前导入保存内容;React 只挂载同一编辑器并绑定现有 Conversation store 写入回调。原存储 key 兼容旧字符串,新写入保存不含运行时节点 ID 的语义快照。等待 skill 目录不会阻塞编辑:斜杠名称保持普通文字,直到匹配的目录项到达。目录到达只重匹配当前文字,不改变胶囊、选区或 Undo 历史。浏览器持有的附件 File 对象不由这一机制持久化;Conversation service 会在切换 Session 期间继续登记它们,切回的输入框会重新接回。[草稿初始化决策](../../../.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md)规定所有权与恢复流程。 已认领的命令是草稿开头的一个原子 chip,认领与该 chip 同生共灭。删除参数和分隔空格不影响认领。光标到达 chip 边缘时,第一次 Backspace 或 Delete 选中整个 chip,再按一次才删除它并释放认领,参数保留为普通文字;按其他键、点击或移动光标会取消选中。在 chip 前插入文字或换行会把它还原为字面 token 并释放认领,撤销会连同认领一起恢复被删除的 chip。持久化的草稿记录 chip 的 token,刷新后命令目录解析出认领即重建 chip;在此之前先编辑了草稿则保留字面 token,Enter 仍会把它作为命令提交。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 @@ -225,6 +225,7 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match - **Factory occurrence 继承渲染位置的 Session**——`conversation.content` 不接受独立寻址的 Session;该能力需要单独的 Session provider。 - **手动继续使用固定产品白名单**——支持的失败码独立于提供方可配置的 `retryableCodes`;修改自动重试策略不会扩展或缩小此操作的范围。即使默认策略不重试 `STREAM_CLOSED`,用户仍可明确发起新轮次。该错误码也可能表示协议违规,因此再次请求不保证能够恢复。 - **composer 内的毛玻璃只在 Chromium 中验证过**——docked composer 设置 `will-change: transform` 后,Chromium 中后代的 `backdrop-filter` 仍会采样背后的 transcript;WebKit 中的表现尚未验证。 +- **刷新会丢弃草稿附件**——只有在 Session 之间切换时附件才会保留;刷新后重新打开的输入框会提示丢失并请用户重新添加,崩溃时不会有提示。Session 未显示期间,粘贴的图片会把字节保留在内存中([决策](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md))。 - **文档级文件拖放未经路由**——每个已挂载的附件视图都会处理文档级文件拖放,因此在右侧栏打开可继续的子代理对话时,一次拖放会把文件同时加入两个 composer;只有窗口级粘贴经过单一的粘贴路由。 - **出错的 Definition 让每次发布都完整回放**——增量 flush 失败后,assembler 回放已加载的完整窗口,以保持视图正确。若某个 Definition 在每次更新中都失败,在其 owner 修复前,每次发布都会回放整个窗口([Window 更新路径](../../../docs/subsystems/conversation.zh.md#window-update-paths))。 diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index f6e9ce4183..32ed12258a 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -52,11 +52,41 @@ interface ConversationAttachmentFace { ): Promise serializeDraftAttachments(attachmentIds: readonly DraftAttachmentId[]): Promise releaseDraftAttachment(id: DraftAttachmentId): void + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] + draftAttachmentSessions(): readonly SessionId[] + releaseDraftSession(sessionId: SessionId): void +} + +/** Per-Session marker that a page unload discarded the draft's browser-owned attachments. */ +const UNLOAD_MARK_PREFIX = 'dsh.composer-draft-attachments-unloaded' + +/** Record that an unloading page held draft attachments for these Sessions. */ +function writeUnloadMarks(sessionIds: readonly SessionId[]): void { + try { + for (const sessionId of sessionIds) localStorage.setItem(`${UNLOAD_MARK_PREFIX}.${sessionId}`, '1') + } catch (error) { + console.error('conversation draft attachment unload marks could not be saved; a reload cannot report the loss', error) + } +} + +/** Remove one Session's unload marker. @returns whether the marker was present. */ +function takeUnloadMark(sessionId: SessionId): boolean { + try { + const key = `${UNLOAD_MARK_PREFIX}.${sessionId}` + const marked = localStorage.getItem(key) !== null + localStorage.removeItem(key) + return marked + } catch (error) { + console.error('conversation draft attachment unload mark could not be read', error) + return false + } } /** Session-addressed input facade registry (SessionInputResolver face + composer-layer extras). */ export class InputHub implements SessionInputResolver { private readonly shells = new WeakMap() + private knownSessionIds: Set | undefined + private lifecycleWatchInstalled = false /** * @param ctx - client root context (services resolved lazily per call — boot order stays free). @@ -168,10 +198,22 @@ export class InputHub implements SessionInputResolver { ] return () => { for (const off of offs) off() + // Snapshot the phase before dispose resets the machine. + const phaseAtTeardown = shell.snapshot.phase const drafts = shell.dispose() this.shells.delete(binding) const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined - for (const attachmentId of drafts) conversation?.releaseDraftAttachment(attachmentId) + if (conversation === undefined) return + if (binding.session.getSnapshot().removed) { + conversation.releaseDraftSession(binding.sessionId) + return + } + // A send caught before its echo retires cannot settle through the retirement path, + // so its attachments release here; every other draft attachment stays registered + // for the Session's next composer. + if (phaseAtTeardown !== 'plain' && phaseAtTeardown !== 'claimed') { + for (const attachmentId of drafts) conversation.releaseDraftAttachment(attachmentId) + } } }, 'conversation.input: session shell') actx.inject(['inputTriggers'], (scope) => { @@ -181,9 +223,64 @@ export class InputHub implements SessionInputResolver { }, 'conversation.input: reference catalogs') }) shell.setDraft(readConversationDraft(binding.sessionId)) + this.ensureLifecycleWatch() + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const retained = conversation?.draftAttachmentIds(binding.sessionId) ?? [] + // A Session switch keeps the draft's attachments registered; this composer re-adopts them. + if (retained.length > 0) shell.addAttachments(retained) + // A reload discarded the browser-owned attachments; say so instead of dropping them silently. + if (takeUnloadMark(binding.sessionId) && retained.length === 0) shell.notify('error', this.t('attachments.unavailable')) return shell } + /** + * Install the root-lifetime watchers once: a Session removed while no composer + * is mounted releases its draft attachments, and an unloading page marks the + * Sessions whose attachments it discards. + */ + private ensureLifecycleWatch(): void { + if (this.lifecycleWatchInstalled) return + this.lifecycleWatchInstalled = true + const sessions = this.sessions() + this.knownSessionIds = new Set(sessions.list.getSnapshot().ids) + this.rootCtx.effect(() => { + const stop = sessions.list.subscribe(() => { this.cleanupRemovedSessions() }) + const conversation = (): ConversationAttachmentFace | undefined => + this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + const onHide = (): void => { writeUnloadMarks(conversation()?.draftAttachmentSessions() ?? []) } + // A back-forward cache restore keeps the registry, so the marks just written are stale. + const onShow = (event: PageTransitionEvent): void => { + if (!event.persisted) return + for (const sessionId of conversation()?.draftAttachmentSessions() ?? []) takeUnloadMark(sessionId) + } + window.addEventListener('pagehide', onHide) + window.addEventListener('pageshow', onShow) + return () => { + stop() + window.removeEventListener('pagehide', onHide) + window.removeEventListener('pageshow', onShow) + this.knownSessionIds = undefined + this.lifecycleWatchInstalled = false + } + }, 'conversation.input: draft attachment lifecycle') + } + + /** Release draft attachments and unload marks for every Session removed from the catalog. */ + private cleanupRemovedSessions(): void { + const known = this.knownSessionIds + /* v8 ignore next -- the catalog subscription is stopped before the known set is cleared. */ + if (known === undefined) return + const liveIds = new Set(this.sessions().list.getSnapshot().ids) + const conversation = this.rootCtx.get('conversation') as ConversationAttachmentFace | undefined + for (const id of [...known]) { + if (liveIds.has(id)) continue + known.delete(id) + conversation?.releaseDraftSession(id) + takeUnloadMark(id) + } + for (const id of liveIds) known.add(id) + } + /** * Resident shell by session id (service-face path; the provide channel has * normally created it already — this covers direct id-addressed access). diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 192446b712..2186b0e80c 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -41,6 +41,7 @@ export const zh = { 'attachment.pathUnavailable': '无法获取文件夹路径,请重新拖入', 'attachment.pathUnsupported': '路径含有无法引用的字符,请改名后再试', 'image.pending': '待发送图片', + 'attachments.unavailable': '部分草稿附件已失效,请重新添加', 'image.openOriginal': '查看原图', 'image.openOriginalLabel': '{label},点击查看原图', 'image.remove': '移除图片 {name}', @@ -447,6 +448,7 @@ export const en = { 'attachment.pathUnavailable': 'Could not obtain the folder path; drag it in again', 'attachment.pathUnsupported': 'The path contains characters a reference cannot carry; rename it and try again', 'image.pending': 'Pending images', + 'attachments.unavailable': 'Some draft attachments are no longer available; add them again', 'image.openOriginal': 'View original', 'image.openOriginalLabel': '{label}, click to view original', 'image.remove': 'Remove image {name}', @@ -852,6 +854,7 @@ export const ja = { 'attachment.pathUnavailable': 'フォルダのパスを取得できませんでした。もう一度ドラッグしてください', 'attachment.pathUnsupported': 'パスに参照できない文字が含まれています。名前を変更して再試行してください', 'image.pending': '保留中の画像', + 'attachments.unavailable': '一部の下書き添付ファイルは利用できなくなりました。再度追加してください', 'image.openOriginal': '元の画像を表示', 'image.openOriginalLabel': '{label}、クリックで元の画像を表示', 'image.remove': '画像{name}を削除', @@ -1255,6 +1258,7 @@ export const es = { 'attachment.pathUnavailable': 'No se pudo obtener la ruta de la carpeta; arrástralo de nuevo', 'attachment.pathUnsupported': 'La ruta contiene caracteres que una referencia no puede contener; cámbiale el nombre y vuelve a intentarlo.', 'image.pending': 'Imágenes pendientes', + 'attachments.unavailable': 'Algunos adjuntos del borrador ya no están disponibles; vuelve a añadirlos', 'image.openOriginal': 'Ver original', 'image.openOriginalLabel': '{label}, haga clic para ver el original', 'image.remove': 'Eliminar imagen {name}', @@ -1660,6 +1664,7 @@ export const fr = { 'attachment.pathUnavailable': "Impossible d'obtenir le chemin du dossier ; fais-le glisser à nouveau", 'attachment.pathUnsupported': "Le chemin contient des caractères qu'une référence ne peut pas transporter ; renommez-le et réessayez", 'image.pending': 'Images en attente', + 'attachments.unavailable': 'Certaines pièces jointes du brouillon ne sont plus disponibles ; ajoutez-les à nouveau', 'image.openOriginal': "Voir l'original", 'image.openOriginalLabel': "{label}, cliquez pour voir l'original", 'image.remove': "Supprimer l'image {name}", @@ -2065,6 +2070,7 @@ export const de = { 'attachment.pathUnavailable': 'Der Ordnerpfad konnte nicht abgerufen werden; Ziehen Sie es erneut hinein', 'attachment.pathUnsupported': 'Der Pfad enthält Zeichen, die eine Referenz nicht enthalten kann; Benennen Sie es um und versuchen Sie es erneut', 'image.pending': 'Ausstehende Bilder', + 'attachments.unavailable': 'Einige Entwurfsanhänge sind nicht mehr verfügbar; füge sie erneut hinzu', 'image.openOriginal': 'Original ansehen', 'image.openOriginalLabel': '{label}, klicken Sie, um das Original anzuzeigen', 'image.remove': 'Bild {name} entfernen', @@ -2470,6 +2476,7 @@ export const ru = { 'attachment.pathUnavailable': 'Не удалось получить путь к папке; перетащите это снова', 'attachment.pathUnsupported': 'Путь содержит символы, которые не может содержать ссылка; переименуй его и попробуй еще раз', 'image.pending': 'Ожидающие изображения', + 'attachments.unavailable': 'Некоторые вложения черновика больше недоступны; добавьте их снова', 'image.openOriginal': 'Посмотреть оригинал', 'image.openOriginalLabel': '{label}, нажмите, чтобы посмотреть оригинал', 'image.remove': 'Удалить изображение {name}', @@ -2875,6 +2882,7 @@ export const pt = { 'attachment.pathUnavailable': 'Não foi possível obter o caminho da pasta; arraste-o novamente', 'attachment.pathUnsupported': 'O caminho contém caracteres que uma referência não pode transportar; renomeie-o e tente novamente', 'image.pending': 'Imagens pendentes', + 'attachments.unavailable': 'Alguns anexos do rascunho não estão mais disponíveis; adicione-os novamente', 'image.openOriginal': 'Ver original', 'image.openOriginalLabel': '{label}, clique para ver o original', 'image.remove': 'Remover imagem {name}', diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index 27cae036db..e9030433be 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -158,6 +158,10 @@ export class ConversationController extends Service implements IConversation { /** Live upload state per draft that uploads when added: every file draft and every uploaded image draft. */ readonly fileUploads: SnapshotStore> = createSnapshotStore>({}) private readonly draftAttachments = new Map() + /** Draft attachment ids per owning Session; they outlive that Session's composer so a return re-adopts them. */ + private readonly sessionDraftIds = new Map>() + /** Reverse ownership lookup for release and Workspace rebinding. */ + private readonly draftAttachmentSession = new Map() private readonly fileUploadOperations = new Map @@ -196,6 +200,8 @@ export class ConversationController extends Service implements IConversation { if (attachment.kind === 'image') revokePreview(attachment.previewUrl) } this.draftAttachments.clear() + this.sessionDraftIds.clear() + this.draftAttachmentSession.clear() this.fileUploads.set({}) }, 'conversation draft attachments') } @@ -332,6 +338,7 @@ export class ConversationController extends Service implements IConversation { if (isImageMediaType(file.type)) { const attachment = browserDraftAttachment(file) this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) probeDimensions(attachment) if (uploadImages) this.beginFileUpload(sessionId, attachment) return attachment @@ -342,6 +349,7 @@ export class ConversationController extends Service implements IConversation { file, } this.draftAttachments.set(attachment.id, attachment) + this.ownDraftAttachment(sessionId, attachment.id) this.beginFileUpload(sessionId, attachment) return attachment }) @@ -369,6 +377,7 @@ export class ConversationController extends Service implements IConversation { for (const id of ids) { const attachment = this.draftAttachments.get(id) if (attachment === undefined) continue + this.ownDraftAttachment(sessionId, id) if (attachment.kind === 'image' && !uploadImages) this.dropUpload(id) else this.beginFileUpload(sessionId, attachment) } @@ -504,11 +513,59 @@ export class ConversationController extends Service implements IConversation { const attachment = this.draftAttachments.get(id) if (attachment === undefined) return this.draftAttachments.delete(id) + this.forgetDraftAttachment(id) if (attachment.kind === 'image') revokePreview(attachment.previewUrl) // The stored Host object stays durable; only the draft's upload state ends. this.dropUpload(id) } + /** + * Draft attachment ids a Session still owns after its composer retired. + * @param sessionId - owning Session identity. + * @returns registered ids in registration order. + */ + draftAttachmentIds(sessionId: SessionId): readonly DraftAttachmentId[] { + return [...this.sessionDraftIds.get(sessionId) ?? []] + } + + /** + * Sessions that still own registered draft attachments. + * @returns Session identities with at least one registered attachment. + */ + draftAttachmentSessions(): readonly SessionId[] { + return [...this.sessionDraftIds.keys()] + } + + /** + * Release every draft attachment one removed Session owns. + * @param sessionId - removed Session identity. + */ + releaseDraftSession(sessionId: SessionId): void { + for (const id of this.draftAttachmentIds(sessionId)) this.releaseDraftAttachment(id) + } + + /** Record, or move after a Workspace rebind, one draft attachment's owning Session. */ + private ownDraftAttachment(sessionId: SessionId, id: DraftAttachmentId): void { + this.forgetDraftAttachment(id) + this.draftAttachmentSession.set(id, sessionId) + let ids = this.sessionDraftIds.get(sessionId) + if (ids === undefined) { + ids = new Set() + this.sessionDraftIds.set(sessionId, ids) + } + ids.add(id) + } + + /** Forget one draft attachment's owning Session. */ + private forgetDraftAttachment(id: DraftAttachmentId): void { + const sessionId = this.draftAttachmentSession.get(id) + if (sessionId === undefined) return + this.draftAttachmentSession.delete(id) + const ids = this.sessionDraftIds.get(sessionId) + ids?.delete(id) + if (ids?.size === 0) this.sessionDraftIds.delete(sessionId) + } + /** Abort one draft's active upload and drop its upload state. */ private dropUpload(id: DraftAttachmentId): void { const operation = this.fileUploadOperations.get(id) @@ -605,6 +662,7 @@ export class ConversationController extends Service implements IConversation { continue } this.draftAttachments.delete(attachment.id) + this.forgetDraftAttachment(attachment.id) this.forgetUpload(attachment.id) if (ref !== undefined && 'mediaType' in ref && uiConversation?.seedImageUrl(sessionId, ref, attachment.previewUrl) === true) continue diff --git a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts new file mode 100644 index 0000000000..787ead89af --- /dev/null +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -0,0 +1,260 @@ +// @vitest-environment jsdom +// Draft attachments outlive their Session's composer: a switch keeps them registered, +// a removed Session releases them, and a page unload reports what it discarded. +import { AttachmentId } from '@deepseek-ai/dsh-attachment' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { FileUploadValue } from '@deepseek-ai/dsh-client-file-upload/client' +import { makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ComposerBlockRegistry } from '../src/client/input/blocks.ts' +import { InputHub } from '../src/client/input/hub.ts' +import { ConversationController } from '../src/client/service.ts' +import { zh } from '../src/client/locales.ts' + +const SESSION = 's1' +const UNLOAD_MARK = `dsh.composer-draft-attachments-unloaded.${SESSION}` + +function sessionId(): SessionId { + return brandString(SESSION) +} + +function uploadValue(name: string): FileUploadValue { + return { + receiptId: brandString(`receipt-${name}`), + file: { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), name, bytes: 3 }, + } +} + +interface UploadBehavior { + uploadFile?: (...input: unknown[]) => Promise +} + +/** One retained Session with the production Conversation service and its input hub. */ +async function bench(prepare?: () => void) { + const runtime = await SlotTestRuntime.create() + const upload = vi.fn((id: SessionId, ...args: unknown[]) => { + const behavior = runtime.sessions.behavior(id) as UploadBehavior + if (behavior.uploadFile === undefined) throw new Error('test file upload has no Session override') + return behavior.uploadFile(...args) + }) + runtime.fileUpload.upload = upload + runtime.fileUpload.uploadImage = vi.fn(() => Promise.resolve({ ok: true as const, value: { + receiptId: brandString('receipt-image'), + image: { attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1 }, + } })) + await runtime.sessions.add({ + id: SESSION, + session: { + prompt: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + updateQueue: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + cancel: vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })), + loadOlder: vi.fn(() => Promise.resolve()), + }, + }) + prepare?.() + let reference = runtime.sessions.retain(sessionId()) + await reference.ready + const hub = new InputHub(runtime.ctx, makeTranslate(zh, {})) + await runtime.ctx.plugin(ConversationController, { + input: hub, + blocks: new ComposerBlockRegistry(), + maxConcurrentFileUploads: 2, + }).await() + const root = runtime.ctx.get('conversation') as ConversationController + const shellNow = () => hub.shellFor(runtime.sessions.binding(SESSION)!) + const shell = shellNow() + const behavior = () => runtime.sessions.behavior(SESSION) as UploadBehavior + /** Retire the Session's composer, as a switch to another Session does. */ + const switchAway = async (): Promise => { + reference.release() + await runtime.flush() + expect(runtime.sessions.binding(SESSION)).toBeUndefined() + } + /** Mount a fresh composer for the Session again. */ + const switchBack = async () => { + reference = runtime.sessions.retain(sessionId()) + await reference.ready + return shellNow() + } + return { runtime, hub, root, shell, upload, behavior, switchAway, switchBack } +} + +function draftFile(name = 'notes.txt'): File { + return new File([new Uint8Array([1, 2, 3])], name, { type: 'text/plain' }) +} + +beforeEach(() => { localStorage.clear() }) +afterEach(() => { vi.restoreAllMocks() }) + +describe('draft attachments across a Session switch', () => { + it('re-adopts settled files and images without uploading them again', async () => { + const b = await bench() + const revoked = vi.spyOn(URL, 'revokeObjectURL') + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const drafts = b.root.createDrafts(sessionId(), [draftFile(), new File([Uint8Array.of(9)], 'pic.png', { type: 'image/png' })], true) + expect(b.shell.addAttachments(drafts.map(draft => draft.id))).toBe(true) + await vi.waitFor(() => { + for (const draft of drafts) expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') + }) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual(drafts.map(draft => draft.id)) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual(drafts.map(draft => draft.id)) + expect(b.root.resolveDraftAttachments(back.snapshot.attachmentIds)).toEqual(drafts) + expect(b.upload).toHaveBeenCalledOnce() + expect(revoked).not.toHaveBeenCalled() + expect(back.notices.getSnapshot()).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps an upload running while the Session is switched away', async () => { + const b = await bench() + try { + let finish!: (value: unknown) => void + b.behavior().uploadFile = vi.fn((...args: unknown[]) => new Promise((resolve) => { + finish = resolve + ;(args[2] as AbortSignal).addEventListener('abort', () => { resolve({ ok: false, error: new Error('aborted') }) }) + })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('uploading') }) + await b.switchAway() + finish({ ok: true, value: uploadValue('big.bin') }) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(b.upload).toHaveBeenCalledOnce() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps a failed upload so it can be retried in place after returning', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.reject(new Error('network lost'))) + const [draft] = b.root.createDrafts(sessionId(), [draftFile('big.bin')], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('error') }) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('big.bin') })) + b.root.retryFileUpload(sessionId(), draft.id) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('removed Sessions', () => { + it('releases the draft attachments of a Session removed while no composer is mounted', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.switchAway() + localStorage.setItem(UNLOAD_MARK, '1') + await b.runtime.sessions.remove(SESSION) + await vi.waitFor(() => { expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) }) + expect(b.root.resolveDraftAttachments([draft.id])).toEqual([]) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('releases the draft attachments when the mounted composer of a removed Session retires', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await b.runtime.sessions.remove(SESSION) + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) +}) + +describe('page unload report', () => { + it('marks Sessions whose attachments an unload discards, and reports them on the next page', async () => { + const first = await bench() + try { + first.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = first.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + first.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + } finally { + await first.runtime.dispose() + } + // A reload starts with an empty registry; the saved mark survives in browser storage. + const second = await bench(() => { localStorage.setItem(UNLOAD_MARK, '1') }) + try { + expect(second.shell.notices.getSnapshot()).toMatchObject({ level: 'error', text: zh['attachments.unavailable'] }) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await second.runtime.dispose() + } + }) + + it('does not report attachments a switch kept, and drops marks a back-forward restore made stale', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + window.dispatchEvent(new Event('pagehide')) + const restore = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(restore, 'persisted', { value: false }) + window.dispatchEvent(restore) + expect(localStorage.getItem(UNLOAD_MARK)).toBe('1') + const cached = new Event('pageshow') as PageTransitionEvent + Object.defineProperty(cached, 'persisted', { value: true }) + window.dispatchEvent(cached) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + localStorage.setItem(UNLOAD_MARK, '1') + await b.switchAway() + const back = await b.switchBack() + expect(back.notices.getSnapshot()).toBeNull() + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + } finally { + await b.runtime.dispose() + } + }) + + it('keeps working when browser storage refuses the marks', async () => { + const b = await bench() + const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('quota') }) + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') }) + window.dispatchEvent(new Event('pagehide')) + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + expect(errors).toHaveBeenCalledTimes(2) + } finally { + await b.runtime.dispose() + } + }) +}) diff --git a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts index e29bf0a8e0..9b93ef4240 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.client.spec.ts @@ -138,7 +138,7 @@ describe('ConversationController', () => { await b.runtime.dispose() }) - it('releases draft previews when their session scope is disposed', async () => { + it('keeps draft previews registered when their session scope is disposed and re-adopts them on return', async () => { const b = await bench() const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:draft-1') const revoked = vi.spyOn(URL, 'revokeObjectURL').mockReturnValue(undefined) @@ -150,8 +150,11 @@ describe('ConversationController', () => { b.root.input.for(b.runtime.sessions.scope('s1')!).addAttachments([attachment.id]) b.reference.release() await b.runtime.flush() - expect(b.root.resolveDraftAttachments([attachment.id])).toEqual([]) - expect(revoked).toHaveBeenCalledWith('blob:draft-1') + expect(b.root.resolveDraftAttachments([attachment.id])).toEqual([attachment]) + expect(revoked).not.toHaveBeenCalled() + const again = b.runtime.sessions.retain('s1' as SessionId) + await again.ready + expect(b.hub.shellFor(b.runtime.sessions.binding('s1')!).snapshot.attachmentIds).toEqual([attachment.id]) } finally { created.mockRestore() revoked.mockRestore() diff --git a/tsconfig.host.json b/tsconfig.host.json index 7e17a942fe..7c78b91ca4 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -173,6 +173,7 @@ "apps/web/tests/present-after-closing-reply.e2e.ts", "apps/web/tests/autolink-cjk-punctuation.e2e.ts", "apps/web/tests/composer-draft-scroll.e2e.ts", + "apps/web/tests/draft-attachment-session-switch.e2e.ts", "apps/web/tests/composer-focus.e2e.ts", "apps/web/tests/composer-placeholder.e2e.ts", "apps/web/tests/context-meter.e2e.ts", From 65543a5f87af53f63a5a16f37dd08b36b93d83e2 Mon Sep 17 00:00:00 2001 From: mektpoy Date: Fri, 13 Nov 2026 18:21:49 +0800 Subject: [PATCH 07/13] fix(client): release only submitted draft attachments on composer teardown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Host 接受消息后,附件立即退出会话归属,注册表仍保留到回显结算; 切回不再把已发出的附件放回输入框,刷新标记也不再误报。 - 输入框退役时只在「消息或命令已经提交」时释放附件;被中止的斜杠行裁决 不会发出消息,附件随草稿保留。 --- ...achments-across-session-switches.i18n.yaml | 4 +- ...aft-attachments-across-session-switches.md | 2 +- ...-attachments-across-session-switches.zh.md | 2 +- .../ui-conversation/src/client/input/hub.ts | 10 ++-- .../ui-conversation/src/client/service.ts | 7 +++ .../draft-attachment-retention.client.spec.ts | 52 +++++++++++++++++++ 6 files changed, 69 insertions(+), 8 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml index c3f436a8db..55d53c8e35 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml @@ -9,8 +9,8 @@ en: 46a55e2fd42657ca zh: da1033d096f2fa56 /agent-note-draft-attachments-across-session-switches/decision: - en: 4fa08f8abfda5e6e - zh: 53775fc23322f1c0 + en: 40697e88c2ed6ca8 + zh: eeb363374b25c3a2 /agent-note-draft-attachments-across-session-switches/alternatives-considered: en: 2c43ad479f4a3577 zh: 07743f45870eb0fe diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md index 8fc611469c..1d4ffc7c51 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md @@ -10,7 +10,7 @@ Switching to another Session and back emptied the composer's attachment rail whi ## Decision -**The Conversation service keeps every draft attachment across a switch.** `ConversationController` records which Session owns each draft attachment. A retiring composer releases its attachments only when a send is still in flight or its Session was removed; otherwise they stay registered, an active upload keeps running, a failed upload keeps its in-place retry, and the Session's next composer re-adopts them in rail order. A Session removed while no composer is mounted releases its attachments through the hub's catalog watch. Picked and dropped files hold only a browser file handle; a pasted image keeps its bytes in memory until it is sent or removed or its Session is removed. +**The Conversation service keeps every draft attachment across a switch.** `ConversationController` records which Session owns each draft attachment. A message the Host accepts leaves that ownership at once, while the registry keeps its attachments until the echo settles them. A retiring composer releases its attachments only when its Session was removed or a message or command was already submitted, because the Client cannot tell whether a submitted command consumed them; an aborted slash-line adjudication keeps them. Otherwise they stay registered, an active upload keeps running, a failed upload keeps its in-place retry, and the Session's next composer re-adopts them in rail order. A Session removed while no composer is mounted releases its attachments through the hub's catalog watch. Picked and dropped files hold only a browser file handle; a pasted image keeps its bytes in memory until it is sent or removed or its Session is removed. **A reload reports discarded attachments instead of restoring them.** On `pagehide`, the input hub marks each Session that still owns draft attachments in browser storage; a back-forward cache restore clears the marks. A composer mounted with a mark and no registered attachments shows the "add them again" notice. diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md index 717f12a13e..5f29991227 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -**Conversation 服务在切换期间保留全部草稿附件。** `ConversationController` 记录每个草稿附件属于哪个会话。退役的输入框只在发送仍在途或其会话已被删除时释放附件;其他情况下附件继续登记,进行中的上传继续进行,失败的上传保留原位重试,会话下一次挂载的输入框按附件栏顺序接回它们。没有挂载输入框时被删除的会话,由 hub 的会话目录监听释放其附件。选择或拖入的文件只占一个浏览器文件句柄;粘贴的图片会把字节保留在内存中,直到发送、移除或其会话被删除。 +**Conversation 服务在切换期间保留全部草稿附件。** `ConversationController` 记录每个草稿附件属于哪个会话。Host 接受消息时,这些附件立即退出会话归属,注册表则保留它们直到回显结算。退役的输入框只在其会话已被删除、或消息与命令已经提交时释放附件,因为客户端无法判断已提交的命令是否用掉了附件;被中止的斜杠行裁决会保留附件。其他情况下附件继续登记,进行中的上传继续进行,失败的上传保留原位重试,会话下一次挂载的输入框按附件栏顺序接回它们。没有挂载输入框时被删除的会话,由 hub 的会话目录监听释放其附件。选择或拖入的文件只占一个浏览器文件句柄;粘贴的图片会把字节保留在内存中,直到发送、移除或其会话被删除。 **刷新时提示被丢弃的附件,而不恢复它们。** `pagehide` 时,输入 hub 在浏览器存储中为每个仍持有草稿附件的会话写一个标记;往返缓存恢复页面时清除这些标记。挂载时有标记且没有已登记附件的输入框,会显示「请重新添加」提示。 diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index 32ed12258a..8944d91981 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -208,10 +208,12 @@ export class InputHub implements SessionInputResolver { conversation.releaseDraftSession(binding.sessionId) return } - // A send caught before its echo retires cannot settle through the retirement path, - // so its attachments release here; every other draft attachment stays registered - // for the Session's next composer. - if (phaseAtTeardown !== 'plain' && phaseAtTeardown !== 'claimed') { + // Teardown aborts adjudication before any message leaves, so those attachments stay with the draft. + // A message or command already submitted cannot settle through its retirement path after teardown, + // and the Client cannot tell whether a submitted command consumed its attachments, so both release + // here rather than risk a duplicate submission; every other draft attachment stays registered for + // the Session's next composer. + if (phaseAtTeardown === 'sending' || phaseAtTeardown === 'submitting') { for (const attachmentId of drafts) conversation.releaseDraftAttachment(attachmentId) } } diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index e9030433be..98454ba0f0 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -285,6 +285,11 @@ export class ConversationController extends Service implements IConversation { ) // The composer owns the attachments until the Host accepts the prompt. const ownership = { accepted: false, retiredUnobserved: false } + // An accepted message's attachments leave the draft: a later composer must not re-adopt them, while + // the registry keeps them until the echo settles their previews or an unobserved retirement releases them. + const disownAccepted = (): void => { + for (const attachment of attachments) this.forgetDraftAttachment(attachment.id) + } const acceptance = Promise.withResolvers() const submission = session.beginSubmission({ mode, @@ -292,6 +297,7 @@ export class ConversationController extends Service implements IConversation { attachments: pendingAttachments, onAccept: () => { ownership.accepted = true + disownAccepted() accept?.() acceptance.resolve(undefined) }, @@ -315,6 +321,7 @@ export class ConversationController extends Service implements IConversation { const result = await Promise.race([session.prompt(content, mode, signal, submission.requestId), acceptance.promise]) if (result !== undefined && !result.ok) return { kind: 'error' } ownership.accepted = true + disownAccepted() // An accepted prompt whose echo already retired unobserved, as when its queue entry was removed. if (ownership.retiredUnobserved) this.releaseDraftAttachments(attachments) return { kind: 'success' } diff --git a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts index 787ead89af..f758d2def7 100644 --- a/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts +++ b/packages/client/ui-conversation/tests/draft-attachment-retention.client.spec.ts @@ -258,3 +258,55 @@ describe('page unload report', () => { } }) }) + +describe('submitted attachments', () => { + it('does not re-adopt or report attachments of an accepted message whose echo has not retired', async () => { + const b = await bench() + try { + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft.id]?.status).toBe('ready') }) + b.shell.setDraft('send with file') + b.shell.submit('queue', 'click') + await vi.waitFor(() => { expect(b.shell.snapshot.phase).toBe('plain') }) + await b.runtime.flush() + // The registry still holds the attachment for the echo; the draft no longer owns it. + expect(b.root.resolveDraftAttachments([draft.id])).toHaveLength(1) + expect(b.root.draftAttachmentIds(sessionId())).toEqual([]) + expect(b.root.draftAttachmentSessions()).toEqual([]) + window.dispatchEvent(new Event('pagehide')) + expect(localStorage.getItem(UNLOAD_MARK)).toBeNull() + await b.switchAway() + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([]) + } finally { + await b.runtime.dispose() + } + }) + + it('keeps the attachments of a slash line whose adjudication a switch aborted', async () => { + const adjudicate = vi.fn(() => new Promise(() => undefined)) + const b = await bench() + try { + const lexicon = { getSnapshot: () => new Map<'/' | '@', readonly string[]>(), subscribe: () => () => undefined } + const triggers = { adjudicate, lexicon, track: vi.fn() } + b.runtime.ctx.provide('inputTriggers', { sessionOf: () => triggers } as never) + b.behavior().uploadFile = vi.fn(() => Promise.resolve({ ok: true, value: uploadValue('notes.txt') })) + const [draft] = b.root.createDrafts(sessionId(), [draftFile()], true) + if (draft === undefined) throw new Error('draft missing') + b.shell.addAttachments([draft.id]) + b.shell.setDraft('/review this file') + b.shell.submit('queue', 'enter') + expect(b.shell.snapshot.phase).toBe('adjudicating') + expect(adjudicate).toHaveBeenCalledOnce() + await b.switchAway() + expect(b.root.draftAttachmentIds(sessionId())).toEqual([draft.id]) + const back = await b.switchBack() + expect(back.snapshot.attachmentIds).toEqual([draft.id]) + } finally { + await b.runtime.dispose() + } + }) +}) From 89ee384d4b30db121a3e21f8354579cff815c277 Mon Sep 17 00:00:00 2001 From: mektpoy Date: Fri, 13 Nov 2026 18:25:28 +0800 Subject: [PATCH 08/13] docs(notes): cite issue #5070 as plain text in the draft attachment note --- ...-11-13-draft-attachments-across-session-switches.i18n.yaml | 4 ++-- .../2026-11-13-draft-attachments-across-session-switches.md | 2 +- ...2026-11-13-draft-attachments-across-session-switches.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml index 55d53c8e35..db0702f47e 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.i18n.yaml @@ -6,8 +6,8 @@ en: 2a1645c8c80d6dff zh: 59277c3754231479 /agent-note-draft-attachments-across-session-switches/problem: - en: 46a55e2fd42657ca - zh: da1033d096f2fa56 + en: 3f4030763e1f0105 + zh: c8a0bc5641d7bed4 /agent-note-draft-attachments-across-session-switches/decision: en: 40697e88c2ed6ca8 zh: eeb363374b25c3a2 diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md index 1d4ffc7c51..8c33335f55 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md @@ -6,7 +6,7 @@ English | [中文](2026-11-13-draft-attachments-across-session-switches.zh.md) ## Problem -Switching to another Session and back emptied the composer's attachment rail while its text survived ([#5070](https://github.com/deepseek-harness/deepseek-harness/issues/5070)). The Session scope disposer released every attachment the retiring composer held and revoked image previews, and nothing could rebuild them. +Switching to another Session and back emptied the composer's attachment rail while its text survived (issue #5070). The Session scope disposer released every attachment the retiring composer held and revoked image previews, and nothing could rebuild them. ## Decision diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md index 5f29991227..645a79c881 100644 --- a/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md @@ -6,7 +6,7 @@ Status: implemented ## 问题 -切到另一个会话再切回时,输入框的附件栏被清空,文字却还在([#5070](https://github.com/deepseek-harness/deepseek-harness/issues/5070))。会话 scope 销毁时会释放退役输入框持有的全部附件并回收图片预览,之后没有任何途径能重建它们。 +切到另一个会话再切回时,输入框的附件栏被清空,文字却还在(issue #5070)。会话 scope 销毁时会释放退役输入框持有的全部附件并回收图片预览,之后没有任何途径能重建它们。 ## 决策 From 6bb530211a82a913ef4338c38c2017163e508199 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Mon, 16 Nov 2026 15:26:01 +0800 Subject: [PATCH 09/13] refactor(connector-account): type the face from the generated Remote and return its results `ConnectorAccountsRemote` repeated the signatures typert generates for `ctx.remote.connectorAccounts`, and `settle` turned a failed Remote result back into a rejection. The face now types `start` and `cancel` from `ClientRemote['connectorAccounts']` and returns the Remote result. The buttons read `ok` and report a failed result or a rejected call as the failure notice, so the page behaves as before. --- .../ui-connector-account/README.i18n.yaml | 4 +-- .../client/ui-connector-account/README.md | 4 +-- .../client/ui-connector-account/README.zh.md | 4 +-- .../src/client/components.tsx | 16 ++++++++--- .../ui-connector-account/src/client/index.ts | 12 ++------- .../ui-connector-account/src/client/state.ts | 5 ++-- .../ui-connector-account/src/client/types.ts | 21 +++++---------- .../tests/apply.client.spec.ts | 11 ++++---- .../tests/components.client.spec.tsx | 27 ++++++++++++------- 9 files changed, 54 insertions(+), 50 deletions(-) diff --git a/packages/client/ui-connector-account/README.i18n.yaml b/packages/client/ui-connector-account/README.i18n.yaml index 64303c4159..175dc891ee 100644 --- a/packages/client/ui-connector-account/README.i18n.yaml +++ b/packages/client/ui-connector-account/README.i18n.yaml @@ -30,8 +30,8 @@ en: 353a48db7e7dd0f7 zh: 653f3d983d3fd572 /deepseek-ai-dsh-client-ui-connector-account/understand-the-implementation: - en: 8c16bb36ce00d4cc - zh: d52d2a6f2beacf21 + en: 6bfc9077699bd3cd + zh: ead092e865285eee /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 1226880ada..e30ecb7bd6 100644 --- a/packages/client/ui-connector-account/README.md +++ b/packages/client/ui-connector-account/README.md @@ -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, 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 surfaces receive `start` and `cancel` callbacks that call the Remote and reject when the Host refuses or the call does not answer; the buttons await them 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 surfaces receive `start` and `cancel` callbacks that call the Remote and return its result; the buttons report the operation of a successful start to `BrowserAccounts`, and a failed result or a rejected call as the failure notice. An account the Host drops loses its bundle entries, and unloading withdraws every entry and the stream. | File | Role | |---|---| @@ -94,7 +94,7 @@ The Host half, `ConnectorAccounts`, is a Remote service. `register()` observes t | [`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 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 | +| [`src/client/types.ts`](src/client/types.ts) | Browser state, notice, and face types | diff --git a/packages/client/ui-connector-account/README.zh.md b/packages/client/ui-connector-account/README.zh.md index 845d244b47..9c1569dfc8 100644 --- a/packages/client/ui-connector-account/README.zh.md +++ b/packages/client/ui-connector-account/README.zh.md @@ -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` 命名空间。各界面收到 `start` 和 `cancel` 两个回调:它们调用 Remote,在 Host 拒绝或调用没有回应时 reject;按钮等待回调结果,并把启动的操作报告给 `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` 命名空间。各界面收到 `start` 和 `cancel` 两个回调:它们调用 Remote 并返回其结果;按钮把启动成功时返回的操作报告给 `BrowserAccounts`,结果为失败或调用被 reject 时报告失败提示。Host 撤下的账号会失去其插件包条目;卸载时撤下所有条目和流。 | 文件 | 职责 | |---|---| @@ -94,7 +94,7 @@ Host 一半 `ConnectorAccounts` 是一个 Remote 服务。`register()` 观察账 | [`src/client/state.ts`](src/client/state.ts) | 流的 store、本浏览器发起的操作,以及它们的页面和提示 | | [`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 类型 | +| [`src/client/types.ts`](src/client/types.ts) | 浏览器状态、提示和 face 类型 | diff --git a/packages/client/ui-connector-account/src/client/components.tsx b/packages/client/ui-connector-account/src/client/components.tsx index 483d8924ff..d931d4bb9a 100644 --- a/packages/client/ui-connector-account/src/client/components.tsx +++ b/packages/client/ui-connector-account/src/client/components.tsx @@ -43,22 +43,30 @@ function useAccountCommand( const [busy, setBusy] = useState(false) // A second click before the re-render still finds the first call pending. const pending = useRef(false) - const call = (operation: () => Promise): void => { + // `operation` resolves to whether the Host accepted the call. + const call = (operation: () => Promise): void => { if (pending.current) return pending.current = true setBusy(true) // The Host keeps the diagnostic; the page reports one retryable outcome. - void operation().catch(() => { face.failed() }).finally(() => { pending.current = false; setBusy(false) }) + void operation() + .then((accepted) => { if (!accepted) face.failed() }) + .catch(() => { face.failed() }) + .finally(() => { pending.current = false; setBusy(false) }) } const run = (entry: ConnectorAccountEntry, command: ConnectorAccountCommand): void => { const { key } = entry switch (command.kind) { case 'start': - call(async () => { face.follow(key, await face.start(key, command.operation)) }) + call(async () => { + const started = await face.start(key, command.operation) + if (started.ok) face.follow(key, started.value) + return started.ok + }) return case 'cancel': { const operation = entry.operation - if (operation !== undefined) call(async () => { await face.cancel(key, operation.id) }) + if (operation !== undefined) call(async () => (await face.cancel(key, operation.id)).ok) return } case 'open': diff --git a/packages/client/ui-connector-account/src/client/index.ts b/packages/client/ui-connector-account/src/client/index.ts index d0e9f7cb05..e0e30d6285 100644 --- a/packages/client/ui-connector-account/src/client/index.ts +++ b/packages/client/ui-connector-account/src/client/index.ts @@ -10,7 +10,6 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, } from './components.tsx' @@ -26,13 +25,6 @@ export type { /** The `connectorAccounts` Remote that `dsh-api-remotes` mounts, and the services the slot registrations need. */ export const inject = ['remote', 'remote.connectorAccounts', 'slots', 'locale'] -/** The value of a Remote call, or a rejection with the Host's message when the Host refused it. */ -async function settle(call: Promise>): Promise { - const result = await call - if (!result.ok) throw new Error(result.error.message) - return result.value -} - function registerBundle(ctx: Context, face: ConnectorAccountFace, packageName: string, account: string): () => void { const bundle = { ...face, account } const dispose = ctx.effect(function* () { @@ -58,8 +50,8 @@ export function apply(ctx: Context): void { ctx.effect(() => async () => { await browser.dispose() }, 'connector-account: stream') const face: ConnectorAccountFace = { hooks: { connectorAccounts: browser.state }, - start: (key, operation) => settle(remote.start(key, operation)), - cancel: (key, id) => settle(remote.cancel(key, id)), + start: (key, operation) => remote.start(key, operation), + cancel: (key, id) => remote.cancel(key, id), resolveText: text => ctx.locale.resolveText(text), follow: (key, id) => { browser.follow(key, id) }, failed: () => { browser.failed() }, diff --git a/packages/client/ui-connector-account/src/client/state.ts b/packages/client/ui-connector-account/src/client/state.ts index 332715e431..7a061d98dc 100644 --- a/packages/client/ui-connector-account/src/client/state.ts +++ b/packages/client/ui-connector-account/src/client/state.ts @@ -4,10 +4,11 @@ */ import type { Context } from '@deepseek-ai/cordis' import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' -import type { ConnectorAccountNotice, ConnectorAccountsRemote, ConnectorAccountsState } from './types.ts' +import type { ConnectorAccountNotice, ConnectorAccountsState } from './types.ts' const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']) @@ -45,7 +46,7 @@ export class BrowserAccounts { * @param ctx - the browser context carrying the Remote client. * @param remote - the `connectorAccounts` Remote. */ - constructor(private readonly ctx: Context, remote: Pick) { + 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'), diff --git a/packages/client/ui-connector-account/src/client/types.ts b/packages/client/ui-connector-account/src/client/types.ts index 89a7a333b0..afff7bc9ad 100644 --- a/packages/client/ui-connector-account/src/client/types.ts +++ b/packages/client/ui-connector-account/src/client/types.ts @@ -1,8 +1,8 @@ /** Browser-side state and face of the accounts the Plugins page shows. */ +import type { ClientRemote } from '@deepseek-ai/dsh-api-remotes/client' import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import type { ConnectorAccountEntry, ConnectorAccountsView, ConnectorOperationId } from '../types.ts' +import type { ConnectorAccountEntry, ConnectorOperationId } from '../types.ts' /** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ export type ConnectorAccountNotice = @@ -18,23 +18,16 @@ export interface ConnectorAccountsState { readonly notice: ConnectorAccountNotice | undefined } -/** The `connectorAccounts` Remote methods the page uses. */ -export interface ConnectorAccountsRemote { - watch(signal: AbortSignal): AsyncIterable - start(key: string, operation: string): Promise> - cancel(key: string, id: ConnectorOperationId): Promise> -} - /** The face every surface entry injects. */ export interface ConnectorAccountFace { hooks: { connectorAccounts: HostObservable } /** - * Start an operation of an account on the Host. Resolves to the operation the Host started, and rejects when the Host - * refuses or the call does not answer. + * Start an operation of an account on the Host. The Remote result carries the operation the Host started, or the + * failure when the Host refuses or the call does not answer. */ - readonly start: (key: string, operation: string) => Promise - /** Cancel an account's operation on the Host; rejects like `start`. */ - readonly cancel: (key: string, id: ConnectorOperationId) => Promise + readonly start: ClientRemote['connectorAccounts']['start'] + /** Cancel an account's operation on the Host; the Remote result carries a failure like `start`. */ + readonly cancel: ClientRemote['connectorAccounts']['cancel'] /** Pick the active language's entry of a registrant's text. */ readonly resolveText: (text: LocalizedText) => string /** Remember an operation this browser started: its authorization page opens here, and its success is reported here. */ 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 6c6ad38b68..4dda30bb1c 100644 --- a/packages/client/ui-connector-account/tests/apply.client.spec.ts +++ b/packages/client/ui-connector-account/tests/apply.client.spec.ts @@ -126,13 +126,14 @@ it('shows one tag and one notice entry for the page and each bundle\'s section a expect(faceOf(toast).hooks.connectorAccounts).toBe(face.hooks.connectorAccounts) expect([...face.hooks.connectorAccounts.getSnapshot().accounts.keys()]).toEqual([FIXTURE, OTHER, 'mcp:custom']) expect(face.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') - expect(await face.start(FIXTURE, 'connect')).toBe(OP) + expect(await face.start(FIXTURE, 'connect')).toEqual({ ok: true, value: OP }) expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') - await face.cancel(FIXTURE, OP) + expect(await face.cancel(FIXTURE, OP)).toEqual({ ok: true, value: undefined }) expect(b.cancel).toHaveBeenCalledWith(FIXTURE, OP) - // A refusal reaches the buttons as a rejection with the Host's message. - b.start.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } as never) - await expect(face.start(FIXTURE, 'connect')).rejects.toThrow('offline') + // A refusal reaches the buttons as the Remote's result. + const refused: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } + b.start.mockResolvedValueOnce(refused) + expect(await face.start(FIXTURE, 'connect')).toBe(refused) face.follow(FIXTURE, OP) face.failed() expect(face.hooks.connectorAccounts.getSnapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) 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 222db693f6..8e645a7bc4 100644 --- a/packages/client/ui-connector-account/tests/components.client.spec.tsx +++ b/packages/client/ui-connector-account/tests/components.client.spec.tsx @@ -4,18 +4,21 @@ 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' 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 { ConnectorAccountActivationEntry, ConnectorAccountBadgeEntry, ConnectorAccountSectionEntry, ConnectorAccountToastEntry, } from '../src/client/components.tsx' import { zh } from '../src/client/locales.ts' -import type { ConnectorAccountsState } from '../src/client/types.ts' +import type { ConnectorAccountFace, ConnectorAccountsState } from '../src/client/types.ts' import type { ConnectorAccountDisplay, ConnectorAccountEntry, ConnectorOperationId } from '../src/types.ts' afterEach(cleanup) const KEY = '@acme/fixture' const OP = 'op-1' as ConnectorOperationId +const STARTED: RemoteResult = { ok: true, value: OP } +const REFUSED: RemoteResult = { ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } 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 }) @@ -41,8 +44,8 @@ function face(change: Partial = {}, accounts: readonly C } return { useConnectorAccounts: (selector: (value: ConnectorAccountsState) => R): R => selector(current), - start: vi.fn(async (_key: string, _operation: string) => OP), - cancel: vi.fn(async (_key: string, _id: ConnectorOperationId) => {}), + start: vi.fn(async () => STARTED), + cancel: vi.fn(async () => ({ ok: true, value: undefined })), account: KEY, resolveText, follow: vi.fn(), failed: vi.fn(), dismissNotice: vi.fn(), t, } } @@ -67,12 +70,12 @@ it('shows the registrant title, status, detail, notes, and hint, and starts each it('disables the buttons while a call is pending or the Host stream is down', async () => { const props = face() - const answer = Promise.withResolvers() + const answer = Promise.withResolvers>() props.start.mockReturnValueOnce(answer.promise) render() fireEvent.click(button('连接演示')) expect(disabled()).toEqual([true]) - await act(async () => { answer.resolve(OP) }) + await act(async () => { answer.resolve(STARTED) }) expect(disabled()).toEqual([false]) expect(props.failed).not.toHaveBeenCalled() cleanup() @@ -127,11 +130,13 @@ it.each<[string, ConnectorAccountDisplay['failure'], string]>([ expect(screen.getByRole('alert').textContent).toBe(expected) }) -it('reports a start that the Host refused or that never answered, without following it', async () => { +it('reports a start whose result is a failure or whose call rejected, without following it', async () => { const props = face() - props.start.mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce(new Error('carrier lost')) + props.start.mockResolvedValueOnce(REFUSED).mockRejectedValueOnce(new Error('Remote method is no longer mounted')) render() await click('连接演示') + expect(props.failed).toHaveBeenCalledOnce() + expect(disabled()).toEqual([false]) await click('连接演示') expect(props.failed).toHaveBeenCalledTimes(2) expect(props.follow).not.toHaveBeenCalled() @@ -150,6 +155,10 @@ it('cancels the operation in progress and opens its authorization page again on expect(windowOpen).toHaveBeenCalledWith('https://example.com/a', '_blank', 'noopener,noreferrer') await click('取消') expect(props.cancel).toHaveBeenCalledWith(KEY, OP) + expect(props.failed).not.toHaveBeenCalled() + props.cancel.mockResolvedValueOnce(REFUSED) + await click('取消') + expect(props.failed).toHaveBeenCalledOnce() // A cancel button with no operation in progress calls nothing. cleanup() const idle = sectionOf(display) @@ -216,12 +225,12 @@ it('connects from the prompt through the operation the display names, or only op it('starts once for a second click before the first call answers', async () => { const props = sectionOf({ ...DISCONNECTED, connect: { kind: 'start', operation: 'connect' } }) - const answer = Promise.withResolvers() + const answer = Promise.withResolvers>() props.start.mockReturnValueOnce(answer.promise) render(prompt(props)) fireEvent.click(button('连接演示')) fireEvent.click(button('连接演示')) - await act(async () => { answer.resolve(OP) }) + await act(async () => { answer.resolve(STARTED) }) expect(props.start).toHaveBeenCalledOnce() expect(props.follow).toHaveBeenCalledOnce() }) From 1e4b19e78e558c59efc22d2ceb5bf941dd7f6f7f Mon Sep 17 00:00:00 2001 From: gengruilin Date: Mon, 16 Nov 2026 15:35:37 +0800 Subject: [PATCH 10/13] chore(connector-account): match the root version 0.2.2-rc.3 --- packages/client/ui-connector-account/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/client/ui-connector-account/package.json b/packages/client/ui-connector-account/package.json index 25dcf492b8..cb95fb0c25 100644 --- a/packages/client/ui-connector-account/package.json +++ b/packages/client/ui-connector-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-connector-account", "description": "Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote", - "version": "0.2.2-rc.2", + "version": "0.2.2-rc.3", "publishConfig": { "access": "public" }, From d245f8e2858c7f411d6bbbb66f1bbfebde41e656 Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 16 Nov 2026 15:55:46 +0800 Subject: [PATCH 11/13] feat(ci): close pull requests after 21 days without activity Refs #8432 --- .github/stale-pull-requests/remind.mjs | 66 ++++++++++++-------- .github/stale-pull-requests/remind.test.mjs | 67 +++++++++++++-------- .github/workflows/stale-pull-requests.yml | 10 +-- 3 files changed, 87 insertions(+), 56 deletions(-) diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index adff87f633..0b863dc865 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -1,24 +1,30 @@ /** - * Daily stale pull-request reminders for the `Stale pull requests` workflow. + * Daily stale pull-request reminders and closing for the `Stale pull requests` workflow. * * A pull request's last activity is the latest of its creation, a commit, a force push, a reopen or ready-for-review * event, and a comment or review from a non-bot account. Other timeline events, such as mentions, labels and cross - * references, do not count, so reminder comments never extend it. After 7 and 14 days without activity the workflow - * comments once per stage and mentions the author. Activity starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` - * and pull requests opened by bots receive no reminders. The workflow never closes pull requests. + * references, do not count, so reminder and closing comments never extend it. After 7 and 14 days without activity the + * workflow comments once per stage and mentions the author. After 21 days without activity, and at least 7 days after + * the 14-day reminder, it comments and closes the pull request; the reminder therefore always gives the author 7 days' + * notice, including for pull requests that were already inactive when the workflow started. Activity, including + * reopening, starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` and pull requests opened by bots are neither + * reminded nor closed. * * Each run reads the timeline of every open pull request that is neither exempt nor bot-authored, because `updated_at` - * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` reminders, least recently + * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` comments, least recently * updated pull requests first, so a backlog spreads over several days within GitHub's content-creation limits. A failed * pull request is reported and skipped. */ -/** Label that exempts a pull request from reminders. */ +/** Label that exempts a pull request from reminders and closing. */ export const EXEMPT_LABEL = 'DO_NOT_CLOSE' /** Days without activity after which each reminder is posted, in ascending order. */ export const REMINDER_DAYS = [7, 14] +/** Days without activity after which a pull request is closed. */ +export const CLOSE_DAYS = 21 + const DAY_MS = 24 * 60 * 60 * 1000 // GitHub asks integrations to wait at least one second between content-creating requests. const COMMENT_INTERVAL_MS = 1000 @@ -55,39 +61,44 @@ function activityTimes(event) { } /** - * Selects the reminder a pull request is due for. + * Selects the reminder or closing a pull request is due for. * @param {object} options * @param {string} options.createdAt Pull-request creation time. * @param {object[]} options.timeline Complete issue timeline of the pull request. * @param {Date} options.now Evaluation time. - * @returns {number | undefined} Due reminder stage in days, or `undefined` when none is due. + * @returns {number | undefined} Due stage in days, `CLOSE_DAYS` for closing, or `undefined` when nothing is due. */ -export function dueReminder({ createdAt, timeline, now }) { +export function dueStage({ createdAt, timeline, now }) { const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite) const lastActivity = Math.max(...times) - const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) - if (due === undefined) return undefined const sent = timeline .filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity) - .map(event => Number(MARKER.exec(event.body ?? '')?.[1])) - return sent.some(days => days >= due) ? undefined : due + .map(event => ({ days: Number(MARKER.exec(event.body ?? '')?.[1]), at: Date.parse(event.created_at) })) + const finalReminder = REMINDER_DAYS.at(-1) + const noticeMs = (CLOSE_DAYS - finalReminder) * DAY_MS + if (now.getTime() - lastActivity >= CLOSE_DAYS * DAY_MS && sent.some(({ days, at }) => days === finalReminder && now.getTime() - at >= noticeMs)) { + return CLOSE_DAYS + } + const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) + if (due === undefined) return undefined + return sent.some(({ days }) => days >= due) ? undefined : due } /** - * Builds the reminder comment. + * Builds the reminder or closing comment. * @param {string} author Pull-request author login. - * @param {number} days Reminder stage in days. + * @param {number} days Stage in days; `CLOSE_DAYS` builds the closing comment. * @returns {string} Comment body. */ -export function reminderBody(author, days) { - return [ - ``, - `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop these reminders.`, - ].join('\n') +export function stageBody(author, days) { + const text = days === CLOSE_DAYS + ? `@${author} This pull request has had no activity for ${days} days and is now closed. Reopen it, or ask a maintainer to reopen it, if you continue the work.` + : `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Pull requests are closed after ${CLOSE_DAYS} days without activity and at least ${CLOSE_DAYS - REMINDER_DAYS.at(-1)} days after the ${REMINDER_DAYS.at(-1)}-day reminder. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop reminders and closing.` + return `\n${text}` } /** - * Posts every due reminder on open pull requests of the workflow repository. + * Posts every due reminder and closes every due pull request among the open pull requests of the workflow repository. * @param {object} options * @param {object} options.github Authenticated Octokit client from `actions/github-script`. * @param {object} options.context Workflow context from `actions/github-script`. @@ -96,7 +107,7 @@ export function reminderBody(author, days) { * @param {(ms: number) => Promise} [options.sleep] Delay between comments. * @returns {Promise} */ -export async function remindStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { +export async function processStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { const { owner, repo } = context.repo const pulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', sort: 'updated', direction: 'asc', per_page: 100 }) let posted = 0 @@ -107,12 +118,17 @@ export async function remindStalePullRequests({ github, context, core, now = new if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue try { const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 }) - const days = dueReminder({ createdAt: pull.created_at, timeline, now }) + const days = dueStage({ createdAt: pull.created_at, timeline, now }) if (days === undefined) continue if (posted > 0) await sleep(COMMENT_INTERVAL_MS) - await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: reminderBody(pull.user.login, days) }) + await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) posted++ - core.info(`#${pull.number}: posted the ${days}-day reminder`) + if (days === CLOSE_DAYS) { + await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) + core.info(`#${pull.number}: closed after ${days} days without activity`) + } else { + core.info(`#${pull.number}: posted the ${days}-day reminder`) + } } catch (error) { failed++ core.warning(`#${pull.number}: ${error.message}`) diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index cb2d56b437..be430e6576 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -1,47 +1,58 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { dueReminder, reminderBody, remindStalePullRequests } from './remind.mjs' +import { dueStage, stageBody, processStalePullRequests } from './remind.mjs' const now = new Date('2026-11-30T00:00:00Z') const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString() const human = { login: 'author', type: 'User' } const bot = { login: 'github-actions[bot]', type: 'Bot' } const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body }) -const reminder = (days, stage) => comment(bot, days, reminderBody('author', stage)) +const reminder = (days, stage) => comment(bot, days, stageBody('author', stage)) test('no reminder is due within 7 days of the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(6), timeline: [], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(6), timeline: [], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) }) test('the latest due stage is posted once after the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(7), timeline: [], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(7), timeline: [], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(17), timeline: [reminder(3, 14)], now }), undefined) +}) + +test('a pull request closes after 21 days without activity and 7 days after the 14-day reminder', () => { + assert.equal(dueStage({ createdAt: daysAgo(21), timeline: [reminder(14, 7), reminder(7, 14)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), 21) + // A pull request that was already inactive gets the 14-day reminder first and 7 days' notice. + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(6, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(30, 7)], now }), 14) + // A 14-day reminder from before the last activity gives no notice. + assert.equal(dueStage({ createdAt: daysAgo(60), timeline: [reminder(40, 14), comment(human, 25)], now }), 14) }) test('human activity restarts the cycle and bot activity does not', () => { const sentBefore = [reminder(30, 7), reminder(23, 14)] - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reopened', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), 21) }) test('mentions, labels and cross references are not activity', () => { const at = (event, days) => ({ event, actor: human, created_at: daysAgo(days) }) // GitHub records a `mentioned` event for the author right after each reminder. - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) }) -test('reminders mention the author and skip exempt and bot-authored pull requests', async () => { +test('reminders and closing mention the author and skip exempt and bot-authored pull requests', async () => { const pull = (number, overrides = {}) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20), ...overrides }) const pulls = [ pull(1), @@ -51,12 +62,14 @@ test('reminders mention the author and skip exempt and bot-authored pull request pull(4, { updated_at: daysAgo(1) }), pull(6), pull(5), + pull(7, { created_at: daysAgo(30) }), ] const comments = [] + const closed = [] const timelines = [] const github = { rest: { - pulls: { list: 'pulls' }, + pulls: { list: 'pulls', update: async params => closed.push(params) }, issues: { listEventsForTimeline: 'timeline', createComment: async params => { @@ -68,20 +81,22 @@ test('reminders mention the author and skip exempt and bot-authored pull request paginate: async (method, params) => { if (method === 'pulls') return pulls timelines.push(params.issue_number) - return [] + return params.issue_number === 7 ? [reminder(9, 14)] : [] }, } const sleeps = [] const warnings = [] const failures = [] const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) - assert.deepEqual(timelines, [1, 4, 6, 5]) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) + assert.deepEqual(timelines, [1, 4, 6, 5, 7]) assert.deepEqual(warnings, ['#6: locked']) assert.equal(failures.length, 1) - assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5]) + assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7]) assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) - assert.deepEqual(sleeps, [1000, 1000, 1000]) + assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) + assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }]) + assert.deepEqual(sleeps, [1000, 1000, 1000, 1000]) }) test('a run posts at most 100 reminders', async () => { @@ -91,6 +106,6 @@ test('a run posts at most 100 reminders', async () => { rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } }, paginate: async method => method === 'pulls' ? pulls : [], } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) assert.equal(comments, 100) }) diff --git a/.github/workflows/stale-pull-requests.yml b/.github/workflows/stale-pull-requests.yml index a0ccb7f2b5..db1c3f8115 100644 --- a/.github/workflows/stale-pull-requests.yml +++ b/.github/workflows/stale-pull-requests.yml @@ -1,4 +1,4 @@ -# Reminds authors of open pull requests after 7 and 14 days without activity; never closes them. +# Reminds authors of open pull requests after 7 and 14 days without activity and closes them after 21 days. # Rules: .github/stale-pull-requests/remind.mjs. name: Stale pull requests @@ -16,7 +16,7 @@ concurrency: jobs: remind: - name: Remind stale pull requests + name: Remind and close stale pull requests runs-on: ubuntu-latest permissions: contents: read @@ -27,9 +27,9 @@ jobs: with: sparse-checkout: .github/stale-pull-requests persist-credentials: false - - name: Post due reminders + - name: Post due reminders and close stale pull requests uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 with: script: | - const { remindStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) - await remindStalePullRequests({ github, context, core }) + const { processStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) + await processStalePullRequests({ github, context, core }) From 00dcb5ec10c95b3c3e93ba3ca512fe3af4e5b014 Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 16 Nov 2026 15:56:40 +0800 Subject: [PATCH 12/13] fix(ci): close stale pull requests before commenting --- .github/stale-pull-requests/remind.mjs | 9 +++------ .github/stale-pull-requests/remind.test.mjs | 18 +++++++++++++----- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index 0b863dc865..2545ec49c2 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -121,14 +121,11 @@ export async function processStalePullRequests({ github, context, core, now = ne const days = dueStage({ createdAt: pull.created_at, timeline, now }) if (days === undefined) continue if (posted > 0) await sleep(COMMENT_INTERVAL_MS) + // Closing first keeps a failed close from repeating the closing comment on later runs. + if (days === CLOSE_DAYS) await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) posted++ - if (days === CLOSE_DAYS) { - await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) - core.info(`#${pull.number}: closed after ${days} days without activity`) - } else { - core.info(`#${pull.number}: posted the ${days}-day reminder`) - } + core.info(days === CLOSE_DAYS ? `#${pull.number}: closed after ${days} days without activity` : `#${pull.number}: posted the ${days}-day reminder`) } catch (error) { failed++ core.warning(`#${pull.number}: ${error.message}`) diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index be430e6576..b8573b7c70 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -63,13 +63,20 @@ test('reminders and closing mention the author and skip exempt and bot-authored pull(6), pull(5), pull(7, { created_at: daysAgo(30) }), + pull(8, { created_at: daysAgo(30) }), ] const comments = [] const closed = [] const timelines = [] const github = { rest: { - pulls: { list: 'pulls', update: async params => closed.push(params) }, + pulls: { + list: 'pulls', + update: async params => { + if (params.pull_number === 8) throw new Error('close failed') + closed.push(params) + }, + }, issues: { listEventsForTimeline: 'timeline', createComment: async params => { @@ -81,7 +88,7 @@ test('reminders and closing mention the author and skip exempt and bot-authored paginate: async (method, params) => { if (method === 'pulls') return pulls timelines.push(params.issue_number) - return params.issue_number === 7 ? [reminder(9, 14)] : [] + return [7, 8].includes(params.issue_number) ? [reminder(9, 14)] : [] }, } const sleeps = [] @@ -89,14 +96,15 @@ test('reminders and closing mention the author and skip exempt and bot-authored const failures = [] const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) - assert.deepEqual(timelines, [1, 4, 6, 5, 7]) - assert.deepEqual(warnings, ['#6: locked']) + assert.deepEqual(timelines, [1, 4, 6, 5, 7, 8]) + // A failed close posts no closing comment, so the next run retries without repeating it. + assert.deepEqual(warnings, ['#6: locked', '#8: close failed']) assert.equal(failures.length, 1) assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7]) assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }]) - assert.deepEqual(sleeps, [1000, 1000, 1000, 1000]) + assert.deepEqual(sleeps, [1000, 1000, 1000, 1000, 1000]) }) test('a run posts at most 100 reminders', async () => { From e8473dbb606940fc7118bc09beaa1deec1559a43 Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 16 Nov 2026 16:06:37 +0800 Subject: [PATCH 13/13] fix(ci): require a closing notice and retry failed closes --- .github/stale-pull-requests/remind.mjs | 29 ++++++++++++--------- .github/stale-pull-requests/remind.test.mjs | 19 ++++++++++---- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index 2545ec49c2..fb625e0d85 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -29,7 +29,8 @@ const DAY_MS = 24 * 60 * 60 * 1000 // GitHub asks integrations to wait at least one second between content-creating requests. const COMMENT_INTERVAL_MS = 1000 const MAX_COMMENTS_PER_RUN = 100 -const MARKER = // +// Reminders posted before closing existed use `stale-pr-reminder` and announce no closing, so they are ignored. +const MARKER = // // Review bots that use ordinary user accounts. const BOT_LOGINS = new Set(['ds-review-bot']) @@ -66,7 +67,9 @@ function activityTimes(event) { * @param {string} options.createdAt Pull-request creation time. * @param {object[]} options.timeline Complete issue timeline of the pull request. * @param {Date} options.now Evaluation time. - * @returns {number | undefined} Due stage in days, `CLOSE_DAYS` for closing, or `undefined` when nothing is due. + * @returns {{ days: number, comment: boolean } | undefined} Due stage in days, `CLOSE_DAYS` for closing, and whether its + * comment is still unposted; `undefined` when nothing is due. A closing whose comment was posted but whose close failed + * is due again without a comment. */ export function dueStage({ createdAt, timeline, now }) { const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite) @@ -77,11 +80,11 @@ export function dueStage({ createdAt, timeline, now }) { const finalReminder = REMINDER_DAYS.at(-1) const noticeMs = (CLOSE_DAYS - finalReminder) * DAY_MS if (now.getTime() - lastActivity >= CLOSE_DAYS * DAY_MS && sent.some(({ days, at }) => days === finalReminder && now.getTime() - at >= noticeMs)) { - return CLOSE_DAYS + return { days: CLOSE_DAYS, comment: !sent.some(({ days }) => days === CLOSE_DAYS) } } const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) - if (due === undefined) return undefined - return sent.some(({ days }) => days >= due) ? undefined : due + if (due === undefined || sent.some(({ days }) => days >= due)) return undefined + return { days: due, comment: true } } /** @@ -94,7 +97,7 @@ export function stageBody(author, days) { const text = days === CLOSE_DAYS ? `@${author} This pull request has had no activity for ${days} days and is now closed. Reopen it, or ask a maintainer to reopen it, if you continue the work.` : `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Pull requests are closed after ${CLOSE_DAYS} days without activity and at least ${CLOSE_DAYS - REMINDER_DAYS.at(-1)} days after the ${REMINDER_DAYS.at(-1)}-day reminder. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop reminders and closing.` - return `\n${text}` + return `\n${text}` } /** @@ -118,13 +121,15 @@ export async function processStalePullRequests({ github, context, core, now = ne if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue try { const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 }) - const days = dueStage({ createdAt: pull.created_at, timeline, now }) - if (days === undefined) continue - if (posted > 0) await sleep(COMMENT_INTERVAL_MS) - // Closing first keeps a failed close from repeating the closing comment on later runs. + const stage = dueStage({ createdAt: pull.created_at, timeline, now }) + if (stage === undefined) continue + const { days } = stage + if (stage.comment) { + if (posted > 0) await sleep(COMMENT_INTERVAL_MS) + await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) + posted++ + } if (days === CLOSE_DAYS) await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) - await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) - posted++ core.info(days === CLOSE_DAYS ? `#${pull.number}: closed after ${days} days without activity` : `#${pull.number}: posted the ${days}-day reminder`) } catch (error) { failed++ diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index b8573b7c70..c6033e1fc5 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { dueStage, stageBody, processStalePullRequests } from './remind.mjs' +import { dueStage as dueAction, stageBody, processStalePullRequests } from './remind.mjs' const now = new Date('2026-11-30T00:00:00Z') const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString() @@ -9,6 +9,7 @@ const human = { login: 'author', type: 'User' } const bot = { login: 'github-actions[bot]', type: 'Bot' } const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body }) const reminder = (days, stage) => comment(bot, days, stageBody('author', stage)) +const dueStage = options => dueAction(options)?.days test('no reminder is due within 7 days of the last activity', () => { assert.equal(dueStage({ createdAt: daysAgo(6), timeline: [], now }), undefined) @@ -31,6 +32,14 @@ test('a pull request closes after 21 days without activity and 7 days after the assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(30, 7)], now }), 14) // A 14-day reminder from before the last activity gives no notice. assert.equal(dueStage({ createdAt: daysAgo(60), timeline: [reminder(40, 14), comment(human, 25)], now }), 14) + // Reminders posted before closing existed announce no closing. + const legacy = comment(bot, 10, '\n@author This pull request has had no activity for 14 days.') + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [legacy], now }), 14) +}) + +test('a closing whose comment was posted retries the close without another comment', () => { + assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14)], now }), { days: 21, comment: true }) + assert.deepEqual(dueAction({ createdAt: daysAgo(30), timeline: [reminder(9, 14), reminder(1, 21)], now }), { days: 21, comment: false }) }) test('human activity restarts the cycle and bot activity does not', () => { @@ -97,12 +106,12 @@ test('reminders and closing mention the author and skip exempt and bot-authored const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) assert.deepEqual(timelines, [1, 4, 6, 5, 7, 8]) - // A failed close posts no closing comment, so the next run retries without repeating it. + // A failed close after its comment is retried on the next run without another comment. assert.deepEqual(warnings, ['#6: locked', '#8: close failed']) assert.equal(failures.length, 1) - assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7]) - assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) - assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) + assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7, 8]) + assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) + assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }]) assert.deepEqual(sleeps, [1000, 1000, 1000, 1000, 1000]) })