From 97545d9c8fe38eb1b99cbcc949cfb1adf87035dd Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 21 Sep 2026 15:57:08 +0800 Subject: [PATCH 01/10] fix(pty): keep the controlled prompt so persistent pwsh settles fast tool-pwsh-persistent installs its own `prompt` function after spawn, so terminal-bash prompt readiness never matched and every send degraded to the silence tier (idleSilenceMs + handoffGraceMs) under production defaults. This is the defect the persistent bash tool fixed for the bash stack. The tool now initializes without a prompt send and detects the no-end-marker fallback through the seam's stdin_read wait reason instead of matching its own prompt text. The private prompt constant and its stripping are deleted, so partial output can carry the backend's own trailing prompt. Tool calls drop from 8493/3722/3832/3759 ms to 1340/255/251/241 ms (spawn and initialization plus the first command, then three warm commands; Windows, production defaults, real Loader composition). The loader composition suite pushes idleSilenceMs beyond the send bound, so every case fails if prompt readiness regresses. --- ...ent-pwsh-keeps-controlled-prompt.i18n.yaml | 6 +++ ...persistent-pwsh-keeps-controlled-prompt.md | 37 +++++++++++++++ ...sistent-pwsh-keeps-controlled-prompt.zh.md | 37 +++++++++++++++ docs/config-catalog.i18n.yaml | 4 +- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- .../tool-pwsh-persistent/README.i18n.yaml | 4 +- packages/shell/tool-pwsh-persistent/README.md | 12 ++--- .../shell/tool-pwsh-persistent/README.zh.md | 12 ++--- .../shell/tool-pwsh-persistent/src/index.ts | 45 +++++-------------- .../tests/loader-composition.spec.ts | 5 ++- .../tool-pwsh-persistent/tests/tools.spec.ts | 42 +++++------------ 12 files changed, 122 insertions(+), 86 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.i18n.yaml create mode 100644 .agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md create mode 100644 .agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md diff --git a/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.i18n.yaml new file mode 100644 index 0000000000..db9c9a3ad8 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md +2026-09-21-persistent-pwsh-keeps-controlled-prompt.md: 748d18f6daafaf036576a911d26647dafbe92261 +2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md: 6425581a6dbb84dfc3b1c4cd4fb732353c4cd5e1 diff --git a/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md new file mode 100644 index 0000000000..748d18f6da --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md @@ -0,0 +1,37 @@ +# Agent Note: Persistent pwsh keeps the backend's controlled prompt + +Status: implemented + +English | [中文](2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md) + +## Problem + +`dsh-tool-pwsh-persistent` initialized its shell with a `prompt` function of its own (`'__DSH_PERSISTENT_PWSH_PROMPT__ '`), overwriting the `prompt` that `dsh-terminal-bash` installs in its pwsh startup sequence. The backend's prompt readiness requires the printable tail after the OSC `133;D` marker to exactly equal the controlled `dsh> ` prompt ([design](../feature/2026-07-16-persistent-pty-sessions.md)), so after initialization no send could settle through it and every send paid the silence tier plus handoff grace. Measured on Windows through the real Loader composition with production defaults: 8493 ms for the first call (spawn, initialization, and command) and 3722/3832/3759 ms for the next three, against 1340/255/251/241 ms with the controlled prompt intact. The package tests masked it by configuring `idleSilenceMs: 300`. + +The [persistent bash tool fixed the identical defect](../../archived/bug-fix/2026-08-15-persistent-bash-keeps-controlled-prompt.md) by giving up its own prompt override; the pwsh twin kept it. The override served the same two consumers there: a viewport-suffix fallback detecting "shell at a prompt without the end marker", and cosmetic stripping of prompt text from partial output. + +## Decision + +The tool no longer installs a prompt. `dsh-terminal-bash` owns the pwsh `prompt` function, installs it during `spawn`, and returns the session only after that startup reached `stdin_read` readiness, so the tool's initialization send had nothing left to establish and is deleted together with its `PWSH_PROMPT_SETUP` command. + +The viewport-suffix fallback is replaced with the seam's own signal: a send that settles as `stdin_read` without the end marker in scrollback returns the captured partial output. The private prompt constant and its stripping are deleted; partial output may now end with the backend's own prompt text, which the tool cannot and should not know. `stripPrompt` collapses to `trimTrailingNewline`, matching `dsh-tool-bash-persistent`. + +## Alternatives considered + +**Align the tool's prompt text with the backend's `dsh> `.** Rejected: it keeps a second installation of one protocol constant and a second owner of it, and the send is redundant because the backend had already installed the identical prompt before `spawn` resolved. + +**Import the controlled prompt into the tool.** Rejected: the prompt is one provider's protocol constant; a Consumer matching it would couple the tool to `dsh-terminal-bash` specifically, and any other mounted pwsh-dialect backend would break it again. + +**Lower `handoffGraceMs`/`idleSilenceMs` instead.** Rejected: no silence value fixes a dead fast path; it rebalances how much every call overpays, and the silence tier is also what absorbs a genuinely broken prompt. + +**Re-assert the pwsh prompt per prompt, as `PROMPT_COMMAND` does for bash.** Rejected: PowerShell has no per-prompt hook outside the `prompt` function itself, so a redefinition cannot be healed the way bash's variable is; the residue stays a documented limitation. + +## Consequences + +Windows, production defaults, real Loader composition: tool calls drop from 8493/3722/3832/3759 ms to 1340/255/251/241 ms (spawn + initialization + first command, then three warm commands). + +The `stdin_read` fallback is behavior, not only cosmetics: where a provider proves a foreground stdin wait, an interactive child now returns captured partial output instead of spinning to the command deadline, and elsewhere the call still runs to `timeoutMs`; the tool README records both. Complete marker-delimited output is unchanged. + +The loader-composition suite now sets `idleSilenceMs: 30000`, above the send bound, so silence can settle nothing and every case fails if prompt readiness regresses. The stub suite drops the initialization-handshake modes and pins the prompt text retained in partial output instead of its absence. + +A model command that redefines `prompt` still removes the readiness marker and degrades later sends to the silence tier: the backend installs its prompt once at startup and cannot re-assert it. diff --git a/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md new file mode 100644 index 0000000000..6425581a6d --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 持久 pwsh 保留后端的受控提示符 + +Status: implemented + +[English](2026-09-21-persistent-pwsh-keeps-controlled-prompt.md) | 中文 + +## Problem + +`dsh-tool-pwsh-persistent` 用自己安装的 `prompt` 函数(`'__DSH_PERSISTENT_PWSH_PROMPT__ '`)初始化其 shell,覆盖了 `dsh-terminal-bash` 在 pwsh 启动序列中安装的 `prompt`。后端的提示符就绪检测要求 OSC `133;D` 标记之后的可打印尾部与受控提示符 `dsh> ` 完全相等([设计](../feature/2026-07-16-persistent-pty-sessions.zh.md)),因此初始化之后任何 send 都无法经由该路径结算,每次 send 都要支付静默层加交接宽限。在 Windows 上通过真实 Loader 组合以生产默认值实测:首次调用(spawn、初始化与命令)8493 毫秒,随后三次为 3722/3832/3759 毫秒;受控提示符完好时为 1340/255/251/241 毫秒。包测试把 `idleSilenceMs` 配成 300,掩盖了该问题。 + +[持久 bash 工具已修复同一缺陷](../../archived/bug-fix/2026-08-15-persistent-bash-keeps-controlled-prompt.md),方式是放弃自己的提示符覆盖;pwsh 孪生工具保留了它。该覆盖在两个工具中服务同样的两个消费点:用视口后缀检测「shell 已回到提示符但没有结束标记」的回退判定,以及从部分输出中剥离提示符文本的美化。 + +## Decision + +工具不再安装提示符。pwsh 的 `prompt` 函数由 `dsh-terminal-bash` 拥有,在 `spawn` 期间安装,且只在该启动流程达到 `stdin_read` 就绪后才返回会话,因此工具的初始化 send 已无可确立之事,与其 `PWSH_PROMPT_SETUP` 命令一并删除。 + +视口后缀回退替换为 seam 自己的信号:一次以 `stdin_read` 结算而 scrollback 中没有结束标记的 send,返回已捕获的部分输出。私有提示符常量及其剥离逻辑删除;部分输出现在可能以后端自己的提示符文本结尾,工具无法也不应知道该文本。`stripPrompt` 收敛为 `trimTrailingNewline`,与 `dsh-tool-bash-persistent` 一致。 + +## Alternatives considered + +**把工具的提示符文本对齐到后端的 `dsh> `。** 被拒绝:这保留了同一个协议常量的第二份安装与第二个拥有者,而且该 send 是多余的——后端在 `spawn` 返回前就已安装相同的提示符。 + +**把受控提示符导入工具。** 被拒绝:提示符是单个提供方的协议常量;Consumer 匹配它就把工具与 `dsh-terminal-bash` 具体耦合,换任何其他 pwsh 方言后端都会再次损坏。 + +**改为调小 `handoffGraceMs`/`idleSilenceMs`。** 被拒绝:任何静默值都修不好已死的快速路径,只是重新分配每次调用多付多少;而静默层同时也是吸收真正损坏提示符的那一层。 + +**像 bash 的 `PROMPT_COMMAND` 那样在每个提示符处重新设定 pwsh 提示符。** 被拒绝:除 `prompt` 函数本身之外,PowerShell 没有每提示符钩子,因此重定义无法像 bash 的变量那样被治好;该残余已记入已知限制。 + +## Consequences + +Windows、生产默认值、真实 Loader 组合:工具调用从 8493/3722/3832/3759 毫秒降至 1340/255/251/241 毫秒(spawn + 初始化 + 首条命令,随后三条热命令)。 + +`stdin_read` 回退是行为而不只是美化:在提供方能证明前台 stdin 等待之处,交互式子进程现在返回已捕获的部分输出,而不是空转到命令期限;其他情况下调用仍会运行到 `timeoutMs`,两者都记入工具 README。由标记界定的完整输出保持不变。 + +loader 组合套件现在把 `idleSilenceMs` 设为 30000,位于 send 上限之上,静默无法结算任何 send,提示符就绪一旦回归,每个用例都会失败。stub 套件删除了初始化握手模式,并改为锚定部分输出中保留的提示符文本,而不是它的缺席。 + +重定义 `prompt` 的模型命令仍会移除就绪标记,并把后续 send 降级到静默层:后端只在启动时安装一次提示符,无法重新设定。 diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 63b1766591..cd86866daf 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/config-catalog.md -config-catalog.md: 59b15e7bbb518abdee55308c191b109547b5185e -config-catalog.zh.md: 4e89ea92944f6e1f2ae8ae0b57f0bec9e9f835d9 +config-catalog.md: f120bf0ffdc64cf298de2e18ed10083ac96485a5 +config-catalog.zh.md: 6cb3e3a6dd92b5b4f877a5b588b4935a28f089f6 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 59b15e7bbb..f120bf0ffd 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -3282,7 +3282,7 @@ export interface Config { } ``` -Source: [`packages/shell/tool-pwsh-persistent/src/index.ts:480`](../packages/shell/tool-pwsh-persistent/src/index.ts) +Source: [`packages/shell/tool-pwsh-persistent/src/index.ts:455`](../packages/shell/tool-pwsh-persistent/src/index.ts) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 4e89ea9294..6cb3e3a6dd 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -3286,7 +3286,7 @@ export interface Config { } ``` -来源:[`packages/shell/tool-pwsh-persistent/src/index.ts:480`](../packages/shell/tool-pwsh-persistent/src/index.ts) +来源:[`packages/shell/tool-pwsh-persistent/src/index.ts:455`](../packages/shell/tool-pwsh-persistent/src/index.ts) diff --git a/packages/shell/tool-pwsh-persistent/README.i18n.yaml b/packages/shell/tool-pwsh-persistent/README.i18n.yaml index b31e3271a9..00dcbdee79 100644 --- a/packages/shell/tool-pwsh-persistent/README.i18n.yaml +++ b/packages/shell/tool-pwsh-persistent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/shell/tool-pwsh-persistent/README.md -README.md: f90442e7e9d8a361a690f66f41a58f1a4fcdd708 -README.zh.md: d634e8e42e186318a8733ee9ef2024e2840a857c +README.md: d4c52d9209118830364b7d20e8ee4a26452ad604 +README.zh.md: eedf8e7135e9bd2c73b70e891658920b5d6c64e8 diff --git a/packages/shell/tool-pwsh-persistent/README.md b/packages/shell/tool-pwsh-persistent/README.md index f90442e7e9..d4c52d9209 100644 --- a/packages/shell/tool-pwsh-persistent/README.md +++ b/packages/shell/tool-pwsh-persistent/README.md @@ -54,7 +54,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### What the agent can rely on -Commands share one shell per agent, so cwd, `$env:` variables, functions, and background jobs persist across calls. Results exclude the private completion markers, the shell prompt, and the echoed input line. A non-zero wrapped command appends `[exit code: N]` — the exact native exit code when the command ran a native program, `1` for a terminating PowerShell error. A shell that exits before reporting that status instead appends `[shell exited: code N]`, `[shell killed by signal: SIG]`, or `[shell exited]` (Windows forced termination reports exit 1 without a signal), then resets and tells the agent the next call starts fresh. Long output keeps the earliest retained prefix plus a clipping notice; if the terminal has already dropped that prefix, the result says so explicitly. +Commands share one shell per agent, so cwd, `$env:` variables, functions, and background jobs persist across calls. Results exclude the private completion markers and the echoed input line. When the shell reads stdin again without having printed the completion marker — an interrupt, a replaced shell, or an interactive foreground child whose stdin wait the provider proves — the call returns the captured partial output, which can end with the backend's own prompt text. A non-zero wrapped command appends `[exit code: N]` — the exact native exit code when the command ran a native program, `1` for a terminating PowerShell error. A shell that exits before reporting that status instead appends `[shell exited: code N]`, `[shell killed by signal: SIG]`, or `[shell exited]` (Windows forced termination reports exit 1 without a signal), then resets and tells the agent the next call starts fresh. Long output keeps the earliest retained prefix plus a clipping notice; if the terminal has already dropped that prefix, the result says so explicitly. ### What can go wrong @@ -73,7 +73,7 @@ This section explains the design decisions behind the tool and points at the cod ### Design philosophy - **A deliberate twin of `dsh-tool-bash-persistent`.** The session registry, polling loop, and reset contract mirror the persistent bash tool by design ([pwsh persistent PTY Agent Note](../../../.agents/notes/archived/architecture/2026-08-11-pwsh-persistent-pty.md)). -- **Prompt-function readiness.** The tool installs its own `prompt` function that prints a BEL-terminated OSC marker plus a printable prompt; the OSC marker carries the last exit code and the printable prompt settles every command, so a model redefinition of `prompt` degrades readiness to the silence tier. +- **Backend-owned prompt readiness.** The shell's `prompt` function belongs to the backend: it prints a BEL-terminated OSC marker plus the controlled printable prompt, and that exact prompt text settles every command through the backend's fast path. The tool neither installs nor matches a prompt of its own, so only a model redefinition of `prompt` degrades readiness to the silence tier. - **PSReadLine echo stripped by anchoring.** PowerShell renders submitted input back into the stream; the marker-anchored extraction and a wrapper-source strip remove the echo, and a wrapper that wraps across the terminal width may leave a partial echo in partial-output results. - **Reset, never repair.** Any uncertain state — an explicit `exit`, a timeout, a send failure, an abort — closes the shell and starts the next call fresh. @@ -81,12 +81,12 @@ This section explains the design decisions behind the tool and points at the cod | File | Role | |---|---| -| [`src/index.ts`](src/index.ts) | Plugin entry: shell registry, prompt setup, command wrapping, scrollback polling, extraction and rendering | +| [`src/index.ts`](src/index.ts) | Plugin entry: shell registry, command wrapping, scrollback polling, extraction and rendering | | — | No runtime invariant companion is published; the adapter's private owner-to-shell cache has no observable event or data relation. Lifecycle tests prove its cleanup without adding a public API solely for an invariant. | ### Command flow -A first command spawns the shell through `ctx.terminals.spawn`, installs the `prompt` override, and waits for readiness. Each command is wrapped into one physical line — `Write-Output` of the start marker, the body escaped with backtick escapes into a double-quoted string, and `Write-Output` of the end marker plus the exit status — so PSReadLine's echo of a wrapped line cannot fabricate completion. The tool polls the scrollback in 1,000-line pages until the end marker or a completed prompt appears, extracts the span, strips the echoed wrapper and prompts, and renders it with any status marker. A timeout aborts the deadline, captures the partial output, and resets the shell. +A first command spawns the shell through `ctx.terminals.spawn`, whose pwsh startup installs the controlled `prompt` function and returns only once the shell reached readiness. Each command is wrapped into one physical line — `Write-Output` of the start marker, the body escaped with backtick escapes into a double-quoted string, and `Write-Output` of the end marker plus the exit status — so PSReadLine's echo of a wrapped line cannot fabricate completion. The tool polls the scrollback in 1,000-line pages until the end marker appears or the send settles as `stdin_read`, extracts the span, strips the echoed wrapper, and renders it with any status marker. A timeout aborts the deadline, captures the partial output, and resets the shell. @@ -128,7 +128,7 @@ Prefix-stable while the configured description and schema remain unchanged. #### What the model sees -Commands share one shell per Agent, so cwd, `$env:` variables, functions, and background jobs persist across calls. Results exclude private completion markers, the shell prompt, and the echoed input line (PSReadLine renders submitted input back into the stream; the marker-anchored extraction and the wrapper-source strip remove it). A nonzero wrapped command appends `[exit code: N]` — the exact native exit code when the command ran a native program, `1` for a terminating PowerShell error. A shell that exits before reporting that status instead appends `[shell exited: code N]`, `[shell killed by signal: SIG]`, or `[shell exited]` when the backend supplies neither (Windows forced termination reports exit 1 without a signal), then resets and tells the model that the next call starts fresh. Long output keeps the earliest retained prefix plus a clipping notice; if the terminal has already dropped that prefix, the result says so explicitly. Timeout returns bounded partial output, closes the uncertain shell, and reports the reset. +Commands share one shell per Agent, so cwd, `$env:` variables, functions, and background jobs persist across calls. Results exclude private completion markers and the echoed input line (PSReadLine renders submitted input back into the stream; the marker-anchored extraction and the wrapper-source strip remove it). When the shell reads stdin again without having printed the completion marker — an interrupt, a replaced shell, or an interactive foreground child whose stdin wait the provider proves — the call returns the captured partial output, which can end with the backend's own prompt text. A nonzero wrapped command appends `[exit code: N]` — the exact native exit code when the command ran a native program, `1` for a terminating PowerShell error. A shell that exits before reporting that status instead appends `[shell exited: code N]`, `[shell killed by signal: SIG]`, or `[shell exited]` when the backend supplies neither (Windows forced termination reports exit 1 without a signal), then resets and tells the model that the next call starts fresh. Long output keeps the earliest retained prefix plus a clipping notice; if the terminal has already dropped that prefix, the result says so explicitly. Timeout returns bounded partial output, closes the uncertain shell, and reports the reset. #### Token effect @@ -149,7 +149,7 @@ These limits define when the tool is a poor fit or needs special care. They are - **Input echo is unavoidable** — PowerShell's PSReadLine renders submitted input back into the terminal stream, and there is no `stty -echo` equivalent. The marker-anchored extraction excludes the echo in complete results; the wrapper-source strip covers fallback paths, but a wrapper that wraps across the terminal width may leave a partial echo in partial-output results, bounded by `maxOutputChars`. - **Raw ESC characters inside model commands are unsupported** — PSReadLine consumes them before execution. The wrapper escapes the control bytes it needs (`[char]27`-built OSC markers, backtick escapes for the body). - **A model redefinition of the `prompt` function removes the readiness marker** — the shell then settles on the silence tier instead of the marker fast path. -- **There is no interactive stdin during a command** — a foreground command that reads input blocks until the command timeout, which resets the shell. +- **There is no interactive stdin during a command** — a foreground child that reads input returns early with partial output only where the provider proves its stdin wait; elsewhere the call runs to `timeoutMs`, which resets the shell. - **SIGTSTP/SIGHUP are unavailable on Windows** (backend-rejected); SIGINT is delivered as a console-wide Ctrl-C input write, which at a prompt cancels the pending line instead of signalling a process. - **Under the Windows ACL sandbox's read-only mode, pwsh starts in ConstrainedLanguage**, which may deny the bootstrap's `[Console]::` encoding pin and prompt marker. Commands can still settle through the printable prompt and silence tier, but non-ASCII output may follow the host code page. - **The BEL-terminated OSC marker remains a readiness signal only** — a BEL event channel to the model stays deferred, aligned with the current implementation. diff --git a/packages/shell/tool-pwsh-persistent/README.zh.md b/packages/shell/tool-pwsh-persistent/README.zh.md index d634e8e42e..eedf8e7135 100644 --- a/packages/shell/tool-pwsh-persistent/README.zh.md +++ b/packages/shell/tool-pwsh-persistent/README.zh.md @@ -54,7 +54,7 @@ kind: "package-reference" ### agent 可以依赖什么 -命令共享每个 agent 一个 shell,因此 cwd、`$env:` 变量、函数与后台任务都会跨调用保留。结果排除私有完成标记、shell 提示符与回显的输入行。非零的包装命令追加 `[exit code: N]`——命令运行原生程序时给出确切原生退出码,PowerShell 终止错误则为 `1`。在报告该状态前就退出的 shell 改为追加 `[shell exited: code N]`、`[shell killed by signal: SIG]` 或 `[shell exited]`(Windows 强制终止报告 exit 1 且没有信号),然后重置并告诉 agent 下一次调用从全新状态开始。长输出保留最早的已保留前缀并附裁剪通知;若 terminal 已经丢弃该前缀,结果会明确说明。 +命令共享每个 agent 一个 shell,因此 cwd、`$env:` 变量、函数与后台任务都会跨调用保留。结果排除私有完成标记与回显的输入行。当 shell 再次读取 stdin 却没有打印完成标记时——一次中断、一个被替换的 shell,或提供方能证明其 stdin 等待的交互式前台子进程——调用返回已捕获的部分输出,其结尾可能是后端自己的提示符文本。非零的包装命令追加 `[exit code: N]`——命令运行原生程序时给出确切原生退出码,PowerShell 终止错误则为 `1`。在报告该状态前就退出的 shell 改为追加 `[shell exited: code N]`、`[shell killed by signal: SIG]` 或 `[shell exited]`(Windows 强制终止报告 exit 1 且没有信号),然后重置并告诉 agent 下一次调用从全新状态开始。长输出保留最早的已保留前缀并附裁剪通知;若 terminal 已经丢弃该前缀,结果会明确说明。 ### 可能出什么问题 @@ -73,7 +73,7 @@ kind: "package-reference" ### 设计理念 - **`dsh-tool-bash-persistent` 的刻意孪生。** 会话注册表、轮询循环与重置约定按设计镜像持久 bash 工具([pwsh 持久 PTY Agent Note](../../../.agents/notes/archived/architecture/2026-08-11-pwsh-persistent-pty.md))。 -- **prompt 函数就绪。** 工具安装自己的 `prompt` 函数,打印 BEL 结尾的 OSC 标记加可打印提示符;OSC 标记携带最后的退出码,可打印提示符让每条命令都能结算,因此模型重定义 `prompt` 会把就绪降级到静默层级。 +- **后端拥有提示符就绪。** shell 的 `prompt` 函数属于后端:它打印 BEL 结尾的 OSC 标记加受控的可打印提示符,该确切提示符文本让每条命令都经由后端快路径结算。工具既不安装也不匹配自己的提示符,因此只有模型重定义 `prompt` 才会把就绪降级到静默层级。 - **PSReadLine 回显靠锚定剥离。** PowerShell 会把提交的输入渲染回流中;标记锚定提取与包装源码剥离移除回显,而跨终端宽度换行的包装可能在部分输出结果中留下部分回显。 - **重置,而非修复。** 任何不确定状态——显式 `exit`、超时、发送失败、中止——都会关闭 shell 并让下一次调用从全新状态开始。 @@ -81,12 +81,12 @@ kind: "package-reference" | 文件 | 职责 | |---|---| -| [`src/index.ts`](src/index.ts) | 插件入口:shell 注册表、prompt 设置、命令包装、scrollback 轮询、提取与渲染 | +| [`src/index.ts`](src/index.ts) | 插件入口:shell 注册表、命令包装、scrollback 轮询、提取与渲染 | | — | 不发布运行时不变式伴生入口;适配器私有的 owner-to-shell 缓存不存在可观察的事件或数据关系。生命周期测试无需仅为不变式增加公共 API 即可验证其清理。 | ### 命令流程 -首条命令通过 `ctx.terminals.spawn` 生成 shell,安装 `prompt` 覆盖,并等待就绪。随后每条命令都包装成一行物理文本——`Write-Output` 起始标记、用反引号转义进双引号字符串的命令体、`Write-Output` 结束标记加退出状态——因此 PSReadLine 对换行包装的回显无法伪造完成。工具以 1,000 行一页轮询 scrollback,直到出现结束标记或完成的提示符,提取区间、剥离回显的包装与提示符,并连同任何状态标记一起渲染。超时会中止截止时间、捕获部分输出并重置 shell。 +首条命令通过 `ctx.terminals.spawn` 生成 shell,其 pwsh 启动流程安装受控的 `prompt` 函数,并只在该 shell 达到就绪后返回。随后每条命令都包装成一行物理文本——`Write-Output` 起始标记、用反引号转义进双引号字符串的命令体、`Write-Output` 结束标记加退出状态——因此 PSReadLine 对换行包装的回显无法伪造完成。工具以 1,000 行一页轮询 scrollback,直到出现结束标记或该 send 以 `stdin_read` 结算,提取区间、剥离回显的包装,并连同任何状态标记一起渲染。超时会中止截止时间、捕获部分输出并重置 shell。 @@ -128,7 +128,7 @@ kind: "package-reference" #### 模型看到什么 -命令共享每个 agent 一个 shell,因此 cwd、`$env:` 变量、函数与后台任务都会跨调用保留。结果排除私有完成标记、shell 提示词与回显的输入行(PSReadLine 会把提交的输入渲染回流中;标记锚定提取与包装源码剥离会移除它)。非零的包装命令追加 `[exit code: N]`——命令运行原生程序时给出确切原生退出码,PowerShell 终止错误则为 `1`。在报告该状态前就退出的 shell 改为追加 `[shell exited: code N]`、`[shell killed by signal: SIG]`,或后端两者都未提供时的 `[shell exited]`(Windows 强制终止报告 exit 1 且没有信号),然后重置并告诉模型下一次调用从全新状态开始。长输出保留最早的已保留前缀并附裁剪通知;若 terminal 已经丢弃该前缀,结果会明确说明。超时返回有界部分输出、关闭不确定的 shell 并报告重置。 +命令共享每个 agent 一个 shell,因此 cwd、`$env:` 变量、函数与后台任务都会跨调用保留。结果排除私有完成标记与回显的输入行(PSReadLine 会把提交的输入渲染回流中;标记锚定提取与包装源码剥离会移除它)。当 shell 再次读取 stdin 却没有打印完成标记时——一次中断、一个被替换的 shell,或提供方能证明其 stdin 等待的交互式前台子进程——调用返回已捕获的部分输出,其结尾可能是后端自己的提示符文本。非零的包装命令追加 `[exit code: N]`——命令运行原生程序时给出确切原生退出码,PowerShell 终止错误则为 `1`。在报告该状态前就退出的 shell 改为追加 `[shell exited: code N]`、`[shell killed by signal: SIG]`,或后端两者都未提供时的 `[shell exited]`(Windows 强制终止报告 exit 1 且没有信号),然后重置并告诉模型下一次调用从全新状态开始。长输出保留最早的已保留前缀并附裁剪通知;若 terminal 已经丢弃该前缀,结果会明确说明。超时返回有界部分输出、关闭不确定的 shell 并报告重置。 #### Token 影响 @@ -149,7 +149,7 @@ kind: "package-reference" - **输入回显不可避免**——PowerShell 的 PSReadLine 会把提交的输入渲染回终端流,而且没有 `stty -echo` 等价物。标记锚定提取在完整结果中排除回显;包装源码剥离覆盖回退路径,但跨终端宽度换行的包装可能在部分输出结果中留下部分回显,受 `maxOutputChars` 设界。 - **模型命令内的原始 ESC 字符不受支持**——PSReadLine 会在执行前消费它们。包装器会转义它需要的控制字节(`[char]27` 构造的 OSC 标记、正文的反引号转义)。 - **模型重定义 `prompt` 函数会移除就绪标记**——shell 随后在静默层级而非标记快路径上结算。 -- **命令期间没有交互 stdin**——读取输入的前台命令会一直阻塞到命令超时,随后重置 shell。 +- **命令期间没有交互 stdin**——读取输入的前台子进程仅在提供方能证明其 stdin 等待时提前返回部分输出;否则调用会运行到 `timeoutMs`,随后重置 shell。 - **Windows 上 SIGTSTP/SIGHUP 不可用**(后端拒绝);SIGINT 以控制台级 Ctrl-C 输入写入投递,在提示词处会取消待处理行而不是向进程发信号。 - **在 Windows ACL 沙箱的只读模式下,pwsh 以 ConstrainedLanguage 启动**,可能拒绝引导的 `[Console]::` 编码固定与 prompt 标记。命令仍可通过可打印提示词与静默层级结算,但非 ASCII 输出可能跟随宿主代码页。 - **BEL 结尾的 OSC 标记目前只是就绪信号**——通向模型的 BEL 事件通道仍被推迟,与当前实现保持一致。 diff --git a/packages/shell/tool-pwsh-persistent/src/index.ts b/packages/shell/tool-pwsh-persistent/src/index.ts index 34f8cf7732..84b7e622ec 100644 --- a/packages/shell/tool-pwsh-persistent/src/index.ts +++ b/packages/shell/tool-pwsh-persistent/src/index.ts @@ -9,7 +9,7 @@ import { randomUUID } from 'node:crypto' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' -import type { TerminalReadResult, TerminalSendResult, TerminalSessionId } from '@deepseek-ai/dsh-terminal' +import type { TerminalReadResult, TerminalSessionId } from '@deepseek-ai/dsh-terminal' import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' import { defineTool } from '@deepseek-ai/dsh-tools' @@ -17,7 +17,6 @@ import { defineTool } from '@deepseek-ai/dsh-tools' const TRUNCATED_MESSAGE = 'To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with Select-String in order to find the line numbers of what you are looking for.' const LOST_PREFIX_MESSAGE = 'The beginning of this command output was dropped by the terminal scrollback limit. The following text is the earliest retained output.\n' const SHELL_RESET_MESSAGE = 'The persistent pwsh shell was reset; the next pwsh call starts from the workspace with a fresh current directory and environment.' -const SHELL_PROMPT = '__DSH_PERSISTENT_PWSH_PROMPT__ ' const TIMEOUT_CODE = 'PERSISTENT_PWSH_TIMEOUT' // One page is enough to find a just-emitted completion marker; the full // scrollback is assembled only when a command settles or needs partial output. @@ -98,12 +97,8 @@ function wrapCommand(command: string, marker: CommandMarkers): string { return `Write-Output '${marker.start}'; $LASTEXITCODE = $null; $__s = 1; try { Invoke-Expression "${body}"; $__ok = $? } catch { $__ok = $false }; if ($null -ne $LASTEXITCODE) { $__s = [int]$LASTEXITCODE } else { $__s = if ($__ok) { 0 } else { 1 } }; Write-Output ('${marker.end}' + $__s)` } -function stripPrompt(text: string): string { - let result = text.replace(/\r?\n$/, '') - while (result.endsWith(SHELL_PROMPT)) { - result = result.slice(0, -SHELL_PROMPT.length) - } - return result.endsWith('\n') ? result.slice(0, -1) : result +function trimTrailingNewline(text: string): string { + return text.replace(/\r?\n$/, '') } function commandOutput( @@ -130,12 +125,6 @@ function commandOutput( } } -function promptCompleted(result: TerminalSendResult): boolean { - return result.viewport.endsWith(SHELL_PROMPT) - || result.viewport.endsWith(`${SHELL_PROMPT}\r\n`) - || result.viewport.endsWith(`${SHELL_PROMPT}\n`) -} - function partialOutput( snapshot: RetainedOutput, marker: CommandMarkers, @@ -146,7 +135,7 @@ function partialOutput( const startMarker = snapshot.text.lastIndexOf(marker.start) if (startMarker >= 0) { return { - text: stripPrompt(snapshot.text.slice(startMarker + marker.start.length).replace(/^\r?\n/, '')), + text: trimTrailingNewline(snapshot.text.slice(startMarker + marker.start.length).replace(/^\r?\n/, '')), incomplete: false, } } @@ -157,7 +146,7 @@ function partialOutput( const fallbackEnd = afterStart.lastIndexOf(marker.end) const beforeEnd = fallbackEnd < 0 ? afterStart : afterStart.slice(0, fallbackEnd) return { - text: stripPrompt(beforeEnd.replaceAll(SHELL_PROMPT, '').replaceAll(wrapper, '')), + text: trimTrailingNewline(beforeEnd.replaceAll(wrapper, '')), incomplete: fallbackTruncated || fallbackStart < 0, } } @@ -252,15 +241,6 @@ async function respondToSessionExit( ].filter(part => part.length > 0).join('\n') } -/** - * The pwsh prompt function that overrides the backend bootstrap value with - * this tool's own prompt. `[char]27`/`[char]7` build the OSC bytes at runtime - * because raw ESC characters in submitted input are unreliable under - * PSReadLine. - */ -const PWSH_PROMPT_SETUP = - "function prompt { [Console]::Write([char]27 + ']133;D;' + [int]$LASTEXITCODE + [char]7); '" + SHELL_PROMPT + "' }" - function persistentShells(ctx: Context, config: ResolvedConfig): PersistentShells { const pending = new WeakMap>() const live = new Map() @@ -307,15 +287,6 @@ function persistentShells(ctx: Context, config: ResolvedConfig): PersistentShell live.delete(owner) }, 'tool-pwsh-persistent owner cache cleanup') } - const setup = ctx.terminals.startSend(owner, spawned.sessionId, { - text: PWSH_PROMPT_SETUP, - submit: true, - signal: combinedSignal, - }) - const result = await setup.done - if (result.sessionStatus.kind === 'exited' || result.waitReason === 'timeout') { - throw new Error('persistent pwsh shell did not accept initialization') - } return spawned.sessionId } catch (error: unknown) { await reset(owner, 'persistent pwsh initialization failed') @@ -414,7 +385,11 @@ async function executeCommand( ctx, shells, owner, id, result.sessionStatus, marker, wrapped, fallback, fallbackTruncated, config, ) } - if (promptCompleted(result)) { + // The shell reads stdin again (its prompt, or a foreground child's own + // read) without having printed the end marker — an interrupt, a replaced + // shell, or an interactive child. Return what was captured instead of + // spinning until the command deadline. + if (result.waitReason === 'stdin_read') { const snapshot = retainedScrollback(ctx, owner, id, latest) return renderCaptured( partialOutput(snapshot, marker, wrapped, fallback, fallbackTruncated), diff --git a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts index eacd51d586..96fe69116c 100644 --- a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts @@ -95,7 +95,10 @@ describe.skipIf(!hasPwsh)('persistent pwsh through a real cordis.yml Loader comp ' shellDialect: pwsh', ' pollIntervalMs: 10', ' exactProbeAfterMs: 20', - ' idleSilenceMs: 300', + // The silence tier is pushed beyond the send bound, so no send below can + // settle as inferred_idle: every case proves the controlled-prompt fast + // path that the production defaults (3.5s silence) would otherwise mask. + ' idleSilenceMs: 30000', ' handoffGraceMs: 300', ' scrollbackLines: 20000', // The first call pays the full pwsh cold-start latency (spawn + .NET + diff --git a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts index c260f818eb..bf2ff8454b 100644 --- a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts @@ -93,8 +93,6 @@ type StubMode = | 'torn-status' | 'finish-torn-status' | 'end-only' - | 'init-exit' - | 'init-timeout' | 'spawn-error' | 'send-error' | 'prompt-after-idle' @@ -109,7 +107,7 @@ const START_PATTERN = /__DSH_PERSISTENT_PWSH_START_[^_]+(?:-[^_]+)*__/ const END_PATTERN = /__DSH_PERSISTENT_PWSH_END_[^:]+:/ class StubTerminalSession implements TerminalBackendSession { - readonly motd = '__DSH_PERSISTENT_PWSH_PROMPT__ ' + readonly motd = 'stub> ' readonly pid = 123 statusValue: TerminalSessionStatus = { kind: 'running' } scrollback = this.motd @@ -126,16 +124,6 @@ class StubTerminalSession implements TerminalBackendSession { startSend(request: TerminalSendRequest): TerminalSendOperation { this.sends += 1 - if (request.text.startsWith('function prompt')) { - if (this.mode === 'init-exit') { - this.statusValue = { kind: 'exited', exitCode: 1, signal: null } - return this.operation(Promise.resolve(this.result('', 'session_exit'))) - } - if (this.mode === 'init-timeout') { - return this.operation(Promise.resolve(this.result('', 'timeout'))) - } - return this.operation(Promise.resolve(this.result(this.motd, 'stdin_read'))) - } if (this.mode === 'send-error') throw new Error('stub send failed') if (this.throwOnSend) throw new Error('PTY session has exited') if (this.mode === 'wait-for-abort' || this.mode === 'end-on-abort') { @@ -346,7 +334,7 @@ describe('tool-pwsh-persistent', () => { expect(text(await call(ctx, owner, 'Write-Output one'))).toBe('hello from stub') expect(text(await call(ctx, owner, 'Write-Output two'))).toBe('hello from stub') expect(stub.sessions).toHaveLength(1) - expect(stub.sessions[0]?.sends).toBe(3) + expect(stub.sessions[0]?.sends).toBe(2) const ownerWithoutCwd = await agent(ctx, undefined) expect(text(await call(ctx, ownerWithoutCwd, 'pwd'))).toBe('hello from stub') @@ -392,7 +380,7 @@ describe('tool-pwsh-persistent', () => { expect(stub.sessions).toHaveLength(2) }) - it('handles inferred idle, prompt fallback, shell exit, clipping, and cleanup', async () => { + it('handles inferred idle, stdin_read fallback, shell exit, clipping, and cleanup', async () => { const { ctx, owner, stub, fiber } = await setup({ backendType: 'stub', maxOutputChars: 10, @@ -405,18 +393,16 @@ describe('tool-pwsh-persistent', () => { session.mode = 'incremental-fallback' session.scrollback = '' - expect(text(await call(ctx, owner, 'incremental fallback'))).toBe('increment') + expect(text(await call(ctx, owner, 'incremental fallback'))).toContain('increment') session.mode = 'prompt-only' const promptFallback = text(await call(ctx, owner, 'bad {')) expect(promptFallback).toContain('pwsh: synt') - expect(promptFallback).not.toContain('DSH_PERSISTENT_PWSH_PROMPT') session.mode = 'prompt-crlf' session.scrollback = '' const crlfPromptFallback = text(await call(ctx, owner, 'bad {')) expect(crlfPromptFallback).toContain('pwsh: synt') - expect(crlfPromptFallback).not.toContain('DSH_PERSISTENT_PWSH_PROMPT') session.mode = 'end-only' session.scrollback = '' @@ -502,7 +488,7 @@ describe('tool-pwsh-persistent', () => { expect(text(await call(ctx, owner, 'paged output'))).toBe('hello from stub') }) - it('sanitizes a prompt fallback reached after multiple polling rounds', async () => { + it('returns a stdin_read fallback reached after multiple polling rounds', async () => { const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 }) await call(ctx, owner, 'warm up') const session = stub.sessions[0]! @@ -511,7 +497,8 @@ describe('tool-pwsh-persistent', () => { const result = text(await call(ctx, owner, 'bad {')) expect(result).toContain('partial syntax output') expect(result).toContain('pwsh: syntax error') - expect(result).not.toContain('DSH_PERSISTENT_PWSH_PROMPT') + // The backend owns the prompt text, so the fallback retains it verbatim. + expect(result.endsWith('stub> ')).toBe(true) expect(result).not.toContain('DSH_PERSISTENT_PWSH_START') }) @@ -546,7 +533,7 @@ describe('tool-pwsh-persistent', () => { const cancelled = call(ctx, owner, 'hang', controller.signal) const queued = call(ctx, owner, 'after cancellation') try { - await expect.poll(() => stub.sessions[0]!.sends).toBe(3) + await expect.poll(() => stub.sessions[0]!.sends).toBe(2) controller.abort({ kind: 'user' }) const result = await cancelled @@ -577,14 +564,14 @@ describe('tool-pwsh-persistent', () => { const running = call(ctx, owner, 'hang', runningController.signal) const queued = call(ctx, owner, 'never sent', queuedController.signal) try { - await expect.poll(() => session.sends).toBe(3) + await expect.poll(() => session.sends).toBe(2) await expect.poll(() => execute.mock.calls.length).toBe(2) queuedController.abort({ kind: 'user' }) runningController.abort({ kind: 'user' }) const result = await queued expect(text(result)).toBe('Error: tool call aborted') expect(result.error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) - expect(session.sends).toBe(3) + expect(session.sends).toBe(2) expect(stub.sessions).toHaveLength(1) expect(session.closed).toContain('persistent pwsh command aborted') } finally { @@ -702,15 +689,6 @@ describe('tool-pwsh-persistent', () => { expect(stub.sessions).toEqual([]) }) - it.each(['init-exit', 'init-timeout'] as const)( - 'fails initialization and closes the unusable shell for %s', - async (mode) => { - const { ctx, owner, stub } = await setup({ backendType: 'stub' }, mode) - expect((await call(ctx, owner, 'pwd')).isError).toBe(true) - expect(stub.sessions[0]?.closed).toContain('persistent pwsh initialization failed') - }, - ) - it('clears a failed spawn without trying to close an unpublished shell', async () => { const { ctx, owner, stub } = await setup({ backendType: 'stub' }, 'spawn-error') expect((await call(ctx, owner, 'pwd')).isError).toBe(true) From 74f4c438de902567e8f28d82e58a654a627bc426 Mon Sep 17 00:00:00 2001 From: Huanqi Cao Date: Mon, 21 Sep 2026 16:53:15 +0800 Subject: [PATCH 02/10] test(pty): pin the pwsh fast path by settle reason The composition suite's idleSilenceMs: 30000 was below the suite's own send bound (dsh-terminal-bash timeoutMs: 300000), so the comment claiming silence could settle nothing was wrong: a regressed send still settled as inferred_idle after ~30 s and only the accumulated case timeout caught it. The case now records every send's waitReason and requires at least six stdin_read settlements with no inferred_idle. Reinstating the removed prompt override fails it in 30 s with 'expected 0 to be greater than or equal to 6' while the output assertions still pass. The silence tier returns to its product default. Also renames the two stale test titles ('private shell prompt', and the cancellation phase that no longer covers an initialization send), pins the stdin_read fallback's session retention, and records the interactive-child consequence of that retention in the package README pair and the Agent Note. --- ...ent-pwsh-keeps-controlled-prompt.i18n.yaml | 4 +-- ...persistent-pwsh-keeps-controlled-prompt.md | 4 +-- ...sistent-pwsh-keeps-controlled-prompt.zh.md | 4 +-- .../tool-pwsh-persistent/README.i18n.yaml | 4 +-- packages/shell/tool-pwsh-persistent/README.md | 2 +- .../shell/tool-pwsh-persistent/README.zh.md | 2 +- .../tests/loader-composition.spec.ts | 31 ++++++++++++++++--- .../tool-pwsh-persistent/tests/tools.spec.ts | 14 ++++++--- 8 files changed, 46 insertions(+), 19 deletions(-) diff --git a/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.i18n.yaml index db9c9a3ad8..4f16b7775b 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md -2026-09-21-persistent-pwsh-keeps-controlled-prompt.md: 748d18f6daafaf036576a911d26647dafbe92261 -2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md: 6425581a6dbb84dfc3b1c4cd4fb732353c4cd5e1 +2026-09-21-persistent-pwsh-keeps-controlled-prompt.md: 3fd42b77d4536215f34c32643526dbb03d21674f +2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md: 88d4e2deef26af4ad92ef4a69d8ae17403027f70 diff --git a/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md index 748d18f6da..3fd42b77d4 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md +++ b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.md @@ -30,8 +30,8 @@ The viewport-suffix fallback is replaced with the seam's own signal: a send that Windows, production defaults, real Loader composition: tool calls drop from 8493/3722/3832/3759 ms to 1340/255/251/241 ms (spawn + initialization + first command, then three warm commands). -The `stdin_read` fallback is behavior, not only cosmetics: where a provider proves a foreground stdin wait, an interactive child now returns captured partial output instead of spinning to the command deadline, and elsewhere the call still runs to `timeoutMs`; the tool README records both. Complete marker-delimited output is unchanged. +The `stdin_read` fallback is behavior, not only cosmetics: where a provider proves a foreground stdin wait, an interactive child returns captured partial output instead of spinning to the command deadline, and elsewhere the call still runs to `timeoutMs`. That early return keeps the session, so a child still reading stdin can consume the next call's command until that call reaches `timeoutMs` and resets the shell; `dsh-tool-bash-persistent` behaves the same way, and distinguishing the shell's own prompt readiness from a child's stdin wait belongs to the seam rather than to either tool. Complete marker-delimited output is unchanged. -The loader-composition suite now sets `idleSilenceMs: 30000`, above the send bound, so silence can settle nothing and every case fails if prompt readiness regresses. The stub suite drops the initialization-handshake modes and pins the prompt text retained in partial output instead of its absence. +The loader-composition suite records every send's `waitReason` and requires at least six `stdin_read` settlements and no `inferred_idle`: the regression is reported by the settle reason itself, not by how long silence takes. Reinstating the removed prompt override fails that assertion after 30 s with `expected 0 to be greater than or equal to 6`, while the case's output assertions still pass. The stub suite drops the initialization-handshake modes and pins the prompt text retained in partial output instead of its absence. A model command that redefines `prompt` still removes the readiness marker and degrades later sends to the silence tier: the backend installs its prompt once at startup and cannot re-assert it. diff --git a/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md index 6425581a6d..88d4e2deef 100644 --- a/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-09-21-persistent-pwsh-keeps-controlled-prompt.zh.md @@ -30,8 +30,8 @@ Status: implemented Windows、生产默认值、真实 Loader 组合:工具调用从 8493/3722/3832/3759 毫秒降至 1340/255/251/241 毫秒(spawn + 初始化 + 首条命令,随后三条热命令)。 -`stdin_read` 回退是行为而不只是美化:在提供方能证明前台 stdin 等待之处,交互式子进程现在返回已捕获的部分输出,而不是空转到命令期限;其他情况下调用仍会运行到 `timeoutMs`,两者都记入工具 README。由标记界定的完整输出保持不变。 +`stdin_read` 回退是行为而不只是美化:在提供方能证明前台 stdin 等待之处,交互式子进程会返回已捕获的部分输出,而不是空转到命令期限;其他情况下调用仍会运行到 `timeoutMs`。该提前返回保留会话,因此仍在读取 stdin 的子进程可能吞掉下一次调用的命令,直到那次调用到达 `timeoutMs` 并重置 shell;`dsh-tool-bash-persistent` 行为相同,而区分「shell 自身的提示符就绪」与「子进程的 stdin 等待」属于 seam,而不是任一工具。由标记界定的完整输出保持不变。 -loader 组合套件现在把 `idleSilenceMs` 设为 30000,位于 send 上限之上,静默无法结算任何 send,提示符就绪一旦回归,每个用例都会失败。stub 套件删除了初始化握手模式,并改为锚定部分输出中保留的提示符文本,而不是它的缺席。 +loader 组合套件记录每次 send 的 `waitReason`,要求至少六次 `stdin_read` 且没有 `inferred_idle`:回归由结算原因本身报告,而不是靠静默层耗时。把删掉的提示符覆盖加回去,该断言会在 30 秒后以 `expected 0 to be greater than or equal to 6` 失败,而同一用例的输出断言仍然通过。stub 套件删除了初始化握手模式,并改为锚定部分输出中保留的提示符文本,而不是它的缺席。 重定义 `prompt` 的模型命令仍会移除就绪标记,并把后续 send 降级到静默层:后端只在启动时安装一次提示符,无法重新设定。 diff --git a/packages/shell/tool-pwsh-persistent/README.i18n.yaml b/packages/shell/tool-pwsh-persistent/README.i18n.yaml index 00dcbdee79..d0e2b2e198 100644 --- a/packages/shell/tool-pwsh-persistent/README.i18n.yaml +++ b/packages/shell/tool-pwsh-persistent/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/shell/tool-pwsh-persistent/README.md -README.md: d4c52d9209118830364b7d20e8ee4a26452ad604 -README.zh.md: eedf8e7135e9bd2c73b70e891658920b5d6c64e8 +README.md: cd78f224f9f85899cca1f578fd0316c6f4caab2f +README.zh.md: 53b0b4cdd69ac94556f16621ccd3d9ca205cc6f4 diff --git a/packages/shell/tool-pwsh-persistent/README.md b/packages/shell/tool-pwsh-persistent/README.md index d4c52d9209..cd78f224f9 100644 --- a/packages/shell/tool-pwsh-persistent/README.md +++ b/packages/shell/tool-pwsh-persistent/README.md @@ -149,7 +149,7 @@ These limits define when the tool is a poor fit or needs special care. They are - **Input echo is unavoidable** — PowerShell's PSReadLine renders submitted input back into the terminal stream, and there is no `stty -echo` equivalent. The marker-anchored extraction excludes the echo in complete results; the wrapper-source strip covers fallback paths, but a wrapper that wraps across the terminal width may leave a partial echo in partial-output results, bounded by `maxOutputChars`. - **Raw ESC characters inside model commands are unsupported** — PSReadLine consumes them before execution. The wrapper escapes the control bytes it needs (`[char]27`-built OSC markers, backtick escapes for the body). - **A model redefinition of the `prompt` function removes the readiness marker** — the shell then settles on the silence tier instead of the marker fast path. -- **There is no interactive stdin during a command** — a foreground child that reads input returns early with partial output only where the provider proves its stdin wait; elsewhere the call runs to `timeoutMs`, which resets the shell. +- **There is no interactive stdin during a command** — where the provider proves a foreground stdin wait, a child that reads input returns early with partial output and leaves the session open, so that child can consume the next call's command until the call reaches `timeoutMs` and resets the shell. Everywhere else the original call itself runs to `timeoutMs`, which resets the shell. - **SIGTSTP/SIGHUP are unavailable on Windows** (backend-rejected); SIGINT is delivered as a console-wide Ctrl-C input write, which at a prompt cancels the pending line instead of signalling a process. - **Under the Windows ACL sandbox's read-only mode, pwsh starts in ConstrainedLanguage**, which may deny the bootstrap's `[Console]::` encoding pin and prompt marker. Commands can still settle through the printable prompt and silence tier, but non-ASCII output may follow the host code page. - **The BEL-terminated OSC marker remains a readiness signal only** — a BEL event channel to the model stays deferred, aligned with the current implementation. diff --git a/packages/shell/tool-pwsh-persistent/README.zh.md b/packages/shell/tool-pwsh-persistent/README.zh.md index eedf8e7135..53b0b4cdd6 100644 --- a/packages/shell/tool-pwsh-persistent/README.zh.md +++ b/packages/shell/tool-pwsh-persistent/README.zh.md @@ -149,7 +149,7 @@ kind: "package-reference" - **输入回显不可避免**——PowerShell 的 PSReadLine 会把提交的输入渲染回终端流,而且没有 `stty -echo` 等价物。标记锚定提取在完整结果中排除回显;包装源码剥离覆盖回退路径,但跨终端宽度换行的包装可能在部分输出结果中留下部分回显,受 `maxOutputChars` 设界。 - **模型命令内的原始 ESC 字符不受支持**——PSReadLine 会在执行前消费它们。包装器会转义它需要的控制字节(`[char]27` 构造的 OSC 标记、正文的反引号转义)。 - **模型重定义 `prompt` 函数会移除就绪标记**——shell 随后在静默层级而非标记快路径上结算。 -- **命令期间没有交互 stdin**——读取输入的前台子进程仅在提供方能证明其 stdin 等待时提前返回部分输出;否则调用会运行到 `timeoutMs`,随后重置 shell。 +- **命令期间没有交互 stdin**——在提供方能证明前台 stdin 等待之处,读取输入的子进程会提前返回部分输出并保留会话,因此该子进程可能吞掉下一次调用的命令,直到那次调用到达 `timeoutMs` 并重置 shell。其他情况下原调用本身会运行到 `timeoutMs`,随后重置 shell。 - **Windows 上 SIGTSTP/SIGHUP 不可用**(后端拒绝);SIGINT 以控制台级 Ctrl-C 输入写入投递,在提示词处会取消待处理行而不是向进程发信号。 - **在 Windows ACL 沙箱的只读模式下,pwsh 以 ConstrainedLanguage 启动**,可能拒绝引导的 `[Console]::` 编码固定与 prompt 标记。命令仍可通过可打印提示词与静默层级结算,但非 ASCII 输出可能跟随宿主代码页。 - **BEL 结尾的 OSC 标记目前只是就绪信号**——通向模型的 BEL 事件通道仍被推迟,与当前实现保持一致。 diff --git a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts index 96fe69116c..8641952fb4 100644 --- a/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/loader-composition.spec.ts @@ -3,7 +3,7 @@ import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import Include from '@deepseek-ai/cordis-plugin-include' @@ -13,6 +13,7 @@ import AgentRegistry from '@deepseek-ai/dsh-agent' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { Agent } from '@deepseek-ai/dsh-agent' import TerminalSessionService from '@deepseek-ai/dsh-terminal' +import type { TerminalWaitReason } from '@deepseek-ai/dsh-terminal' import * as TerminalBash from '@deepseek-ai/dsh-terminal-bash' import SandboxProvider from '@deepseek-ai/dsh-sandbox' import type { ConfinedArgv, SandboxPolicy } from '@deepseek-ai/dsh-sandbox' @@ -95,10 +96,9 @@ describe.skipIf(!hasPwsh)('persistent pwsh through a real cordis.yml Loader comp ' shellDialect: pwsh', ' pollIntervalMs: 10', ' exactProbeAfterMs: 20', - // The silence tier is pushed beyond the send bound, so no send below can - // settle as inferred_idle: every case proves the controlled-prompt fast - // path that the production defaults (3.5s silence) would otherwise mask. - ' idleSilenceMs: 30000', + // The silence tier keeps its product default; the case body records each + // send's wait reason, which pins the controlled-prompt fast path directly + // instead of relying on how long silence would take to settle. ' handoffGraceMs: 300', ' scrollbackLines: 20000', // The first call pays the full pwsh cold-start latency (spawn + .NET + @@ -143,6 +143,22 @@ describe.skipIf(!hasPwsh)('persistent pwsh through a real cordis.yml Loader comp await context.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } }) await context.loader.await() + const terminals = context.terminals + const startSend = terminals.startSend.bind(terminals) + // A send that lost the controlled-prompt fast path settles as inferred_idle + // after the silence tier, so recording why every send settled detects that + // regression immediately instead of through accumulated wall-clock. + const settleReasons: TerminalWaitReason[] = [] + vi.spyOn(terminals, 'startSend').mockImplementation((owner, id, request) => { + const operation = startSend(owner, id, request) + void operation.done.then( + (settled) => { settleReasons.push(settled.waitReason) }, + // A rejected send is the tool's error path, not a settle reason. + () => {}, + ) + return operation + }) + const owner = await agent(context, root) const signal = new AbortController().signal const execute = (id: string, command: string) => context!.tools.execute({ @@ -180,5 +196,10 @@ describe.skipIf(!hasPwsh)('persistent pwsh through a real cordis.yml Loader comp const exited = text(await execute('exit', 'exit')) expect(exited).toContain('next pwsh call starts from the workspace') expect(text(await execute('after-exit', 'Write-Output "$PWD"'))).toBe(root) + + // Six commands settle on the controlled prompt; no send may fall back to the + // silence tier, which is the 3.5 s-per-call degradation this suite pins. + expect(settleReasons.filter(reason => reason === 'stdin_read').length).toBeGreaterThanOrEqual(6) + expect(settleReasons).not.toContain('inferred_idle') }, 120_000) }) diff --git a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts index bf2ff8454b..2957c34b54 100644 --- a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts @@ -356,7 +356,7 @@ describe('tool-pwsh-persistent', () => { expect(result).not.toContain('Invoke-Expression') }) - it('preserves command output that equals the private shell prompt', async () => { + it("preserves command output that equals the backend's prompt text", async () => { const { ctx, owner, stub } = await setup({ backendType: 'stub' }) await call(ctx, owner, 'warm up') const session = stub.sessions[0]! @@ -404,6 +404,12 @@ describe('tool-pwsh-persistent', () => { const crlfPromptFallback = text(await call(ctx, owner, 'bad {')) expect(crlfPromptFallback).toContain('pwsh: synt') + // The stdin_read fallback returns captured output without resetting the + // shell, so later calls keep the same session; the README names the + // interactive-child consequence of that retention. + expect(session.closed).toEqual([]) + expect(stub.sessions).toHaveLength(1) + session.mode = 'end-only' session.scrollback = '' const missingStart = text(await call(ctx, owner, 'recover marker')) @@ -656,14 +662,14 @@ describe('tool-pwsh-persistent', () => { } }) - it.each(['initialization', 'command', 'cleanup'] as const)('preserves a distinct %s failure during cancellation', async (phase) => { + it.each(['command', 'cleanup'] as const)('preserves a distinct %s failure during cancellation', async (phase) => { const { ctx, owner } = await setup() - if (phase === 'command') await call(ctx, owner, 'warm up') + await call(ctx, owner, 'warm up') const controller = new AbortController() const failure = new Error(`${phase} failed`) vi.spyOn(ctx.terminals, 'startSend').mockImplementationOnce(() => { controller.abort({ kind: 'user' }) - throw phase === 'cleanup' ? new Error('initialization failed') : failure + throw phase === 'cleanup' ? new Error('send failed') : failure }) if (phase === 'cleanup') vi.spyOn(ctx.terminals, 'kill').mockRejectedValueOnce(failure) const result = await call(ctx, owner, 'fails', controller.signal) From adbb0e0dc4c0b8a5cf97b9be736490453631df03 Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Tue, 22 Sep 2026 11:39:14 +0800 Subject: [PATCH 03/10] fix(client): update the contact form URL and drop its account UID prefill The Contact us entry now opens the current Feishu questionnaire, and the URL no longer carries the signed-in account UID: contactUs stops reading the account profile, contactUrl stops writing prefill_uid and hide_uid, and the remaining build and browser context fields keep their existing behavior. The url, package tests and the bilingual README and account-login note state the same current facts. --- ...026-09-14-deepseek-account-login.i18n.yaml | 4 ++-- .../2026-09-14-deepseek-account-login.md | 2 +- .../2026-09-14-deepseek-account-login.zh.md | 2 +- .../ui-settings-account/README.i18n.yaml | 4 ++-- packages/client/ui-settings-account/README.md | 2 +- .../client/ui-settings-account/README.zh.md | 2 +- .../src/client/contact-url.ts | 6 ++--- .../ui-settings-account/src/client/index.ts | 2 -- .../ui-settings-account/src/contact-config.ts | 2 +- .../tests/apply.client.spec.ts | 7 ++++-- .../tests/contact-url.client.spec.ts | 23 ++++++++++--------- 11 files changed, 28 insertions(+), 28 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.i18n.yaml index a97feda0c1..3d6874cde0 100644 --- a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md -2026-09-14-deepseek-account-login.md: 65405b293cdea14a231d8d700589f9c3e7ef6db7 -2026-09-14-deepseek-account-login.zh.md: 0aca011826006a0fb8f0557464187b73da377238 +2026-09-14-deepseek-account-login.md: 9b323e03d6c60612092ac5834064770719d71560 +2026-09-14-deepseek-account-login.zh.md: ab50c4758de0567a96a59cfe8966e378d6b8de14 diff --git a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md index 65405b293c..9b323e03d6 100644 --- a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md +++ b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md @@ -36,7 +36,7 @@ The account plugin supplies choice, waiting, failure and timeout dialogs through Platform embedding transfers a grant from Host to Electron over private Node IPC and then once to the trusted Platform main frame through a sandboxed preload. Preload performs one synchronous IPC before page scripts execute; the main process only validates the sender and returns prepared memory. Platform reads the token synchronously thereafter without a readiness API. A failed initialization retains embedded mode and a throwing getter. Account UI projections remain credential-free. The Platform document can read this credential, so its script security is part of account protection; context isolation protects native capabilities, not a token intentionally returned to the document. Replacing or removing the grant destroys the document and its temporary session. -Support questionnaires receive only the Platform UID and available environment metadata through explicit prefill fields. Account tokens and masked contact details stay out of questionnaire URLs. The account provider projects the current-user UID for this purpose; the UI uses the latest account snapshot so sign-out cannot reuse a previous UID. +Support questionnaires receive only available environment metadata through explicit prefill fields. Account UIDs, tokens and masked contact details stay out of questionnaire URLs. Private proxy development can explicitly map authorization and completion URLs to platformOrigin with rewriteBrowserOrigin. Both pages retain their fixed paths and full query strings; allowing a remote origin without mapping it would send the browser outside the configured environment. Shipped configuration requires same-origin URLs. diff --git a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md index 0aca011826..ab50c4758d 100644 --- a/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md @@ -36,7 +36,7 @@ API Key 与账号记录独立保存。账号 token 没有过期或刷新流程 Platform 内嵌通过私有 Node IPC 将授权从 Host 传给 Electron,再经沙箱 preload 一次性传给受信任的 Platform 主 frame。preload 在页面脚本执行前执行一次同步 IPC;主进程仅校验调用来源并返回已准备的内存数据。Platform 此后同步读取 token,无需就绪接口。初始化失败时保留内嵌模式,由 getter 抛错。账号 UI 投影仍不包含凭证。Platform 文档能够读取此凭证,因此其脚本安全也是账号保护的一部分;上下文隔离保护原生能力,不能隐藏有意返回给文档的 token。替换或移除授权会销毁文档及其临时会话。 -支持问卷仅通过显式预填字段接收 Platform UID 和已有的环境信息,URL 不包含账号 token 或脱敏联系方式。账号提供者为此投影 current-user 的 UID;UI 使用最新账号快照,避免退出登录后复用旧 UID。 +支持问卷仅通过显式预填字段接收已有的环境信息,URL 不包含账号 UID、token 或脱敏联系方式。 私有代理开发可通过 rewriteBrowserOrigin 显式将授权页和完成页映射到 platformOrigin。两者保留固定路径和完整查询字符串;仅放宽来源而不做映射会让浏览器离开配置的环境。发布配置要求浏览器地址同源。 diff --git a/packages/client/ui-settings-account/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index cb697284a7..67f94258b5 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings-account/README.md -README.md: fdbbc4c391e7b4d6f6111de936b23f2fa101f3e3 -README.zh.md: 64acaa4b975c5b37213990bb866b268c9a689d1e +README.md: 30d41fb49262619fd34f1bcd1abfec49d1248438 +README.zh.md: 1916bb2bb37704e5ecc22589620add82ce74780f diff --git a/packages/client/ui-settings-account/README.md b/packages/client/ui-settings-account/README.md index fdbbc4c391..30d41fb492 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -28,7 +28,7 @@ Balances use Platform Web currency formatting: two decimal places and digit grou Desktop usage and top-up actions open an isolated native Platform view below a 48px return bar. Back destroys the view and preserves the Account settings page. Browser clients retain external links. Loading failures retain the return action and show a centered localized error with Retry. Retry reloads the same destination; renderer commands never receive the account token. -Contact us opens the Feishu questionnaire in the system browser on Desktop or a new browser tab on Web. It supplies the available Platform UID, build version, UI locale and physical screen resolution as prefill_* parameters, with hide_*=1 for every context field; tokens and contact details are excluded. Configure contactFormUrl on the ui-settings-account plugin to select another HTTPS form. contactSource defaults to empty until the questionnaire supports a Harness source option; OS and device fields remain unfilled, matching the Web implementation. +Contact us opens the Feishu questionnaire in the system browser on Desktop or a new browser tab on Web. It supplies the available build version, UI locale and physical screen resolution as prefill_* parameters, with hide_*=1 for every context field; the account UID, tokens and contact details are excluded. Configure contactFormUrl on the ui-settings-account plugin to select another HTTPS form. contactSource defaults to empty until the questionnaire supports a Harness source option; OS and device fields remain unfilled, matching the Web implementation. The sidebar account menu uses the shared Menu surface, backdrop blur, spacing, and row typography; feature styles only size its launcher. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index 64acaa4b97..1916bb2bb3 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -28,7 +28,7 @@ kind: "package-reference" Desktop 的用量和充值操作在 48px 返回栏下方打开隔离的原生 Platform 视图。返回操作销毁视图并保留 Account 设置页。浏览器客户端继续使用外链。加载失败时保留返回操作,居中显示本地化错误提示和“重试”按钮。重试重新加载同一目标页面;渲染进程命令不接收账号 token。 -“联系我们”在 Desktop 的系统浏览器或 Web 的新标签页打开飞书问卷。链接通过 prefill_* 参数填写已有的 Platform UID、构建版本、界面语言和屏幕物理分辨率,并为所有上下文字段设置 hide_*=1;不传 token 或联系方式。可在 ui-settings-account 插件配置 contactFormUrl,切换到另一个 HTTPS 问卷。问卷支持 Harness 来源选项前,contactSource 默认为空;OS 和设备字段沿用 Web 实现,保持未填写。 +“联系我们”在 Desktop 的系统浏览器或 Web 的新标签页打开飞书问卷。链接通过 prefill_* 参数填写已有的构建版本、界面语言和屏幕物理分辨率,并为所有上下文字段设置 hide_*=1;不传账号 UID、token 或联系方式。可在 ui-settings-account 插件配置 contactFormUrl,切换到另一个 HTTPS 问卷。问卷支持 Harness 来源选项前,contactSource 默认为空;OS 和设备字段沿用 Web 实现,保持未填写。 侧边栏账号菜单使用公共 Menu 的表面、背景模糊、间距和菜单项排版;功能样式仅设置入口布局。 diff --git a/packages/client/ui-settings-account/src/client/contact-url.ts b/packages/client/ui-settings-account/src/client/contact-url.ts index f285260c64..5620f99d00 100644 --- a/packages/client/ui-settings-account/src/client/contact-url.ts +++ b/packages/client/ui-settings-account/src/client/contact-url.ts @@ -1,15 +1,13 @@ /** Feishu questionnaire context follows the Platform Web ticket fields. */ import type { Config } from '../contact-config.ts' -import type { AccountProfile } from '@deepseek-ai/dsh-deepseek-account/types' /** * Build an external questionnaire URL without authentication credentials. * @param config - questionnaire destination and supported source option. - * @param context - currently available account and browser environment. + * @param context - currently available build and browser environment. * @returns questionnaire URL with hidden, optionally prefilled context fields. */ export function contactUrl(config: Config, context: { - uid: AccountProfile['id'] version: string | undefined locale: string width: number @@ -21,7 +19,7 @@ export function contactUrl(config: Config, context: { const width = Math.round(context.width * ratio) const height = Math.round(context.height * ratio) const fields = { - uid: context.uid, source: config.contactSource, app_version: context.version, + source: config.contactSource, app_version: context.version, os_version: undefined, device_brand: undefined, device_model: undefined, app_locale: context.locale, screen_resolution: width > 0 && height > 0 ? `${width}x${height}` : undefined, } diff --git a/packages/client/ui-settings-account/src/client/index.ts b/packages/client/ui-settings-account/src/client/index.ts index 3226eab0e6..3cc65e4668 100644 --- a/packages/client/ui-settings-account/src/client/index.ts +++ b/packages/client/ui-settings-account/src/client/index.ts @@ -84,9 +84,7 @@ export function apply(ctx: Context): void { ...nativePlatform === undefined ? {} : { platform: nativePlatform }, refresh, contactUs() { - const profile = snapshot.details?.profile const url = contactUrl(config, { - uid: profile?.status === 'ready' ? profile.value.id : null, version: process.env.DSH_CLIENT_VERSION, locale: ctx.locale.getSnapshot().active === 'zh' ? 'zh-CN' : 'en', width: window.screen.width, height: window.screen.height, pixelRatio: window.devicePixelRatio, diff --git a/packages/client/ui-settings-account/src/contact-config.ts b/packages/client/ui-settings-account/src/contact-config.ts index 65d4bb06a0..ee9cc3f3b6 100644 --- a/packages/client/ui-settings-account/src/contact-config.ts +++ b/packages/client/ui-settings-account/src/contact-config.ts @@ -10,7 +10,7 @@ export interface Config { } /** Validate public questionnaire options. */ export const Config: z, Config> = z.object({ - contactFormUrl: z.string().pattern(/^https:\/\/[^/\s]+\//).default('https://trtgsjkv6r.feishu.cn/share/base/form/shrcnhcHE4A6lQaQ3v0raCXmBAg'), + contactFormUrl: z.string().pattern(/^https:\/\/[^/\s]+\//).default('https://trtgsjkv6r.feishu.cn/share/base/form/shrcnlCoGElW7MQznGy9r3YYXcg'), contactSource: z.string().default(''), }) /** Bootstrap key containing no account credentials. */ diff --git a/packages/client/ui-settings-account/tests/apply.client.spec.ts b/packages/client/ui-settings-account/tests/apply.client.spec.ts index e1bf83f08e..348924b9ca 100644 --- a/packages/client/ui-settings-account/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-account/tests/apply.client.spec.ts @@ -38,7 +38,9 @@ it('shares account actions across seats, publishes dialog ownership, and opens c 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) + const signedOut = new URL(String(open.mock.calls.at(-1)![0])) + expect(signedOut.searchParams.has('prefill_uid')).toBe(false) + expect(signedOut.searchParams.has('hide_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) }) @@ -48,7 +50,8 @@ it('shares account actions across seats, publishes dialog ownership, and opens c 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.has('prefill_uid')).toBe(false) + expect(support.searchParams.has('hide_uid')).toBe(false) expect(support.searchParams.get('prefill_app_locale')).toBe('zh-CN') await c.unload(SELF) expect(c.ctx.slots.entries('settings.launcher')).toHaveLength(0) diff --git a/packages/client/ui-settings-account/tests/contact-url.client.spec.ts b/packages/client/ui-settings-account/tests/contact-url.client.spec.ts index 57d049e559..943c75cfe8 100644 --- a/packages/client/ui-settings-account/tests/contact-url.client.spec.ts +++ b/packages/client/ui-settings-account/tests/contact-url.client.spec.ts @@ -1,38 +1,39 @@ import { expect, it } from 'vitest' -import type { AccountUserId } from '@deepseek-ai/dsh-deepseek-account/types' import { Config } from '../src/contact-config.ts' import { contactUrl } from '../src/client/contact-url.ts' it('prefills available support context and hides all context fields', () => { const config = Config({ contactSource: 'app_harness' }) const url = new URL(contactUrl(config, { - uid: 'user&123' as AccountUserId, version: '1.2.3', locale: 'zh-CN', - width: 1512, height: 982, pixelRatio: 2, + version: '1.2.3', locale: 'zh-CN', width: 1512, height: 982, pixelRatio: 2, })) expect(url.origin).toBe('https://trtgsjkv6r.feishu.cn') expect(Object.fromEntries(url.searchParams)).toEqual({ - hide_uid: '1', prefill_uid: 'user&123', hide_source: '1', prefill_source: 'app_harness', - hide_app_version: '1', prefill_app_version: '1.2.3', hide_os_version: '1', + hide_source: '1', prefill_source: 'app_harness', hide_app_version: '1', prefill_app_version: '1.2.3', + hide_os_version: '1', hide_device_brand: '1', hide_device_model: '1', hide_app_locale: '1', prefill_app_locale: 'zh-CN', hide_screen_resolution: '1', prefill_screen_resolution: '3024x1964', }) + expect(url.searchParams.has('prefill_uid')).toBe(false) + expect(url.searchParams.has('hide_uid')).toBe(false) }) -it('opens a configured form without stale account context when signed out', () => { - const url = new URL(contactUrl(Config({ contactFormUrl: 'https://example.test/form/?prefill_uid=old&prefill_source=old' }), { - uid: null, version: undefined, locale: 'en', width: 0, height: 0, pixelRatio: 1, +it('opens a configured form without stale context when unavailable', () => { + const url = new URL(contactUrl(Config({ contactFormUrl: 'https://example.test/form/?prefill_app_version=old&prefill_source=old' }), { + version: undefined, locale: 'en', width: 0, height: 0, pixelRatio: 1, })) expect(url.origin).toBe('https://example.test') - expect(url.searchParams.has('prefill_uid')).toBe(false) + expect(url.searchParams.has('prefill_app_version')).toBe(false) expect(url.searchParams.has('prefill_source')).toBe(false) expect(url.searchParams.has('prefill_screen_resolution')).toBe(false) - expect(url.searchParams.get('hide_uid')).toBe('1') + expect(url.searchParams.get('hide_source')).toBe('1') + expect(url.searchParams.get('hide_app_version')).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, + version: undefined, locale: 'en', width: 800, height: 600, pixelRatio, })) expect(url.searchParams.get('prefill_screen_resolution')).toBe('800x600') }) From 817623750aac9578b4e8cfa381f3d7eb5004f8f7 Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Tue, 22 Sep 2026 12:02:54 +0800 Subject: [PATCH 04/10] fix(desktop): match Platform login theme Opened and copied authorization links carried no palette, so the Platform login page rendered its own stored preference. Append the effective Desktop palette as theme=light or theme=dark, resolving system through the theme source the preload publishes. The theme source now reaches nativeTheme on Windows as well: the preload drops its macOS-only guard, since shouldUseDarkColors is read for every platform, and gates the DOMContentLoaded listener with once. --- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 2 +- apps/desktop/README.zh.md | 2 +- apps/desktop/src/main.ts | 18 +++++- apps/desktop/src/preload-theme.ts | 15 +++-- apps/desktop/tests/main-startup.spec.ts | 20 ++++++- .../tests/preload-theme.client.spec.ts | 58 +++++++++++++++++++ apps/desktop/tests/welcome-startup.spec.ts | 11 +++- 8 files changed, 112 insertions(+), 18 deletions(-) create mode 100644 apps/desktop/tests/preload-theme.client.spec.ts diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index d74baaa4b8..6e44ed8a7c 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/desktop/README.md -README.md: 711e65fb5feaea601800218801d138a0df9b3f97 -README.zh.md: 183d195a9af485c9ffe5a3e5bf65e3a459582b93 +README.md: 59f18ea269f303e267d5e9597d8748e2a8fed134 +README.zh.md: eb1594e032fea2da38f778e6b2217bd52587af91 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 711e65fb5f..59f18ea269 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -405,7 +405,7 @@ An unpackaged Electron process uses `.desktop-build/development/project` under i - Dependency lifecycle scripts follow pnpm’s build permissions; Desktop provides no separate approval dialog. - The desktop shell shares sessions, settings, credentials, workspaces, and storage under `$DSH_HOME` with CLI dsh, while executable packages, plugin activation, and lockfiles remain separate. -Sign in opens the configured platform page in the system browser. The Host owns PKCE and a temporary loopback callback, saves the credential before entering the workspace, and redirects the browser to the platform completion page. Cancel withdraws the local attempt even if the platform page later approves it. Settings offers Account sign-out; without a separate API key, sign-out returns to the welcome window. Packaged applications register dsh://open to show the window without passing credentials. On macOS, the development launcher prepares an ad-hoc-signed `Harness Dev.app` under `.desktop-build/development`, declares `dsh` in its Info.plist, and registers it with Launch Services. It loads the current workspace and records the selected development home, browser-data path, and debug settings for cold starts. Starting this bundle makes it the default `dsh://` handler; starting the packaged application registers the packaged handler again. The generated bundle does not contain account tokens and requires the workspace and prepared runtime to remain available. +Sign in opens the configured platform page in the system browser. The Host owns PKCE and a temporary loopback callback, saves the credential before entering the workspace, and redirects the browser to the platform completion page. Opened and copied authorization links carry the effective Desktop theme as `theme=light` or `theme=dark`; `system` resolves at the time of the action. Cancel withdraws the local attempt even if the platform page later approves it. Settings offers Account sign-out; without a separate API key, sign-out returns to the welcome window. Packaged applications register dsh://open to show the window without passing credentials. On macOS, the development launcher prepares an ad-hoc-signed `Harness Dev.app` under `.desktop-build/development`, declares `dsh` in its Info.plist, and registers it with Launch Services. It loads the current workspace and records the selected development home, browser-data path, and debug settings for cold starts. Starting this bundle makes it the default `dsh://` handler; starting the packaged application registers the packaged handler again. The generated bundle does not contain account tokens and requires the workspace and prepared runtime to remain available. An expired login displays a timeout heading with explicit Sign in again and Add API Key actions. Opening the API-key form dismisses the authorization view; late account-state notifications do not replace an in-progress key entry. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 183d195a9a..eb1594e032 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -405,7 +405,7 @@ node apps/desktop/node_modules/pnpm/bin/pnpm.mjs --dir apps/desktop run test:upd - 依赖的生命周期脚本遵循 pnpm 的构建权限;Desktop 不提供单独的审批对话框。 - 桌面壳与 CLI dsh 共享 `$DSH_HOME` 下的会话、设置、凭据、工作区和存储,但可执行包、插件激活和锁文件彼此隔离。 -登录会在系统浏览器中打开配置的平台页面。Host 负责 PKCE 和临时本机回调,在进入工作区前保存凭证,再将浏览器跳转到平台完成页。即使平台页面随后批准,取消仍会撤销本地尝试。设置中的账号页面提供退出;没有独立 API Key 时,退出后返回欢迎窗。打包应用注册 dsh://open,只显示窗口而不传递凭证。macOS 开发启动器在 `.desktop-build/development` 下准备经临时签名的 `Harness Dev.app`,在 Info.plist 中声明 `dsh` 并注册到 Launch Services。它加载当前工作区,并记录选定的开发 home、浏览器数据路径和调试设置,以供冷启动使用。启动此应用会将其设为 `dsh://` 默认处理程序;启动打包应用会重新注册打包版处理程序。生成的应用包不包含账号 token,依赖工作区和已准备的运行环境继续存在。 +登录会在系统浏览器中打开配置的平台页面。Host 负责 PKCE 和临时本机回调,在进入工作区前保存凭证,再将浏览器跳转到平台完成页。打开和复制的授权链接通过 `theme=light` 或 `theme=dark` 携带当前生效的 Desktop 主题;`system` 在执行操作时解析。即使平台页面随后批准,取消仍会撤销本地尝试。设置中的账号页面提供退出;没有独立 API Key 时,退出后返回欢迎窗。打包应用注册 dsh://open,只显示窗口而不传递凭证。macOS 开发启动器在 `.desktop-build/development` 下准备经临时签名的 `Harness Dev.app`,在 Info.plist 中声明 `dsh` 并注册到 Launch Services。它加载当前工作区,并记录选定的开发 home、浏览器数据路径和调试设置,以供冷启动使用。启动此应用会将其设为 `dsh://` 默认处理程序;启动打包应用会重新注册打包版处理程序。生成的应用包不包含账号 token,依赖工作区和已准备的运行环境继续存在。 登录超时后显示超时标题,并提供重新登录和添加 API Key 按钮。打开 API Key 表单会关闭授权视图;后续账号状态通知不会覆盖正在填写的密钥。 diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 46ce1f45c1..9d5497101e 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -127,6 +127,20 @@ function chromeFallbackFill(): string { return nativeTheme.shouldUseDarkColors ? '#1b1b1c' : '#f9fafb' } +/** + * Add the effective Desktop palette to a Platform authorization URL so the + * login page opens in the application's theme. `system` resolves through + * `nativeTheme.shouldUseDarkColors`, which follows the theme source the + * application preload publishes. + * @param authorizeUrl - validated Platform authorization URL. + * @returns the authorization URL carrying `theme=light` or `theme=dark`. + */ +function platformLoginUrl(authorizeUrl: string): string { + const url = new URL(authorizeUrl) + url.searchParams.set('theme', nativeTheme.shouldUseDarkColors ? 'dark' : 'light') + return url.href +} + function createWindow(preload: string, show = false, primary = false): BrowserWindow { const window = new BrowserWindow({ width: 1280, @@ -333,7 +347,7 @@ async function main(): Promise { const attempt = state.attempt if (attempt?.phase === 'waiting-browser' && attempt.authorizeUrl !== undefined && openedAttempt !== attempt.id) { openedAttempt = attempt.id - void shell.openExternal(attempt.authorizeUrl).catch(() => undefined) + void shell.openExternal(platformLoginUrl(attempt.authorizeUrl)).catch(() => undefined) } if ((attempt?.phase === 'failed' || attempt?.phase === 'expired') && returnedAttempt !== attempt.id) { returnedAttempt = attempt.id @@ -892,7 +906,7 @@ async function main(): Promise { if (state?.attempt?.id !== id || state.attempt.phase !== 'waiting-browser' || state.attempt.authorizeUrl === undefined) { throw new Error('desktop welcome: login link is unavailable') } - await clipboard.writeText(state.attempt.authorizeUrl) + await clipboard.writeText(platformLoginUrl(state.attempt.authorizeUrl)) }, saveApiKey: async (apiKey) => { if (backend.host === undefined || welcomeBackend === undefined) return { ok: false } diff --git a/apps/desktop/src/preload-theme.ts b/apps/desktop/src/preload-theme.ts index cb1acb9699..1274e5b3c4 100644 --- a/apps/desktop/src/preload-theme.ts +++ b/apps/desktop/src/preload-theme.ts @@ -1,4 +1,4 @@ -/** Mirrors the Web UI's theme source into the macOS native theme so window vibrancy follows the app palette. */ +/** Mirrors the Web UI's theme source into Electron's native theme so native chrome and Platform login pages follow the app palette. */ import { ipcRenderer } from 'electron' import { DESKTOP_IPC } from './ipc.ts' @@ -7,14 +7,13 @@ import { DESKTOP_IPC } from './ipc.ts' const THEME_SOURCE_ATTRIBUTE = 'data-ds-theme-source' /** - * On macOS, watches `html[data-ds-theme-source]` and forwards each value to - * the main process, which sets `nativeTheme.themeSource` — the sidebar - * vibrancy material then follows the app's theme preference instead of the - * OS appearance, while `system` keeps following the OS. Other platforms - * never send. + * Watches `html[data-ds-theme-source]` and forwards each value to the main + * process, which sets `nativeTheme.themeSource`. The macOS sidebar vibrancy + * material then follows the app's theme preference instead of the OS + * appearance while `system` keeps following the OS, and the resolved + * `shouldUseDarkColors` palette travels with the Platform login link. */ export function syncNativeTheme(): void { - if (process.platform !== 'darwin') return let sent: string | undefined const send = (): void => { const value = document.documentElement.getAttribute(THEME_SOURCE_ATTRIBUTE) @@ -28,6 +27,6 @@ export function syncNativeTheme(): void { } // The preload runs before the document root exists; the theme bootstrap // script writes the attribute before DOMContentLoaded. - if (document.readyState === 'loading') window.addEventListener('DOMContentLoaded', observe) + if (document.readyState === 'loading') window.addEventListener('DOMContentLoaded', observe, { once: true }) else observe() } diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 26c31d906c..00a79e9963 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -165,7 +165,7 @@ const harness = await vi.hoisted(async () => { get publishUpdate() { return publishUpdate! }, set publishUpdate(value: (state: DesktopUpdateState) => DesktopUpdateState) { publishUpdate = value }, dialog: { showOpenDialog: vi.fn(), showErrorBox: vi.fn(), showMessageBox: vi.fn() }, - openExternal: vi.fn(), + openExternal: vi.fn(async () => {}), protocolHandle: vi.fn<(scheme: string, handler: (request: Request) => Response | Promise) => void>(), applyRelease: vi.fn(() => { preparing.resolve(); return prepared.promise }), disableAllPlugins: vi.fn(async () => { @@ -1617,3 +1617,21 @@ it.each(['failed', 'expired'] as const)('focuses DSH once when browser authoriza harness.publishAccount(state) expect(window.focus).toHaveBeenCalledTimes(1) }) + +it.each([['light', false], ['dark', true]] as const)('opens Platform authorization in the effective %s palette', async (theme, shouldUseDarkColors) => { + await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() + await harness.hostStarted.promise + harness.hosts[0]!.ready.resolve() + await Promise.resolve(invoke(DESKTOP_IPC.boot)) + harness.nativeTheme.shouldUseDarkColors = shouldUseDarkColors + const state: AccountView = { + status: 'signed-out', links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' }, + attempt: { id: 'test-theme-attempt' as NonNullable['id'], phase: 'waiting-browser', + authorizeUrl: 'https://platform.deepseek.com/dsh/authorize?state=state-1' }, + } + harness.publishAccount(state) + harness.publishAccount(state) + expect(harness.openExternal).toHaveBeenCalledExactlyOnceWith(`https://platform.deepseek.com/dsh/authorize?state=state-1&theme=${theme}`) +}) diff --git a/apps/desktop/tests/preload-theme.client.spec.ts b/apps/desktop/tests/preload-theme.client.spec.ts new file mode 100644 index 0000000000..90cd23eab0 --- /dev/null +++ b/apps/desktop/tests/preload-theme.client.spec.ts @@ -0,0 +1,58 @@ +// @vitest-environment jsdom +import { afterEach, expect, it, vi } from 'vitest' +import { DESKTOP_IPC } from '../src/ipc.ts' +import { syncNativeTheme } from '../src/preload-theme.ts' + +const send = vi.hoisted(() => vi.fn()) +vi.mock('electron', () => ({ ipcRenderer: { send } })) + +/** Observers created by the module under test; jsdom keeps one document per file. */ +const observers = new Set() +const NativeMutationObserver = MutationObserver + +/** Records every observer so teardown detaches it from the shared document. */ +class TrackedMutationObserver extends NativeMutationObserver { + constructor(callback: MutationCallback) { + super(callback) + observers.add(this) + } +} + +afterEach(() => { + for (const observer of observers) observer.disconnect() + observers.clear() + document.documentElement.removeAttribute('data-ds-theme-source') + vi.unstubAllGlobals() + vi.restoreAllMocks() + send.mockClear() +}) + +it.each(['darwin', 'win32'] as const)('mirrors the application theme source on %s', async (platform) => { + vi.stubGlobal('MutationObserver', TrackedMutationObserver) + vi.spyOn(process, 'platform', 'get').mockReturnValue(platform) + document.documentElement.setAttribute('data-ds-theme-source', 'dark') + syncNativeTheme() + expect(send).toHaveBeenCalledExactlyOnceWith(DESKTOP_IPC.nativeThemeSet, 'dark') + document.documentElement.setAttribute('data-ds-theme-source', 'system') + await vi.waitFor(() => { expect(send).toHaveBeenLastCalledWith(DESKTOP_IPC.nativeThemeSet, 'system') }) + expect(send).toHaveBeenCalledTimes(2) + for (const observer of observers) observer.disconnect() + send.mockClear() + document.documentElement.setAttribute('data-ds-theme-source', 'light') + await new Promise((resolve) => { queueMicrotask(resolve) }) + expect(send).not.toHaveBeenCalled() +}) + +it('waits for the document root and then stops listening for it', () => { + vi.stubGlobal('MutationObserver', TrackedMutationObserver) + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + vi.spyOn(document, 'readyState', 'get').mockReturnValue('loading') + syncNativeTheme() + expect(send).not.toHaveBeenCalled() + document.documentElement.setAttribute('data-ds-theme-source', 'light') + window.dispatchEvent(new Event('DOMContentLoaded')) + expect(send).toHaveBeenCalledExactlyOnceWith(DESKTOP_IPC.nativeThemeSet, 'light') + document.documentElement.setAttribute('data-ds-theme-source', 'dark') + window.dispatchEvent(new Event('DOMContentLoaded')) + expect(send).toHaveBeenCalledOnce() +}) diff --git a/apps/desktop/tests/welcome-startup.spec.ts b/apps/desktop/tests/welcome-startup.spec.ts index db461e59e2..6dd4080692 100644 --- a/apps/desktop/tests/welcome-startup.spec.ts +++ b/apps/desktop/tests/welcome-startup.spec.ts @@ -31,6 +31,7 @@ const state = vi.hoisted(() => ({ windowOptions: undefined as BrowserWindowConstructorOptions | undefined, menu: vi.fn(), operations: undefined as WelcomeOperations | undefined, + nativeTheme: { themeSource: 'system', shouldUseDarkColors: false }, })) vi.mock('electron', () => ({ @@ -67,7 +68,7 @@ vi.mock('electron', () => ({ async loadURL(url: string) { state.contents = this.webContents; await state.loadWorkspace(url); this.ready?.() } }, net: { fetch: vi.fn() }, - nativeTheme: { themeSource: 'system' }, + nativeTheme: state.nativeTheme, session: { defaultSession: { setPermissionCheckHandler: vi.fn(), setPermissionRequestHandler: vi.fn(), webRequest: { onBeforeSendHeaders: vi.fn() }, } }, @@ -177,11 +178,15 @@ it('starts the Host for welcome onboarding and opens the workspace on skip witho attempt: { id: attemptId, phase: 'waiting-browser', authorizeUrl: 'https://example.test/login' } } state.accountState.mockResolvedValue(account) await state.operations!.copySignInLink(attemptId) - expect(state.copy).toHaveBeenCalledExactlyOnceWith('https://example.test/login') + expect(state.copy).toHaveBeenCalledExactlyOnceWith('https://example.test/login?theme=light') + state.nativeTheme.shouldUseDarkColors = true + await state.operations!.copySignInLink(attemptId) + expect(state.copy).toHaveBeenLastCalledWith('https://example.test/login?theme=dark') + state.nativeTheme.shouldUseDarkColors = false await expect(state.operations!.copySignInLink('stale' as typeof attemptId)).rejects.toThrow('login link is unavailable') state.accountState.mockResolvedValue({ ...account, attempt: { id: attemptId, phase: 'expired' } }) await expect(state.operations!.copySignInLink(attemptId)).rejects.toThrow('login link is unavailable') - expect(state.copy).toHaveBeenCalledOnce() + expect(state.copy).toHaveBeenCalledTimes(2) await state.operations!.skip() expect(state.loadWorkspace).not.toHaveBeenCalled() expect(state.showWorkspace).toHaveBeenCalledOnce() From 13fe312e154a5b855a3f56c3e3ff357e1db1c9e1 Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Tue, 22 Sep 2026 15:26:39 +0800 Subject: [PATCH 05/10] test(desktop): fix login theme CI fixtures --- apps/desktop/tests/preload.e2e.ts | 49 ++++++++++++++++++- .../tests/account.spec.ts | 16 +++--- 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/apps/desktop/tests/preload.e2e.ts b/apps/desktop/tests/preload.e2e.ts index 1926d811ee..1022b3a8b8 100644 --- a/apps/desktop/tests/preload.e2e.ts +++ b/apps/desktop/tests/preload.e2e.ts @@ -6,26 +6,73 @@ import { describe, expect, it, vi } from 'vitest' const preload = (name: string): string => fileURLToPath(new URL(`../lib/${name}.cjs`, import.meta.url)) +/** + * Browser globals a sandboxed Electron preload sees. A preload runs while the + * document is still loading, so the theme preload defers its first read to + * `DOMContentLoaded` and observes later `html[data-ds-theme-source]` changes. + * @returns context globals plus the root attribute transitions the Web UI performs. + */ +function browserEnvironment() { + const attributes = new Map() + const listeners = new Map void>>() + const observers: Array<() => void> = [] + const document = { + readyState: 'loading', + documentElement: { + dataset: {} as Record, + getAttribute: (name: string): string | null => attributes.get(name) ?? null, + setAttribute: (name: string, value: string): void => { attributes.set(name, value) }, + }, + } + const window = { + addEventListener: (type: string, listener: () => void): void => { + listeners.set(type, [...listeners.get(type) ?? [], listener]) + }, + } + class SandboxMutationObserver { + constructor(callback: () => void) { observers.push(callback) } + observe(): void {} + } + return { + globals: { document, window, MutationObserver: SandboxMutationObserver }, + /** Writes the theme root attribute and settles the document, as the theme bootstrap does before DOMContentLoaded. */ + loadTheme(value: string): void { + attributes.set('data-ds-theme-source', value) + for (const listener of listeners.get('DOMContentLoaded') ?? []) listener() + }, + /** Applies a later theme preference change through the observer the preload registered. */ + changeTheme(value: string): void { + attributes.set('data-ds-theme-source', value) + for (const observer of observers) observer() + }, + } +} + describe.skipIf(!existsSync(preload('preload-app')))('built sandboxed Desktop preloads', () => { it.each(['preload-app', 'preload-welcome'])('%s loads without filesystem module access', (name) => { const exposed = new Map>() const invoke = vi.fn(() => Promise.resolve({ languages: ['en-US'], preference: 'zh' })) const send = vi.fn() + const browser = browserEnvironment() const electron = { contextBridge: { exposeInMainWorld: (key: string, value: Record) => { exposed.set(key, value) } }, ipcRenderer: { invoke, send, on: vi.fn(), off: vi.fn() }, } runInNewContext(readFileSync(preload(name), 'utf8'), { + ...browser.globals, require: (id: string) => { if (id !== 'electron') throw new Error(`sandbox cannot load ${id}`) return electron }, process: { argv: ['electron', '--dsh-welcome-locale=en'] }, location: new URL('dsh-app://app/'), - document: { documentElement: { dataset: {} } }, exports: {}, }) if (name === 'preload-app') { + browser.loadTheme('dark') + expect(send).toHaveBeenCalledWith('dsh-desktop:native-theme-set', 'dark') + browser.changeTheme('light') + expect(send).toHaveBeenCalledWith('dsh-desktop:native-theme-set', 'light') const bridge = exposed.get('__DSH_LOCALE__') as { read(): unknown; onChange(locale: string): void } bridge.read() expect(invoke).toHaveBeenCalledWith('dsh-desktop:locale-bootstrap') diff --git a/packages/credentials/deepseek-account-platform/tests/account.spec.ts b/packages/credentials/deepseek-account-platform/tests/account.spec.ts index f1b22c47b0..e71e0d7b94 100644 --- a/packages/credentials/deepseek-account-platform/tests/account.spec.ts +++ b/packages/credentials/deepseek-account-platform/tests/account.spec.ts @@ -483,12 +483,16 @@ it('adds private deployment cookies to every Platform request without exposing t expect(JSON.stringify(await f.account.getState())).not.toContain('test_gate') await f.account.signOut() await expect.poll(f.logoutCount).toBe(1) - expect(f.receivedHeaders.map(item => item.path)).toEqual([ - '/auth-api/v0/dsh/auth_init', '/auth-api/v0/dsh/auth_exchange', - '/auth-api/v0/users/current', '/api/v0/users/get_user_summary', '/auth-api/v0/users/logout', - ]) - expect(f.receivedHeaders.every(item => item.cookie === 'test_gate=synthetic')).toBe(true) - expect(f.receivedHeaders.slice(2).every(item => item.authorization === 'dsh_mock_test')).toBe(true) + const headers = f.receivedHeaders + const paths = headers.map(item => item.path) + // The profile and wallet queries are independent requests, so their arrival order is scheduler-dependent. + expect(paths.slice(0, 2)).toEqual(['/auth-api/v0/dsh/auth_init', '/auth-api/v0/dsh/auth_exchange']) + expect(paths.slice(2, -1).sort()).toEqual(['/api/v0/users/get_user_summary', '/auth-api/v0/users/current']) + expect(paths.at(-1)).toBe('/auth-api/v0/users/logout') + expect(headers.every(item => item.cookie === 'test_gate=synthetic')).toBe(true) + const grantedPaths = new Set(['/auth-api/v0/users/current', '/api/v0/users/get_user_summary', '/auth-api/v0/users/logout']) + expect(headers.filter(item => grantedPaths.has(item.path ?? '')).every(item => item.authorization === 'dsh_mock_test')).toBe(true) + expect(headers.filter(item => !grantedPaths.has(item.path ?? '')).every(item => item.authorization === undefined)).toBe(true) }) it('rejects reserved, duplicate and malformed deployment headers without disclosing values', () => { From f50059e425c15b902a22b73e9af474885097f40e Mon Sep 17 00:00:00 2001 From: lsdsjy <1356263+lsdsjy@users.noreply.github.com> Date: Tue, 22 Sep 2026 15:34:58 +0800 Subject: [PATCH 06/10] fix(desktop): theme workspace sign-in links --- apps/desktop/src/preload-theme.ts | 5 +- .../tests/preload-theme.client.spec.ts | 10 +-- .../ui-settings-account/README.i18n.yaml | 4 +- packages/client/ui-settings-account/README.md | 2 +- .../client/ui-settings-account/README.zh.md | 2 +- .../client/ui-settings-account/package.json | 4 +- .../src/client/AccountMenu.tsx | 6 +- .../src/client/AccountOnboarding.tsx | 5 +- .../src/client/AccountSection.tsx | 16 +++-- .../src/client/SignInDialog.tsx | 7 +- .../src/client/authorize-url.ts | 14 ++++ .../ui-settings-account/src/client/index.ts | 17 +++-- .../tests/account.client.spec.tsx | 64 +++++++++++++++---- .../tests/apply.client.spec.ts | 11 ++++ .../tests/onboarding.client.spec.tsx | 7 ++ .../tests/sign-in-dialog.client.spec.tsx | 28 +++++++- .../client/ui-settings-account/tsconfig.json | 3 + pnpm-lock.yaml | 3 + 18 files changed, 161 insertions(+), 47 deletions(-) create mode 100644 packages/client/ui-settings-account/src/client/authorize-url.ts diff --git a/apps/desktop/src/preload-theme.ts b/apps/desktop/src/preload-theme.ts index 1274e5b3c4..19d390b490 100644 --- a/apps/desktop/src/preload-theme.ts +++ b/apps/desktop/src/preload-theme.ts @@ -10,8 +10,9 @@ const THEME_SOURCE_ATTRIBUTE = 'data-ds-theme-source' * Watches `html[data-ds-theme-source]` and forwards each value to the main * process, which sets `nativeTheme.themeSource`. The macOS sidebar vibrancy * material then follows the app's theme preference instead of the OS - * appearance while `system` keeps following the OS, and the resolved - * `shouldUseDarkColors` palette travels with the Platform login link. + * appearance while `system` keeps following the OS; the main process reads + * the same value back as `shouldUseDarkColors` when it needs the resolved + * palette for a Platform login link. */ export function syncNativeTheme(): void { let sent: string | undefined diff --git a/apps/desktop/tests/preload-theme.client.spec.ts b/apps/desktop/tests/preload-theme.client.spec.ts index 90cd23eab0..2f0da9b97a 100644 --- a/apps/desktop/tests/preload-theme.client.spec.ts +++ b/apps/desktop/tests/preload-theme.client.spec.ts @@ -36,14 +36,9 @@ it.each(['darwin', 'win32'] as const)('mirrors the application theme source on % document.documentElement.setAttribute('data-ds-theme-source', 'system') await vi.waitFor(() => { expect(send).toHaveBeenLastCalledWith(DESKTOP_IPC.nativeThemeSet, 'system') }) expect(send).toHaveBeenCalledTimes(2) - for (const observer of observers) observer.disconnect() - send.mockClear() - document.documentElement.setAttribute('data-ds-theme-source', 'light') - await new Promise((resolve) => { queueMicrotask(resolve) }) - expect(send).not.toHaveBeenCalled() }) -it('waits for the document root and then stops listening for it', () => { +it('defers observation until the document root exists', () => { vi.stubGlobal('MutationObserver', TrackedMutationObserver) vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') vi.spyOn(document, 'readyState', 'get').mockReturnValue('loading') @@ -52,7 +47,4 @@ it('waits for the document root and then stops listening for it', () => { document.documentElement.setAttribute('data-ds-theme-source', 'light') window.dispatchEvent(new Event('DOMContentLoaded')) expect(send).toHaveBeenCalledExactlyOnceWith(DESKTOP_IPC.nativeThemeSet, 'light') - document.documentElement.setAttribute('data-ds-theme-source', 'dark') - window.dispatchEvent(new Event('DOMContentLoaded')) - expect(send).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-settings-account/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index e5508b767d..0dbd02cfdc 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-settings-account/README.md -README.md: f024f7ef6506c1c9317d80660aaa0c8221e6a51e -README.zh.md: 2868d46a11db60cfec57f1eee6b146316b989288 +README.md: 016d1161214cf5723de6d5d63dc54542b8382571 +README.zh.md: 56ff93217bf97126878a0c7d5fed889a5e3f56f2 diff --git a/packages/client/ui-settings-account/README.md b/packages/client/ui-settings-account/README.md index f024f7ef65..016d116121 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -46,7 +46,7 @@ The Account section appears first in Settings only while signed in; it is hidden The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storage APIs; the [architecture](../../../docs/architecture.md) explains application composition. -Account login uses a dismissible dialog before the model onboarding credential editor. The dialog uses a compact, right-aligned action row with the primary action last. The sidebar displays the profile name, falling back to the server-masked phone number or email when the name is absent; it stays blank while the profile is loading. Dialog copy and the sidebar account label are not text-selectable; the copy-link button remains available and restores its label two seconds after each successful copy. Clipboard failures show Copy failed on the link for two seconds without interrupting sign-in. Waiting shows a copyable authorization link and a loading indicator; timeout and failure require an explicit retry. Sign-in failures render in that dialog; the launcher's inline failure line reports only a failed sign-out. Closing a waiting dialog cancels its Host attempt. The sidebar can reopen the same API-key editor through the settings coordinator. +Account login uses a dismissible dialog before the model onboarding credential editor. The dialog uses a compact, right-aligned action row with the primary action last. The sidebar displays the profile name, falling back to the server-masked phone number or email when the name is absent; it stays blank while the profile is loading. Dialog copy and the sidebar account label are not text-selectable; the copy-link button remains available and restores its label two seconds after each successful copy. Clipboard failures show Copy failed on the link for two seconds without interrupting sign-in. Waiting shows a copyable authorization link and a loading indicator; timeout and failure require an explicit retry. The dialog's Copy sign-in link and the Settings Open link append the resolved Desktop palette as `theme=light` or `theme=dark` from the live theme snapshot, so both routes reach the Platform page in the current application theme without touching the stored preference. Sign-in failures render in that dialog; the launcher's inline failure line reports only a failed sign-out. Closing a waiting dialog cancels its Host attempt. The sidebar can reopen the same API-key editor through the settings coordinator. A terminal account-state stream failure appears in the sign-in dialog or Account settings. Plugin unload suppresses late failure reports. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index 2868d46a11..56ff93217b 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -46,7 +46,7 @@ Desktop 的用量和充值操作在 48px 返回栏下方打开隔离的原生 Pl [凭证子系统](../../../docs/subsystems/credentials.zh.md)定义存储接口;[架构](../../../docs/architecture.zh.md)说明应用组合。 -账号登录在模型引导的凭证编辑器之前显示可关闭的弹窗。弹窗底部采用紧凑的右对齐横排操作,主操作位于末尾。侧边栏优先显示昵称,缺少昵称时显示服务端返回的脱敏手机号或邮箱;资料加载期间保持留空。 弹窗文字和侧边栏账号状态文字不可选中,复制登录链接按钮始终可用,并在每次复制成功两秒后恢复原文案。剪贴板失败时,链接原位显示“复制失败”两秒,不中断登录。等待状态提供可复制的授权链接和加载图标;超时和失败均须用户手动重试。登录失败在该弹窗内呈现;侧边栏入口的内联失败提示仅用于退出登录失败。关闭等待弹窗会取消对应 Host 登录流程。侧边栏通过设置协调器重新打开同一个 API Key 编辑器。 +账号登录在模型引导的凭证编辑器之前显示可关闭的弹窗。弹窗底部采用紧凑的右对齐横排操作,主操作位于末尾。侧边栏优先显示昵称,缺少昵称时显示服务端返回的脱敏手机号或邮箱;资料加载期间保持留空。 弹窗文字和侧边栏账号状态文字不可选中,复制登录链接按钮始终可用,并在每次复制成功两秒后恢复原文案。剪贴板失败时,链接原位显示“复制失败”两秒,不中断登录。等待状态提供可复制的授权链接和加载图标;超时和失败均须用户手动重试。弹窗的“复制登录链接”和设置页的“打开”链接会从当前主题快照读取 Desktop 生效配色,追加 `theme=light` 或 `theme=dark`,使两条路径都以当前应用主题打开 Platform 页面,且不写入已保存的主题偏好。登录失败在该弹窗内呈现;侧边栏入口的内联失败提示仅用于退出登录失败。关闭等待弹窗会取消对应 Host 登录流程。侧边栏通过设置协调器重新打开同一个 API Key 编辑器。 账户状态流的终止错误会显示在登录对话框或账户设置中。插件卸载后不再报告延迟到达的错误。 diff --git a/packages/client/ui-settings-account/package.json b/packages/client/ui-settings-account/package.json index c2701b6f22..6ebc0756ed 100644 --- a/packages/client/ui-settings-account/package.json +++ b/packages/client/ui-settings-account/package.json @@ -30,7 +30,8 @@ "inject": [ "@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-client-ui-settings", - "@deepseek-ai/dsh-client-locale" + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-theme" ], "platform": "web" } @@ -52,6 +53,7 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:^", "@deepseek-ai/dsh-client-ui-settings": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", + "@deepseek-ai/dsh-client-ui-theme": "workspace:^", "@deepseek-ai/dsh-deepseek-account": "workspace:^", "@testing-library/react": "^16.1.0", "@types/big.js": "^6.2.2", diff --git a/packages/client/ui-settings-account/src/client/AccountMenu.tsx b/packages/client/ui-settings-account/src/client/AccountMenu.tsx index 5a2a07b71f..606312ae2d 100644 --- a/packages/client/ui-settings-account/src/client/AccountMenu.tsx +++ b/packages/client/ui-settings-account/src/client/AccountMenu.tsx @@ -16,9 +16,10 @@ export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsLocale<' * @returns account menu launcher. */ export function AccountMenu({ - wide, openSettings, openOnboarding, useAccount, signOut, contactUs, showLogin, start, cancel, t, + wide, openSettings, openOnboarding, useAccount, useTheme, signOut, contactUs, showLogin, start, cancel, t, }: AccountMenuProps) { const account = useAccount(state => state) + const colorScheme = useTheme(snapshot => snapshot.active.colorScheme) const signedIn = account.view?.status === 'credential-stored' const profile = account.details?.profile const label = profile === undefined ? null : profile.status === 'ready' @@ -55,7 +56,8 @@ export function AccountMenu({ else if (id === 'signin') beginSignIn() else void logout() }} /> - {account.loginVisible && !account.onboarding && { showLogin(false) }} useApiKey={() => { showLogin(false); openOnboarding('deepseek-official') }} />} {logoutFailed && {t('failed')}} diff --git a/packages/client/ui-settings-account/src/client/AccountOnboarding.tsx b/packages/client/ui-settings-account/src/client/AccountOnboarding.tsx index 8dfcb08c48..e07c81c6db 100644 --- a/packages/client/ui-settings-account/src/client/AccountOnboarding.tsx +++ b/packages/client/ui-settings-account/src/client/AccountOnboarding.tsx @@ -6,12 +6,13 @@ import type { AccountSectionInjected } from './AccountSection.tsx' import { SignInDialog } from './SignInDialog.tsx' /** @param props - onboarding completion, account state and actions. @returns account dialog while signed out. */ -export function AccountOnboarding({ complete, useApiKey, useAccount, setOnboarding, showLogin, start, cancel, t }: +export function AccountOnboarding({ complete, useApiKey, useAccount, useTheme, setOnboarding, showLogin, start, cancel, t }: PropsRuntime<'settings.models.sign-in'> & PropsLocale<'settings.account'> & InjectFace) { const account = useAccount(value => value) + const colorScheme = useTheme(snapshot => snapshot.active.colorScheme) useEffect(() => { setOnboarding(true); return () => { setOnboarding(false) } }, [setOnboarding]) useEffect(() => { if (account.view?.status === 'credential-stored') complete() }, [account.view?.status, complete]) if (!account.view || account.view.status === 'credential-stored') return null - return { showLogin(false); complete() }} useApiKey={() => { showLogin(false); useApiKey() }} /> } diff --git a/packages/client/ui-settings-account/src/client/AccountSection.tsx b/packages/client/ui-settings-account/src/client/AccountSection.tsx index 89616b9cc8..1dccd18f84 100644 --- a/packages/client/ui-settings-account/src/client/AccountSection.tsx +++ b/packages/client/ui-settings-account/src/client/AccountSection.tsx @@ -4,9 +4,11 @@ import { useEffect, useState } from 'react' import { Button, IconRightUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { AccountDetails, AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' import type { PropsRuntime, PropsLocale, InjectFace, HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client' import { PlatformOverlay, type PlatformBridge } from './PlatformOverlay.tsx' import { formatBalance } from './formatBalance.ts' import { AccountAvatar } from './AccountAvatar.tsx' +import { authorizeUrlWithTheme } from './authorize-url.ts' import css from './AccountSection.module.css' /** Safe account snapshot shared by the settings page and launcher. */ @@ -30,8 +32,12 @@ export interface AccountSectionInjected { /** Desktop-only commands; absent in ordinary browsers. */ platform?: PlatformBridge - /** Host-owned account stream observed through framework hooks. */ - hooks: { account: HostObservable } + /** Host-owned account stream and theme snapshots observed through framework hooks. */ + hooks: { + account: HostObservable + /** Palette the Platform login pages follow. */ + theme: HostObservable + } /** @returns after account details are refreshed; concurrent refreshes share a request. */ refresh: () => Promise /** Open the external support questionnaire with the current account and environment. */ @@ -51,8 +57,9 @@ export interface AccountSectionInjected { export type AccountSectionProps = PropsRuntime<'settings.section'> & PropsLocale<'settings.account'> & InjectFace /** @param props - localized actions and account subscription. @returns account settings UI. */ -export function AccountSection({ t, useAccount, start, cancel, refresh, platform }: AccountSectionProps) { +export function AccountSection({ t, useAccount, useTheme, start, cancel, refresh, platform }: AccountSectionProps) { const { view: state, details, failed: streamFailed } = useAccount(value => value) + const colorScheme = useTheme(snapshot => snapshot.active.colorScheme) const [platformPage, setPlatformPage] = useState<'usage' | 'top-up'>() const [failed, setFailed] = useState(false) const [busy, setBusy] = useState(false) @@ -107,7 +114,8 @@ export function AccountSection({ t, useAccount, start, cancel, refresh, platform } {active &&
- {attempt.authorizeUrl && + {attempt.authorizeUrl && {t('open')} }