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 b6a41569d2..60eec8a71e 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: 9d9853617a3b7e288084c93eac4e150f3c180999 -2026-09-14-deepseek-account-login.zh.md: d9cdbed25b0ae79caa4c61b310383cc52d8b586a +2026-09-14-deepseek-account-login.md: 458e020c2000fd3db5ee9806e99d4b653710cb1e +2026-09-14-deepseek-account-login.zh.md: 2fb59009302309a67e2c3ec99050685ba39b4212 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 9d9853617a..458e020c20 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 d9cdbed25b..2fb5900930 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/.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..4f16b7775b --- /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: 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 new file mode 100644 index 0000000000..3fd42b77d4 --- /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 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 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 new file mode 100644 index 0000000000..88d4e2deef --- /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`。该提前返回保留会话,因此仍在读取 stdin 的子进程可能吞掉下一次调用的命令,直到那次调用到达 `timeoutMs` 并重置 shell;`dsh-tool-bash-persistent` 行为相同,而区分「shell 自身的提示符就绪」与「子进程的 stdin 等待」属于 seam,而不是任一工具。由标记界定的完整输出保持不变。 + +loader 组合套件记录每次 send 的 `waitReason`,要求至少六次 `stdin_read` 且没有 `inferred_idle`:回归由结算原因本身报告,而不是靠静默层耗时。把删掉的提示符覆盖加回去,该断言会在 30 秒后以 `expected 0 to be greater than or equal to 6` 失败,而同一用例的输出断言仍然通过。stub 套件删除了初始化握手模式,并改为锚定部分输出中保留的提示符文本,而不是它的缺席。 + +重定义 `prompt` 的模型命令仍会移除就绪标记,并把后续 send 降级到静默层:后端只在启动时安装一次提示符,无法重新设定。 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 5567a0c681..862299b9a2 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -143,6 +143,7 @@ pnpm applies local patches to the following packages at install time, so shipped - `@fortune-sheet/core@1.0.4` — [`patches/@fortune-sheet__core@1.0.4.patch`](patches/@fortune-sheet__core@1.0.4.patch) - `@fortune-sheet/react@1.0.4` — [`patches/@fortune-sheet__react@1.0.4.patch`](patches/@fortune-sheet__react@1.0.4.patch) - `@yao-pkg/pkg@6.21.0` — [`patches/@yao-pkg__pkg@6.21.0.patch`](patches/@yao-pkg__pkg@6.21.0.patch) +- `exceljs@4.4.0` — [`patches/exceljs@4.4.0.patch`](patches/exceljs@4.4.0.patch) - `node-pty@1.2.0-beta.15` — [`patches/node-pty@1.2.0-beta.15.patch`](patches/node-pty@1.2.0-beta.15.patch) ## Official Claude Code platform payloads 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 4e13cc34ef..d9c55f44ae 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, @@ -340,7 +354,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 @@ -904,7 +918,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..5091984fdb 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,15 @@ 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`. Native chrome and renderer + * `prefers-color-scheme` queries on every platform then follow the app's + * theme preference instead of the OS appearance while `system` keeps + * following the OS; the macOS sidebar vibrancy material is one such consumer. + * The main process reads the same value back as `shouldUseDarkColors` when a + * Platform login link needs the resolved palette. */ 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 +29,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 13ef5ed9f0..94409491f6 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 () => { @@ -1634,3 +1634,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..2f0da9b97a --- /dev/null +++ b/apps/desktop/tests/preload-theme.client.spec.ts @@ -0,0 +1,50 @@ +// @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) +}) + +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') + 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') +}) 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/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() diff --git a/apps/web/tests/built-boot.expected.e2e.ts b/apps/web/tests/built-boot.expected.e2e.ts index 46115eff44..7ab01184fc 100644 --- a/apps/web/tests/built-boot.expected.e2e.ts +++ b/apps/web/tests/built-boot.expected.e2e.ts @@ -121,24 +121,27 @@ it('boots the built plugin graph and renders a fixture session end to end', asyn within(contextPanel).getByText('Tool definitions') within(contextPanel).getByText('Messages') - // The write/edit turns render a real diff card through the assembled graph - // (the keyed FileMutationRow composing ToolRow + DiffBlock), not just the - // fixture's raw text. The card is collapsed by default, so expand each edit/ - // write row first. The write turn's `hello fixture\n` proves the terminator - // rule end to end: a trailing newline terminates its line, so the footer reads - // `+1` (not a phantom `+2`) and one distinct file. The `+ ` prefix is a CSS - // ::before, so it is absent from textContent — assert on the line body and the - // footer. - const mutationRows = [...document.querySelectorAll('[data-variant="write"],[data-variant="edit"]')] + // The built ToolRow and DiffBlock share the write fixture's trailing-newline + // semantics: `hello fixture\n` contributes one addition. Counts belong to the + // tool row; the diff's line markers are CSS pseudo-elements, absent from textContent. + const mutationRows = [...document.querySelectorAll('[data-variant="write"],[data-variant="edit"]')] expect(mutationRows.length).toBeGreaterThan(0) + const writeRow = mutationRows.find(row => row.getAttribute('data-variant') === 'write' + && row.textContent?.includes('new-demo.txt')) + if (writeRow === undefined) throw new Error('fixture write row missing') + expect(within(writeRow).getAllByText('+1 -0', { exact: true })).toHaveLength(1) + expect(writeRow.querySelector('[data-diff]')).toBeNull() for (const row of mutationRows) { const toggle = row.querySelector('[data-expandable]') if (toggle !== null) act(() => { fireEvent.click(toggle) }) } const diffCards = [...document.querySelectorAll('[data-diff]')] expect(diffCards.length).toBeGreaterThan(0) - const footers = diffCards.map(card => card.textContent ?? '') - expect(footers.some(text => text.includes('hello fixture') && text.includes('+1 -0 · 1 file'))).toBe(true) + const writeDiff = writeRow.querySelector('[data-diff]') + if (writeDiff === null) throw new Error('expanded fixture write diff missing') + within(writeDiff).getByText('hello fixture', { exact: true }) + expect(within(writeRow).getAllByText('+1 -0', { exact: true })).toHaveLength(1) + expect(writeDiff.textContent).not.toContain('+1 -0') // The web render intent reaches the assembled boot graph: the fixture's // web_search / web_fetch turns render their keyed WebRow cards, proving the diff --git a/apps/web/tests/code-card-layout.e2e.ts b/apps/web/tests/code-card-layout.e2e.ts new file mode 100644 index 0000000000..172d2d2ec9 --- /dev/null +++ b/apps/web/tests/code-card-layout.e2e.ts @@ -0,0 +1,160 @@ +/** Browser geometry for read offsets and horizontally scrolled diff fills. */ +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { ToolCallId, createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session' +import type { JsonValue } from '@deepseek-ai/dsh-util-values' +import { launchWebScaffold, seedSession, watchConsole, type WebScaffold } from './scaffold.ts' +import { expandTurnProcesses, newEnglishPage, saveFailureShot } from './support.ts' + +const LONG_LINE = 'source_columns_'.repeat(80) +const OFFSETS = [999, 99_999] + +/** Seed durable tool results without invoking a model or allocating a large file. */ +function layoutFixture(): string { + const calls: { name: string; args: Record; result: string; meta: JsonValue }[] = OFFSETS.map((offset) => { + const path = `offset-${offset}.txt` + const lines = [{ number: offset, text: 'short' }, { number: offset + 1, text: LONG_LINE }] + return { + name: 'read', args: { file_path: path, offset }, + result: `${path}\nfile\n\n${lines.map(line => `${line.number}: ${line.text}`).join('\n')}\n`, + meta: { path, offset, lines, totalLines: offset + 2 }, + } + }) + const oldText = `old_${LONG_LINE}\nshort old` + const newText = `new_${LONG_LINE}\nshort new` + calls.push({ + name: 'edit', args: { file_path: 'long.txt', old_string: oldText, new_string: newText }, + result: 'Edited long.txt', meta: { diffs: [{ path: 'long.txt', oldText, newText }] }, + }) + const session = Session.create(SessionId('code-card-layout-source')) + session.append('turn/start', { turn: 1 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Inspect the source windows and edit the long lines.' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + session.append('step/start', { turn: 1, step: 1 }) + const namedCalls = calls.map((call, index) => ({ ...call, id: ToolCallId(`layout-${index}`), arguments: JSON.stringify(call.args) })) + session.append('assistant/message', { + stream: [], turn: 1, step: 1, + message: createAssistantMessage({ + content: namedCalls.map(call => ({ type: 'tool-call', id: call.id, name: call.name, arguments: call.arguments })), + source: { provider: 'fixture', model: 'fixture' }, + }), + }, { surfaceOp: 'append' }) + for (const call of namedCalls) { + const source = session.append('tool/call', { turn: 1, step: 1, callId: call.id, name: call.name, arguments: call.arguments }) + session.append('tool/result', { + turn: 1, step: 1, meta: call.meta, + message: createToolResultMessage({ callId: call.id, content: [{ type: 'text', text: call.result }], isError: false }), + }, { surfaceOp: 'append', sourceEventSeqs: [source.seq] }) + } + session.append('step/end', { turn: 1, step: 1 }) + session.append('step/start', { turn: 1, step: 2 }) + session.append('assistant/message', { + stream: [], turn: 1, step: 2, + message: createAssistantMessage({ + content: [{ type: 'text', text: 'CODE_LAYOUT_DONE' }], source: { provider: 'fixture', model: 'fixture' }, + }), + }, { surfaceOp: 'append' }) + session.append('step/end', { turn: 1, step: 2 }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + return [ + JSON.stringify({ type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 0, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0 }), + ...session.snapshotEvents().map(event => JSON.stringify(event)), '', + ].join('\n') +} + +describe('web e2e: code-card layout', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + await seedSession(scaffold, layoutFixture(), 'code-card-layout') + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.locator('[role="treeitem"]').first().click() + await page.locator('[role="treeitem"]').nth(1).click() + await page.getByText('CODE_LAYOUT_DONE', { exact: true }).waitFor() + await expandTurnProcesses(page) + for (const row of await page.locator('[data-variant="read"], [data-variant="edit"]').all()) { + await row.locator('[data-expandable]').click() + } + await page.locator('[data-read]').nth(1).waitFor() + await page.locator('[data-diff]').waitFor() + }) + + afterAll(async () => { + try { await browser?.close() } finally { await scaffold?.close() } + }) + + it.each(OFFSETS)('keeps offset %i line numbers clear of aligned source in both wrap modes', async (offset) => { + onTestFailed(() => saveFailureShot(page, `code-card-offset-${offset}`)) + const card = page.locator('[data-read]').filter({ hasText: `offset-${offset}.txt` }) + const wrap = card.getByRole('button', { name: 'Wrap lines', exact: true }) + const heights: number[] = [] + for (const wrapped of [false, true]) { + if (wrapped) await wrap.click() + expect(await wrap.getAttribute('aria-pressed')).toBe(String(wrapped)) + const rows = await card.locator('[class*="gutter"]').evaluateAll(gutters => gutters.map((gutter) => { + const content = gutter.nextElementSibling! + const range = document.createRange() + range.selectNodeContents(gutter) + const glyphs = range.getBoundingClientRect() + const slot = gutter.getBoundingClientRect() + const source = content.getBoundingClientRect() + return { + fits: glyphs.left >= slot.left - 1 && glyphs.right <= slot.right + 1, + gap: source.left - glyphs.right, left: source.left, height: source.height, + } + })) + expect(rows).toHaveLength(2) + expect(rows.every(row => row.fits && row.gap >= 11)).toBe(true) + expect(rows[0]!.left).toBe(rows[1]!.left) + heights.push(rows[1]!.height) + } + expect(heights[1]!).toBeGreaterThan(heights[0]!) + await wrap.click() + }) + + it.each([false, true])('fills long diff rows through horizontal scrolling with dark=%s', async (dark) => { + onTestFailed(() => saveFailureShot(page, `code-card-diff-${dark}`)) + await page.evaluate(value => document.body.toggleAttribute('data-ds-dark-theme', value), dark) + const card = page.locator('[data-diff]') + const body = card.locator(':scope > div').nth(1) + const wrap = card.getByRole('button', { name: 'Wrap lines', exact: true }) + for (const wrapped of [false, true]) { + if (wrapped) await wrap.click() + const result = await body.evaluate((element) => { + element.scrollLeft = element.scrollWidth + const viewport = element.getBoundingClientRect() + const rows = [...element.children].filter(row => ['+ ', '- '].includes(getComputedStyle(row, '::before').content.replaceAll('"', ''))) + return { + overflow: element.scrollWidth - element.clientWidth, + fills: rows.map(row => ({ + width: row.getBoundingClientRect().width, right: row.getBoundingClientRect().right, + fill: getComputedStyle(row).backgroundColor, marker: getComputedStyle(row).boxShadow, + })), + scrollWidth: element.scrollWidth, right: viewport.right, + } + }) + expect(result.fills).toHaveLength(4) + if (wrapped) expect(result.overflow).toBeLessThanOrEqual(1) + else expect(result.overflow).toBeGreaterThan(100) + for (const row of result.fills) { + expect(row.width).toBeGreaterThanOrEqual(result.scrollWidth - 1) + expect(row.right).toBeGreaterThanOrEqual(result.right - 1) + expect(row.fill).toMatch(dark ? /0\.12\)$/ : /0\.08\)$/) + expect(row.marker).toContain('inset') + } + } + await wrap.click() + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) +}) diff --git a/apps/web/tests/diff-context.e2e.ts b/apps/web/tests/diff-context.e2e.ts index cf893ac7ec..5f94739c5e 100644 --- a/apps/web/tests/diff-context.e2e.ts +++ b/apps/web/tests/diff-context.e2e.ts @@ -55,7 +55,8 @@ describe.skipIf(MODE === 'record').each(CASES)('web e2e: $name', (scenario) => { const card = edit.locator('[data-diff]') await card.waitFor() expect(await card.getByText(scenario.shared, { exact: true }).count()).toBe(1) - expect(await card.textContent()).toContain(`${scenario.totals} · 1 file`) + expect(await edit.getByText(scenario.totals, { exact: true }).count()).toBe(1) + expect(await card.textContent()).not.toContain(scenario.totals) const snapshotDir = `${ROOT}/web/${scenario.name}` await compareOrRefreshGolden(`${snapshotDir}/ui.expected.md`, await captureStableAria(page, '[data-variant="edit"]', scaffold.workspaceCwd), MODE) diff --git a/apps/web/tests/document-preview.e2e.ts b/apps/web/tests/document-preview.e2e.ts index 2a2a2ba60d..af48f48e2c 100644 --- a/apps/web/tests/document-preview.e2e.ts +++ b/apps/web/tests/document-preview.e2e.ts @@ -104,6 +104,58 @@ async function hideDocumentZoom(page: Page, preview: Locator): Promise { await expect.poll(() => preview.locator('[data-document-zoom-controls]').getAttribute('data-document-zoom-visible')).toBeNull() } +it.skipIf(MODE === 'record')('resizes the spreadsheet canvas with its pane while retaining the selected cell', async () => { + const scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: 5, compareReplaySession: false }) + let browser: Browser | undefined + try { + browser = await chromium.launch() + const page = await newEnglishPage(browser) + onTestFailed(async () => { await saveFailureShot(page, `screenshots/0908-document-preview/excel-resize-${process.pid}`) }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const settled = scaffold.whenTurnSettled() + const input = page.locator('[data-composer-input]').first() + await input.fill(PROMPT) + await input.press('Enter') + const sessionId = await settled + const cwd = scaffold.ctx.agents.get(sessionId)?.session.header.cwd + if (cwd === undefined) throw new Error('settled Session has no workspace cwd') + await writeFile(join(cwd, 'budget.xlsx'), await excelFixture()) + await page.getByText('LIGHTHOUSE', { exact: true }).waitFor() + const column = page.locator('[data-rightbar-col]') + await page.locator('[data-sidebar-right-expand]').click() + await column.locator('[data-sidebar-right-guide-entry="files"]').click() + await column.locator('[data-files-state="tree"]').waitFor({ state: 'visible' }) + await column.locator('[data-files-entry="file"]').getByRole('button', { name: 'budget.xlsx', exact: true }).click() + const excel = column.locator('[data-excel-preview]') + await excel.locator('.luckysheet-sheets-item-name').getByText('公式与格式', { exact: true }).click() + await excel.locator('.fortune-sheet-overlay').click({ position: { x: 140, y: 30 } }) + const formula = excel.locator('.fortune-fx-input') + await expect.poll(() => formula.innerText()).toBe('46281') + const canvas = excel.locator('canvas').first() + const originalCanvas = await canvas.elementHandle() + const original = await canvas.boundingBox() + if (original === null || originalCanvas === null) throw new Error('spreadsheet canvas is unavailable') + const panel = page.locator('[data-sidebar-right-panel]') + const panelBounds = await panel.boundingBox() + if (panelBounds === null) throw new Error('sidebar panel is unavailable') + const viewport = page.viewportSize() + const layout = await page.addStyleTag({ content: `[data-sidebar-right-panel] { width: ${panelBounds.width + 160}px !important; }` }) + await expect.poll(async () => Math.round((await canvas.boundingBox())!.width - original.width)).toBe(160) + await expect.poll(() => formula.innerText()).toBe('46281') + expect(await originalCanvas.evaluate(node => node.isConnected)).toBe(true) + expect(page.viewportSize()).toEqual(viewport) + await successShot(page, 'excel-resize-wide') + await layout.evaluate((node) => { node.textContent = '' }) + await expect.poll(async () => Math.round((await canvas.boundingBox())!.width)).toBe(Math.round(original.width)) + expect(await formula.innerText()).toBe('46281') + await successShot(page, 'excel-resize-restored') + await originalCanvas.dispose() + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } +}) + describe.skipIf(MODE === 'record')('web e2e: document preview through Files', () => { let scaffold: WebScaffold let browser: Browser @@ -799,7 +851,12 @@ else process.exit(1); })).toEqual({ scrollTop, scrollportBelowBanner: true, firstLineAbove: true }) await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(page.url()).origin }) await page.evaluate(() => navigator.clipboard.writeText('')) - await codeBlock.getByRole('button', { name: 'Copy', exact: true }).click() + const copyCode = codeBlock.getByRole('button', { name: 'Copy', exact: true }) + expect(await codeBlock.getByRole('button').count()).toBe(1) + expect(await copyCode.textContent()).toBe('') + await copyCode.hover() + await page.getByRole('tooltip', { name: 'Copy', exact: true }).waitFor() + await copyCode.click() await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(codeLines.join('\n')) sections.push([ '## Code paging', '', diff --git a/apps/web/tests/excel-opc.e2e.ts b/apps/web/tests/excel-opc.e2e.ts new file mode 100644 index 0000000000..a3a49e3248 --- /dev/null +++ b/apps/web/tests/excel-opc.e2e.ts @@ -0,0 +1,92 @@ +/** Independent-writer XLSX previews through a replayed Session and the shipped browser Worker. */ +import { writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser, type Page } from 'playwright' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { excelOpeningCases, excelOpeningFixture } from '../../../packages/client/ui-sidebar-documentpreview/tests/excel-opening-fixture.ts' +import { excelOpcCases, excelOpcFixture } from '../../../packages/client/ui-sidebar-documentpreview/tests/excel-opc-fixture.ts' +import { excelXmlCases, excelXmlFixture } from '../../../packages/client/ui-sidebar-documentpreview/tests/excel-xml-fixture.ts' +import { assertFixtureInventory, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage } from './support.ts' + +const snapshotDirectory = fileURLToPath(new URL('../../../snapshots/web/excel-opc', import.meta.url)) +const mode = webSnapshotMode() + +describe.skipIf(mode === 'record')('web e2e: independent-writer Excel previews', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let consoleErrors: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({ + developerTools: false, + replayFixture: fileURLToPath(new URL('../../../snapshots/web/lifecycle-chrome/session.v3.jsonl', import.meta.url)), + compareReplaySession: false, + }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + consoleErrors = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + }) + + afterAll(async () => { + try { await browser?.close() } finally { await scaffold?.close() } + }) + + it('opens comments, Tables and equivalent OPC encodings without hiding cell data', async () => { + const settled = scaffold.whenTurnSettled() + const input = page.locator('[data-composer-input]').first() + await input.fill('Reply with the single word LIGHTHOUSE and stop.') + await input.press('Enter') + const sessionId = await settled + await page.getByText('LIGHTHOUSE', { exact: true }).waitFor() + const cwd = scaffold.ctx.agents.get(sessionId)?.session.header.cwd + if (cwd === undefined) throw new Error('Excel preview Session has no workspace') + for (const name of excelOpcCases) await writeFile(join(cwd, `${name}.xlsx`), await excelOpcFixture(name)) + for (const name of excelOpeningCases) await writeFile(join(cwd, `${name}.xlsx`), await excelOpeningFixture(name)) + for (const name of excelXmlCases) await writeFile(join(cwd, `${name}.xlsx`), await excelXmlFixture(name)) + + const column = page.locator('[data-rightbar-col]') + await page.locator('[data-sidebar-right-expand]').click() + await column.locator('[data-sidebar-right-guide-entry="files"]').click() + await column.locator('[data-files-state="tree"]').waitFor() + await column.locator('[data-files-reload]').click() + const files = column.locator('[data-dockkit-tab]').filter({ has: page.getByText('Files', { exact: true }) }) + const preview = column.locator('[data-textpreview-url]') + const excel = preview.locator('[data-excel-preview]') + const sheets = excel.locator('.luckysheet-sheets-item-name') + const notice = excel.locator('[data-excel-unsupported-notice]') + const rows = ['# Independent-writer Excel previews', ''] + await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(page.url()).origin }) + for (const name of [...excelOpcCases, ...excelOpeningCases, ...excelXmlCases]) { + await files.click() + await column.locator('[data-files-entry="file"]').getByRole('button', { name: `${name}.xlsx`, exact: true }).click() + await expect.poll(async () => (await preview.getAttribute('data-textpreview-url'))?.endsWith(`/${name}.xlsx`)).toBe(true) + await sheets.getByText('数据', { exact: true }).waitFor() + await excel.locator('.fortune-sheet-overlay').click({ position: { x: 70, y: 30 } }) + await expect.poll(() => excel.locator('.fortune-fx-input').innerText()).toBe('Item') + await page.keyboard.press('ControlOrMeta+C') + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toMatch(/^Item\r?\n$/) + const rich = excelXmlCases.some(candidate => candidate === name) + const opening = excelOpeningCases.some(candidate => candidate === name) + expect(await notice.count()).toBe(name === 'combined' || rich || opening ? 1 : 0) + if (name === 'combined' || rich || opening) { + const features = rich ? 'charts, images, shapes, conditional formatting' + : name === 'orphan-drawing' ? 'conditional formatting' : 'charts, conditional formatting' + expect(await notice.innerText()).toBe(`This preview does not support ${features} in this workbook. Open it in a system application for the full experience.`) + } + rows.push(`- ${name}.xlsx: 数据 opened; Item copied`) + } + expect(await sheets.getByText('隐藏页', { exact: true }).isVisible()).toBe(false) + const warning = await notice.innerText() + expect(warning).toBe('This preview does not support charts, images, shapes, conditional formatting in this workbook. Open it in a system application for the full experience.') + rows.push('- Relocated workbook: hidden sheet omitted', `- Relocated workbook notice: ${warning}`) + expect(consoleErrors.pageErrors).toEqual([]) + expect(consoleErrors.warnings).toEqual([]) + await compareOrRefreshGolden(join(snapshotDirectory, 'excel.expected.md'), rows.join('\n'), mode) + await assertFixtureInventory(snapshotDirectory, ['excel.expected.md']) + }) +}) diff --git a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md index 49e14d0030..ab3230e5bd 100644 --- a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md +++ b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md @@ -34,8 +34,10 @@ - text: Edit - button "src/tokens.css" - text: +1 -1 +- text: css +- button "Wrap lines" - button "Copy" -- text: "src/tokens.css - --inline-code: #EBEEF2; + --inline-code: #F5F5F5; └ +1 -1 · 1 file" +- text: "src/tokens.css - --inline-code: #EBEEF2; + --inline-code: #F5F5F5;" - button "Inspect" - button "Tool call str_replace_editor · create" [expanded] - text: "IN { \"command\": \"create\", \"path\": \"docs/press.md\", \"file_text\": \"# Press kit\\n\" } OUT Created docs/press.md" @@ -45,7 +47,8 @@ - button "Read docs/guide.md" [expanded]: - text: Read - button "docs/guide.md" -- text: docs/guide.md +- text: Code block docs/guide.md +- button "Wrap lines" - button "Copy" - text: "# Link style guide guide line 2 guide line 3 guide line 4" - button "Expand 4 more lines": … 4 more lines @@ -136,6 +139,7 @@ - paragraph: - img "Token preview" - text: css +- button "Wrap lines" [pressed] - button "Copy" - code: "--inline-code: #F5F5F5;" - paragraph: LINK_GALLERY_DONE diff --git a/apps/web/tests/expected/cordis-history/ui.expected.md b/apps/web/tests/expected/cordis-history/ui.expected.md index 89feb57a78..45381454fa 100644 --- a/apps/web/tests/expected/cordis-history/ui.expected.md +++ b/apps/web/tests/expected/cordis-history/ui.expected.md @@ -23,6 +23,7 @@ - tab "Host" [selected] - tabpanel "Host": - text: javascript + - button "Wrap lines" [pressed] - button "Copy" - code: "return { name: \"snapshot-noop\", apply(ctx) {} }" - text: Result Defined snap-1/pkg-1 (snapshot noop); it is not running yet. Use cordis_run to activate this Package. Run controls live in the Cordis panel above Settings diff --git a/apps/web/tests/expected/navigation-panes/code-card.expected.md b/apps/web/tests/expected/navigation-panes/code-card.expected.md new file mode 100644 index 0000000000..20b377502a --- /dev/null +++ b/apps/web/tests/expected/navigation-panes/code-card.expected.md @@ -0,0 +1,4 @@ +- text: Code block +- button "Wrap lines" [pressed] +- button "Copy" +- code: echo WATERFALL diff --git a/apps/web/tests/expected/thinking-markdown/ui.expected.md b/apps/web/tests/expected/thinking-markdown/ui.expected.md index ba8e88404d..5f243d6976 100644 --- a/apps/web/tests/expected/thinking-markdown/ui.expected.md +++ b/apps/web/tests/expected/thinking-markdown/ui.expected.md @@ -214,6 +214,7 @@ - text: . - math: a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + a + 1 1 + 1 x - text: typescript +- button "Wrap lines" [pressed] - button "Copy" - code: const value = "reasoning code" - paragraph: {{longToken}} diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index 4ab75b3ba0..2aaaaf5d0a 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -27,6 +27,8 @@ const TRAJECTORY_EXPECTED = join(SNAPSHOT_DIR, 'trajectory.expected.md') const TIMING_EXPECTED = join(SNAPSHOT_DIR, 'timing.expected.md') const SEARCH_EXPECTED = join(SNAPSHOT_DIR, 'search-results.expected.md') const TERMINAL_EXPECTED = join(SNAPSHOT_DIR, 'terminal-card.expected.md') +const CODE_CARD_DIR = fileURLToPath(new URL('./expected/navigation-panes', import.meta.url)) +const CODE_CARD_EXPECTED = join(CODE_CARD_DIR, 'code-card.expected.md') const MODE = webSnapshotMode() const SEED_ID = 'navigation-panes-web-e2e' const EXPORTED_LOG_FILE = `session.v${SESSION_FORMAT_VERSION}.jsonl` @@ -218,6 +220,28 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { await expect.poll(() => page.getByRole('heading', { name: 'Navigation Summary' }).count(), { timeout: 15_000 }).toBe(1) }, 90_000) + it.skipIf(MODE === 'record')('renders recorded Markdown with icon tooltips and switchable wrapping', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-code-card')) + await ensureSeedOpen(page) + const selector = '.md-code-block:has-text("echo WATERFALL")' + const block = page.locator(selector) + await block.waitFor({ timeout: 15_000 }) + await compareOrRefreshGolden(CODE_CARD_EXPECTED, await captureStableAria(page, selector, scaffold.workspaceCwd), MODE) + const code = block.locator('pre') + const source = await code.textContent() + const copy = block.getByRole('button', { name: 'Copy', exact: true }) + await copy.hover() + await page.getByRole('tooltip', { name: 'Copy', exact: true }).waitFor() + const unwrap = block.getByRole('button', { name: 'Wrap lines', exact: true }) + await unwrap.hover() + await page.getByRole('tooltip', { name: 'Do not wrap lines', exact: true }).waitFor() + await unwrap.click() + await expect.poll(() => code.evaluate(element => getComputedStyle(element).whiteSpace)).toBe('pre') + await block.getByRole('button', { name: 'Wrap lines', exact: true }).click() + await expect.poll(() => code.evaluate(element => getComputedStyle(element).whiteSpace)).toBe('pre-wrap') + expect(await code.textContent()).toBe(source) + }, 60_000) + it.skipIf(MODE === 'record')('renders the trajectory ledger and opens its local record inspector', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-trajectory')) await ensureSeedOpen(page) @@ -521,6 +545,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { }, 60_000) it.skipIf(MODE === 'record')('keeps the recorded fixture inventory exact', async () => { + await assertFixtureInventory(CODE_CARD_DIR, ['code-card.expected.md']) await assertFixtureInventory(SNAPSHOT_DIR, [ 'session.v3.jsonl', 'search-results.expected.md', 'trajectory.expected.md', 'terminal-card.expected.md', 'timing.expected.md', diff --git a/apps/web/tests/queue-actions.e2e.ts b/apps/web/tests/queue-actions.e2e.ts index 0f8f0f89fc..c5317cb3fb 100644 --- a/apps/web/tests/queue-actions.e2e.ts +++ b/apps/web/tests/queue-actions.e2e.ts @@ -34,6 +34,10 @@ const MODE = webSnapshotMode() const ACTIVE_PROMPT = 'Reply with a one-sentence description of event sourcing, then stop.' const REMOVE = 'Queue item to remove' const EDIT = 'Queue item to edit' +// The edited value is deliberately multi-line: the inline editor must keep the +// line breaks through the queue mutation and into the model-bound user message. +const EDITED_CONTENT = 'Edited\nqueue item' +// The dock preview flattens the queued text, so row locators match this form. const EDITED = 'Edited queue item' const TAIL = 'Queue item preserved after stop' const WAKE = 'Wake the preserved queue' @@ -187,7 +191,7 @@ describe('web e2e: queue row actions', () => { const editRow = page.locator('[data-queue-dock] li', { hasText: EDIT }) await editRow.getByRole('button', { name: 'Edit queued message' }).click() const editor = page.getByRole('textbox', { name: 'Edit queued message' }) - await editor.fill(EDITED) + await editor.fill(EDITED_CONTENT) const save = page.getByRole('button', { name: 'Save queued message' }) await save.hover() const saveTooltip = page.getByRole('tooltip', { name: 'Save queued message', exact: true }) @@ -308,7 +312,7 @@ describe('web e2e: queue row actions', () => { .toEqual(['aborted', 'completed', 'completed', 'completed']) expect(sessionEvents.flatMap(event => event.type === 'user/message' && event.data.source.kind === 'user' ? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []) - : [])).toEqual([ACTIVE_PROMPT, EDITED, TAIL, WAKE]) + : [])).toEqual([ACTIVE_PROMPT, EDITED_CONTENT, TAIL, WAKE]) await expect.poll(() => page.locator('[data-queue-dock]').count()).toBe(0) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) diff --git a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md index dd1688b8dd..a2443a2e47 100644 --- a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md +++ b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md @@ -11,6 +11,7 @@ - status: Deep diving... - button "Deep diving for {{duration}}" [disabled] [expanded] - text: ts +- button "Wrap lines" [pressed] - button "Copy" - code: "const first: number = 1 const second = \"two\" let tail" - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/apps/web/tests/streaming-fence-highlight.e2e.ts b/apps/web/tests/streaming-fence-highlight.e2e.ts index 6d65cdca0d..48017c982d 100644 --- a/apps/web/tests/streaming-fence-highlight.e2e.ts +++ b/apps/web/tests/streaming-fence-highlight.e2e.ts @@ -85,7 +85,7 @@ async function fenceTree(block: ReturnType): Promise const pre = element.querySelector('pre.shiki') if (pre === null) throw new Error('streaming fence did not render through the shiki arm') return { - language: element.querySelector('[class*="infostring"]')?.textContent ?? '', + language: element.querySelector('[data-code-block-banner] [class*="language"]')?.textContent ?? '', pre: { className: pre.className, style: pre.style.cssText, diff --git a/apps/web/tests/thinking-markdown.e2e.ts b/apps/web/tests/thinking-markdown.e2e.ts index 94c9cb8a09..ea2a6efb76 100644 --- a/apps/web/tests/thinking-markdown.e2e.ts +++ b/apps/web/tests/thinking-markdown.e2e.ts @@ -170,6 +170,8 @@ describe('web e2e: secondary Thinking Markdown', () => { await page.evaluate(async () => { await document.fonts.ready }) const styles = await markdown.evaluate((root, secondary) => { const elements = [...root.querySelectorAll('h1,h2,h3,h4,h5,h6,p,li,a,strong,em,pre,pre code,pre span,th,td,.katex')] + const prose = elements.filter(element => element.closest('pre') === null) + const code = elements.filter(element => element.closest('pre') !== null) const scrollers = [...root.querySelectorAll('[class*="tableScroll"],.katex-display,p:has(.katex),ul:has(.katex)')] const shortFormulas = [...root.querySelectorAll('p')].filter(element => element.textContent?.startsWith('Short ')) // Native KaTeX baselines vary with host fonts; compact adds one pixel for descender ink. @@ -190,9 +192,13 @@ describe('web e2e: secondary Thinking Markdown', () => { const banner = root.querySelector('[data-code-block-banner]')?.parentElement const loose = [...root.querySelectorAll('li p')].find(element => element.textContent === 'Loose middle paragraph.') return { - secondarySize: elements.every(element => getComputedStyle(element).fontSize === secondary.fontSize), - secondaryLine: elements.filter(element => !element.classList.contains('katex')) + secondarySize: prose.every(element => getComputedStyle(element).fontSize === secondary.fontSize), + secondaryLine: prose.filter(element => !element.classList.contains('katex')) .every(element => getComputedStyle(element).lineHeight === secondary.lineHeight), + codeTypography: code.length > 0 && code.every((element) => { + const style = getComputedStyle(element) + return style.fontSize === '11px' && style.lineHeight === '19px' + }), tertiaryColor: elements.every(element => getComputedStyle(element).color === secondary.color), tertiaryMarkers: [...root.querySelectorAll('li')] .every(element => getComputedStyle(element, '::marker').color === secondary.color), @@ -216,7 +222,7 @@ describe('web e2e: secondary Thinking Markdown', () => { } }, summaryStyle) expect(styles, `Thinking typography at ${String(width)}px`).toEqual({ - secondarySize: true, secondaryLine: true, tertiaryColor: true, tertiaryMarkers: true, + secondarySize: true, secondaryLine: true, codeTypography: true, tertiaryColor: true, tertiaryMarkers: true, contained: true, bannerStatic: true, looseSpacing: true, wideContentBounded: true, displayMathScrolls: true, shortMathNaturalHeight: true, shortMathNoScrollbar: true, longAtomScrolls: true, mathListMarkerSpace: true, diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 3c7faf36b5..4554f81ee0 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -26,6 +26,7 @@ "tests/server-restart.e2e.ts", "tests/default-product-isolation.e2e.ts", "tests/diff-context.e2e.ts", + "tests/code-card-layout.e2e.ts", "tests/scaffold.ts", "tests/voice-input.e2e.ts", "tests/voice-setup.e2e.ts", @@ -53,6 +54,7 @@ "tests/details-session-lifecycle.e2e.ts", "tests/sessionless-header.e2e.ts", "tests/document-preview.e2e.ts", + "tests/excel-opc.e2e.ts", "tests/office-fixture.ts", "tests/sidebar-browser.e2e.ts", "tests/plugin-config.e2e.ts", diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 77fe8802d8..16898d7745 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: 4d2fe53661495ecaa2010dc466ae4a5e3df8508a -config-catalog.zh.md: 3f38d368e2bcfe5ac2c7d407e1a82c0972d1af48 +config-catalog.md: d65619dfdb2f1f8406f93ba32cdcca5b27dace75 +config-catalog.zh.md: 1dc8a03f22c98b1e388032bd51f0a5e5b2f65c6e diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 4d2fe53661..d65619dfdb 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -679,7 +679,7 @@ Requires: `credentials` · `authorization` export interface Config { /** Platform origin serving auth-api and browser pages. */ platformOrigin?: string - /** Native desktop identity for Host API and embedded Platform requests; null omits the client platform header. */ + /** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */ desktopPlatform?: 'darwin' | 'win32' | null /** Optional frontend deployment selector for embedded Usage and Top-up pages. */ embeddedPageDist?: string @@ -3507,7 +3507,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 3f38d368e2..1dc8a03f22 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -681,7 +681,7 @@ export interface Config { export interface Config { /** Platform origin serving auth-api and browser pages. */ platformOrigin?: string - /** Native desktop identity for Host API and embedded Platform requests; null omits the client platform header. */ + /** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */ desktopPlatform?: 'darwin' | 'win32' | null /** Optional frontend deployment selector for embedded Usage and Top-up pages. */ embeddedPageDist?: string @@ -3509,7 +3509,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/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index e3c0fdb127..7461948374 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.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/user/guide/providers.md -providers.md: 81ccba8b0665fa1f7666b5724aab4a8b3d183bbf -providers.zh.md: 1afb7e7bf616206290e5cc4a90ef45b4250a9596 +providers.md: 773ff6722a8558720a458f7574940972cf976958 +providers.zh.md: 6d618ed1e9eec17e8c4a000d00cc6987d0a6af14 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 81ccba8b06..773ff6722a 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -20,7 +20,7 @@ Providers that sign in with OAuth, such as Codex, are not supported here yet. ## Add a custom model API -Switch the card to **Custom model API** for a relay, a company gateway, a self-hosted server, or any provider absent from the installed catalog. Supply a lowercase Provider ID, base URL, API protocol, credential, and at least one model. The **API protocol** must be the one your gateway speaks, and the picker offers three: OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages, stored in `settings.yaml` as `openai-completions`, `openai-responses`, and `anthropic-messages`. A provider speaks one protocol, so a gateway that serves two needs two providers. +Switch the card to **Custom model API** for a relay, a company gateway, a self-hosted server, or any provider absent from the installed catalog. Supply a lowercase Provider ID, base URL, API protocol, credential, and at least one model. The **API protocol** must be the one your gateway speaks, and the picker offers three: OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages, stored in the active profile's `cordis.patch.yml` as `openai-completions`, `openai-responses`, and `anthropic-messages`. A provider speaks one protocol, so a gateway that serves two needs two providers. ![The custom model API form: Provider ID, display name, base URL, API protocol, and API key](providers-custom-form.png) @@ -44,6 +44,8 @@ The generated [plugin configuration catalog](../../config-catalog.md) lists ever ::: tip Additional settings The Models page exposes the API key, display name, base URL, API protocol, and each model's id, display name, context window, max output tokens, and input types. Configure reasoning effort levels, request-compatibility switches, headers, timeouts, and retry policy in `$DSH_HOME/profiles//cordis.patch.yml`, the same document the page writes. Edit it directly, or, when the browser runs on the same machine as the server, open it with **Open configuration file** in the Settings header; the adapters re-read it on the next request, so nothing needs a restart. The subsections below cover the fields most gateways need. + +For the standard Web UI launch with `dsh web`, `` is `web`, so the path is `$DSH_HOME/profiles/web/cordis.patch.yml`. If you launch a custom profile, use the name selected at startup instead. ::: ### Image input @@ -132,14 +134,14 @@ Each key is a level the menu offers, and its value is the spelling sent on the w An `off` left empty sends nothing, which only stops a model that thinks on request; an `off` given a value sends that value as `reasoning_effort` instead. A model that thinks unless told not to — DeepSeek V4 behind an OpenAI-compatible gateway, for example — needs `compat.thinkingFormat: deepseek`, which makes `off` send `thinking: {type: disabled}` and every other level send `thinking: {type: enabled}` beside the effort: ```yaml - models: - - id: deepseek-v4-pro - compat: - thinkingFormat: deepseek - reasoningEfforts: - off: - high: high - max: max + models: + - id: deepseek-v4-pro + compat: + thinkingFormat: deepseek + reasoningEfforts: + off: + high: high + max: max ``` A built-in provider's model whose gateway does not reason loses its levels with `reasoningEfforts: false` under `modelOverrides`; selecting an effort for it is then refused as `UNSUPPORTED_REASONING_EFFORT`. DeepSeek's own route needs none of this: its models already offer `off`, `low`, `high`, and `max`, and `llm-deepseek.reasoningEffort` sets the default the picker starts from: @@ -174,11 +176,11 @@ Two account for most of it. A model that declares reasoning has its system promp A route's `compat` is the default for its models, and a model's own wins field by field, so one model can be corrected without restating the route: ```yaml - models: - - id: my-model - - id: my-reasoner - compat: - thinkingFormat: deepseek + models: + - id: my-model + - id: my-reasoner + compat: + thinkingFormat: deepseek ``` What neither sets keeps the installed catalog's value for that model, and what the catalog does not describe falls to pi-ai's detection. Give every switch you name a value: a key left empty (`supportsDeveloperRole:`) is refused rather than ignored, because an empty value would erase what the catalog knows while saying nothing in its place. A name no protocol accepts is refused too, and the message lists the ones that are available. diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index 1afb7e7bf6..6d618ed1e9 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -20,7 +20,7 @@ ## 添加自定义模型 API -对于中转站、公司网关、自建服务器或已安装目录中不存在的提供商,把卡片切换到**自定义模型 API**。提供小写 Provider ID、基础 URL、API 协议、凭据和至少一个模型。**API 协议**必须选网关实际使用的那一种,选择框提供三种:OpenAI Chat Completions、OpenAI Responses 和 Anthropic Messages,在 `settings.yaml` 中分别存为 `openai-completions`、`openai-responses` 和 `anthropic-messages`。一个提供商只使用一种协议,网关同时提供两种时需要建两个提供商。 +对于中转站、公司网关、自建服务器或已安装目录中不存在的提供商,把卡片切换到**自定义模型 API**。提供小写 Provider ID、基础 URL、API 协议、凭据和至少一个模型。**API 协议**必须选网关实际使用的那一种,选择框提供三种:OpenAI Chat Completions、OpenAI Responses 和 Anthropic Messages,在当前 profile 的 `cordis.patch.yml` 中分别存为 `openai-completions`、`openai-responses` 和 `anthropic-messages`。一个提供商只使用一种协议,网关同时提供两种时需要建两个提供商。 ![自定义模型 API 表单:Provider ID、显示名称、API 地址、API 协议、API 密钥](providers-custom-form.zh.png) @@ -44,6 +44,8 @@ Provider ID 是永久的,因为请求、已保存会话、模型默认值和 ::: tip 其他设置 模型页提供 API 密钥、显示名称、API 地址、API 协议,以及每个模型的 ID、显示名称、上下文窗口、最大输出 token 数和输入类型。推理等级、请求兼容性开关、请求头、超时和重试策略在 `$DSH_HOME/profiles//cordis.patch.yml` 中设置,也就是模型页写入的同一份文档。可以直接编辑它;浏览器与服务器在同一台机器时,也可以点击设置页顶部的**打开配置文件**打开它。适配器会在下一次请求时重新读取,无需重启任何东西。下面各小节介绍多数网关会用到的字段。 + +按常规方式通过 `dsh web` 启动 Web UI 时,`` 就是 `web`,完整路径为 `$DSH_HOME/profiles/web/cordis.patch.yml`。如果使用自定义 profile,请替换为启动时指定的名称。 ::: ### 图片输入 @@ -132,14 +134,14 @@ DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。 留空的 `off` 什么都不发送,这只能让「按请求才思考」的模型停下来;给 `off` 一个值,则会把该值作为 `reasoning_effort` 发送。对于「不明确关闭就会思考」的模型——例如 OpenAI 兼容网关后面的 DeepSeek V4——需要 `compat.thinkingFormat: deepseek`:它让 `off` 发送 `thinking: {type: disabled}`,其他每个等级则在 effort 之外再发送 `thinking: {type: enabled}`: ```yaml - models: - - id: deepseek-v4-pro - compat: - thinkingFormat: deepseek - reasoningEfforts: - off: - high: high - max: max + models: + - id: deepseek-v4-pro + compat: + thinkingFormat: deepseek + reasoningEfforts: + off: + high: high + max: max ``` 网关并不提供推理能力的内置提供商模型,可在 `modelOverrides` 下用 `reasoningEfforts: false` 去掉其等级;之后再为它选择等级会被拒绝并报 `UNSUPPORTED_REASONING_EFFORT`。DeepSeek 自身的路由不需要以上任何配置:其模型已经提供 `off`、`low`、`high` 和 `max`,`llm-deepseek.reasoningEffort` 设置选择器的起始默认值: @@ -174,11 +176,11 @@ DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。 路由的 `compat` 是其模型的默认值,模型自身的则逐字段胜出,因此更正某一个模型无需重述整条路由: ```yaml - models: - - id: my-model - - id: my-reasoner - compat: - thinkingFormat: deepseek + models: + - id: my-model + - id: my-reasoner + compat: + thinkingFormat: deepseek ``` 两者都未设置的字段,沿用已安装 catalog 为该模型记录的值;catalog 也未描述的,落到 pi-ai 的检测。凡是写下的开关都要给值:冒号后留空的键(`supportsDeveloperRole:`)会被拒绝而不是被忽略,因为空值会抹掉 catalog 已知的信息,却又没有给出任何替代。任何协议都不接受的名字同样会被拒绝,报错会列出可用的那些。 diff --git a/packages/client/locale/src/locales/en.ts b/packages/client/locale/src/locales/en.ts index d16b4913ae..d21b7d67f7 100644 --- a/packages/client/locale/src/locales/en.ts +++ b/packages/client/locale/src/locales/en.ts @@ -7,6 +7,9 @@ export const en = { 'close': 'Close', 'copy': 'Copy', 'copied': 'Copied', + 'codeBlock.title': 'Code block', + 'codeBlock.wrap': 'Wrap lines', + 'codeBlock.unwrap': 'Do not wrap lines', 'copy.failed': 'Copy failed', 'copy.value': 'Copy value', 'copy.json': 'Copy JSON', diff --git a/packages/client/locale/src/locales/zh.ts b/packages/client/locale/src/locales/zh.ts index 2e932cef41..d7b215babd 100644 --- a/packages/client/locale/src/locales/zh.ts +++ b/packages/client/locale/src/locales/zh.ts @@ -5,6 +5,9 @@ export const zh = { 'close': '关闭', 'copy': '复制', 'copied': '复制成功', + 'codeBlock.title': '代码块', + 'codeBlock.wrap': '自动换行', + 'codeBlock.unwrap': '取消自动换行', 'copy.failed': '复制失败', 'copy.value': '复制值', 'copy.json': '复制 JSON', diff --git a/packages/client/ui-agent-preset/src/client/PresetGuideDialog.tsx b/packages/client/ui-agent-preset/src/client/PresetGuideDialog.tsx index 6ecb534f02..8ca5270d52 100644 --- a/packages/client/ui-agent-preset/src/client/PresetGuideDialog.tsx +++ b/packages/client/ui-agent-preset/src/client/PresetGuideDialog.tsx @@ -1,6 +1,7 @@ /** Read-only help stays local to Settings and never changes the selected preset. */ import { useId, useLayoutEffect, useRef, useState } from 'react' import type { KeyboardEvent, ReactNode } from 'react' +import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import { Button, IconCloseOutlineRegular, IconListPenOutlineRegular, MarkdownText, Modal, SegmentedTabs, Tag } from '@deepseek-ai/dsh-client-ui-primitives' import type { AgentPresetSettingsKey } from './locales.ts' import css from './PresetGuideDialog.module.css' @@ -35,10 +36,10 @@ export function presetGuide(id: string, trust: string): PresetGuide | undefined /** Curated usage dictionaries contain only level-three example sections. */ function GuideUsage({ text, t }: { text: string - t: (key: AgentPresetSettingsKey) => string + t: TranslateNS<'settings.agentPreset'> }): ReactNode { const labels = { - code: { copyLabel: t('guideCopy'), copiedLabel: t('guideCopied') }, + code: { copyLabel: t('guideCopy'), copiedLabel: t('guideCopied'), toolbarLabels: { codeLabel: t('codeBlock.title'), wrapLabel: t('codeBlock.wrap'), unwrapLabel: t('codeBlock.unwrap') } }, footnotes: t('guideFootnotes'), } return text.split(/(?=^### )/m).map((section) => { @@ -67,7 +68,7 @@ function GuideUsage({ text, t }: { export function PresetGuideDialog({ guide, initialPage, t, onClose }: { guide: PresetGuide initialPage: PresetGuidePage - t: (key: AgentPresetSettingsKey) => string + t: TranslateNS<'settings.agentPreset'> onClose: () => void }): ReactNode { const [page, setPage] = useState(initialPage) @@ -144,7 +145,7 @@ export function PresetGuideDialog({ guide, initialPage, t, onClose }: { diff --git a/packages/client/ui-chat/src/client/markdown-labels.ts b/packages/client/ui-chat/src/client/markdown-labels.ts index 6c30b99396..8818ea8f14 100644 --- a/packages/client/ui-chat/src/client/markdown-labels.ts +++ b/packages/client/ui-chat/src/client/markdown-labels.ts @@ -10,7 +10,7 @@ import type { ChatViewSlotProps } from './contract/slots.ts' */ export function markdownLabels(t: ChatViewSlotProps['t']): MarkdownLabels { return { - code: { copyLabel: t('copy'), copiedLabel: t('copied') }, + code: { copyLabel: t('copy'), copiedLabel: t('copied'), toolbarLabels: { codeLabel: t('codeBlock.title'), wrapLabel: t('codeBlock.wrap'), unwrapLabel: t('codeBlock.unwrap') } }, footnotes: t('markdown.footnotes'), } } diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 192a0da89b..99eba4e710 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/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-conversation/README.md -README.md: a58ae14a450a18ae4bc89dc0dc5cc6fb664d48e0 -README.zh.md: 20d6cab01e7b5fc4c9b075a993783c9df8121413 +README.md: 48df40483632a7c63ec59d389f920d4dd663155b +README.zh.md: f5c34657264f97d8f0178859dcba5e3fc981f17d diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index a58ae14a45..48df404836 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -68,7 +68,7 @@ Active transcripts in the main occurrence expose content-width drag handles in t The width-handle indicator follows the pointer only during a captured drag; ordinary hover leaves its position unchanged. -The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text, and durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. +The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. QueueDock reads `next-turn` directly from the Session `inbox` projection, including cold recovered messages. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text in a textarea that grows with its content, so line breaks survive re-editing; Enter saves, Shift+Enter breaks the line, and Escape cancels. Durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; queue and history observation by that `rpcId` retires the echo once. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents disable attachment intake and skip local echoes because their transport does not preserve the browser request id. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 20d6cab01e..f5c3465726 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -68,7 +68,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 宽度拖拽条的指示线只在已捕获指针的拖拽期间跟随指针,普通悬停不改变其位置。 -常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态展示字面发送文本,持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 +常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。QueueDock 直接从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态在可随内容增高的 textarea 中展示字面发送文本,因此重新编辑不会丢失换行;Enter 保存,Shift+Enter 换行,Escape 取消。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;queue 或历史以同一 `rpcId` 被观察后,回显只退休一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理禁用附件入口,也不创建本地回显,因为其 transport 不保留浏览器 request id。 diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 8ddad82052..aab4735316 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -307,8 +307,6 @@ export const zh = { 'tool.autoReviewRejected': 'Auto review 已拒绝', 'tool.autoReviewNotExecuted': '工具未执行。原因:{reason}', 'tool.autoReviewReasonFallback': 'Auto review 未授权此次操作', - 'diff.files.one': '{count} 个文件', - 'diff.files.other': '{count} 个文件', 'diff.collapseAria': '收起差异', 'diff.expandAria': '展开其余 {count} 行差异', 'diff.expandRest': '… 其余 {count} 行', @@ -661,8 +659,6 @@ export const en = { 'tool.autoReviewRejected': 'Rejected by Auto review', 'tool.autoReviewNotExecuted': 'Tool was not executed. Reason: {reason}', 'tool.autoReviewReasonFallback': 'Auto review did not authorize this action', - 'diff.files.one': '{count} file', - 'diff.files.other': '{count} files', 'diff.collapseAria': 'Collapse diff', 'diff.expandAria': 'Expand {count} more diff lines', 'diff.expandRest': '… {count} more lines', diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css index 516ba7e83a..ca1abd25d2 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css @@ -124,7 +124,8 @@ align-items: center; gap: 10px; width: 100%; - height: 36px; + /* Grows with the inline editor's content; the other rows stay 36px. */ + min-height: 36px; padding: 4px 5px 4px 12px; border-radius: 8px; } @@ -211,13 +212,17 @@ .editor { box-sizing: border-box; - height: 28px; - padding: 0 8px; + min-height: 28px; + /* Six 20px text lines plus padding and border, then the editor scrolls. */ + max-height: 127px; + padding: 3px 8px; border: 0.5px solid var(--dsw-alias-border-l4); border-radius: 6px; outline: none; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); + overflow-y: auto; + resize: none; } .editor:focus { diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx index 22f0730795..03146f3e4c 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx @@ -1,5 +1,5 @@ import type { Context } from '@deepseek-ai/cordis' -import { useEffect, useId, useMemo, useState } from 'react' +import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -98,6 +98,53 @@ function QueueThumb({ attachment, loadImage, label }: { : {label} } +/** + * Inline editor for one queued row. A textarea rather than an input: HTML + * strips newlines from single-line input values, so editing a multi-line + * queued message through one rewrites it as a single line. It grows with its + * content up to the CSS cap, then scrolls. Enter saves, Shift+Enter breaks the + * line, Escape cancels. + */ +function QueueEditor({ text, label, onChange, onSave, onCancel }: { + text: string + label: string + onChange: (text: string) => void + onSave: () => void + onCancel: () => void +}) { + const ref = useRef(null) + + useLayoutEffect(() => { + const node = ref.current + /* v8 ignore next -- the ref is attached before layout effects run. */ + if (node === null) return + node.style.height = 'auto' + // scrollHeight excludes the border that the border-box height includes. + node.style.height = `${node.scrollHeight + node.offsetHeight - node.clientHeight}px` + }, [text]) + + return ( +