fix(account): cover lifecycle failures and restore CI compatibility
This commit is contained in:
1 parent
0d985d55a2
commit
2a1eb24285
42 files changed
+984
-92
No files matched your search
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md
|
||||
2026-09-14-deepseek-account-login.md: e49a928d5a75b1925627a03c2f7dbc6269977258
|
||||
2026-09-14-deepseek-account-login.zh.md: 575c703e7726b35486a086a98838122a7b0cc3a7
|
||||
2026-09-14-deepseek-account-login.md: 65405b293cdea14a231d8d700589f9c3e7ef6db7
|
||||
2026-09-14-deepseek-account-login.zh.md: 0aca011826006a0fb8f0557464187b73da377238
|
||||
@@ -58,6 +58,8 @@ Separate accountRequestHeaders route account data and embedded Platform traffic
|
||||
|
||||
The Host binds private Platform sessions to the account provider lifetime. Removal or watch termination clears Electron’s session; replacement subscribes to the new provider, and disposed reads cannot publish old credentials.
|
||||
|
||||
The client distinguishes plugin disposal from terminal account-stream failure. RemoteStream aborts its signal after either outcome, so the plugin owns a separate disposal flag to preserve failure feedback while suppressing reports after unload.
|
||||
|
||||
## Verification
|
||||
|
||||
Provider tests exercise real loopback callbacks, invalid state, delayed exchange cancellation, credential persistence, sign-out, and official-origin restrictions. Desktop tests cover the native action bridge and localized entry. Manual development integration uses the platform dev middleware Mock and the real Electron Host, including cancellation before browser approval. Production backend credentials and installer scheme registration require release-environment validation.
|
||||
|
||||
@@ -58,6 +58,8 @@ exchange 的 user 数据在凭证提交后供首次资料读取使用,展示
|
||||
|
||||
Host 将私有 Platform 会话绑定到账号提供者的生命周期。提供者移除或订阅结束时清空 Electron 会话;替换后订阅新的提供者,已释放的读取不得发布旧凭据。
|
||||
|
||||
客户端区分插件卸载和账户状态流的终止错误。RemoteStream 在两种情况下都会中止其信号,因此插件独立记录卸载状态,保留错误反馈并抑制卸载后的报告。
|
||||
|
||||
## 验证
|
||||
|
||||
提供者测试覆盖真实本机回调、错误 state、延迟兑换取消、凭证持久化、退出和官方来源限制。桌面测试覆盖原生操作桥接与本地化入口。手动开发联调使用平台 dev middleware Mock 和真实 Electron Host,包括在浏览器批准前取消。生产后端凭证及安装器 scheme 注册仍需发布环境验证。
|
||||
|
||||
@@ -36,7 +36,7 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
|
||||
process.send({ type: 'booting', packageManager: options.packageManager });
|
||||
return new Promise((resolve, reject) => process.once('disconnect', () => {
|
||||
if (${String(fail)}) { reject(new Error('fixture boot failure')); return; }
|
||||
resolve({ ctx: { plugin: async () => {}, effect: () => {}, on: () => {},
|
||||
resolve({ ctx: { plugin: async () => {}, effect: () => {}, on: () => {}, inject: () => {},
|
||||
connection: { authenticatedUrl: value => value }, webServer: { port: 19387 } },
|
||||
shutdown: { shutdown: async () => writeFileSync(${JSON.stringify(join(root, 'stopped'))}, 'stopped') } });
|
||||
}));
|
||||
@@ -69,8 +69,10 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
|
||||
expect(boot.packageManager.env.ELECTRON_RUN_AS_NODE).toBe('1')
|
||||
expect(boot.packageManager.env.PATH).toBe(`${nodeBin}${delimiter}${process.env.PATH ?? ''}`)
|
||||
child.disconnect()
|
||||
expect(await exited).toBe(fail ? 1 : 0)
|
||||
const exitCode = await exited
|
||||
await drained
|
||||
expect(child.signalCode).toBeNull()
|
||||
expect(exitCode, stderr).toBe(fail ? 1 : 0)
|
||||
expect(stderr).not.toContain('ERR_IPC_CHANNEL_CLOSED')
|
||||
expect(stderr).not.toContain('Unhandled')
|
||||
if (fail) expect(stderr).toContain('fixture boot failure')
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/event-producer-consumer.md
|
||||
event-producer-consumer.md: 13ac82b2c9fb0b2aeeaa2bec9c736db5b5b63992
|
||||
event-producer-consumer.zh.md: bfd2ca7dbcd1b874b34ad2c45eceeaf84ffa70ec
|
||||
event-producer-consumer.zh.md: fce8463041181139e45fb5f3a9ab14c87117135f
|
||||
@@ -77,7 +77,7 @@
|
||||
| `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tools/src/index.ts:190`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) |
|
||||
| `tools/result` | `emit` | [`packages/core/tools/src/index.ts:198`](../packages/core/tools/src/index.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`agent-instructions`](../packages/context/agent-instructions), [`subagent-in-process-driver`](../packages/subagent/subagent-in-process-driver), [`tool-present`](../packages/deliverables/tool-present) |
|
||||
| `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:88`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | `remotes` |
|
||||
| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:34`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `ui-sidebar-documentpreview` |
|
||||
| `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:34`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `ui-sidebar-documentpreview`, `ui-theme` |
|
||||
| `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow), [`workflow`](../packages/workflow/workflow) |
|
||||
| `workflow/agent-start` | `emit` | [`packages/workflow/workflow/src/index.ts:68`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow), [`workflow`](../packages/workflow/workflow) |
|
||||
| `workflow/end` | `emit` | [`packages/workflow/workflow/src/index.ts:89`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`workflow`](../packages/workflow/workflow) |
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/module-graph.md
|
||||
module-graph.md: 868a51d96e818b6e815defd6acce758ab7251d0b
|
||||
module-graph.zh.md: aa8edca41eeff8d8a05c03e3310e09ed7b3eaabd
|
||||
module-graph.md: fc5c06727e58705ac6d9b44470b1b37010dc3223
|
||||
module-graph.zh.md: 6911d9820932569c7a666b47a8bd53696fdb6393
|
||||
+17
-1
@@ -113,6 +113,7 @@ flowchart TD
|
||||
pkg_acp["acp"]
|
||||
end
|
||||
subgraph group_api["packages/api"]
|
||||
pkg_api_account_controller["api-account-controller"]
|
||||
pkg_api_gateway["api-gateway"]
|
||||
pkg_api_job_controller["api-job-controller"]
|
||||
pkg_api_remotes["api-remotes"]
|
||||
@@ -179,6 +180,7 @@ flowchart TD
|
||||
pkg_client_ui_schedule["client-ui-schedule"]
|
||||
pkg_client_ui_session["client-ui-session"]
|
||||
pkg_client_ui_settings["client-ui-settings"]
|
||||
pkg_client_ui_settings_account["client-ui-settings-account"]
|
||||
pkg_client_ui_settings_agent_loop["client-ui-settings-agent-loop"]
|
||||
pkg_client_ui_settings_general["client-ui-settings-general"]
|
||||
pkg_client_ui_settings_models["client-ui-settings-models"]
|
||||
@@ -226,6 +228,8 @@ flowchart TD
|
||||
pkg_authorization["authorization"]
|
||||
pkg_credentials["credentials"]
|
||||
pkg_credentials_local["credentials-local"]
|
||||
pkg_deepseek_account["deepseek-account"]
|
||||
pkg_deepseek_account_platform["deepseek-account-platform"]
|
||||
end
|
||||
subgraph group_deliverables["packages/deliverables"]
|
||||
pkg_tool_present["tool-present"]
|
||||
@@ -424,6 +428,7 @@ flowchart TD
|
||||
pkg_browser_use --> pkg_brand
|
||||
pkg_computer_use --> pkg_brand
|
||||
pkg_credentials --> pkg_invariants
|
||||
pkg_deepseek_account --> pkg_brand
|
||||
pkg_experimental_inspector --> pkg_client_modules
|
||||
pkg_experimental_inspector --> pkg_host_webserver
|
||||
pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse
|
||||
@@ -455,6 +460,8 @@ flowchart TD
|
||||
pkg_web_search_exa --> pkg_web
|
||||
pkg_web_search_perplexity --> pkg_launch_environment
|
||||
pkg_web_search_perplexity --> pkg_web
|
||||
pkg_api_account_controller --> pkg_deepseek_account
|
||||
pkg_api_account_controller --> pkg_typert_protocol
|
||||
pkg_api_remotes --> pkg_scope
|
||||
pkg_api_terminal_controller --> pkg_subprocess
|
||||
pkg_attachment_local --> pkg_attachment
|
||||
@@ -481,6 +488,10 @@ flowchart TD
|
||||
pkg_app_boot --> pkg_home_paths
|
||||
pkg_app_boot --> pkg_launch_environment
|
||||
pkg_app_boot --> pkg_system_prompt
|
||||
pkg_deepseek_account_platform --> pkg_authorization
|
||||
pkg_deepseek_account_platform --> pkg_credentials
|
||||
pkg_deepseek_account_platform --> pkg_deepseek_account
|
||||
pkg_deepseek_account_platform --> pkg_host_webserver
|
||||
pkg_experimental_webworker_runtime --> pkg_client_connection
|
||||
pkg_experimental_webworker_runtime --> pkg_client_modules
|
||||
pkg_experimental_webworker_runtime --> pkg_host_webserver
|
||||
@@ -539,6 +550,7 @@ flowchart TD
|
||||
pkg_llm_deepseek --> pkg_atomic_write
|
||||
pkg_llm_deepseek --> pkg_attachment
|
||||
pkg_llm_deepseek --> pkg_credentials
|
||||
pkg_llm_deepseek --> pkg_deepseek_account
|
||||
pkg_llm_deepseek --> pkg_deepseek_llm_api_extensions
|
||||
pkg_llm_deepseek --> pkg_fs
|
||||
pkg_llm_deepseek --> pkg_home_paths
|
||||
@@ -1388,6 +1400,7 @@ flowchart TD
|
||||
| [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — |
|
||||
| [`client-ui-session`](../packages/client/ui-session) | `client` | — |
|
||||
| [`client-ui-settings`](../packages/client/ui-settings) | `client` | — |
|
||||
| [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — |
|
||||
| [`client-ui-settings-agent-loop`](../packages/client/ui-settings-agent-loop) | `client` | — |
|
||||
| [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | — |
|
||||
| [`client-ui-settings-models`](../packages/client/ui-settings-models) | `client` | — |
|
||||
@@ -1442,6 +1455,7 @@ flowchart TD
|
||||
| [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) |
|
||||
| [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) |
|
||||
| [`credentials`](../packages/credentials/credentials) | `credentials` | [`invariants`](../packages/runtime-diagnostics/invariants) |
|
||||
| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`brand`](../packages/util/brand) |
|
||||
| [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) |
|
||||
@@ -1458,6 +1472,7 @@ flowchart TD
|
||||
| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`http-proxy`](../packages/util/http-proxy), [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) |
|
||||
| [`web-search-exa`](../packages/web/web-search-exa) | `web` | [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) |
|
||||
| [`web-search-perplexity`](../packages/web/web-search-perplexity) | `web` | [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) |
|
||||
| [`api-account-controller`](../packages/api/account-controller) | `api` | [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) |
|
||||
| [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) |
|
||||
@@ -1473,6 +1488,7 @@ flowchart TD
|
||||
| [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
|
||||
| [`api-gateway`](../packages/api/gateway) | `api` | [`client-connection`](../packages/client/connection) |
|
||||
| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`system-prompt`](../packages/core/system-prompt) |
|
||||
| [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |
|
||||
@@ -1496,7 +1512,7 @@ flowchart TD
|
||||
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
|
||||
| [`shell`](../packages/shell/shell) | `shell` | [`sandbox`](../packages/sandbox/sandbox), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`workspace`](../packages/workspace/workspace) | `workspace` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage`](../packages/storage/storage), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`llm-deepseek`](../packages/llm/llm-deepseek) | `llm` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`atomic-write`](../packages/util/atomic-write), [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
|
||||
| [`llm-deepseek`](../packages/llm/llm-deepseek) | `llm` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`atomic-write`](../packages/util/atomic-write), [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
|
||||
| [`llm-pi-ai`](../packages/llm/llm-pi-ai) | `llm` | [`attachment`](../packages/attachment/attachment), [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`fs`](../packages/fs/fs), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
|
||||
| [`agent`](../packages/core/agent) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values), [`workspace`](../packages/workspace/workspace) |
|
||||
| [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs) |
|
||||
|
||||
+17
-1
@@ -115,6 +115,7 @@ flowchart TD
|
||||
pkg_acp["acp"]
|
||||
end
|
||||
subgraph group_api["packages/api"]
|
||||
pkg_api_account_controller["api-account-controller"]
|
||||
pkg_api_gateway["api-gateway"]
|
||||
pkg_api_job_controller["api-job-controller"]
|
||||
pkg_api_remotes["api-remotes"]
|
||||
@@ -181,6 +182,7 @@ flowchart TD
|
||||
pkg_client_ui_schedule["client-ui-schedule"]
|
||||
pkg_client_ui_session["client-ui-session"]
|
||||
pkg_client_ui_settings["client-ui-settings"]
|
||||
pkg_client_ui_settings_account["client-ui-settings-account"]
|
||||
pkg_client_ui_settings_agent_loop["client-ui-settings-agent-loop"]
|
||||
pkg_client_ui_settings_general["client-ui-settings-general"]
|
||||
pkg_client_ui_settings_models["client-ui-settings-models"]
|
||||
@@ -228,6 +230,8 @@ flowchart TD
|
||||
pkg_authorization["authorization"]
|
||||
pkg_credentials["credentials"]
|
||||
pkg_credentials_local["credentials-local"]
|
||||
pkg_deepseek_account["deepseek-account"]
|
||||
pkg_deepseek_account_platform["deepseek-account-platform"]
|
||||
end
|
||||
subgraph group_deliverables["packages/deliverables"]
|
||||
pkg_tool_present["tool-present"]
|
||||
@@ -426,6 +430,7 @@ flowchart TD
|
||||
pkg_browser_use --> pkg_brand
|
||||
pkg_computer_use --> pkg_brand
|
||||
pkg_credentials --> pkg_invariants
|
||||
pkg_deepseek_account --> pkg_brand
|
||||
pkg_experimental_inspector --> pkg_client_modules
|
||||
pkg_experimental_inspector --> pkg_host_webserver
|
||||
pkg_host_directory_picker_auto --> pkg_client_ui_directory_picker_browse
|
||||
@@ -457,6 +462,8 @@ flowchart TD
|
||||
pkg_web_search_exa --> pkg_web
|
||||
pkg_web_search_perplexity --> pkg_launch_environment
|
||||
pkg_web_search_perplexity --> pkg_web
|
||||
pkg_api_account_controller --> pkg_deepseek_account
|
||||
pkg_api_account_controller --> pkg_typert_protocol
|
||||
pkg_api_remotes --> pkg_scope
|
||||
pkg_api_terminal_controller --> pkg_subprocess
|
||||
pkg_attachment_local --> pkg_attachment
|
||||
@@ -483,6 +490,10 @@ flowchart TD
|
||||
pkg_app_boot --> pkg_home_paths
|
||||
pkg_app_boot --> pkg_launch_environment
|
||||
pkg_app_boot --> pkg_system_prompt
|
||||
pkg_deepseek_account_platform --> pkg_authorization
|
||||
pkg_deepseek_account_platform --> pkg_credentials
|
||||
pkg_deepseek_account_platform --> pkg_deepseek_account
|
||||
pkg_deepseek_account_platform --> pkg_host_webserver
|
||||
pkg_experimental_webworker_runtime --> pkg_client_connection
|
||||
pkg_experimental_webworker_runtime --> pkg_client_modules
|
||||
pkg_experimental_webworker_runtime --> pkg_host_webserver
|
||||
@@ -541,6 +552,7 @@ flowchart TD
|
||||
pkg_llm_deepseek --> pkg_atomic_write
|
||||
pkg_llm_deepseek --> pkg_attachment
|
||||
pkg_llm_deepseek --> pkg_credentials
|
||||
pkg_llm_deepseek --> pkg_deepseek_account
|
||||
pkg_llm_deepseek --> pkg_deepseek_llm_api_extensions
|
||||
pkg_llm_deepseek --> pkg_fs
|
||||
pkg_llm_deepseek --> pkg_home_paths
|
||||
@@ -1390,6 +1402,7 @@ flowchart TD
|
||||
| [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — |
|
||||
| [`client-ui-session`](../packages/client/ui-session) | `client` | — |
|
||||
| [`client-ui-settings`](../packages/client/ui-settings) | `client` | — |
|
||||
| [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — |
|
||||
| [`client-ui-settings-agent-loop`](../packages/client/ui-settings-agent-loop) | `client` | — |
|
||||
| [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | — |
|
||||
| [`client-ui-settings-models`](../packages/client/ui-settings-models) | `client` | — |
|
||||
@@ -1444,6 +1457,7 @@ flowchart TD
|
||||
| [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) |
|
||||
| [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) |
|
||||
| [`credentials`](../packages/credentials/credentials) | `credentials` | [`invariants`](../packages/runtime-diagnostics/invariants) |
|
||||
| [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`brand`](../packages/util/brand) |
|
||||
| [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) |
|
||||
@@ -1460,6 +1474,7 @@ flowchart TD
|
||||
| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`http-proxy`](../packages/util/http-proxy), [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) |
|
||||
| [`web-search-exa`](../packages/web/web-search-exa) | `web` | [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) |
|
||||
| [`web-search-perplexity`](../packages/web/web-search-perplexity) | `web` | [`launch-environment`](../packages/util/launch-environment), [`web`](../packages/web/web) |
|
||||
| [`api-account-controller`](../packages/api/account-controller) | `api` | [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) |
|
||||
| [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) |
|
||||
@@ -1475,6 +1490,7 @@ flowchart TD
|
||||
| [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
|
||||
| [`api-gateway`](../packages/api/gateway) | `api` | [`client-connection`](../packages/client/connection) |
|
||||
| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`system-prompt`](../packages/core/system-prompt) |
|
||||
| [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) |
|
||||
| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |
|
||||
@@ -1498,7 +1514,7 @@ flowchart TD
|
||||
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
|
||||
| [`shell`](../packages/shell/shell) | `shell` | [`sandbox`](../packages/sandbox/sandbox), [`subprocess`](../packages/subprocess/subprocess) |
|
||||
| [`workspace`](../packages/workspace/workspace) | `workspace` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage`](../packages/storage/storage), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol) |
|
||||
| [`llm-deepseek`](../packages/llm/llm-deepseek) | `llm` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`atomic-write`](../packages/util/atomic-write), [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
|
||||
| [`llm-deepseek`](../packages/llm/llm-deepseek) | `llm` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`atomic-write`](../packages/util/atomic-write), [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
|
||||
| [`llm-pi-ai`](../packages/llm/llm-pi-ai) | `llm` | [`attachment`](../packages/attachment/attachment), [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`fs`](../packages/fs/fs), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
|
||||
| [`agent`](../packages/core/agent) | `core` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values), [`workspace`](../packages/workspace/workspace) |
|
||||
| [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs) |
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/** Account Remote delegation preserves provider results, failures, and stream lifetime. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account'
|
||||
import type { AccountView, SignInAttemptId } from '../src/types.ts'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import AccountController from '../src/index.ts'
|
||||
|
||||
const roots: Context[] = []
|
||||
afterEach(async () => { await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) })
|
||||
const state: AccountView = { status: 'signed-out', links: { usageUrl: 'https://platform.example/usage', topUpUrl: 'https://platform.example/top_up' }, attempt: null }
|
||||
|
||||
function fixture() {
|
||||
const ctx = new Context()
|
||||
roots.push(ctx)
|
||||
const provider = {
|
||||
getState: vi.fn<DeepSeekAccount['getState']>().mockResolvedValue(state),
|
||||
getProfile: vi.fn<DeepSeekAccount['getProfile']>().mockResolvedValue({ status: 'failed' }),
|
||||
getBalance: vi.fn<DeepSeekAccount['getBalance']>().mockResolvedValue(null),
|
||||
startSignIn: vi.fn<DeepSeekAccount['startSignIn']>().mockResolvedValue(state),
|
||||
cancelSignIn: vi.fn<DeepSeekAccount['cancelSignIn']>().mockResolvedValue(state),
|
||||
signOut: vi.fn<DeepSeekAccount['signOut']>().mockResolvedValue(state),
|
||||
watch: vi.fn<DeepSeekAccount['watch']>(),
|
||||
}
|
||||
ctx.provide('deepseekAccount', provider as never)
|
||||
return { provider, controller: new AccountController(ctx) }
|
||||
}
|
||||
|
||||
it('delegates account operations without coupling profile and balance queries', async () => {
|
||||
const { provider, controller } = fixture()
|
||||
expect(await controller.getState()).toBe(state)
|
||||
expect(await controller.getProfile()).toEqual({ status: 'failed' })
|
||||
expect(provider.getBalance).not.toHaveBeenCalled()
|
||||
expect(await controller.getBalance()).toBeNull()
|
||||
expect(await controller.startSignIn('zh-CN', 'http://127.0.0.1:8080', 'desktop')).toBe(state)
|
||||
expect(provider.startSignIn).toHaveBeenCalledExactlyOnceWith('zh-CN', 'http://127.0.0.1:8080', 'desktop')
|
||||
const id = 'attempt' as SignInAttemptId
|
||||
expect(await controller.cancelSignIn(id)).toBe(state)
|
||||
expect(provider.cancelSignIn).toHaveBeenCalledExactlyOnceWith(id)
|
||||
expect(await controller.signOut()).toBe(state)
|
||||
expect(provider.signOut).toHaveBeenCalledExactlyOnceWith()
|
||||
const failure = new Error('storage unavailable')
|
||||
provider.signOut.mockRejectedValueOnce(failure)
|
||||
await expect(controller.signOut()).rejects.toBe(failure)
|
||||
})
|
||||
|
||||
it('passes the subscriber lifetime to the provider and returns its state stream', async () => {
|
||||
const { provider, controller } = fixture()
|
||||
const lifetime = new AbortController()
|
||||
const stream: AsyncIterable<AccountView> = { async *[Symbol.asyncIterator]() { yield state } }
|
||||
provider.watch.mockReturnValue(stream)
|
||||
expect(controller.watch(lifetime.signal)).toBe(stream)
|
||||
expect(provider.watch).toHaveBeenCalledExactlyOnceWith(lifetime.signal)
|
||||
const received: AccountView[] = []
|
||||
for await (const value of stream) received.push(value)
|
||||
expect(received).toEqual([state])
|
||||
})
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-settings-account/README.md
|
||||
README.md: b6fc4087b211b7cbb91ca3a43fbaeb7e80b46e35
|
||||
README.zh.md: 2d1c00570d0cd026b6d9c0be91a8c54ac8f160b0
|
||||
README.md: fdbbc4c391e7b4d6f6111de936b23f2fa101f3e3
|
||||
README.zh.md: 64acaa4b975c5b37213990bb866b268c9a689d1e
|
||||
@@ -46,6 +46,8 @@ The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storag
|
||||
|
||||
Account login uses a dismissible dialog before the model onboarding credential editor. The dialog uses a compact, right-aligned action row with the primary action last. The sidebar displays the profile name, falling back to the server-masked phone number or email when the name is absent; it stays blank while the profile is loading. Dialog copy and the sidebar account label are not text-selectable; the copy-link button remains available and restores its label two seconds after each successful copy. Clipboard failures show Copy failed on the link for two seconds without interrupting sign-in. Waiting shows a copyable authorization link and a loading indicator; timeout and failure require an explicit retry. Sign-in failures render in that dialog; the launcher's inline failure line reports only a failed sign-out. Closing a waiting dialog cancels its Host attempt. The sidebar can reopen the same API-key editor through the settings coordinator. Browser login preopens a tab on the click and navigates it only when that attempt receives its authorization URL; blocked popups retain the copy-link route. The original tab retains the authorization window handle and closes it on failure, timeout, or cancellation. Login feedback stays in the original tab; callbacks never navigate to a second Web UI.
|
||||
|
||||
A terminal account-state stream failure appears in the sign-in dialog or Account settings. Plugin unload suppresses late failure reports.
|
||||
|
||||
The balance card shows recharge funds and positive bonus credit in separate rows. Empty or nonpositive bonus wallets hide the bonus row and its divider; currencies retain their own amounts.
|
||||
|
||||
<a id="model-experience"></a>
|
||||
|
||||
@@ -46,6 +46,8 @@ Desktop 的用量和充值操作在 48px 返回栏下方打开隔离的原生 Pl
|
||||
|
||||
账号登录在模型引导的凭证编辑器之前显示可关闭的弹窗。弹窗底部采用紧凑的右对齐横排操作,主操作位于末尾。侧边栏优先显示昵称,缺少昵称时显示服务端返回的脱敏手机号或邮箱;资料加载期间保持留空。 弹窗文字和侧边栏账号状态文字不可选中,复制登录链接按钮始终可用,并在每次复制成功两秒后恢复原文案。剪贴板失败时,链接原位显示“复制失败”两秒,不中断登录。等待状态提供可复制的授权链接和加载图标;超时和失败均须用户手动重试。登录失败在该弹窗内呈现;侧边栏入口的内联失败提示仅用于退出登录失败。关闭等待弹窗会取消对应 Host 登录流程。侧边栏通过设置协调器重新打开同一个 API Key 编辑器。浏览器登录在点击时预先打开标签页,只有该次流程收到授权地址后才导航;弹窗被拦截时保留复制链接入口。原标签页保留授权窗口引用,并在失败、超时或取消时关闭它。登录反馈留在原标签页,回调不会导航到第二个 Web UI。
|
||||
|
||||
账户状态流的终止错误会显示在登录对话框或账户设置中。插件卸载后不再报告延迟到达的错误。
|
||||
|
||||
余额卡片分行展示充值余额与正额赠金余额。赠送钱包为空或没有正余额时,隐藏赠金行及其分隔线;不同币种分别显示。
|
||||
|
||||
<a id="model-experience"></a>
|
||||
|
||||
@@ -53,7 +53,7 @@ export function AccountMenu({
|
||||
if (id === 'settings') { setOpen(false); openSettings() }
|
||||
else if (id === 'contact') { setOpen(false); contactUs() }
|
||||
else if (id === 'signin') beginSignIn()
|
||||
else if (id === 'signout') void logout()
|
||||
else void logout()
|
||||
}} />
|
||||
{account.loginVisible && !account.onboarding && <SignInDialog account={account} start={start} cancel={cancel} t={t}
|
||||
close={() => { showLogin(false) }} useApiKey={() => { showLogin(false); openOnboarding('deepseek-official') }} />}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
.card,
|
||||
.balanceCard {
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border: 0.5px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 10px;
|
||||
background: var(--dsw-alias-bg-module-platform);
|
||||
}
|
||||
@@ -74,7 +74,7 @@
|
||||
}
|
||||
|
||||
.divider {
|
||||
border-top: 1px solid var(--dsw-alias-border-l2);
|
||||
border-top: 0.5px solid var(--dsw-alias-border-l2);
|
||||
}
|
||||
|
||||
.links,
|
||||
@@ -96,7 +96,7 @@
|
||||
height: 32px;
|
||||
min-width: 58px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border: 0.5px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 12px;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
height: 48px;
|
||||
flex: none;
|
||||
padding: 6px 16px;
|
||||
border-bottom: 1px solid var(--dsw-alias-border-l1);
|
||||
border-bottom: 0.5px solid var(--dsw-alias-border-l1);
|
||||
app-region: drag;
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@
|
||||
height: 32px;
|
||||
min-width: 58px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border: 0.5px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 18px;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
|
||||
@@ -30,8 +30,7 @@ export function PlatformOverlay({ bridge, page, backLabel, loadingLabel, failure
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const [status, setStatus] = useState<'loading' | 'loaded' | 'failed'>('loading')
|
||||
useEffect(() => {
|
||||
const element = viewport.current
|
||||
if (element === null) return
|
||||
const element = viewport.current as HTMLDivElement
|
||||
const previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
const background = Array.from(document.body.children).filter((element): element is HTMLElement =>
|
||||
element instanceof HTMLElement && element !== layer.current).map(element => ({ element, inert: element.inert }))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
.dialog { user-select: none; box-sizing: border-box; border: 1px solid var(--dsw-alias-border-inverted); }
|
||||
.dialog { user-select: none; box-sizing: border-box; border: 0.5px solid var(--dsw-alias-border-inverted); }
|
||||
.content { display: flex; flex-direction: column; width: 100%; }
|
||||
.header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 22px 24px 12px; }
|
||||
.title { margin: 0; font-size: 16px; line-height: 24px; font-weight: 500; color: var(--dsw-alias-label-primary); }
|
||||
@@ -7,7 +7,7 @@
|
||||
.actions { box-sizing: border-box; display: flex; justify-content: flex-end; align-items: center; width: 100%; padding: 0 24px; gap: 8px; }
|
||||
.primaryButton, .secondaryButton { box-sizing: border-box; min-width: 72px; height: 36px; border-radius: 12px; font-size: 14px; line-height: 22px; }
|
||||
.primaryButton { padding: 0 16px; font-weight: 500; }
|
||||
.secondaryButton { padding: 0 14px; border: 1px solid var(--dsw-alias-border-l2); }
|
||||
.secondaryButton { padding: 0 14px; border: 0.5px solid var(--dsw-alias-border-l2); }
|
||||
.description { margin: 0; padding: 0 24px; font-size: 14px; line-height: 22px; color: var(--dsw-alias-label-primary); }
|
||||
.link { border: 0; padding: 0; background: transparent; color: inherit; font: inherit; text-decoration: underline; cursor: pointer; }
|
||||
.spinner { flex: none; animation: spin 1s linear infinite; }
|
||||
|
||||
@@ -25,6 +25,7 @@ export function SignInDialog({ account, start, cancel, close, useApiKey, t }: {
|
||||
const timer = setTimeout(() => { setCopyResult(null) }, 2000)
|
||||
return () => { clearTimeout(timer) }
|
||||
}, [copyResult])
|
||||
const authorizeUrl = attempt?.authorizeUrl
|
||||
const phase = attempt?.phase
|
||||
const active = busy || phase === 'initializing' || phase === 'waiting-browser' || phase === 'exchanging' || phase === 'committing'
|
||||
const expired = phase === 'expired'
|
||||
@@ -46,10 +47,9 @@ export function SignInDialog({ account, start, cancel, close, useApiKey, t }: {
|
||||
if (active && attempt) await cancel(attempt.id)
|
||||
await start()
|
||||
}
|
||||
const copyLink = async () => {
|
||||
if (!attempt?.authorizeUrl) return
|
||||
const copyLink = async (authorizeUrl: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(attempt.authorizeUrl)
|
||||
await navigator.clipboard.writeText(authorizeUrl)
|
||||
setCopyResult({ messageKey: 'copiedLink' })
|
||||
} catch { setCopyResult({ messageKey: 'copyFailed' }) }
|
||||
}
|
||||
@@ -63,8 +63,8 @@ export function SignInDialog({ account, start, cancel, close, useApiKey, t }: {
|
||||
</button>
|
||||
</div>
|
||||
{waiting ? <p className={css.description}>
|
||||
{t('browserPrompt')}<button type="button" className={css.link} disabled={!attempt?.authorizeUrl}
|
||||
onClick={() => { void copyLink() }}>
|
||||
{t('browserPrompt')}<button type="button" className={css.link} disabled={!authorizeUrl}
|
||||
onClick={authorizeUrl ? () => { void copyLink(authorizeUrl) } : undefined}>
|
||||
{t(copyResult?.messageKey ?? 'copyLink')}
|
||||
</button>{t('browserDescription')}
|
||||
</p> : <p className={css.description}>
|
||||
|
||||
@@ -67,7 +67,8 @@ export function apply(ctx: Context): void {
|
||||
const stream = ctx.remote.$stream<AccountView>({
|
||||
name: 'account', open: signal => ctx.remote.account.watch(signal), ended: () => new Error('account stream ended'),
|
||||
})
|
||||
ctx.effect(() => () => stream.dispose(), 'account: state stream')
|
||||
let disposed = false
|
||||
ctx.effect(() => () => { disposed = true; return stream.dispose() }, 'account: state stream')
|
||||
void (async () => {
|
||||
for await (const frame of stream) {
|
||||
revision++
|
||||
@@ -77,7 +78,7 @@ export function apply(ctx: Context): void {
|
||||
frame.accept()
|
||||
void refresh()
|
||||
}
|
||||
})().catch(() => { if (!stream.signal.aborted) publish({ ...snapshot, failed: true }) })
|
||||
})().catch(() => { if (!disposed) publish({ ...snapshot, failed: true }) })
|
||||
const nativePlatform = (globalThis as typeof globalThis & { dshPlatform?: PlatformBridge }).dshPlatform
|
||||
const operations: AccountSectionInjected = {
|
||||
...nativePlatform === undefined ? {} : { platform: nativePlatform },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup, fireEvent, render, screen, act } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { AccountDetails, AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types'
|
||||
import type { PlatformBridge } from '../src/client/PlatformOverlay.tsx'
|
||||
@@ -321,3 +321,92 @@ it('opens more account information externally without invoking the embedded Plat
|
||||
fireEvent.click(link)
|
||||
expect(platform.open).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['initializing', 'waiting-browser', 'exchanging'] as const)('shows %s and lets the user cancel the active attempt', async (phase) => {
|
||||
const operations = mount({ status: 'signed-out', attempt: { id: 'attempt' as SignInAttemptId, phase, authorizeUrl: 'https://example.test/authorize' } })
|
||||
expect(screen.getByRole('link', { name: en.open }).getAttribute('href')).toBe('https://example.test/authorize')
|
||||
expect(screen.getByRole('status').textContent).toBe(phase === 'initializing' ? en.initializing : phase === 'waiting-browser' ? en.waiting : en.completing)
|
||||
await act(async () => { fireEvent.click(screen.getByRole('button', { name: en.cancel })) })
|
||||
expect(operations.cancel).toHaveBeenCalledExactlyOnceWith('attempt')
|
||||
})
|
||||
|
||||
it.each(['failed', 'expired'] as const)('allows a new sign-in after the attempt is %s', (phase) => {
|
||||
mount({ status: 'signed-out', attempt: { id: 'attempt' as SignInAttemptId, phase } })
|
||||
expect(screen.getByRole('button', { name: en.signIn }).hasAttribute('disabled')).toBe(false)
|
||||
})
|
||||
|
||||
it('shows unavailable details and keeps external Platform links usable in a browser', () => {
|
||||
mount({ status: 'credential-stored', attempt: null }, en, {
|
||||
profile: { status: 'failed' }, balance: { status: 'failed' },
|
||||
})
|
||||
expect(screen.getByText(en.profileUnavailable)).toBeTruthy()
|
||||
expect(screen.getByText(en.balanceUnavailable)).toBeTruthy()
|
||||
for (const name of [en.usage, en.topUp]) {
|
||||
const event = new MouseEvent('click', { bubbles: true, cancelable: true })
|
||||
screen.getByRole('link', { name }).dispatchEvent(event)
|
||||
expect(event.defaultPrevented).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('reports a rejected settings login and disables login while initial state is unavailable', async () => {
|
||||
const operations = mount({ status: 'signed-out', attempt: null })
|
||||
cleanup()
|
||||
let snapshot: AccountSnapshot = { view: undefined, details: undefined, failed: true }
|
||||
const props = { ...({} as GlobalStandardProps), ...operations,
|
||||
start: vi.fn(async () => { throw new Error('unavailable') }),
|
||||
useAccount: <T,>(select: (value: AccountSnapshot) => T) => select(snapshot), close: () => {},
|
||||
t: (key: string) => en[key as AccountKey],
|
||||
}
|
||||
const view = render(<AccountSection {...props} />)
|
||||
expect(screen.getByRole('button', { name: en.signIn }).hasAttribute('disabled')).toBe(true)
|
||||
expect(screen.getByRole('status').textContent).toBe(en.failed)
|
||||
snapshot = operations.hooks.account.getSnapshot()
|
||||
view.rerender(<AccountSection {...props} />)
|
||||
await act(async () => { fireEvent.click(screen.getByRole('button', { name: en.signIn })) })
|
||||
expect(screen.getByRole('status').textContent).toBe(en.failed)
|
||||
})
|
||||
|
||||
it('dismisses a collapsed menu and hands its login dialog to the API-key onboarding step', async () => {
|
||||
const operations = mount({ status: 'credential-stored', attempt: null }, en, { profile: { status: 'failed' } })
|
||||
cleanup()
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
const openOnboarding = vi.fn()
|
||||
let snapshot = operations.hooks.account.getSnapshot()
|
||||
const props = { ...({} as GlobalStandardProps), ...operations, wide: false, openSettings: vi.fn(), openOnboarding,
|
||||
useAccount: <T,>(select: (value: AccountSnapshot) => T) => select(snapshot), t: (key: string) => en[key as AccountKey] }
|
||||
const view = render(<AccountMenu {...props} />)
|
||||
expect(screen.getByRole('button', { name: en.menu }).textContent).toBe('')
|
||||
fireEvent.click(screen.getByRole('button', { name: en.menu }))
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
snapshot = { ...snapshot, view: { ...snapshot.view!, status: 'signed-out' }, loginVisible: true }
|
||||
view.rerender(<AccountMenu {...props} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: en.close }))
|
||||
expect(operations.showLogin).toHaveBeenLastCalledWith(false)
|
||||
fireEvent.click(screen.getByRole('button', { name: en.addApiKey }))
|
||||
expect(openOnboarding).toHaveBeenCalledExactlyOnceWith('deepseek-official')
|
||||
snapshot = { ...snapshot, onboarding: true }
|
||||
view.rerender(<AccountMenu {...props} />)
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
})
|
||||
|
||||
it('reports resize failure, ignores late native failures, and tolerates a removed IPC receiver', async () => {
|
||||
let resize: (() => void) | undefined
|
||||
vi.stubGlobal('ResizeObserver', class { constructor(callback: () => void) { resize = callback } observe() {} disconnect() {} })
|
||||
const loaded = Promise.withResolvers<undefined>()
|
||||
const platform: PlatformBridge = { open: () => loaded.promise,
|
||||
setBounds: vi.fn(async () => { throw new Error('resize failed') }), close: vi.fn(async () => { throw new Error('window gone') }) }
|
||||
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
|
||||
svg.setAttribute('tabindex', '0')
|
||||
document.body.append(svg)
|
||||
onTestFinished(() => { svg.remove() })
|
||||
svg.focus()
|
||||
mount({ status: 'credential-stored', attempt: null }, en, undefined, platform)
|
||||
await act(async () => { fireEvent.click(screen.getByRole('link', { name: en.usage })) })
|
||||
await act(async () => { resize!() })
|
||||
expect(platform.setBounds).toHaveBeenCalled()
|
||||
expect(screen.getByText(en.platformFailed)).toBeTruthy()
|
||||
await act(async () => { fireEvent.click(screen.getByRole('button', { name: en.backToHarness })) })
|
||||
await act(async () => { loaded.reject(new Error('late failure')); await loaded.promise.catch(() => {}) })
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
// @vitest-environment jsdom
|
||||
/** Account operations and request lifetimes in the shipped web composition. */
|
||||
import { afterEach, expect, vi } from 'vitest'
|
||||
import { ok } from '@deepseek-ai/dsh-remote-mock'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { createClientTest, type TestClient, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts'
|
||||
import type { AccountDetails, AccountView, AccountUserId, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types'
|
||||
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { AccountSectionInjected } from '../src/client/AccountSection.tsx'
|
||||
import { CONTACT_CONFIG_GLOBAL } from '../src/contact-config.ts'
|
||||
|
||||
const it = createClientTest({ roster: webApp })
|
||||
const SELF = '@deepseek-ai/dsh-client-ui-settings-account'
|
||||
const view: AccountView = { status: 'signed-out', attempt: null, links: { usageUrl: '', topUpUrl: '' } }
|
||||
const stored: AccountView = { ...view, status: 'credential-stored' }
|
||||
const profile: AccountDetails['profile'] = { status: 'ready', value: { id: 'account-user' as AccountUserId, name: 'User', contact: null } }
|
||||
function operations(c: TestClient): AccountSectionInjected {
|
||||
const injected: object = c.ctx.slots.entries('settings.launcher')[0]!.inject!()
|
||||
return injected as AccountSectionInjected
|
||||
}
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
|
||||
|
||||
it('shares account actions across seats, publishes dialog ownership, and opens contextual support', async ({ start }) => {
|
||||
vi.stubGlobal(CONTACT_CONFIG_GLOBAL, { contactFormUrl: 'https://example.test/form/', contactSource: 'harness' })
|
||||
const open = vi.spyOn(window, 'open').mockReturnValue(null)
|
||||
const c = await start()
|
||||
const actions = operations(c)
|
||||
expect(c.ctx.slots.entries('settings.models.sign-in')[0]!.inject!()).toBe(actions)
|
||||
await actions.refresh()
|
||||
expect(c.mock.remote.account.getProfile).not.toHaveBeenCalled()
|
||||
const listener = vi.fn()
|
||||
const off = actions.hooks.account.subscribe(listener)
|
||||
actions.showLogin(true)
|
||||
actions.setOnboarding(true)
|
||||
expect(actions.hooks.account.getSnapshot()).toMatchObject({ loginVisible: true, onboarding: true })
|
||||
expect(listener).toHaveBeenCalledTimes(2)
|
||||
off()
|
||||
actions.showLogin(false)
|
||||
expect(listener).toHaveBeenCalledTimes(2)
|
||||
actions.contactUs()
|
||||
expect(new URL(String(open.mock.calls.at(-1)![0])).searchParams.has('prefill_uid')).toBe(false)
|
||||
c.mock.remote.account.getProfile.mockResolvedValue(ok(profile))
|
||||
c.mock.streams.push('account/watch', stored)
|
||||
await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details?.profile).toEqual(profile) })
|
||||
const entry = c.ctx.slots.entries('settings.section').find(entry => entry.options.id === 'account')!
|
||||
expect(entry.inject!()).toBe(actions)
|
||||
expect(resolveSlotLabel(entry.options.label)).toBe('Account')
|
||||
vi.spyOn(c.ctx.locale, 'getSnapshot').mockReturnValue({ ...c.ctx.locale.getSnapshot(), active: 'zh' })
|
||||
actions.contactUs()
|
||||
const support = new URL(String(open.mock.calls.at(-1)![0]))
|
||||
expect(support.searchParams.get('prefill_uid')).toBe('account-user')
|
||||
expect(support.searchParams.get('prefill_app_locale')).toBe('zh-CN')
|
||||
await c.unload(SELF)
|
||||
expect(c.ctx.slots.entries('settings.launcher')).toHaveLength(0)
|
||||
}, 60_000)
|
||||
|
||||
it('coalesces refreshes, publishes independent failures, and rejects stale responses after sign-out or unload', async ({ start }) => {
|
||||
const c = await start()
|
||||
const actions = operations(c)
|
||||
const pending = Promise.withResolvers<ReturnType<typeof ok<AccountDetails['profile'] | null>>>()
|
||||
c.mock.remote.account.getProfile.mockReturnValueOnce(pending.promise)
|
||||
c.mock.remote.account.getBalance.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) })
|
||||
c.mock.streams.push('account/watch', stored)
|
||||
await vi.waitFor(() => { expect(c.mock.remote.account.getProfile).toHaveBeenCalledOnce() })
|
||||
const a = actions.refresh()
|
||||
expect(actions.refresh()).toBe(a)
|
||||
c.mock.streams.push('account/watch', view)
|
||||
await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) })
|
||||
pending.resolve(ok(profile))
|
||||
await a
|
||||
expect(actions.hooks.account.getSnapshot().details).toBeUndefined()
|
||||
c.mock.remote.account.getProfile.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) })
|
||||
c.mock.remote.account.getBalance.mockRejectedValueOnce(new Error('offline'))
|
||||
c.mock.streams.push('account/watch', stored)
|
||||
await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details).toEqual({ profile: { status: 'failed' }, balance: { status: 'failed' } }) })
|
||||
const pendingAgain = Promise.withResolvers<ReturnType<typeof ok<AccountDetails['profile'] | null>>>()
|
||||
c.mock.remote.account.getProfile.mockReturnValueOnce(pendingAgain.promise)
|
||||
const request = actions.refresh()
|
||||
await c.unload(SELF)
|
||||
pendingAgain.resolve(ok(profile))
|
||||
await request
|
||||
expect(actions.hooks.account.getSnapshot().details?.profile).toEqual({ status: 'failed' })
|
||||
}, 60_000)
|
||||
|
||||
for (const desktop of [false, true]) it(`uses the browser or Desktop login carrier (Desktop: ${desktop}) and exposes operation errors`, async ({ start, mock }) => {
|
||||
vi.spyOn(window, 'open').mockReturnValue(null)
|
||||
if (desktop) vi.stubGlobal('dshDesktop', {})
|
||||
const c = await start()
|
||||
const actions = operations(c)
|
||||
mock.remote.account.startSignIn.mockResolvedValue(ok(view))
|
||||
await actions.start()
|
||||
expect(mock.remote.account.startSignIn).toHaveBeenCalledWith('en', window.location.origin, desktop ? 'desktop' : 'web')
|
||||
const failure = { ok: false as const, error: new RemoteError('gateway/internal', 'offline', {}) }
|
||||
mock.remote.account.startSignIn.mockResolvedValueOnce(failure)
|
||||
await expect(actions.start()).rejects.toThrow('account start failed')
|
||||
expect(actions.hooks.account.getSnapshot()).toMatchObject({ loginVisible: true, loginFailed: true })
|
||||
const id = 'cancel-me' as SignInAttemptId
|
||||
mock.remote.account.cancelSignIn.mockResolvedValueOnce(ok(view)).mockResolvedValueOnce(failure)
|
||||
await actions.cancel(id)
|
||||
await expect(actions.cancel(id)).rejects.toThrow('account cancel failed')
|
||||
mock.remote.account.signOut.mockResolvedValueOnce(ok(view)).mockResolvedValueOnce(failure)
|
||||
await actions.signOut()
|
||||
await expect(actions.signOut()).rejects.toThrow('account sign-out failed')
|
||||
}, 60_000)
|
||||
|
||||
it('uses the Desktop stream origin and exposes the native platform bridge', async ({ start, mock }) => {
|
||||
const c = await start()
|
||||
vi.stubGlobal('dshDesktop', {})
|
||||
vi.stubGlobal('__DSH_TRANSPORT__', { streamBaseUrl: 'http://localhost:9876/stream' })
|
||||
const platform = { open: vi.fn(), setBounds: vi.fn(), close: vi.fn() }
|
||||
vi.stubGlobal('dshPlatform', platform)
|
||||
await c.reload(SELF)
|
||||
const actions = operations(c)
|
||||
expect(actions.platform).toBe(platform)
|
||||
mock.remote.account.startSignIn.mockResolvedValue(ok(view))
|
||||
await actions.start()
|
||||
expect(mock.remote.account.startSignIn).toHaveBeenCalledWith('en', 'http://localhost:9876', 'desktop')
|
||||
}, 60_000)
|
||||
|
||||
|
||||
it('publishes a terminal state-stream failure without mistaking it for plugin disposal', async ({ start }) => {
|
||||
const c = await start()
|
||||
const actions = operations(c)
|
||||
await c.mock.streams.opened('account/watch', 1)
|
||||
c.mock.streams.end('account/watch')
|
||||
await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().failed).toBe(true) })
|
||||
}, 60_000)
|
||||
|
||||
it('ignores a terminal stream error when plugin disposal already owns teardown', async ({ start }) => {
|
||||
const c = await start()
|
||||
let disposal: Promise<void> | undefined
|
||||
const original = c.ctx.remote.$stream.bind(c.ctx.remote)
|
||||
const spy = vi.spyOn(c.ctx.remote, '$stream').mockImplementation((options) => {
|
||||
const stream = original(options)
|
||||
stream.signal.addEventListener('abort', () => { disposal = c.unload(SELF) }, { once: true })
|
||||
return stream
|
||||
})
|
||||
await c.reload(SELF)
|
||||
spy.mockRestore()
|
||||
const actions = operations(c)
|
||||
await c.mock.streams.opened('account/watch', 2)
|
||||
c.mock.streams.end('account/watch')
|
||||
await vi.waitFor(() => { expect(disposal).toBeDefined() })
|
||||
await disposal
|
||||
expect(actions.hooks.account.getSnapshot().failed).toBe(false)
|
||||
}, 60_000)
|
||||
@@ -0,0 +1,20 @@
|
||||
/** Public questionnaire options are emitted in the page bootstrap. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { expect, it, onTestFinished } from 'vitest'
|
||||
import type { IndexInjection } from '@deepseek-ai/dsh-host-webserver'
|
||||
import { apply, Config } from '../src/index.ts'
|
||||
import { CONTACT_CONFIG_GLOBAL } from '../src/contact-config.ts'
|
||||
|
||||
it('injects configured contact options and removes the listener on disposal', async () => {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
const config = Config({ contactSource: 'harness' })
|
||||
apply(ctx, config)
|
||||
const table: IndexInjection[] = []
|
||||
ctx.emit('webserver/index-inject', table)
|
||||
expect(table).toEqual([{ kind: 'global', name: CONTACT_CONFIG_GLOBAL, value: config }])
|
||||
await ctx.fiber.dispose()
|
||||
table.length = 0
|
||||
ctx.emit('webserver/index-inject', table)
|
||||
expect(table).toEqual([])
|
||||
})
|
||||
@@ -29,3 +29,10 @@ it('opens a configured form without stale account context when signed out', () =
|
||||
expect(url.searchParams.get('hide_uid')).toBe('1')
|
||||
expect(() => Config({ contactFormUrl: 'javascript:alert(1)' })).toThrow()
|
||||
})
|
||||
|
||||
it.each([NaN, Infinity])('uses CSS pixel dimensions when device pixel ratio is %s', (pixelRatio) => {
|
||||
const url = new URL(contactUrl(Config({}), {
|
||||
uid: null, version: undefined, locale: 'en', width: 800, height: 600, pixelRatio,
|
||||
}))
|
||||
expect(url.searchParams.get('prefill_screen_resolution')).toBe('800x600')
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
// @vitest-environment jsdom
|
||||
/** The credential onboarding step owns login until dismissal or completion. */
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { AccountOnboarding } from '../src/client/AccountOnboarding.tsx'
|
||||
import type { AccountSnapshot } from '../src/client/AccountSection.tsx'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { en } from '../src/client/locales.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
it('claims onboarding while loading, offers API key fallback, and completes after login', () => {
|
||||
let account: AccountSnapshot = { view: undefined, details: undefined, failed: false }
|
||||
const unused = (): never => { throw new Error('AccountOnboarding does not consume global hooks') }
|
||||
const globals: GlobalStandardProps = {
|
||||
usePanelInfo: unused, useSessions: unused, useSessionStatus: unused,
|
||||
useSessionRetainInfo: unused, useResource: unused, useWorkspaces: unused,
|
||||
}
|
||||
const props = {
|
||||
...globals,
|
||||
complete: vi.fn(), useApiKey: vi.fn(), setOnboarding: vi.fn(), showLogin: vi.fn(),
|
||||
useAccount: <T,>(select: (snapshot: AccountSnapshot) => T) => select(account),
|
||||
start: vi.fn(async () => {}), cancel: vi.fn(async () => {}), signOut: vi.fn(async () => {}),
|
||||
refresh: vi.fn(async () => {}), contactUs: vi.fn(), t: makeTranslate(en),
|
||||
}
|
||||
const view = render(<AccountOnboarding {...props} />)
|
||||
expect(props.setOnboarding).toHaveBeenCalledExactlyOnceWith(true)
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
account = { ...account, view: { status: 'signed-out', attempt: null, links: { usageUrl: '', topUpUrl: '' } } }
|
||||
view.rerender(<AccountOnboarding {...props} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: en.addApiKey }))
|
||||
expect(props.showLogin).toHaveBeenLastCalledWith(false)
|
||||
expect(props.useApiKey).toHaveBeenCalledOnce()
|
||||
fireEvent.click(screen.getByRole('button', { name: en.close }))
|
||||
expect(props.complete).toHaveBeenCalledOnce()
|
||||
account = { ...account, view: { ...account.view!, status: 'credential-stored' } }
|
||||
view.rerender(<AccountOnboarding {...props} />)
|
||||
expect(props.complete).toHaveBeenCalledTimes(2)
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
view.unmount()
|
||||
expect(props.setOnboarding).toHaveBeenLastCalledWith(false)
|
||||
})
|
||||
@@ -132,3 +132,27 @@ it('does not start another attempt when cancellation fails', async () => {
|
||||
expect(screen.getByRole('dialog', { name: en.failureTitle })).toBeTruthy()
|
||||
expect(screen.getByRole('button', { name: en.retry }).hasAttribute('disabled')).toBe(false)
|
||||
})
|
||||
|
||||
it('dismisses an idle dialog and closes after the account becomes signed in', () => {
|
||||
const props = mount(null)
|
||||
fireEvent.keyDown(document, { key: 'Enter' })
|
||||
expect(props.close).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: en.close }))
|
||||
expect(props.close).toHaveBeenCalledOnce()
|
||||
cleanup()
|
||||
render(<SignInDialog {...props} account={{ ...props.account, view: { ...props.account.view, status: 'credential-stored' } }} />)
|
||||
expect(props.close).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('keeps an outstanding start open until the request settles', async () => {
|
||||
const props = mount(null)
|
||||
cleanup()
|
||||
const pending = Promise.withResolvers<undefined>()
|
||||
props.start.mockReturnValueOnce(pending.promise)
|
||||
render(<SignInDialog {...props} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: en.signIn }))
|
||||
fireEvent.click(screen.getByRole('button', { name: en.close }))
|
||||
expect(props.close).not.toHaveBeenCalled()
|
||||
await act(async () => { pending.resolve(undefined); await pending.promise })
|
||||
expect(screen.getByRole('button', { name: en.signIn }).hasAttribute('disabled')).toBe(false)
|
||||
})
|
||||
@@ -445,3 +445,11 @@ it('explicitly reopens one onboarding editor during an existing session', () =>
|
||||
renderSlot.mockClear()
|
||||
expect(screen.queryByTestId('onboarding')).toBeNull()
|
||||
})
|
||||
|
||||
it('opens Account from the contributed sidebar launcher', () => {
|
||||
const { renderSlot } = mount({ rows: [{ id: 'account', order: -10, label: 'Account' }] })
|
||||
const launcher = renderSlot.mock.calls.find(call => call[0] === 'settings.launcher')!
|
||||
act(() => { (launcher[1] as { openSettings: () => void }).openSettings() })
|
||||
expect(screen.getByTestId('section-account')).toBeTruthy()
|
||||
expect(screen.getByRole('button', { name: 'Account' }).querySelector('svg')).not.toBeNull()
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Window drag-region ownership, asserted against the CSS text on disk:
|
||||
* `-webkit-app-region: drag` appears only in the two chrome bands that mount
|
||||
* before all content — ui-layout's frame band and ui-sidebar's logo row.
|
||||
* `-webkit-app-region: drag` belongs to window chrome: the frame band,
|
||||
* sidebar logo row, and the full-window Platform overlay's return bar.
|
||||
* Electron composes app-regions from window geometry in DOM order, ignoring
|
||||
* stacking: a drag rule on a content container overrides the no-drag of any
|
||||
* overlay mounted earlier, so its controls drag the window instead of
|
||||
@@ -15,6 +15,7 @@ import { packageStylesheets, parseRules } from './stylesheet-scan.ts'
|
||||
const DRAG_OWNERS = [
|
||||
'client/ui-layout/src/client/AppFrame.module.css',
|
||||
'client/ui-sidebar/src/client/SidebarRoot.module.css',
|
||||
'client/ui-settings-account/src/client/PlatformOverlay.module.css',
|
||||
]
|
||||
|
||||
/**
|
||||
@@ -60,10 +61,18 @@ describe('window drag-region ownership', () => {
|
||||
expect(offenders([`/packages/${DRAG_OWNERS[0]!}`], () => drag)).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps -webkit-app-region: drag inside the two chrome bands', () => {
|
||||
it('keeps -webkit-app-region: drag inside the owned chrome bands', () => {
|
||||
expect(offenders(packageStylesheets(), file => readFileSync(file, 'utf8'))).toEqual([])
|
||||
})
|
||||
|
||||
it('limits the Platform overlay drag region to its return bar and excludes the return button', () => {
|
||||
const file = packageStylesheets().find(candidate => candidate.endsWith('/client/ui-settings-account/src/client/PlatformOverlay.module.css'))!
|
||||
const css = readFileSync(file, 'utf8')
|
||||
expect(dragSelectors(css)).toEqual(['.header'])
|
||||
expect(parseRules(css).find(rule => rule.selectors.includes('.back'))?.declarations)
|
||||
.toContainEqual(['app-region', 'no-drag'])
|
||||
})
|
||||
|
||||
it('still finds a drag band in every allowlisted owner', () => {
|
||||
// An owner that stops declaring drag should leave the allowlist with it.
|
||||
for (const owner of DRAG_OWNERS) {
|
||||
|
||||
@@ -485,7 +485,7 @@ it('rejects a commit attempted after local cancellation', async () => {
|
||||
} finally { finish.resolve(undefined) }
|
||||
})
|
||||
|
||||
it('finishes an admitted commit without reporting cancellation during storage', async () => {
|
||||
it.each(['local', 'caller'] as const)('finishes an admitted commit during %s cancellation', async (source) => {
|
||||
const ctx = await harness()
|
||||
const admitted = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
@@ -499,12 +499,50 @@ it('finishes an admitted commit without reporting cancellation during storage',
|
||||
key: KEY, label: 'Account', methods: [{ id: 'browser', label: 'Browser' }],
|
||||
run: session => session.commit({ kind: 'grant', payload: { token: 'saved' } }),
|
||||
})
|
||||
const running = ctx.authorization.begin({ key: KEY, interaction: surface() })
|
||||
const controller = new AbortController()
|
||||
const running = ctx.authorization.begin({ key: KEY, interaction: surface(), signal: controller.signal })
|
||||
try {
|
||||
await admitted.promise
|
||||
ctx.authorization.cancel(KEY)
|
||||
if (source === 'local') ctx.authorization.cancel(KEY)
|
||||
else controller.abort()
|
||||
release.resolve(undefined)
|
||||
await expect(running).resolves.toEqual({ status: 'authorized' })
|
||||
expect(await ctx.credentials.readRecord(KEY)).toMatchObject({ payload: { token: 'saved' } })
|
||||
} finally { release.resolve(undefined); write.mockRestore() }
|
||||
})
|
||||
|
||||
it('rejects a settled session commit before and during the next attempt', async () => {
|
||||
const ctx = await harness()
|
||||
const first = Promise.withResolvers<AuthorizationSession>()
|
||||
const second = Promise.withResolvers<AuthorizationSession>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
let attempts = 0
|
||||
ctx.authorization.registerFlow({
|
||||
key: KEY, label: 'Account', methods: [{ id: 'browser', label: 'Browser' }],
|
||||
async run(session) {
|
||||
attempts += 1
|
||||
if (attempts === 1) first.resolve(session)
|
||||
else {
|
||||
second.resolve(session)
|
||||
await release.promise
|
||||
}
|
||||
await session.commit({ kind: 'grant', payload: { token: `grant-${String(attempts)}` } })
|
||||
},
|
||||
})
|
||||
await expect(ctx.authorization.begin({ key: KEY, interaction: surface() }))
|
||||
.resolves.toEqual({ status: 'authorized' })
|
||||
const settled = await first.promise
|
||||
const late = { kind: 'grant' as const, payload: { token: 'late' } }
|
||||
await expect(settled.commit(late)).rejects.toMatchObject({ code: 'CANCELLED' })
|
||||
|
||||
const running = ctx.authorization.begin({ key: KEY, interaction: surface() })
|
||||
try {
|
||||
await second.promise
|
||||
await expect(settled.commit(late)).rejects.toMatchObject({ code: 'CANCELLED' })
|
||||
expect(await ctx.credentials.readRecord(KEY)).toMatchObject({ payload: { token: 'grant-1' } })
|
||||
} finally {
|
||||
release.resolve(undefined)
|
||||
await running
|
||||
}
|
||||
expect(await ctx.credentials.readRecord(KEY)).toMatchObject({ payload: { token: 'grant-2' } })
|
||||
})
|
||||
@@ -129,7 +129,7 @@ export class PlatformAccount extends DeepSeekAccount {
|
||||
run: (session) => {
|
||||
const attempt = this.attempt
|
||||
if (attempt === undefined) return Promise.reject(new PlatformAuthError('protocol'))
|
||||
attempt.running = this.run(session)
|
||||
attempt.running = this.run(session, attempt)
|
||||
return attempt.running
|
||||
},
|
||||
})
|
||||
@@ -187,6 +187,30 @@ export class PlatformAccount extends DeepSeekAccount {
|
||||
|
||||
private async getDetail<K extends keyof AccountDetails>(field: K): Promise<AccountDetails[K] | null> {
|
||||
const lifetime = this.detailsLifetime
|
||||
const stored = await this.readCurrentGrant(lifetime)
|
||||
if (stored === null || lifetime.signal.aborted) return null
|
||||
if (field === 'profile' && this.attempt?.initialProfile?.token === stored.token) {
|
||||
const initial = this.attempt.initialProfile.value
|
||||
delete this.attempt.initialProfile
|
||||
return initial as AccountDetails[K]
|
||||
}
|
||||
const details = await readAccountDetail(field, this.origin, stored.token,
|
||||
AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]),
|
||||
{ ...this.accountRequestHeaders, ...this.clientHeaders })
|
||||
return this.detailsLifetime !== lifetime ? null : details
|
||||
}
|
||||
|
||||
override async getPlatformSession(): Promise<PlatformSession | null> {
|
||||
const lifetime = this.detailsLifetime
|
||||
const stored = await this.readCurrentGrant(lifetime)
|
||||
if (stored === null || lifetime.signal.aborted) return null
|
||||
const requestHeaders = { ...this.accountRequestHeaders, ...this.clientHeaders }
|
||||
return { origin: this.origin, token: stored.token,
|
||||
...(this.embeddedPageDist ? { embeddedPageDist: this.embeddedPageDist } : {}),
|
||||
...(Object.keys(requestHeaders).length ? { requestHeaders } : {}) }
|
||||
}
|
||||
|
||||
private async readCurrentGrant(lifetime: AbortController): Promise<z.infer<typeof grant> | null> {
|
||||
if (this.closed) return null
|
||||
const record = await this.ctx.credentials.readRecord(KEY)
|
||||
if (record === undefined || lifetime.signal.aborted) return null
|
||||
@@ -195,30 +219,7 @@ export class PlatformAccount extends DeepSeekAccount {
|
||||
if (!parsed.success) throw new PlatformAuthError('storage')
|
||||
// A private origin override must never forward a grant issued by another environment.
|
||||
if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol')
|
||||
if (field === 'profile' && this.attempt?.initialProfile?.token === parsed.data.token) {
|
||||
const initial = this.attempt.initialProfile.value
|
||||
delete this.attempt.initialProfile
|
||||
return initial as AccountDetails[K]
|
||||
}
|
||||
const details = await readAccountDetail(field, this.origin, parsed.data.token,
|
||||
AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]),
|
||||
{ ...this.accountRequestHeaders, ...this.clientHeaders })
|
||||
return this.detailsLifetime !== lifetime ? null : details
|
||||
}
|
||||
|
||||
override async getPlatformSession(): Promise<PlatformSession | null> {
|
||||
const lifetime = this.detailsLifetime
|
||||
if (this.closed) return null
|
||||
const record = await this.ctx.credentials.readRecord(KEY)
|
||||
if (record === undefined || lifetime.signal.aborted) return null
|
||||
if (record.kind !== 'grant') throw new PlatformAuthError('storage')
|
||||
const parsed = grant.safeParse(record.payload)
|
||||
if (!parsed.success) throw new PlatformAuthError('storage')
|
||||
if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol')
|
||||
const requestHeaders = { ...this.accountRequestHeaders, ...this.clientHeaders }
|
||||
return { origin: this.origin, token: parsed.data.token,
|
||||
...(this.embeddedPageDist ? { embeddedPageDist: this.embeddedPageDist } : {}),
|
||||
...(Object.keys(requestHeaders).length ? { requestHeaders } : {}) }
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
override async resolveToken(url: string): Promise<string | undefined> {
|
||||
@@ -350,15 +351,12 @@ export class PlatformAccount extends DeepSeekAccount {
|
||||
private changed(): void { for (const listener of this.listeners) listener() }
|
||||
|
||||
private update(attempt: Attempt, value: Partial<SignInAttemptView>): void {
|
||||
if (this.attempt !== attempt) return
|
||||
const { authorizeUrl: _url, ...rest } = attempt.view
|
||||
attempt.view = { ...rest, ...value }
|
||||
this.changed()
|
||||
}
|
||||
|
||||
private async run(session: AuthorizationSession): Promise<void> {
|
||||
const attempt = this.attempt
|
||||
if (attempt === undefined) throw new PlatformAuthError('protocol')
|
||||
private async run(session: AuthorizationSession, attempt: Attempt): Promise<void> {
|
||||
const webServer = this.ctx.get('webServer')
|
||||
if (webServer === undefined) throw new PlatformAuthError('protocol')
|
||||
const verifier = randomBytes(32).toString('base64url')
|
||||
@@ -401,15 +399,7 @@ export class PlatformAccount extends DeepSeekAccount {
|
||||
code_challenge: challenge, code_challenge_method: 'S256', state, redirect_uri: redirectUri, locale: attempt.locale,
|
||||
login_source: attempt.loginSource,
|
||||
}, signal), { reportInput: true })
|
||||
if (!init.success) {
|
||||
console.info('[deepseek-account] payload rejected', {
|
||||
stage: 'auth_init', issues: init.error.issues.map(issue => ({
|
||||
path: issue.path, code: issue.code,
|
||||
receivedType: issue.input === null ? 'null' : Array.isArray(issue.input) ? 'array' : typeof issue.input,
|
||||
})),
|
||||
})
|
||||
throw new PlatformAuthError('protocol')
|
||||
}
|
||||
if (!init.success) this.rejectPayload('auth_init', init.error)
|
||||
const authorizeUrl = browserUrl(init.data.authorize_url, this.origin, '/dsh/authorize', this.rewriteBrowserOrigin)
|
||||
authorizeId = init.data.authorize_id
|
||||
signal.throwIfAborted()
|
||||
@@ -431,15 +421,7 @@ export class PlatformAccount extends DeepSeekAccount {
|
||||
code: receivedCode, code_verifier: verifier, redirect_uri: redirectUri,
|
||||
device_id: identity.id, device_model: `${platform()}-${arch()}`, os_version: `${platform()} ${release()}`,
|
||||
}, signal), { reportInput: true })
|
||||
if (!result.success) {
|
||||
console.info('[deepseek-account] payload rejected', {
|
||||
stage: 'auth_exchange', issues: result.error.issues.map(issue => ({
|
||||
path: issue.path, code: issue.code,
|
||||
receivedType: issue.input === null ? 'null' : Array.isArray(issue.input) ? 'array' : typeof issue.input,
|
||||
})),
|
||||
})
|
||||
throw new PlatformAuthError('protocol')
|
||||
}
|
||||
if (!result.success) this.rejectPayload('auth_exchange', result.error)
|
||||
const completionUrl = new URL(browserUrl(result.data.authorized_url, this.origin, '/dsh/authorized', this.rewriteBrowserOrigin))
|
||||
completionUrl.searchParams.set('login_source', attempt.loginSource)
|
||||
attempt.completionUrl = completionUrl.href
|
||||
@@ -466,6 +448,16 @@ export class PlatformAccount extends DeepSeekAccount {
|
||||
}
|
||||
}
|
||||
|
||||
private rejectPayload(stage: string, error: z.ZodError): never {
|
||||
console.info('[deepseek-account] payload rejected', {
|
||||
stage, issues: error.issues.map(issue => ({
|
||||
path: issue.path, code: issue.code,
|
||||
receivedType: issue.input === null ? 'null' : Array.isArray(issue.input) ? 'array' : typeof issue.input,
|
||||
})),
|
||||
})
|
||||
throw new PlatformAuthError('protocol')
|
||||
}
|
||||
|
||||
private cancelRequest(authorizeId: string, verifier: string): void {
|
||||
if (this.closed) return
|
||||
const cancellation = this.request('auth_cancel', { authorize_id: authorizeId, code_verifier: verifier },
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { Context, Service } from '@deepseek-ai/cordis'
|
||||
import { mkdtemp, rm, readFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { createServer as createTcpServer, connect, type Socket } from 'node:net'
|
||||
import { createServer as createTcpServer, connect, Socket } from 'node:net'
|
||||
import { join } from 'node:path'
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
||||
import { createServer, IncomingMessage, ServerResponse } from 'node:http'
|
||||
import WebServer from '@deepseek-ai/dsh-host-webserver'
|
||||
import AuthorizationService from '@deepseek-ai/dsh-authorization'
|
||||
import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local'
|
||||
@@ -145,7 +145,7 @@ async function fixture(
|
||||
})
|
||||
await provider
|
||||
cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose(); await web.dispose() })
|
||||
const account = ctx.deepseekAccount
|
||||
const account = ctx.deepseekAccount as PlatformAccount
|
||||
const states = new AbortController()
|
||||
cleanups.push(async () => { states.abort() })
|
||||
async function wait(phase: string) {
|
||||
@@ -852,3 +852,341 @@ it.each([undefined, [{ currency: 'EUR', balance: '1' }], [{ currency: 'CNY', bal
|
||||
expect(await f.account.getBalance()).toEqual({ status: 'failed' })
|
||||
},
|
||||
)
|
||||
|
||||
it.each([{ kind: 'api-key' as const, key: 'wrong-kind' }, { kind: 'grant' as const, payload: { version: 0 } }])(
|
||||
'rejects invalid stored account records across account consumers: $kind', async (record) => {
|
||||
const f = await fixture()
|
||||
const key = credentialKey('deepseek-account-platform', 'default')
|
||||
await f.ctx.credentials.modifyRecord(key, () => Promise.resolve(record))
|
||||
await expect(f.account.getState()).rejects.toThrow('account: storage')
|
||||
await expect(f.account.getProfile()).rejects.toThrow('account: storage')
|
||||
await expect(f.account.getPlatformSession()).rejects.toThrow('account: storage')
|
||||
await expect(f.account.resolveToken('https://api.deepseek.com')).rejects.toThrow('account: storage')
|
||||
await expect(f.account.signOut()).rejects.toThrow('account: storage')
|
||||
},
|
||||
)
|
||||
|
||||
it('returns no credentials when signed out or disposed', async () => {
|
||||
const f = await fixture()
|
||||
expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined()
|
||||
expect(await f.account.getPlatformSession()).toBeNull()
|
||||
await f.account.cancelSignIn('missing' as import('@deepseek-ai/dsh-deepseek-account').SignInAttemptId)
|
||||
await f.dispose()
|
||||
expect(await f.account.getProfile()).toBeNull()
|
||||
expect(await f.account.getPlatformSession()).toBeNull()
|
||||
await expect(f.account.startSignIn('en', f.callbackOrigin, 'web')).rejects.toThrow('account: protocol')
|
||||
await expect(f.account.signOut()).rejects.toThrow('account: protocol')
|
||||
})
|
||||
|
||||
it('rejects sign-out and inference grants issued by another environment', async () => {
|
||||
const f = await fixture(undefined, {}, false, {}, 'https://private.example')
|
||||
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({
|
||||
kind: 'grant', payload: { version: 1, token: 'real-token', issuer: 'https://other.example' },
|
||||
}))
|
||||
expect(await f.account.resolveToken('https://private.example')).toBeUndefined()
|
||||
await expect(f.account.signOut()).rejects.toThrow('account: protocol')
|
||||
})
|
||||
|
||||
it('never sends a development issuer grant to official inference', async () => {
|
||||
const f = await fixture()
|
||||
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({
|
||||
kind: 'grant', payload: { version: 1, token: 'real-token', issuer: f.origin },
|
||||
}))
|
||||
expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('merges account cookies when there are no base cookies', async () => {
|
||||
const f = await fixture(undefined, {}, false, { cookie: 'account=value' })
|
||||
await storeAccount(f)
|
||||
expect(await f.account.getPlatformSession()).toMatchObject({ requestHeaders: { cookie: 'account=value' } })
|
||||
})
|
||||
|
||||
it.each([null, []])('rejects invalid initialization and exchange payload fields: %j', async (value) => {
|
||||
const f = await fixture()
|
||||
f.initResponse({ authorize_id: value })
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
await f.wait('failed')
|
||||
f.initResponse({})
|
||||
f.exchangeResponse({ token: value })
|
||||
await f.account.startSignIn('zh', f.callbackOrigin, 'web')
|
||||
await f.wait('waiting-browser')
|
||||
const callback = await fetch(f.callback(), { redirect: 'manual' })
|
||||
expect(callback.status).toBe(200)
|
||||
expect(await callback.text()).toContain('登录失败')
|
||||
expect((await f.wait('failed')).status).toBe('signed-out')
|
||||
})
|
||||
|
||||
it.each([{ kind: 'api-key' as const, key: 'wrong-kind' }, { kind: 'grant' as const, payload: null }])(
|
||||
'rejects invalid durable grants during service initialization: $kind', async (record) => {
|
||||
const f = await fixture()
|
||||
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve(record))
|
||||
await expect(f.account[Service.init]()).rejects.toThrow('account: storage')
|
||||
},
|
||||
)
|
||||
|
||||
it.each(['ftp://api.example', 'https://user:[email protected]', 'https://api.example/path',
|
||||
'https://api.example/?query=1', 'https://api.example/#fragment'])('rejects invalid inference origin %s', async (inferenceOrigin) => {
|
||||
expect(() => new PlatformAccount(new Context(), { inferenceOrigin })).toThrow('account: inferenceOrigin')
|
||||
})
|
||||
|
||||
it('rejects authorization begun without a local account attempt', async () => {
|
||||
const f = await fixture()
|
||||
await expect(f.ctx.authorization.begin({ key: credentialKey('deepseek-account-platform', 'default'),
|
||||
interaction: { notify: () => undefined, prompt: () => Promise.resolve('') },
|
||||
})).rejects.toThrow('account: protocol')
|
||||
})
|
||||
|
||||
it('fails sign-in when its shared callback server is absent', async () => {
|
||||
const f = await fixture()
|
||||
const get = vi.spyOn(f.ctx, 'get').mockImplementation(() => undefined)
|
||||
try {
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
expect((await f.wait('failed')).attempt?.errorCode).toBe('protocol')
|
||||
} finally { get.mockRestore() }
|
||||
})
|
||||
|
||||
it('reports a credential commit failure without redirecting to success', async () => {
|
||||
const f = await fixture()
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'desktop')
|
||||
await f.wait('waiting-browser')
|
||||
const original = f.ctx.credentials.modifyRecord.bind(f.ctx.credentials)
|
||||
const modify = vi.spyOn(f.ctx.credentials, 'modifyRecord').mockImplementation((key, mutate) =>
|
||||
key === credentialKey('deepseek-account-platform', 'default') ? Promise.reject(new Error('store unavailable')) : original(key, mutate))
|
||||
try {
|
||||
const callback = await fetch(f.callback(), { redirect: 'manual' })
|
||||
expect(callback.status).toBe(204)
|
||||
expect((await f.wait('failed')).attempt?.errorCode).toBe('storage')
|
||||
} finally { modify.mockRestore() }
|
||||
})
|
||||
|
||||
it('rejects a device record of the wrong kind before exchanging', async () => {
|
||||
const f = await fixture()
|
||||
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'device'), () => Promise.resolve({ kind: 'api-key', key: 'wrong' }))
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'desktop')
|
||||
await f.wait('waiting-browser')
|
||||
expect((await fetch(f.callback(), { redirect: 'manual' })).status).toBe(204)
|
||||
expect((await f.wait('failed')).attempt?.errorCode).toBe('storage')
|
||||
expect(f.count()).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects callbacks with missing state and callbacks arriving during exchange', async () => {
|
||||
const f = await fixture()
|
||||
f.hold()
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
await f.wait('waiting-browser')
|
||||
expect((await fetch(`${f.init().redirect_uri}?code=test`)).status).toBe(400)
|
||||
const callback = fetch(f.callback(), { redirect: 'manual' })
|
||||
await f.exchanged.promise
|
||||
expect((await fetch(f.callback())).status).toBe(410)
|
||||
f.release.resolve(undefined)
|
||||
expect((await callback).status).toBe(302)
|
||||
})
|
||||
|
||||
it.each(['initializing', 'waiting-browser'])('expires the attempt while %s', async (phase) => {
|
||||
const f = await fixture()
|
||||
const timeout = vi.spyOn(globalThis, 'setTimeout')
|
||||
if (phase === 'initializing') f.onInit(() => {
|
||||
const timer = timeout.mock.calls.find(([, delay]) => delay === 600_000)?.[0]
|
||||
if (typeof timer !== 'function') throw new Error('missing initial deadline')
|
||||
timer()
|
||||
})
|
||||
try {
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
if (phase === 'waiting-browser') {
|
||||
await f.wait('waiting-browser')
|
||||
const timer = timeout.mock.calls.filter(([, delay]) => typeof delay === 'number' && delay > 590_000).at(-1)?.[0]
|
||||
if (typeof timer !== 'function') throw new Error('missing browser deadline')
|
||||
timer()
|
||||
}
|
||||
expect((await f.wait('expired')).status).toBe('signed-out')
|
||||
} finally { timeout.mockRestore() }
|
||||
})
|
||||
|
||||
it('holds cancellation and disposal until an admitted account write completes', async () => {
|
||||
const f = await fixture()
|
||||
const admitted = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const original = f.ctx.credentials.modifyRecord.bind(f.ctx.credentials)
|
||||
const modify = vi.spyOn(f.ctx.credentials, 'modifyRecord').mockImplementation(async (key, mutate) => {
|
||||
if (key === credentialKey('deepseek-account-platform', 'default')) {
|
||||
admitted.resolve(undefined)
|
||||
await release.promise
|
||||
}
|
||||
return original(key, mutate)
|
||||
})
|
||||
let callback: Promise<Response> | undefined
|
||||
try {
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
const state = await f.wait('waiting-browser')
|
||||
callback = fetch(f.callback(), { redirect: 'manual' })
|
||||
await admitted.promise
|
||||
const cancelled = f.account.cancelSignIn(state.attempt!.id)
|
||||
const disposed = f.dispose()
|
||||
release.resolve(undefined)
|
||||
expect((await callback).status).toBe(302)
|
||||
expect((await cancelled).status).toBe('credential-stored')
|
||||
await disposed
|
||||
} finally {
|
||||
release.resolve(undefined)
|
||||
await callback
|
||||
modify.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('waits for local sign-out before beginning a new authorization', async () => {
|
||||
const f = await fixture()
|
||||
await storeAccount(f)
|
||||
const admitted = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const original = f.ctx.credentials.deleteRecord.bind(f.ctx.credentials)
|
||||
const remove = vi.spyOn(f.ctx.credentials, 'deleteRecord').mockImplementation(async (key) => {
|
||||
admitted.resolve(undefined)
|
||||
await release.promise
|
||||
return original(key)
|
||||
})
|
||||
try {
|
||||
const out = f.account.signOut()
|
||||
await admitted.promise
|
||||
const login = f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
release.resolve(undefined)
|
||||
expect((await out).status).toBe('signed-out')
|
||||
expect((await login).attempt?.phase).toBe('initializing')
|
||||
await f.wait('waiting-browser')
|
||||
} finally { release.resolve(undefined); remove.mockRestore() }
|
||||
})
|
||||
|
||||
it('does not begin a remote logout after disposal starts during local removal', async () => {
|
||||
const f = await fixture()
|
||||
await storeAccount(f)
|
||||
const admitted = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const original = f.ctx.credentials.deleteRecord.bind(f.ctx.credentials)
|
||||
const remove = vi.spyOn(f.ctx.credentials, 'deleteRecord').mockImplementation(async (key) => {
|
||||
admitted.resolve(undefined)
|
||||
await release.promise
|
||||
return original(key)
|
||||
})
|
||||
try {
|
||||
const out = f.account.signOut()
|
||||
await admitted.promise
|
||||
const disposed = f.dispose()
|
||||
release.resolve(undefined)
|
||||
expect((await out).status).toBe('signed-out')
|
||||
await disposed
|
||||
expect(f.logoutCount()).toBe(0)
|
||||
} finally { release.resolve(undefined); remove.mockRestore() }
|
||||
})
|
||||
|
||||
it.each([false, true])('settles a previous attempt before concurrent restart or disposal: %s', async (dispose) => {
|
||||
const f = await fixture()
|
||||
f.hold()
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
await f.wait('waiting-browser')
|
||||
const callback = fetch(f.callback(), { redirect: 'manual' })
|
||||
await f.exchanged.promise
|
||||
const cancel = f.account.cancelSignIn((await f.account.getState()).attempt!.id)
|
||||
await f.wait('cancelled')
|
||||
const first = f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
if (dispose) {
|
||||
const rejected = expect(first).rejects.toThrow('account: protocol')
|
||||
const disposed = f.dispose()
|
||||
f.release.resolve(undefined)
|
||||
await rejected
|
||||
await disposed
|
||||
} else {
|
||||
const second = f.account.startSignIn('zh', f.callbackOrigin, 'web')
|
||||
f.release.resolve(undefined)
|
||||
expect((await first).attempt?.id).toBe((await second).attempt?.id)
|
||||
await f.wait('waiting-browser')
|
||||
}
|
||||
await cancel
|
||||
expect((await callback).status).toBe(204)
|
||||
})
|
||||
|
||||
it('rejects unsupported interaction and projects unexpected authorization failures safely', async () => {
|
||||
const f = await fixture()
|
||||
const begin = vi.spyOn(f.ctx.authorization, 'begin').mockImplementation(async (request) => {
|
||||
request.interaction.notify({ message: 'ignored' })
|
||||
await expect(request.interaction.prompt({ kind: 'text', message: 'unsupported' })).rejects.toThrow('account: protocol')
|
||||
throw new Error('private implementation failure')
|
||||
})
|
||||
try {
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
expect((await f.wait('failed')).attempt?.errorCode).toBe('protocol')
|
||||
} finally { begin.mockRestore() }
|
||||
})
|
||||
|
||||
it('rejects callback requests whose raw URL is absent or malformed', async () => {
|
||||
const f = await fixture()
|
||||
const register = vi.spyOn(f.ctx.webServer, 'register')
|
||||
try {
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
await f.wait('waiting-browser')
|
||||
const route = register.mock.calls.find(([route]) => route.path === '/oauth/callback')?.[0]
|
||||
if (route === undefined) throw new Error('missing callback route')
|
||||
for (const url of [undefined, 'http://[']) {
|
||||
const socket = new Socket()
|
||||
const req = new IncomingMessage(socket)
|
||||
req.method = 'GET'
|
||||
req.url = url
|
||||
const res = new ServerResponse(req)
|
||||
try {
|
||||
await route.handler(req, res)
|
||||
expect(res.statusCode).toBe(400)
|
||||
expect(res.writableEnded).toBe(true)
|
||||
} finally { res.destroy(); socket.destroy() }
|
||||
}
|
||||
} finally { register.mockRestore() }
|
||||
})
|
||||
|
||||
it('settles an attempt after its browser callback connection closes during exchange', async () => {
|
||||
const f = await fixture()
|
||||
f.hold()
|
||||
const response = Promise.withResolvers<ServerResponse>()
|
||||
const serverClosed = Promise.withResolvers<undefined>()
|
||||
const original = f.ctx.webServer.register.bind(f.ctx.webServer)
|
||||
const register = vi.spyOn(f.ctx.webServer, 'register').mockImplementation(route => original({
|
||||
...route, handler: (req, res) => {
|
||||
response.resolve(res)
|
||||
res.once('error', () => undefined)
|
||||
res.once('close', () => { serverClosed.resolve(undefined) })
|
||||
return route.handler(req, res)
|
||||
},
|
||||
}))
|
||||
await f.account.startSignIn('en', f.callbackOrigin, 'web')
|
||||
await f.wait('waiting-browser')
|
||||
const socket = connect(Number(new URL(f.callbackOrigin).port), '127.0.0.1')
|
||||
const closed = new Promise<void>(resolve => socket.once('close', () => { resolve() }))
|
||||
try {
|
||||
await new Promise<void>(resolve => socket.once('connect', resolve))
|
||||
socket.write(`GET ${new URL(f.callback()).pathname}${new URL(f.callback()).search} HTTP/1.1\r\nHost: localhost\r\n\r\n`)
|
||||
await f.exchanged.promise
|
||||
const callbackResponse = await response.promise
|
||||
vi.spyOn(callbackResponse, 'end').mockImplementation(() => callbackResponse)
|
||||
callbackResponse.destroy(new Error('callback transport failed'))
|
||||
socket.destroy()
|
||||
await closed
|
||||
await serverClosed.promise
|
||||
f.release.resolve(undefined)
|
||||
await f.wait('succeeded')
|
||||
expect((await f.account.signOut()).status).toBe('signed-out')
|
||||
} finally { socket.destroy(); f.release.resolve(undefined); await closed; register.mockRestore() }
|
||||
})
|
||||
|
||||
it('invalidates account reads before the shared grant lookup returns to its caller', async () => {
|
||||
const f = await fixture()
|
||||
await storeAccount(f)
|
||||
const key = credentialKey('deepseek-account-platform', 'default')
|
||||
const original = f.ctx.credentials.readRecord.bind(f.ctx.credentials)
|
||||
const read = vi.spyOn(f.ctx.credentials, 'readRecord').mockImplementation(async (requested) => {
|
||||
const record = await original(requested)
|
||||
// The first checkpoint lets grant validation finish; the second invalidates its consumer.
|
||||
queueMicrotask(() => { queueMicrotask(() => { f.ctx.emit('credentials/record-updated', key) }) })
|
||||
return record
|
||||
})
|
||||
try {
|
||||
expect(await f.account.getPlatformSession()).toBeNull()
|
||||
expect(await f.account.getProfile()).toBeNull()
|
||||
expect(f.detailRequests).toEqual([])
|
||||
} finally { read.mockRestore() }
|
||||
})
|
||||
@@ -5,3 +5,8 @@ it.each([undefined, null, '', 'https://example.test/avatar.png'])('projects Plat
|
||||
expect(profile({ id: 'user', email: '[email protected]', id_profile: { name: 'User', picture } }).avatarUrl)
|
||||
.toBe(picture || null)
|
||||
})
|
||||
|
||||
it('projects missing display fields and empty contact values as null', () => {
|
||||
expect(profile({ email: '' })).toEqual({ id: null, avatarUrl: null, name: null, contact: null })
|
||||
expect(profile({ email: '', id_profile: { name: '' } }).name).toBeNull()
|
||||
})
|
||||
@@ -91,3 +91,25 @@ it('reports browser URL rejection rules without exposing the destination', () =>
|
||||
output.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ name: 'HTTP failure', response: () => new Response('private-error', { status: 503 }), code: 'network' },
|
||||
{ name: 'missing body', response: () => new Response(null), code: 'network' },
|
||||
{ name: 'oversized body', response: () => new Response('x'.repeat(65_537)), code: 'protocol' },
|
||||
{ name: 'invalid JSON', response: () => new Response('{private-invalid'), code: 'protocol' },
|
||||
{ name: 'missing envelope data', response: () => new Response('{"code":0}'), code: 'protocol' },
|
||||
{ name: 'broken response stream', response: () => new Response(new ReadableStream({
|
||||
start(controller) { controller.error(new Error('private-stream-error')) },
|
||||
})), code: 'protocol' },
|
||||
])('rejects $name without exposing response data', async ({ response, code }) => {
|
||||
const output = vi.spyOn(console, 'info').mockImplementation(() => undefined)
|
||||
const fetcher = vi.spyOn(globalThis, 'fetch').mockResolvedValue(response())
|
||||
try {
|
||||
await expect(requestPlatform('https://platform.deepseek.com', 'auth_init', {},
|
||||
new AbortController().signal, {})).rejects.toThrow(`account: ${code}`)
|
||||
expect(JSON.stringify(output.mock.calls)).not.toContain('private-')
|
||||
} finally {
|
||||
fetcher.mockRestore()
|
||||
output.mockRestore()
|
||||
}
|
||||
})
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/experimental/webworker-runtime/README.md
|
||||
README.md: 326a266090b3cf341f39f2d2d747aa6d515a7b0e
|
||||
README.zh.md: 37b7938b41791767549d37ea5aceb2ad461e8d51
|
||||
README.md: 3a5d702c2163c19daa3230ffd14270b4f236f2d9
|
||||
README.zh.md: a987fed1db5f607aee4e95e2faf96575c1d0c904
|
||||
@@ -28,7 +28,7 @@ The public npm package exposes the runtime library at its root, the self-contain
|
||||
Three build artifacts and one source-owned process layer:
|
||||
|
||||
- **`lib/index.js` (assembly library)** — `createWorkerHost`/`startWorkerHost` mount the base image and any ordered data overlays (`storage/`), install the module loader (`module-system/`) and the `process` shim, boot the tree through the image's own `dsh-app-boot`, and hand the tunnel its serving seams. Overlays may replace files only under `home/` and `workspace/`; they cannot replace the base manifest, configuration, or modules. The image layout contract (`image-layout.ts`: virtual root, config/manifest paths, empty directories, the `lowered` wrapper-contract gate) is shared with the packer. The Worker supplies `profileContext` for an editable profile at `home/profiles/preview/`: the packed rows seed its insertion patch, and ConfigEditor persists overrides in that VFS patch. ConfigEditor reconciles each write and Loader commits live values; package management and Node module HMR stay disabled. Deployment overlays keep JSONL session logs plaintext and preset roots at the image's `config/agent-presets`. Configuration edits last for the current Worker lifetime.
|
||||
- **`lib/worker.js` (worker bundle)** — the assembly plus this package's Node-compatibility layer as one self-contained ES module. The module proxy table (`module-proxies.ts`) is the only platform fork: `node:*` builtins over VFS/tunnel/browser primitives, structural stubs that fail loud on the console for what a browser cannot do, and native/binary package replacements. `node:module` supplies `createRequire().resolve` and `.resolve.paths()` over the image package root, so unchanged packages can discover manifests without evaluating their modules. The `node:util` JSON-data comparator compares own enumerable properties, preserving Node admission decisions for recorded fields such as `__proto__`. The global `process` shim carries Node detection fields including `title`, preventing Worker execution from entering DOM-only branches. The pack-time parser reports statically named module requests, including module-scope direct calls of the form `createRequire(import.meta.url)('pkg')` through a named `node:module` or `module` import, to the packer's reachability walk. Stored, CommonJS-obtained, and rebased `createRequire` calls require image entry seeds. VFS mutations drive `node:fs` callback, polling, and promise watchers; open descriptors retain file identity and access mode across rename, replacement, and unlink, `FileHandle.stat({ bigint: true })` reports the same device and inode identity as a path stat while the name still refers to that file, and `FileHandle.chmod()` updates the opened file identity; `readable-stream` supplies the stream state machine used by file streams and unchanged image packages such as Chokidar and readdirp. AsyncLocalStorage carries sync-stack causality across `await` through the snapshot/restore faces the pack-time lowering injects. The worker holds no compiler: an image the packer did not lower is refused at mount. The callback `fs.realpath.native` alias resolves within the mounted VFS and supports `util.promisify`.
|
||||
- **`lib/worker.js` (worker bundle)** — the assembly plus this package's Node-compatibility layer as one self-contained ES module. The module proxy table (`module-proxies.ts`) is the only platform fork: `node:*` builtins over VFS/tunnel/browser primitives, structural stubs that fail loud on the console for what a browser cannot do, and native/binary package replacements. `node:module` supplies `createRequire().resolve` and `.resolve.paths()` over the image package root, so unchanged packages can discover manifests without evaluating their modules. The `node:util` JSON-data comparator compares own enumerable properties, preserving Node admission decisions for recorded fields such as `__proto__`. The global `process` shim carries Node detection fields including `title`, preventing Worker execution from entering DOM-only branches. The pack-time parser reports statically named module requests, including module-scope direct calls of the form `createRequire(import.meta.url)('pkg')` through a named `node:module` or `module` import, to the packer's reachability walk. Stored, CommonJS-obtained, and rebased `createRequire` calls require image entry seeds. VFS mutations drive `node:fs` callback, polling, and promise watchers; open descriptors retain file identity and access mode across rename, replacement, and unlink, `FileHandle.stat({ bigint: true })` reports the same device and inode identity as a path stat while the name still refers to that file, and `FileHandle.chmod()` updates the opened file identity; `readable-stream` supplies `node:stream/promises` completion and pipeline helpers and the stream state machine used by file streams and unchanged image packages such as Chokidar and readdirp. AsyncLocalStorage carries sync-stack causality across `await` through the snapshot/restore faces the pack-time lowering injects. The worker holds no compiler: an image the packer did not lower is refused at mount. The callback `fs.realpath.native` alias resolves within the mounted VFS and supports `util.promisify`.
|
||||
- **`src/shell/` (the worker's own process layer)** — a browser worker cannot fork, so `node:child_process` is not a stub but an implementation: `spawn` starts the command in its own Web Worker — this same bundle, told by its first frame to be a shell process — and reports it through the `ChildProcess` surface the subprocess service consumes. The command runs off the host's thread, `SIGKILL` terminates it whatever it is doing, and it reaches the VFS only by message (the host serves those frames). Worker platform executables preserve native-package protocols such as Landlock without replacing their JavaScript packages or coupling their implementations to `node:child_process`; ordinary commands use the package's evaluator and coreutils command table. The grammar is `@yarnpkg/parsers`' `parseShell`, while `execSync`/`fork` still refuse because they need a real process.
|
||||
- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream<Uint8Array>` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply.
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ kind: "package-library"
|
||||
一条 tsdown 管线产出三个构建产物;另有一层由源码维护的进程实现:
|
||||
|
||||
- **`lib/index.js`(装配库)**——`createWorkerHost`/`startWorkerHost` 挂载基础镜像和按序排列的数据 overlays(`storage/`)、安装模块加载器(`module-system/`)与 `process` shim、经镜像自带的 `dsh-app-boot` 启动插件树,并把服务 seam 交给隧道。Overlay 只能替换 `home/` 与 `workspace/` 下的文件,不能替换基础 manifest、配置或模块。镜像布局契约(`image-layout.ts`:虚拟根、config/manifest 路径、空目录、`lowered` 包装契约门)与 packer 共享。Worker 为 `home/profiles/preview/` 下可编辑的 profile 提供 `profileContext`:打包行初始化其插入 patch,ConfigEditor 将覆盖值持久化到该 VFS patch。ConfigEditor 协调每次写入,Loader 提交实时值;包管理和 Node 模块 HMR 保持禁用。部署 overlay 保持 JSONL 会话日志为明文,preset 根指向镜像内 `config/agent-presets`。配置修改在当前 Worker 生命周期内有效。预设声明包含在组合后的配置中。
|
||||
- **`lib/worker.js`(worker 束)**——装配库加本包的 Node 兼容层,合成一个自含 ES module。模块代理表(`module-proxies.ts`)是唯一平台叉口:`node:*` 内建走 VFS、隧道和浏览器原语,浏览器做不到的走结构化 stub(调用即在 console 报错并抛出),native/binary 包则替换执行后端。`node:module` 在镜像 package 根之上提供 `createRequire().resolve` 与 `.resolve.paths()`,使未修改的包无需执行目标模块即可发现 manifest。`node:util` 的 JSON 数据比较器检查可枚举的自有属性,使 `__proto__` 等记录字段的准入判定与 Node 一致。全局 `process` shim 带有包括 `title` 在内的 Node 环境识别字段,避免 Worker 执行误入仅适用于 DOM 的分支。pack 期解析器会把名称静态可知的模块请求报告给 packer 的可达性遍历,其中包括通过 `node:module` 或 `module` 具名导入在模块作用域直接发起的 `createRequire(import.meta.url)('pkg')` 调用。保存、经 CommonJS 获取或另设基准的 `createRequire` 调用需要镜像入口种子。VFS mutation 驱动 `node:fs` 的 callback、polling 和 promise watcher;打开的 descriptor 在 rename、replacement 和 unlink 后仍保留文件身份与访问模式,只要文件名仍指向该文件,`FileHandle.stat({ bigint: true })` 报告的 device 与 inode 身份就与路径 stat 相同,`FileHandle.chmod()` 则更新打开文件身份的权限;`readable-stream` 提供文件流以及 Chokidar、readdirp 等未修改镜像包所用的流状态机。AsyncLocalStorage 经 pack 时降低注入的 snapshot/restore 面在 `await` 间携带同步栈因果。worker 不带编译器:packer 未降低的镜像在挂载时被拒。回调式 `fs.realpath.native` 别名在已挂载的 VFS 内解析路径,并支持 `util.promisify`。
|
||||
- **`lib/worker.js`(worker 束)**——装配库加本包的 Node 兼容层,合成一个自含 ES module。模块代理表(`module-proxies.ts`)是唯一平台叉口:`node:*` 内建走 VFS、隧道和浏览器原语,浏览器做不到的走结构化 stub(调用即在 console 报错并抛出),native/binary 包则替换执行后端。`node:module` 在镜像 package 根之上提供 `createRequire().resolve` 与 `.resolve.paths()`,使未修改的包无需执行目标模块即可发现 manifest。`node:util` 的 JSON 数据比较器检查可枚举的自有属性,使 `__proto__` 等记录字段的准入判定与 Node 一致。全局 `process` shim 带有包括 `title` 在内的 Node 环境识别字段,避免 Worker 执行误入仅适用于 DOM 的分支。pack 期解析器会把名称静态可知的模块请求报告给 packer 的可达性遍历,其中包括通过 `node:module` 或 `module` 具名导入在模块作用域直接发起的 `createRequire(import.meta.url)('pkg')` 调用。保存、经 CommonJS 获取或另设基准的 `createRequire` 调用需要镜像入口种子。VFS mutation 驱动 `node:fs` 的 callback、polling 和 promise watcher;打开的 descriptor 在 rename、replacement 和 unlink 后仍保留文件身份与访问模式,只要文件名仍指向该文件,`FileHandle.stat({ bigint: true })` 报告的 device 与 inode 身份就与路径 stat 相同,`FileHandle.chmod()` 则更新打开文件身份的权限;`readable-stream` 提供 `node:stream/promises` 的完成等待与管道方法,以及文件流以及 Chokidar、readdirp 等未修改镜像包所用的流状态机。AsyncLocalStorage 经 pack 时降低注入的 snapshot/restore 面在 `await` 间携带同步栈因果。worker 不带编译器:packer 未降低的镜像在挂载时被拒。回调式 `fs.realpath.native` 别名在已挂载的 VFS 内解析路径,并支持 `util.promisify`。
|
||||
- **`src/shell/`(worker 自己的进程层)**——浏览器 worker 无法 fork,所以 `node:child_process` 不是 stub 而是实现:`spawn` 把命令放进它自己的 Web Worker——就是这同一个束,由首帧告诉它「你是 shell 进程」——并以 subprocess 服务消费的 `ChildProcess` 面报告结果。命令不占宿主线程,`SIGKILL` 不管它在干什么都能终止它,而它只能靠消息触达 VFS(由宿主应答这些帧)。Worker 平台 executable 在不替换 JavaScript 包、也不把具体实现耦合进 `node:child_process` 的情况下保持 Landlock 等 native 包协议;普通命令使用本包的求值器与 coreutils 命令表。语法来自 `@yarnpkg/parsers` 的 `parseShell`,而 `execSync`/`fork` 依然拒绝,因为它们需要真进程。
|
||||
- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream<Uint8Array>` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。
|
||||
|
||||
|
||||
@@ -61,6 +61,8 @@ export const MODULE_PROXIES: Record<string, string> = {
|
||||
'dns/promises': './node/builtin_modules/mock/dns/promises.ts',
|
||||
'node:net': './node/builtin_modules/mock/net.ts',
|
||||
'node:stream': './node/builtin_modules/implemented/stream.ts',
|
||||
'node:stream/promises': './node/builtin_modules/implemented/stream/promises.ts',
|
||||
'stream/promises': './node/builtin_modules/implemented/stream/promises.ts',
|
||||
'node:vm': './node/builtin_modules/mock/vm.ts',
|
||||
'node:worker_threads': './node/builtin_modules/mock/worker_threads.ts',
|
||||
'node:sqlite': './node/builtin_modules/mock/sqlite.ts',
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/** Promise-based stream completion and pipelines from the shared readable-stream implementation. */
|
||||
import { promises } from '../stream.ts'
|
||||
|
||||
/** Shared stream completion promise, including abort and listener cleanup options. */
|
||||
export const finished = promises.finished
|
||||
|
||||
/** Shared stream pipeline promise, including backpressure and error propagation. */
|
||||
export const pipeline = promises.pipeline
|
||||
|
||||
/** CommonJS interop marker consumed by the worker module loader. */
|
||||
export const __esModule = true
|
||||
|
||||
/** CommonJS-compatible promise namespace. */
|
||||
export default promises
|
||||
@@ -34,6 +34,7 @@ import * as nodeOs from './builtin_modules/implemented/os.ts'
|
||||
import * as nodePath from './builtin_modules/implemented/path.ts'
|
||||
import * as nodePerfHooks from './builtin_modules/implemented/perf_hooks.ts'
|
||||
import * as nodeStream from './builtin_modules/implemented/stream.ts'
|
||||
import * as nodeStreamPromises from './builtin_modules/implemented/stream/promises.ts'
|
||||
import * as nodeTimersPromises from './builtin_modules/implemented/timers/promises.ts'
|
||||
import * as nodeTty from './builtin_modules/implemented/tty.ts'
|
||||
import * as nodeUrl from './builtin_modules/implemented/url.ts'
|
||||
@@ -76,6 +77,7 @@ const BUILTINS: Record<string, StaticModuleFactory> = {
|
||||
perf_hooks: () => nodePerfHooks,
|
||||
sqlite: () => nodeSqlite,
|
||||
stream: () => nodeStream,
|
||||
'stream/promises': () => nodeStreamPromises,
|
||||
'timers/promises': () => nodeTimersPromises,
|
||||
tty: () => nodeTty,
|
||||
url: () => nodeUrl,
|
||||
|
||||
@@ -89,6 +89,28 @@ describe('module identity through the loader', () => {
|
||||
expect(require('tty')).toBe(require('node:tty'))
|
||||
})
|
||||
|
||||
it('shares promise stream helpers and observes completion and errors through the loader', async () => {
|
||||
const require = loaderRequire()
|
||||
const stream = require('node:stream') as typeof import('node:stream')
|
||||
const promises = require('node:stream/promises') as typeof import('node:stream/promises')
|
||||
expect(require('stream/promises')).toBe(promises)
|
||||
expect(promises.finished).toBe(stream.promises.finished)
|
||||
expect(promises.pipeline).toBe(stream.promises.pipeline)
|
||||
|
||||
const output = new stream.Writable({ write(_chunk, _encoding, callback) { callback() } })
|
||||
const baseline = output.listenerCount('error')
|
||||
const completed = promises.finished(output, { cleanup: true })
|
||||
output.end('done')
|
||||
await completed
|
||||
expect(output.listenerCount('error')).toBe(baseline)
|
||||
|
||||
const failed = new stream.Writable({ write(_chunk, _encoding, callback) { callback(new Error('write failed')) } })
|
||||
const rejected = expect(promises.finished(failed, { cleanup: true })).rejects.toThrow('write failed')
|
||||
failed.end('broken')
|
||||
await rejected
|
||||
expect(failed.listenerCount('error')).toBe(0)
|
||||
})
|
||||
|
||||
it('reports that worker file descriptors are not terminals', () => {
|
||||
const tty = loaderRequire()('tty') as { isatty(fd: number): boolean }
|
||||
expect(tty.isatty(2)).toBe(false)
|
||||
|
||||
@@ -56,7 +56,7 @@ describe('Messages Files requests', () => {
|
||||
createToolResultMessage({ callId, isError: false, content: [{ type: 'image', attachment: ref }, { type: 'image', attachment: ref }] })]
|
||||
await chunks(h.adapter.stream(options({ model, messages })))
|
||||
expect(h.readImageRequest).toHaveBeenCalledTimes(1)
|
||||
expect(h.ensureUploaded).toHaveBeenCalledWith(expect.anything(), { baseURL: 'https://gateway.example/custom', apiKey: 'test-key' }, expect.anything(), expect.any(AbortSignal))
|
||||
expect(h.ensureUploaded).toHaveBeenCalledWith(expect.anything(), { baseURL: 'https://gateway.example/custom', apiKey: 'test-key', accountCredential: false }, expect.anything(), expect.any(AbortSignal))
|
||||
const [url, init] = fetchImpl.mock.calls[0]!
|
||||
expect(url).toBe('https://gateway.example/custom/v1/messages')
|
||||
expect(new Headers(init?.headers).get('anthropic-beta')).toBe('files-api-2025-04-14')
|
||||
|
||||
@@ -305,3 +305,16 @@ describe('bundleRoster on a scratch installation', () => {
|
||||
expect(() => scratch.roster(['@t/misnamed'])).toThrow('names "@t/real", expected @t/alias')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
it('exhausts uneven linked-bundle search paths before reporting a missing plugin', () => {
|
||||
const scratch = new Scratch()
|
||||
onTestFinished(() => { rmSync(scratch.root, { recursive: true, force: true }) })
|
||||
const bundle = join(scratch.root, 'workspace', 'nested', 'deeper', 'bundle')
|
||||
mkdirSync(bundle, { recursive: true })
|
||||
writeFileSync(join(bundle, 'package.json'), JSON.stringify({ name: '@t/deep', dsh: { bundle: { patch: './cordis.patch.yml' } } }))
|
||||
writeFileSync(join(bundle, 'cordis.patch.yml'), "- insert:\n - id: missing\n name: '@t/absent'\n")
|
||||
scratch.bundle('@t/base', '- insert: []\n')
|
||||
symlinkSync(bundle, join(scratch.root, 'app', 'node_modules', '@t', 'deep'), 'junction')
|
||||
expect(() => scratch.roster(['@t/base', '@t/deep'])).toThrow('cannot resolve plugin package @t/absent')
|
||||
})
|
||||
Reference in new issue
Block a user