diff --git a/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.i18n.yaml index 9ad1682b62..2a62045ef1 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.md -2026-08-09-broken-preset-roster-rows.md: fef6a183b10f98b8ae9d2b42701380c69bc83462 -2026-08-09-broken-preset-roster-rows.zh.md: 196bcf4ef16325a1d7692d2ea13d9fa683d500f4 +2026-08-09-broken-preset-roster-rows.md: 069585957d4d99598cc38e4a7c6bc8c8d82490ca +2026-08-09-broken-preset-roster-rows.zh.md: d541292b59496464eb91bc03278e0800af16c4a3 diff --git a/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.md b/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.md index fef6a183b1..069585957d 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.md +++ b/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.md @@ -26,7 +26,7 @@ Surfaces split by their job: the management section renders broken rows as marke - **`PRESET_ID` moved to `types.ts`** so discovery and authoring share one containment vocabulary; authoring re-exports it unchanged. - **The reason is one line.** js-yaml appends a multi-line code-frame snippet; the roster card is not a terminal, so `compositionProblem` keeps the first line. - **Two mount.spec races were left untouched deliberately**: `ensureStanding` is still reachable with a preset resolved just before deletion (the private-path tests), and its stamp/unstampable semantics are unchanged — the health check happens before, in the public route. -- **Creator-mode guidance rides the same PR**: the `cordis` preset's persona now forbids editing the shipped install (corrupting `cordis` would disable the mode itself) and points authoring at `${DSH_HOME:-$HOME/.dsh}/.agent-presets//`; its skill teaches `preset.yml` metadata, the copy-first workflow, the one-escalation sandbox reality (the preset root lies outside the session workspace), and honest verification (the agent cannot start sessions; the settings page's red marking is the user's check). Verified live: asked to edit the shipped `cordis` composition directly, the composed agent refuses citing both rules and offers the copy path; asked for a real preset, it lands it under `$DSH_HOME`, batches writes into one escalation, self-checks with the loader dialect, and hands verification to the user. +- **Creator-mode guidance rides the same PR**: the `cordis` preset's persona forbids editing the shipped install (corrupting `cordis` would disable the mode itself) and points authoring at `${DSH_HOME:-$HOME/.dsh}/.agent-presets//`; its skill teaches `preset.yml` metadata, the copy-first workflow, and the one-escalation sandbox reality (the preset root lies outside the session workspace). Verified live: asked to edit the shipped `cordis` composition directly, the composed agent refuses citing both rules and offers the copy path; asked for a real preset, it lands it under `$DSH_HOME` and batches writes into one escalation. The verification half of that guidance — that the agent cannot start sessions, so the settings page's red marking is the user's check — is superseded by [the authoring agent mount-validates its own composition](2026-08-11-preset-authoring-agent-validates-its-own-composition.md): the shape check below is not validation, and `standingKeyFor` gives the agent the real one. The health decision in this note is unchanged. ## Alternatives considered diff --git a/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.zh.md b/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.zh.md index 196bcf4ef1..d541292b59 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-09-broken-preset-roster-rows.zh.md @@ -26,7 +26,7 @@ Status: implemented - **`PRESET_ID` 移到 `types.ts`**,让发现与创作共享同一份包含边界词汇;authoring 原样转发导出。 - **原因只留一行。** js-yaml 会附上多行代码框摘录;名单卡片不是终端,`compositionProblem` 只保留首行。 - **mount.spec 的两个竞态用例特意不动**:`ensureStanding` 仍可能拿到删除前一刻解析出的 preset(私有路径测试),其 stamp/unstampable 语义不变——健康检查发生在此之前的公开路径上。 -- **创造模式的引导随同一 PR 落地**:`cordis` preset 的 persona 现在禁止编辑随附安装(损坏 `cordis` 会禁用这一模式本身),并把创作指向 `${DSH_HOME:-$HOME/.dsh}/.agent-presets//`;其技能新教了 `preset.yml` 元信息、先复制再改的流程、一次升级的沙箱现实(preset 根目录在会话工作区之外)与诚实的验证方式(agent 无法自己启动会话;设置页的红色标记是用户的检查项)。已实测:被要求直接改随附 `cordis` 组装时,组装出的 agent 援引两条规则拒绝并给出复制路径;被要求真正创建 preset 时,它落在 `$DSH_HOME` 下、把写入合并为一次升级、用加载器方言自查、并把验证交还用户。 +- **创造模式的引导随同一 PR 落地**:`cordis` preset 的 persona 禁止编辑随附安装(损坏 `cordis` 会禁用这一模式本身),并把创作指向 `${DSH_HOME:-$HOME/.dsh}/.agent-presets//`;其技能教了 `preset.yml` 元信息、先复制再改的流程与一次升级的沙箱现实(preset 根目录在会话工作区之外)。已实测:被要求直接改随附 `cordis` 组装时,组装出的 agent 援引两条规则拒绝并给出复制路径;被要求真正创建 preset 时,它落在 `$DSH_HOME` 下并把写入合并为一次升级。该引导中关于验证的那一半——agent 无法自己启动会话,因而设置页的红色标记是用户的检查项——已由[创作 preset 的 agent 自行挂载校验其组装](2026-08-11-preset-authoring-agent-validates-its-own-composition.md)取代:下文的结构检查不是校验,而 `standingKeyFor` 才给了 agent 真正的校验手段。本篇的健康检查决策不变。 ## 曾考虑的替代方案 diff --git a/.agents/notes/implemented/bug-fix/2026-08-11-preset-authoring-agent-validates-its-own-composition.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-11-preset-authoring-agent-validates-its-own-composition.i18n.yaml new file mode 100644 index 0000000000..67d2b330b1 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-11-preset-authoring-agent-validates-its-own-composition.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-08-11-preset-authoring-agent-validates-its-own-composition.md +2026-08-11-preset-authoring-agent-validates-its-own-composition.md: 6b9cdf32b70e3ab4adc9f3b0e20bb3d2245486c7 +2026-08-11-preset-authoring-agent-validates-its-own-composition.zh.md: e6e8dabcd886a6331d294744b667552caa01e7b4 diff --git a/.agents/notes/implemented/bug-fix/2026-08-11-preset-authoring-agent-validates-its-own-composition.md b/.agents/notes/implemented/bug-fix/2026-08-11-preset-authoring-agent-validates-its-own-composition.md new file mode 100644 index 0000000000..6b9cdf32b7 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-11-preset-authoring-agent-validates-its-own-composition.md @@ -0,0 +1,71 @@ +# Agent Note: The preset-authoring agent mount-validates its own composition + +Status: implemented + +English | [中文](2026-08-11-preset-authoring-agent-validates-its-own-composition.zh.md) + +## Problem + +The `cordis` preset ships `editing-cordis-compositions`, the only guidance an agent has when it authors a preset. Four of its statements were false, and the two that carried the most weight pointed at the rule the skill itself calls "the rule that catches people". + +It named `tool-bash` as the worked example of a row whose name hides a service — "reads like a tool but provides `bashEnv`". `tool-bash` provides nothing; it declares `inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`, and `bashEnv` comes from the host composition's own `bash-env` row. An agent wrapping `tool-bash` in an `isolate` realm on that advice strands the row waiting for a service its realm hides, and the whole preset fails to mount. + +Its `isolate` example composed `tasks-local` with `tool-tasks`. `tasks-local` is host-plane, and the shipped compositions say in their own comments that an entry-local realm around `tool-tasks` makes `run_in_background` answer "background tasks unavailable". The example contradicted the file next to it. + +It described a string realm label as pooling one instance across subtrees. Labels join realms; `provide()` still throws on the second registration under the same realm symbol, which `standard`'s header comment already stated. + +It sent the agent to a package's README to learn whether a row publishes a service. Every harness package declares `files`, and no declaration includes its README, so an installed deployment carries none. There that instruction cannot be followed at all. + +Underneath all four sat a capability claim: the agent "cannot start one \[a session\] yourself", so verification was hand-reading YAML fields and handing the result to the user through the settings page's red marking. That marking is discovery's shape check, which is far weaker than the sentence implied. + +## Decision + +The skill teaches the agent to mount-validate its own composition through `ctx.agentPresets`, and every remaining example is taken from a shipped composition in the same repository. + +`standingKeyFor(id)` is the check. It runs `ensureStanding()` — the same real mount a session start performs, minus the agent — so it rejects a row whose package does not resolve, a row whose config is invalid, a service published into the root realm, and a row that never activated. A failed mount deletes the standing entry and disposes its scope, leaving nothing behind; a successful one installs the standing generation the first real session would have installed anyway. The skill therefore places it as the final check on a finished edit rather than a per-line loop. + +The skill states plainly that `list()`'s `broken` field is **not** validation. Discovery's health check proves the file parses in the loader's dialect and holds named rows, and every one of the four failures above passes it. + +The agent reaches the roster service the way `cordis_mount` documents: a temporary plugin declaring `inject: ['agentPresets', 'tools']` that registers a tool for itself, because a mount returns only its own acknowledgement and a registered tool is how a service answer reaches the model on the next step. The skill ships that plugin verbatim. `agentPresets` is in the generated `cordis_inspect what:"api"` catalog with full JSDoc, and the sandbox façade gates services on `fiber.inject` alone rather than an allowlist, so nothing about this path is special-cased for the skill. + +`copy(from, id, name)` is named as the authoring write, in place of a shell copy: it validates the id, refuses one any root supplies, rolls a failed copy back, rewrites the copy's `preset.yml`, and runs host-side without sandbox escalation. The escalation guidance stays, moved to where it applies — editing `agent.cordis.yml` afterwards still writes outside the session workspace. + +"Whether a row publishes a service" resolves through `cordis_inspect what:"services"`, which names the owning fiber of every live service. + +The guidance keeps `${DSH_HOME:-$HOME/.dsh}/.agent-presets/` as the answer to "where do my presets live" — it is where every `dsh` launcher puts them — while routing the path an agent actually reads or edits through `list()` or `resolve()`. `Config.roots` defaults to `[]` and `apps/cli` patches both roots in, `writableRoot()` takes the first `user` one, and no call reports either path; `authorable` answers only whether a writable root exists, and `list()` cannot reveal a user root that holds nothing yet. Stating the path is therefore right for talking to a person and wrong for feeding a file tool. + +The prohibition on touching the shipped install is promoted from a paragraph inside the authoring steps to a top `## Off-limits` section, extended to cover editing the host composition as a workaround. The new self-validation calls do not weaken it: `copy()` refuses an id any root supplies, and `remove()` refuses a preset that ships with the deployment. + +## Measured behavior + +Each row was produced by booting the shipped Web composition and calling the tools through `ctx.tools.execute` on an agent composed from `cordis` — no model in the loop. + +| Composition under test | `list()` `broken` | `standingKeyFor()` | +|---|---|---| +| row names an absent package | empty | `Cannot find package '@deepseek-ai/dsh-does-not-exist'` | +| service row with no realm, name the host supplies | empty | `service "tasks" has been registered at ` | +| service row with no realm, name the host does not supply | empty | `row(s) published process-global service(s) [workflows]; …` | +| same row inside `isolate` | empty | mounts | +| consumer row with no provider | empty | `1 row(s) did not activate: … waiting for workflows` | +| row missing a required config field | empty | `invalid config: $.allowParallelInProgress missing required value` | + +The skill's own `cordis_mount` snippet was executed verbatim through the tool registry: it mounts, its `preset_check` tool appears in the composing agent's catalog on the next read, and it answers `mounted OK` for a valid preset and the mount rejection for an invalid one. + +## Alternatives considered + +**Leaving verification with the user and only fixing the four errors.** The errors and the capability claim share a cause — the guidance was written from the preset layer's public surface rather than from what the composed agent can reach — and an agent that cannot check its work hands over compositions whose defects the settings page cannot see either. + +**Teaching `list()`'s `broken` field as the check.** It is the one the settings page shows, so it reads like the intended answer. It passes every failure that matters, and presenting it as validation is what made the original guidance feel complete. + +**Adding a first-class preset-validation tool to the preset.** The composed path already exists and is documented by `cordis_mount`'s own schema; a dedicated tool would add a model-facing row to a preset whose point is that the runtime is reachable without one. + +## Consequences + +- A successful validation leaves a standing generation that is never reclaimed, which is the [standing-mount](../architecture/2026-08-08-per-preset-standing-mounts.md) cost the roster already carries per generation — the agent pays it once at the end of an edit instead of the user paying it at the first session. +- The skill now depends on `cordis_inspect`'s generated API catalog staying current for `agentPresets`; `verify-cordis-api` in `doc-sync` is what holds that. +- Two examples are now quotations of `standard`'s composition. They drift if that file's `delegation` group changes, which the `web-agent-presets` e2e does not catch. +- The four corrected statements were the skill's only concrete illustrations of the realm rule. Replacing rather than deleting them keeps the rule teachable; the replacements are verifiable by reading one shipped file. + +## Related + +Supersedes the creator-guidance bullet in [broken presets are roster rows](2026-08-09-broken-preset-roster-rows.md), whose health-check decision remains current — this note reverses only its "the agent cannot start sessions; the settings page's red marking is the user's check" conclusion. Authoring's copy-only shape is owned by [copy-only preset authoring](../simplification/2026-08-08-copy-only-preset-authoring.md). diff --git a/.agents/notes/implemented/bug-fix/2026-08-11-preset-authoring-agent-validates-its-own-composition.zh.md b/.agents/notes/implemented/bug-fix/2026-08-11-preset-authoring-agent-validates-its-own-composition.zh.md new file mode 100644 index 0000000000..e6e8dabcd8 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-08-11-preset-authoring-agent-validates-its-own-composition.zh.md @@ -0,0 +1,71 @@ +# Agent Note: 创作 preset 的 agent 自行挂载校验其组装 + +Status: implemented + +[English](2026-08-11-preset-authoring-agent-validates-its-own-composition.md) | 中文 + +## Problem + +`cordis` preset 随包发布 `editing-cordis-compositions`,它是 agent 创作 preset 时唯一的指导来源。其中四条陈述与事实不符,而分量最重的两条恰好指向该 skill 自称「最容易让人栽跟头的规则」。 + +它把 `tool-bash` 当作「行名看不出发布服务」的示例——「看着像工具,其实 provides `bashEnv`」。`tool-bash` 不发布任何服务,它声明 `inject: ['tools', 'bash', 'systemPrompt', 'bashEnv']`,`bashEnv` 来自宿主组装自己的 `bash-env` 行。agent 照此给 `tool-bash` 套上 `isolate` realm,该行会永远等待被自己的 realm 挡住的服务,整个 preset 挂载失败。 + +它的 `isolate` 示例把 `tasks-local` 与 `tool-tasks` 组在一起。`tasks-local` 位于宿主平面,而已发布组装在自己的注释里写明:给 `tool-tasks` 套 entry-local realm 会让 `run_in_background` 回答「background tasks unavailable」。示例与紧挨着它的文件互相矛盾。 + +它把字符串 realm label 描述为跨子树共享一个实例。label 只是加入同一 realm,`provide()` 在同一 realm symbol 下第二次注册仍然抛错——`standard` 的头部注释早已如此说明。 + +它让 agent 去读包的 README 判断某行是否发布服务。每个 harness 包都声明了 `files`,且没有任何一份声明包含自己的 README,因此装机部署中一份也没有。在那里该指令根本无法执行。 + +四条之下还压着一个能力断言:agent「自己起不了会话」,于是校验退化成肉眼核对 YAML 字段,再把结果经设置页的红色标记交给用户。那个标记是发现阶段的结构检查,远弱于这句话给人的印象。 + +## Decision + +skill 教 agent 通过 `ctx.agentPresets` 自行挂载校验其组装,其余每个示例都取自同一仓库中已发布的组装。 + +`standingKeyFor(id)` 是校验手段。它走 `ensureStanding()`——与会话启动完全相同的真实挂载,只是不创建 agent——因此能拒绝包无法解析的行、配置非法的行、把服务发布进根 realm 的行,以及始终未激活的行。挂载失败会删除常驻条目并 dispose 其 scope,不留残留;挂载成功则装上首次真实会话本来也会装上的那个常驻代际。因此 skill 把它安排为完成编辑后的最终检查,而不是逐行循环。 + +skill 明确写出:`list()` 的 `broken` 字段**不是**校验。发现阶段的健康检查只证明文件能被 Loader 的方言解析且行带 `name`,上述四类失败全部能通过它。 + +agent 按 `cordis_mount` 自身文档所述的方式够到 roster 服务:挂一个声明 `inject: ['agentPresets', 'tools']` 的临时插件,并为自己注册一个工具——因为挂载只返回自身的确认信息,而已注册的工具才是服务结果在下一步抵达模型的途径。skill 逐字附上该插件。`agentPresets` 位于生成的 `cordis_inspect what:"api"` 目录中并带完整 JSDoc,沙箱 façade 仅凭 `fiber.inject` 而非白名单放行服务,因此这条路径没有为该 skill 做任何特例。 + +`copy(from, id, name)` 被指定为创作写入手段,取代 shell 复制:它校验 id、拒绝任何根已提供的 id、失败时回滚、重写副本的 `preset.yml`,并在宿主侧运行而无需沙箱升级。沙箱升级的说明保留,移到真正适用之处——其后编辑 `agent.cordis.yml` 仍然写在会话工作区之外。 + +「某行是否发布服务」改由 `cordis_inspect what:"services"` 回答,它会给出每个存活服务的持有 fiber。 + +指导保留 `${DSH_HOME:-$HOME/.dsh}/.agent-presets/` 作为「我的 preset 在哪」的答案——每个 `dsh` 启动器都把它们放在那里——同时把 agent 实际读取或编辑的路径改走 `list()` 或 `resolve()`。`Config.roots` 默认为 `[]`,两个根均由 `apps/cli` 补入,`writableRoot()` 取其中第一个 `user` 根,且没有任何调用会报告任一路径;`authorable` 只回答是否存在可写根,而 `list()` 无法揭示一个尚且为空的用户根。因此写出该路径对人讲是对的,喂给文件工具是错的。 + +禁止改动随发布安装的约束,从创作步骤中的一段提升为顶部的 `## Off-limits` 一节,并扩展到禁止改宿主组装绕行。新增的自校验调用不削弱它:`copy()` 拒绝任何根已提供的 id,`remove()` 拒绝随部署发布的 preset。 + +## Measured behavior + +下表每一行都由启动已发布的 Web 组装、并在由 `cordis` 组装出的 agent 上经 `ctx.tools.execute` 调用工具得出——全程无模型参与。 + +| 被测组装 | `list()` 的 `broken` | `standingKeyFor()` | +|---|---|---| +| 行指向不存在的包 | 空 | `Cannot find package '@deepseek-ai/dsh-does-not-exist'` | +| 服务行未套 realm,名字宿主已提供 | 空 | `service "tasks" has been registered at ` | +| 服务行未套 realm,名字宿主未提供 | 空 | `row(s) published process-global service(s) [workflows]; …` | +| 同一行置于 `isolate` 内 | 空 | 挂载成功 | +| 消费者行无人提供服务 | 空 | `1 row(s) did not activate: … waiting for workflows` | +| 行缺少必填配置字段 | 空 | `invalid config: $.allowParallelInProgress missing required value` | + +skill 自带的 `cordis_mount` 代码片段经工具注册表逐字执行:它成功挂载,其 `preset_check` 工具在下一次读取时出现在组装该 agent 的目录中,对有效 preset 回答 `mounted OK`,对无效 preset 回答挂载拒绝原因。 + +## Alternatives considered + +**把校验留给用户,只修四处错误。** 这些错误与那句能力断言同源——指导是按 preset 层的公开面写的,而不是按被组装出的 agent 实际够得到的东西写的——而无法自查的 agent 交出的组装,其缺陷设置页同样看不见。 + +**把 `list()` 的 `broken` 字段教成校验手段。** 它正是设置页展示的字段,看起来像是预期答案。它对所有要紧的失败一律放行,而把它当成校验,正是原指导显得完整的原因。 + +**给 preset 加一个一等的 preset 校验工具。** 组合出的路径已经存在,且由 `cordis_mount` 自己的 schema 记载;专用工具会给一个「无需专用工具即可够到运行时」的 preset 再添一个面向模型的行。 + +## Consequences + +- 校验成功会留下一个永不回收的常驻代际,这是 roster 按代际本就承担的[常驻挂载](../architecture/2026-08-08-per-preset-standing-mounts.md)代价——由 agent 在编辑收尾时付一次,而不是由用户在首次会话时付。 +- skill 现在依赖 `cordis_inspect` 生成的 API 目录对 `agentPresets` 保持最新;`doc-sync` 中的 `verify-cordis-api` 是守住这一点的门禁。 +- 有两个示例现在是对 `standard` 组装的引用。若该文件的 `delegation` 组发生变化它们会漂移,而 `web-agent-presets` e2e 捕捉不到。 +- 被修正的四条陈述原本是该 skill 对 realm 规则仅有的具体图示。选择替换而非删除,规则才仍然可教;替换后的示例读一个已发布文件即可核验。 + +## Related + +取代[破损 preset 是 roster 行](2026-08-09-broken-preset-roster-rows.md)中关于创作模式指导的那一条,其健康检查决策依然有效——本篇只推翻它「agent 起不了会话;设置页的红色标记是用户的检查手段」这一结论。创作的 copy-only 形态由[copy-only preset 创作](../simplification/2026-08-08-copy-only-preset-authoring.md)负责。 diff --git a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.i18n.yaml b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.i18n.yaml index 3e3e892063..c24d181e58 100644 --- a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.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/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md -2026-07-22-web-multimodal-image-input-and-durable-attachments.md: ea234e557553dda03ef2b707b60d47d3f43eb8f8 -2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md: be478ece73039201a820d804435610faea4cb3fe +2026-07-22-web-multimodal-image-input-and-durable-attachments.md: f1fbcbd29b188505e647265c4c974886c066e936 +2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md: a55467cacc412b6f313dd932a0e4868965c039ea diff --git a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md index ea234e5575..f1fbcbd29b 100644 --- a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md +++ b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.md @@ -18,17 +18,17 @@ Peer products converge on an attachment rail above the editor, but their storage Pasted or dropped raster images are the Web composer's first consumer of a durable attachment capability. Unsent files remain temporary client-owned draft state. The host validates and durably commits every accepted user image before appending its message event. A provider adapter that produces structured image output must durably commit the output before appending its assistant block. Canonical user and assistant content contains only role-neutral `ImageBlock` references. -Version one supports PNG, JPEG, WebP, and GIF paste and drag-and-drop, image-only or mixed prompts, historical user and assistant image rendering, and original-image preview on double-click. File picking, generic files, PDF, audio, video, image copying, and a custom context menu remain separate follow-ups. +Version one supports PNG, JPEG, WebP, and GIF paste and drag-and-drop, image-only or mixed prompts, historical user and assistant image rendering, and original-image preview on a single click (display and interaction specifics superseded in part by the [attachment-display alignment note](2026-08-11-web-attachment-display-alignment.md)). File picking, generic files, PDF, audio, video, image copying, and a custom context menu remain separate follow-ups. ### Product behavior - Pasting or dropping one or more supported images adds ordered thumbnails above the textarea without inserting placeholder text. Dragging files over the composer highlights the drop target. - The same resident `InputBar` renders the rail in both blank-session Hero and active-session layouts. The rail is hidden when empty and scrolls horizontally instead of widening the composer. -- Each approximately 72-by-72-pixel thumbnail has a remove action and opens its original draft image on double-click. +- Each 64-by-64-pixel thumbnail carries a hover-revealed remove control inside the card and opens its original draft image on a single click; overflow pages with edge arrows instead of a visible scrollbar. - A prompt may contain text and images or images only. Pure text paste remains native browser behavior; mixed clipboard content inserts its text normally while adding its files to the rail, and file-only paste prevents default browser handling. File drops on the composer always prevent browser navigation and report unsupported files locally. - A failed send restores the complete text and image draft without clobbering text or images added while the request was in flight. Removal, successful send, session-scope disposal, rendered-history disposal, and application disposal revoke the object URLs they own. - Historical user and assistant images use one `MessageImage` control. Inline images preserve intrinsic aspect ratio, do not upscale, and stay within a 240-by-240-pixel box. -- Double-clicking a message image opens the stored original in a viewport-bounded modal. Escape, the close control, and backdrop activation close it and restore focus. +- Clicking a message image opens the stored original in a viewport-bounded modal. Escape, the close control, and backdrop activation close it and restore focus. - Version one does not override the browser context menu and provides no explicit image-copy action. ### Storage lifecycle and ownership @@ -122,7 +122,7 @@ Base64 crosses JSON-RPC once and is discarded after persistence. The host valida Model catalog entries gain optional merge-extensible input modality declarations. A missing declaration means unknown; a present list without `image` is an explicit negative capability. -The host is the authoritative preflight boundary. It resolves the session's latest routed provider/model, falling back through agent options to host defaults; if that model explicitly excludes image input, it rejects the prompt before writing any attachment or event, and the client restores the draft. Image-bearing prompt admission and model selection share one per-agent serial boundary, and a dequeued prompt remains pending until its durable message event publishes ([ordering decision](../bug-fix/2026-07-29-atomic-web-image-admission.md)); a steering carrier gates from its enqueue until its `steering/message` event publishes, closing the outbox hop that never enters the queued mirror. Selection rejects a text-only target while an image is pending publication or remains in the session's current derived history. Compaction can remove old images and make a later text-only selection valid; idle without publication releases a claimed queued carrier, while steering retained in the outbox stays gated until publication or discard. `session.updateQueue` edits accept text content only, so a queue edit cannot inject an image past this admission boundary. Unknown capability proceeds to the adapter guard so uncatalogued model identifiers remain usable. The browser rejects unsupported declared image media types before allocating preview URLs, but it does not snapshot deployment limits or model capability: a handshake snapshot cannot represent a session's current target after `session.selectModel`, and deployment policy may change independently. The host validates the complete batch against current byte, count, aggregate, media, dimension, pixel, and routed-model policy before writing any attachment or event; its rejection renders through the composer error strip. +The host is the authoritative preflight boundary. It resolves the session's latest routed provider/model, falling back through agent options to host defaults; if that model explicitly excludes image input, it rejects the prompt before writing any attachment or event, and the client restores the draft. Image-bearing prompt admission and model selection share one per-agent serial boundary, and a dequeued prompt remains pending until its durable message event publishes ([ordering decision](../bug-fix/2026-07-29-atomic-web-image-admission.md)); a steering carrier gates from its enqueue until its `steering/message` event publishes, closing the outbox hop that never enters the queued mirror. Selection rejects a text-only target while an image is pending publication or remains in the session's current derived history. Compaction can remove old images and make a later text-only selection valid; idle without publication releases a claimed queued carrier, while steering retained in the outbox stays gated until publication or discard. `session.updateQueue` edits accept text content only, so a queue edit cannot inject an image past this admission boundary. Unknown capability proceeds to the adapter guard so uncatalogued model identifiers remain usable. The browser rejects unsupported declared image media types before allocating preview URLs, but it does not snapshot deployment limits or model capability: a handshake snapshot cannot represent a session's current target after `session.selectModel`, and deployment policy may change independently. The host validates the complete batch against current byte, count, aggregate, media, dimension, pixel, and routed-model policy before writing any attachment or event; its rejection announces through the composer's transient toast. The Pi-AI adapter is the first visual-input route: it resolves `ctx.attachments` at request time, recursively converts each durable image reference including references nested inside tool results, and emits native image content only for models that declare image input. The shipped composition registers Pi-AI OpenAI and Anthropic routes alongside the text-only default DeepSeek route; selecting the active provider/model remains a host composition or profile concern rather than an image-input CLI feature. Request-time service resolution keeps Cordis load order from freezing optional attachment availability. The hand-written DeepSeek adapter throws typed `UNSUPPORTED_CONTENT` for an image anywhere in the request, including nested tool results. No adapter may flatten or skip an image. @@ -163,7 +163,7 @@ The attachment packages form the interface/implementation side of one capability ### Implementation -The implemented slice includes the attachment seam, role-neutral image block, Pi-AI input conversion, DeepSeek rejection, durable host ordering, Web upload/read protocol, current image-limit enforcement, bounded Web request bodies, in-memory draft images, paste/drop rail, user and assistant history rendering, double-click preview, compaction handling, and keyless assembled Web coverage. +The implemented slice includes the attachment seam, role-neutral image block, Pi-AI input conversion, DeepSeek rejection, durable host ordering, Web upload/read protocol, current image-limit enforcement, bounded Web request bodies, in-memory draft images, paste/drop rail, user and assistant history rendering, single-click preview, compaction handling, and keyless assembled Web coverage. No compatibility shim is required for the pre-release prompt wire; all call sites and fixtures change with the introducing slice. diff --git a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md index be478ece73..a55467cacc 100644 --- a/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md +++ b/.agents/notes/implemented/feature/2026-07-22-web-multimodal-image-input-and-durable-attachments.zh.md @@ -18,17 +18,17 @@ Status: implemented 粘贴或拖放的光栅图片是 Web 输入区对持久附件能力的首个应用场景。未发送文件仍是由客户端持有的临时草稿状态。宿主在追加相应消息事件前,校验并持久提交每张已接受的用户图片。生成结构化图片输出的提供方适配器在追加相应助手块前,也必须持久提交输出。规范用户内容与助手内容只包含角色无关的 `ImageBlock` 引用。 -第一版支持粘贴和拖放 PNG、JPEG、WebP 与 GIF,支持仅图片或混合提示词,支持渲染历史用户图片与助手图片,并支持双击预览原图。文件选择、通用文件、PDF、音频、视频、图片复制和自定义上下文菜单仍分别作为后续工作。 +第一版支持粘贴和拖放 PNG、JPEG、WebP 与 GIF,支持仅图片或混合提示词,支持渲染历史用户图片与助手图片,并支持单击预览原图(展示与交互细节部分由[附件展示对齐 Note](2026-08-11-web-attachment-display-alignment.md)取代)。文件选择、通用文件、PDF、音频、视频、图片复制和自定义上下文菜单仍分别作为后续工作。 ### 产品行为 - 粘贴或拖放一张或多张受支持的图片后,文本框上方会按顺序显示缩略图,但不会插入占位文本。文件拖入输入区时会高亮放置目标。 - 同一个常驻 `InputBar` 会在空白会话 Hero 和活跃会话布局中渲染附件栏。附件栏为空时隐藏,通过横向滚动避免撑宽输入区。 -- 每个缩略图约为 72 × 72 像素,带有移除操作;双击时打开草稿原图。 +- 每个缩略图为 64 × 64 像素,移除按钮位于卡片内部、悬停时显示;单击打开草稿原图,溢出用两端箭头翻页而非可见滚动条。 - 提示词可同时包含文本与图片,也可仅包含图片。粘贴纯文本时保持浏览器原生行为;粘贴混合的剪贴板内容时,文本会正常插入,文件则同时添加到附件栏;仅粘贴文件时才阻止浏览器的默认处理。在输入区放置文件时总会阻止浏览器导航,并在本地报告不受支持的文件。 - 发送失败时恢复完整的文本与图片草稿,但不会覆盖请求飞行期间新增的文本或图片。移除、发送成功、会话 scope 释放、已渲染历史记录释放和应用释放都会撤销各自持有的对象 URL。 - 历史用户图片与助手图片共用一个 `MessageImage` 控件。行内图片保持固有宽高比、不放大,并限制在 240 × 240 像素的边界框内。 -- 双击消息图片会在不超出视口的模态框中打开存储的原图。按 Escape、激活关闭控件或激活背景区域都会关闭模态框并恢复焦点。 +- 单击消息图片会在不超出视口的模态框中打开存储的原图。按 Escape、激活关闭控件或激活背景区域都会关闭模态框并恢复焦点。 - 第一版不覆盖浏览器上下文菜单,也不提供明确的图片复制操作。 ### 存储生命周期与归属 @@ -122,7 +122,7 @@ Base64 只跨越一次 JSON-RPC,并在持久化后丢弃。宿主会校验规 模型目录项增加可选且可合并扩展的输入模态声明。缺少声明表示未知;声明存在但不含 `image`,则明确表示不支持图片。 -宿主是权威的前置检查边界。它会解析会话最新路由到的提供方和模型,并在缺失时依次回退到 agent 选项和宿主默认值;如果该模型明确排除图片输入,宿主会在写入任何附件或事件前拒绝提示词,客户端则恢复草稿。包含图片的提示词准入与模型选择共用一个逐 agent 的串行边界,而且已经出队的提示词在其持久消息事件发布前仍保持待发布状态([顺序决策](../bug-fix/2026-07-29-atomic-web-image-admission.md));steering 载体则从入队起就参与门槛,直到其 `steering/message` 事件发布为止,堵住了从不进入排队镜像的 outbox 窗口。当图片正等待发布或仍存在于会话当前的派生历史中时,模型选择会拒绝纯文本目标。压缩(compaction)可以移除旧图片,使之后选择纯文本目标变得有效;未发布任何事件即转入空闲时,已认领的 queued 载体会被释放,而保留在 outbox 中的 steering 在发布或丢弃前始终受门槛约束。`session.updateQueue` 的编辑只接受文本内容,因此队列编辑无法绕过该准入边界注入图片。能力未知时继续进入适配器强制检查,使未收录的模型标识符仍然可用。浏览器会在分配预览 URL 前拒绝声明不支持的图片媒体类型,但不会为部署限制或模型能力保留快照:握手快照无法表达 `session.selectModel` 之后会话的当前目标,部署策略也可能独立变化。宿主会根据当前的单张字节数、图片数量、总字节数、媒体类型、尺寸、像素数和路由模型策略校验整个批次,再写入任何附件或事件;其拒绝通过 composer 错误条呈现。 +宿主是权威的前置检查边界。它会解析会话最新路由到的提供方和模型,并在缺失时依次回退到 agent 选项和宿主默认值;如果该模型明确排除图片输入,宿主会在写入任何附件或事件前拒绝提示词,客户端则恢复草稿。包含图片的提示词准入与模型选择共用一个逐 agent 的串行边界,而且已经出队的提示词在其持久消息事件发布前仍保持待发布状态([顺序决策](../bug-fix/2026-07-29-atomic-web-image-admission.md));steering 载体则从入队起就参与门槛,直到其 `steering/message` 事件发布为止,堵住了从不进入排队镜像的 outbox 窗口。当图片正等待发布或仍存在于会话当前的派生历史中时,模型选择会拒绝纯文本目标。压缩(compaction)可以移除旧图片,使之后选择纯文本目标变得有效;未发布任何事件即转入空闲时,已认领的 queued 载体会被释放,而保留在 outbox 中的 steering 在发布或丢弃前始终受门槛约束。`session.updateQueue` 的编辑只接受文本内容,因此队列编辑无法绕过该准入边界注入图片。能力未知时继续进入适配器强制检查,使未收录的模型标识符仍然可用。浏览器会在分配预览 URL 前拒绝声明不支持的图片媒体类型,但不会为部署限制或模型能力保留快照:握手快照无法表达 `session.selectModel` 之后会话的当前目标,部署策略也可能独立变化。宿主会根据当前的单张字节数、图片数量、总字节数、媒体类型、尺寸、像素数和路由模型策略校验整个批次,再写入任何附件或事件;其拒绝通过 composer 的短时 toast 播报。 Pi-AI 适配器是首条视觉输入路径:它在请求时解析 `ctx.attachments`,递归转换每个持久图片引用,包括嵌套在工具结果中的引用,并且仅为声明支持图片输入的模型生成提供方原生图片内容。交付的组合会同时注册 Pi-AI OpenAI、Anthropic 路由和仅支持文本的默认 DeepSeek 路由;选择当前提供方/模型仍由宿主组合或配置承担,而不是图片输入 CLI(命令行界面)的功能。在请求时解析服务,可避免 Cordis 加载顺序将可选附件服务的可用性固化。手写 DeepSeek 适配器遇到请求中任何位置的图片时都会抛出类型化的 `UNSUPPORTED_CONTENT` 错误,包括嵌套工具结果中的图片。任何适配器都不得将图片展平或跳过。 @@ -163,7 +163,7 @@ Pi-AI 适配器是首条视觉输入路径:它在请求时解析 `ctx.attachme ### 实现 -已实现的范围包括附件服务边界、角色无关的图片块、Pi-AI 输入转换、DeepSeek 拒绝、宿主持久化顺序、Web 上传与读取协议、当前图片限制执行、大小受限的 Web 请求体、内存草稿图片、粘贴与拖放附件栏、用户与助手历史图片渲染、双击预览、压缩处理,以及组装后无需密钥的 Web 覆盖。 +已实现的范围包括附件服务边界、角色无关的图片块、Pi-AI 输入转换、DeepSeek 拒绝、宿主持久化顺序、Web 上传与读取协议、当前图片限制执行、大小受限的 Web 请求体、内存草稿图片、粘贴与拖放附件栏、用户与助手历史图片渲染、单击预览、压缩处理,以及组装后无需密钥的 Web 覆盖。 预发布提示词协议不需要兼容包装层;引入相应切片时会同时修改所有调用点和 fixture。 diff --git a/.agents/notes/implemented/feature/2026-08-10-web-plugin-configuration.i18n.yaml b/.agents/notes/implemented/feature/2026-08-10-web-plugin-configuration.i18n.yaml new file mode 100644 index 0000000000..a27cb812e9 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-10-web-plugin-configuration.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/feature/2026-08-10-web-plugin-configuration.md +2026-08-10-web-plugin-configuration.md: 7375f496c7af1a695243444fe56aca7262d3dedd +2026-08-10-web-plugin-configuration.zh.md: 59d65db39bcc2306983f2a26dcf252164d7a6f37 diff --git a/.agents/notes/implemented/feature/2026-08-10-web-plugin-configuration.md b/.agents/notes/implemented/feature/2026-08-10-web-plugin-configuration.md new file mode 100644 index 0000000000..7375f496c7 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-10-web-plugin-configuration.md @@ -0,0 +1,50 @@ +# Agent Note: Plugin configuration in the web settings page + +Status: implemented + +English | [中文](2026-08-10-web-plugin-configuration.zh.md) + +## Problem + +Everything a plugin can be configured with lived in `cordis.yml`. A user who wanted a longer shell timeout, a different search endpoint, or fewer parallel tool calls had to find the composition file, know its shape, and restart — while the Models page had shown for months that a settings namespace can be edited from the browser and take effect immediately. + +The seam that made the Models page possible was already general: any plugin may register a namespace, and `settings.describe` serves its schema, its layers, and its revision. What was missing was on the two ends. No plugin outside the LLM adapters and the permission service had registered one, and there was no surface for a namespace that is not a model provider. + +## Decision + +Three host-plane plugins register their own settings namespace, and one browser-side section renders whatever the deployment exposes. + +**Layering, unchanged.** A section resolves as schema defaults → the plugin's composition entry → the user layer. Each plugin passes its `cordis.yml` entry as the `base` and reads its config through a source thunk, so a stored change reaches the next use and a detaching settings provider leaves the composition entry running. Constraints the schema cannot express — positive and finite, the timer bound on `graceMs`, the parallel cap being a positive integer — become the section validator, so a bad value is refused at the write instead of at the next command. + +**The shell namespace names the capability, not an implementation.** `BASH_SETTINGS_NAMESPACE` is exported by `@deepseek-ai/dsh-bash` because a host composes exactly one provider of `ctx.bash`: the win32 layer swaps the POSIX rows for the pwsh ones, and mounting both fails loud on a duplicate service registration. Both families therefore register the same namespace with their own schema and entry without ever colliding, and a `settings.yaml` carried between platforms keeps resolving on both — schemastery objects preserve keys the active schema does not declare. + +**A section is a subset when the plugin config is bigger than what a user owns.** `agent-loop` exposes only `maxParallelToolCalls`; its `agents` array is consumed once when the service starts, so a stored change there could only look like it had an effect. + +**The provider projects, rather than captures.** `web-search-deepseek` hands its provider a thunk instead of an options value, so an endpoint or model change reaches the next search without re-registering the provider — which would make the web seam's provider selection observable to the user as a flicker. + +**Exposure stays a Host allowlist.** The three namespaces join `WEB_SETTINGS_NAMESPACES`; registration alone still never crosses the transport, and a namespace absent from that list answers `settings-not-exposed` exactly as an unregistered one does. + +**The section knows no namespace.** `dsh-client-ui-plugin-config` declares a `settings.plugin.item` slot and renders the cards registered into it, so a plugin that ships a browser half owns its card and its controls. Each card binds its namespace through the client settings scope, which gained the two things a form needs: the raw `user` layer, whose key PRESENCE is what marks a field overridden, and `unset`, which clears one field back to the composition layer. A card renders nothing while its namespace is unavailable, so a deployment that does not compose the owning plugin shows no trace of it. + +**A card stages its edits and writes them on save.** Controls hold no draft of their own: the card's form owns the staged text, every control renders it, and only **Save** turns it into document mutations. A settings write is durable and revision-fenced, so a control that committed as it settled spent a revision on a value the user had not decided to store and could not preview; the reset stages the composed default the same way. Because the Host's validators own the constraints no schema can express, the form reads the section back after writing and reports a save that did not land instead of predicting the outcome, keeping those drafts for the user to correct. The credential control is staged with the rest even though it writes through the credentials domain, so one save covers everything the card shows. + +## Alternatives considered + +- **A registration-time exposure declaration replacing the allowlist.** The honest shape — the namespace's owner declares its own exposure, and a plugin distributed outside this repository can surface its configuration without a change in `packages/host/apiproxy`. Deferred because it changes the seam contract, every existing registration site, and the anti-enumeration semantics at once, and because a plugin exposing an arbitrary schema needs a fail-closed redaction path first: a secret reachable only through a union or transform is currently returned verbatim. +- **A generic schema-driven form renderer.** Declined again for the reason recorded in the [web-config-plane note](../architecture/2026-07-30-web-config-plane.md): field truth without a presentation vocabulary produced an unusable card. Three plugins of hand-written controls cost about the same and read better, and the slot keeps the fourth plugin from having to negotiate with this package. +- **Editing preset-mounted plugins from this page.** Out of scope, and not merely unbuilt: a preset's rows carry their configuration inline in `agent.cordis.yml` and cannot register a settings namespace at all, because a second session mounting the same preset would fail on a duplicate registration. A user layer shared across presets would also overwrite the fields a preset uses to define its agent's identity — its persona text, its delegation wiring — which are per-preset by design. +- **One namespace per executor package instead of the capability-named `bash`.** Declined because the composed executor differs by platform while the settings document does not: a user who set a timeout on macOS would silently lose it on Windows. +- **Writing the search key into the settings section.** Declined because the literal would then have to ride a `describe` response to be rendered. The card reports only whether a key is configured and writes through the credentials domain, addressed by the reference the section names. +- **Committing each control as it settles, with no save.** Built first, and replaced: blur is not a decision. It spent a namespace revision per control, gave the user nothing to preview or undo before the write, and left an invalid draft silently discarded — a value the Host's validator refuses simply snapped back with no reason given. One save per card makes the write a gesture the user performs. +- **Letting the provider read its options per property.** The thunk was read at each use site so read sites could stay unchanged, which quietly broke the contract the constructor states: `search()` awaits credential resolution and then reads the endpoint, model, and budget, so a settings write landing inside that await sent the key resolved from the old section to the endpoint named by the new one. Each operation now snapshots once at its entry and threads that snapshot into credential resolution. +- **Validating the fields in the browser to keep the save honest.** Declined: the constraints live in the owning plugin's section validator, and restating them here would make two homes for one rule that could disagree per release. The card checks only what its own control can decide — that a numeric draft is a number — and lets the Host answer for the rest, which is why the save reads the section back. + +## Consequences + +A user edits the shell's command timeout and output cap, the agent loop's parallel tool-call cap, and the search provider's key, endpoint, and per-request budget from the settings page, with each field marking whether they set it and offering a reset. + +Two costs are real. Adding a fourth plugin still requires an entry in the apiproxy allowlist, so the page's reach is a Host decision rather than a plugin's. And the plugins the web deployment moved into the agent plane — the file tools, the skills, compaction, the todo tool — appear nowhere here, which is most of what a user might expect to find; their configuration remains the preset editor's. + +The bash and pwsh executors now expose `config` as a getter over a source thunk rather than a readonly field. Every read site was already per-call, so nothing else changed, but a subclass that captured `this.config` at construction would silently pin the composition entry. + +`verify-cordis-config` gained one check, paid for by this branch: merging master's rename of the client manifest field (`dshClient` → `dsh.client`) left this package declaring the old name, and the whole section vanished from the browser with no error anywhere — the row composed, the empty node half activated, and the browser roster scan simply never matched it. Nothing could catch that, because the composition file cannot tell a surface plugin from a Host plugin: the difference lives in the manifest. The gate now requires a `packages/client` package's `./client` export and its `dsh.client` declaration to agree in both directions. The check is scoped to that group because a Host package's `./client` export is the typed wire face its browser consumers import, not a plugin the roster serves. diff --git a/.agents/notes/implemented/feature/2026-08-10-web-plugin-configuration.zh.md b/.agents/notes/implemented/feature/2026-08-10-web-plugin-configuration.zh.md new file mode 100644 index 0000000000..59d65db39b --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-10-web-plugin-configuration.zh.md @@ -0,0 +1,50 @@ +# Agent Note: Plugin configuration in the web settings page + +Status: implemented + +[English](2026-08-10-web-plugin-configuration.md) | 中文 + +## 问题 + +插件的一切可配置项都只存在于 `cordis.yml`。想要更长的 shell 超时、不同的搜索端点或更少的并行工具调用,用户必须找到组装文件、了解它的形状,然后重启——而 Models 页几个月来一直在证明:settings 命名空间可以在浏览器里编辑并立即生效。 + +支撑 Models 页的那条 seam 本就是通用的:任何插件都可以注册命名空间,`settings.describe` 会提供它的 schema、分层与 revision。缺的是两端。除 LLM 适配器与权限服务外,没有插件注册过命名空间;而对于非模型提供方的命名空间,也没有任何表层。 + +## 决策 + +三个宿主平面插件各自注册 settings 命名空间,一个浏览器侧分区渲染该部署所暴露的一切。 + +**分层不变。** 一个分节按 schema 默认值 → 插件的组装条目 → 用户层解析。每个插件把自己的 `cordis.yml` 条目作为 `base` 传入,并通过 source thunk 读取配置,因此存储的变更会作用于下一次使用,而脱离的 settings 提供方会让组装条目继续运行。schema 无法表达的约束——正有限、`graceMs` 的定时器上界、并行上限必须是正整数——成为分节的校验器,因此错误的值在写入时被拒绝,而不是到下一条命令时才失败。 + +**shell 命名空间命名的是能力,而非某个实现。** `BASH_SETTINGS_NAMESPACE` 由 `@deepseek-ai/dsh-bash` 导出,因为一个宿主只组装一个 `ctx.bash` 提供方:win32 层会把 POSIX 行换成 pwsh 行,而同时挂载两者会因服务重复注册在加载期失败。因此两个家族都能用自己的 schema 与条目注册同一个命名空间而永不相撞;在平台间携带的 `settings.yaml` 也能在两边继续解析——schemastery 对象会保留当前 schema 未声明的键。 + +**当插件配置大于用户所拥有的部分时,分节就是一个子集。** `agent-loop` 只暴露 `maxParallelToolCalls`;它的 `agents` 数组在服务启动时被消费一次,所以存储在那里的变更只会看起来生效。 + +**提供方按次投影,而不是固化。** `web-search-deepseek` 交给提供方的是一个 thunk 而非 options 值,因此端点或模型的变更无需重新注册提供方即可作用于下一次搜索——重新注册会让 web seam 的提供方选择以闪断的形式被用户看到。 + +**暴露仍是 Host 的白名单。** 这三个命名空间加入 `WEB_SETTINGS_NAMESPACES`;仅有注册依然不会跨越传输边界,而不在该名单中的命名空间会与未注册的命名空间得到完全相同的 `settings-not-exposed`。 + +**该分区不认识任何命名空间。** `dsh-client-ui-plugin-config` 声明 `settings.plugin.item` slot 并渲染注册进来的卡片,因此带浏览器半侧的插件拥有自己的卡片与控件。每张卡片通过客户端 settings scope 绑定其命名空间,而该 scope 补上了表单所需的两样东西:原始 `user` 层——键的**存在**才标记字段被覆盖——以及把单个字段清回组装层的 `unset`。命名空间不可用时卡片什么都不渲染,因此未组装该插件的部署不会显示它的任何痕迹。 + +**卡片暂存修改,保存时才写入。** 控件不持有自己的草稿:暂存文本归卡片的表单所有,所有控件渲染的都是它,只有**保存**才把它变成文档变更。settings 写入是持久且带 revision 栅栏的,因此「失焦即提交」的控件会为用户尚未决定存储、也无从预览的值花掉一个 revision;重置同样只是暂存组装默认值。schema 表达不了的约束归 Host 的校验器所有,所以表单在写入后回读分节、报告没有落盘的保存,而不是自行预测结果,并保留这些草稿供用户修改。密钥控件虽然经由 credentials 领域写入,也和其余字段一起暂存,因此一次保存覆盖卡片上的全部内容。 + +## 备选方案 + +- **用注册期的暴露声明取代白名单。** 这才是诚实的形状——命名空间的拥有方声明自己的暴露,在本仓库之外分发的插件也无需改动 `packages/host/apiproxy` 就能呈现自己的配置。之所以暂缓,是因为它会同时改变 seam 契约、全部现有注册点与防枚举语义;而且插件要暴露任意 schema,还得先有 fail-closed 的脱敏路径:目前只能经由 union 或 transform 抵达的 secret 会被原样返回。 +- **通用 schema 驱动的表单渲染器。** 再次否决,理由与 [web-config-plane 笔记](../architecture/2026-07-30-web-config-plane.md)所记一致:没有呈现词汇的字段真值产出的是无法使用的卡片。三个插件的手写控件成本相当而可读性更好,且该 slot 让第四个插件无需与本包协商。 +- **在本页编辑 preset 挂载的插件。** 超出范围,而且不只是「尚未实现」:preset 的行把配置内联在 `agent.cordis.yml` 中,且根本无法注册 settings 命名空间——同一 preset 挂载第二个会话时会因重复注册而失败。跨 preset 共享的用户层还会覆盖 preset 用来定义其 agent 身份的字段——人设文本、委派接线——而这些字段按设计就是各 preset 各自的。 +- **按执行器包各取一个命名空间,而非按能力命名的 `bash`。** 否决,因为被组装的执行器随平台不同,而设置文档不随平台不同:在 macOS 上设过超时的用户,到 Windows 上会悄无声息地失去它。 +- **把搜索密钥写进 settings 分节。** 否决,因为那样字面值就必须搭乘 `describe` 响应才能被渲染。卡片只报告是否已配置密钥,并按分节所命名的引用经由 credentials 领域写入。 +- **每个控件失焦即提交,不设保存。** 最初就是这么做的,后被替换:失焦不是决定。它每个控件花掉一个命名空间 revision,写入前不给用户任何预览或撤销的余地,还会把无效草稿悄悄丢弃——被 Host 校验器拒绝的值只是弹回原样,不给任何理由。每张卡片一个保存,才让写入成为用户执行的动作。 +- **让提供方按属性逐次读取 options。** 最初为了不改动读取点而在每个使用处读 thunk,这悄悄违背了构造函数自己声明的契约:`search()` 先 await 凭据解析,之后才读端点、模型与预算,因此落在那段 await 里的设置写入会把按旧分节解析出的密钥发往新分节命名的端点。现在每次操作在入口只快照一次,并把该快照传进凭据解析。 +- **在浏览器端校验字段,好让保存诚实。** 否决:这些约束住在拥有方插件的分节校验器里,在这里重述一遍就会让同一条规则有两个家,且可能随版本各说各话。卡片只判断自己的控件能判断的事——数字草稿是不是数字——其余交给 Host 回答,这正是保存要回读分节的原因。 + +## 影响 + +用户可以在设置页编辑 shell 的命令超时与输出上限、agent 循环的并行工具调用上限,以及搜索提供方的密钥、端点与单次请求预算,每个字段都标注是否由自己设定,并提供重置。 + +有两项真实代价。加入第四个插件仍需要在 apiproxy 白名单里添一条,因此本页的覆盖面是 Host 的决定而非插件的决定。而 web 部署移入 agent 平面的那些插件——文件工具、技能、压缩、todo 工具——在这里一个都不出现,而它们恰恰是用户最可能期待找到的;它们的配置仍归 preset 编辑器。 + +bash 与 pwsh 执行器现在把 `config` 暴露为 source thunk 之上的 getter,而不再是 readonly 字段。所有读取点本就是按次读取,因此别无变化;但若某个子类在构造期捕获 `this.config`,就会悄然把组装条目钉死。 + +`verify-cordis-config` 新增一项检查,代价由本分支付过:合并 master 对客户端清单字段的重命名(`dshClient` → `dsh.client`)后,本包仍声明旧名,于是整个分区从浏览器上消失,且任何地方都不报错——行照常组装、空的 node 半侧照常激活,只是浏览器 roster 扫描永远匹配不到它。这一点无从被既有门禁发现,因为组装文件区分不了 surface 插件与 Host 插件:差别在清单里。现在门禁要求 `packages/client` 包的 `./client` 导出与 `dsh.client` 声明双向一致。之所以只限这一组:Host 包的 `./client` 导出是给浏览器消费方 import 的类型化 wire face,不是 roster 要服务的插件。 diff --git a/.agents/notes/implemented/feature/2026-08-11-web-attachment-display-alignment.i18n.yaml b/.agents/notes/implemented/feature/2026-08-11-web-attachment-display-alignment.i18n.yaml new file mode 100644 index 0000000000..24bd9f6081 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-11-web-attachment-display-alignment.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/feature/2026-08-11-web-attachment-display-alignment.md +2026-08-11-web-attachment-display-alignment.md: 18c732c078ef6efd17e5c83708ba6e68ac663ce6 +2026-08-11-web-attachment-display-alignment.zh.md: 8a4222c31cd1fa2ad75ca314513c057fdb780d07 diff --git a/.agents/notes/implemented/feature/2026-08-11-web-attachment-display-alignment.md b/.agents/notes/implemented/feature/2026-08-11-web-attachment-display-alignment.md new file mode 100644 index 0000000000..18c732c078 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-11-web-attachment-display-alignment.md @@ -0,0 +1,33 @@ +# Agent Note: Web attachment display aligns with DeepSeek Chat via attachment atoms + +Status: implemented + +English | [中文](2026-08-11-web-attachment-display-alignment.zh.md) + +## Problem + +The web composer's image surfaces missed basic usability (user feedback, issue #2248). The remove control hung outside each 72px thumbnail at `top/right: -6px`, so the rail's `overflow-x` box clipped it and clicks aimed at it often missed; previews opened only on double-click, an affordance nothing advertised except a tooltip; a rail wider than the composer produced a raw horizontal scrollbar inside the capsule; and image-intake rejections plus prompt failures (for example `attachment-error` when the selected model takes no image input) rendered as persistent inline red strips above the card. Every one of these surfaces already has a settled design in DeepSeek Chat that users know: single-click preview, an inside-the-card hover-revealed remove control, hidden-scrollbar arrow paging, and a transient top-center toast. + +The first multimodal ship recorded these surfaces in the [web multimodal note](2026-07-22-web-multimodal-image-input-and-durable-attachments.md); this note supersedes its display and interaction specifics (thumbnail geometry, click affordance, error presentation) while its attachment seam, admission, and durability decisions stand. + +All of this UI also lived inside `dsh-client-ui-conversation` — the rail inline in the 700-line `InputBar`, the history image and lightbox in `chat/` and `skeleton/` — with no seam that another surface could reuse and nothing enforcing the pure-props discipline the pieces already had. + +## Decision + +Attachment display lives in a new zero-cordis atoms package, `@deepseek-ai/dsh-client-ui-attachment` (`packages/client/ui-attachment`), patterned on `dsh-client-ui-primitives`: `AttachmentRail` (64px/16px-radius thumbnails, single-click `onOpen`, inside-the-card remove control revealed on hover or focus and permanent under `pointer: coarse`, hidden scrollbar with circular edge arrows recomputed from scroll geometry, vertical-wheel horizontal pan clamped to 60px/tick, end-reveal on growth), `MessageImage`/`ImageGallery` (single-click preview), and `ImageLightbox`. Strings arrive as label props; `ui-conversation` bridges its `conversation` dictionary through `src/client/image-labels.ts` and keeps the machine wiring (draft ids, preview state, intake callbacks). The cross-package import is sanctioned exactly because the package is an atoms library, not a client plugin: plugin-to-plugin component imports stay forbidden, and the composer's rail is composer-owned rendering, not a slot. + +Both overlays body-portal: the lightbox opened from a chat message sits under transformed ancestors that would trap `position: fixed` in their own box (the backdrop covered only the chat column), so `ImageLightbox` and `Toast` render through `createPortal(document.body)` and cover the viewport from every opener. The transient banner is a `ui-primitives` `Toast` atom (120px from the viewport top, horizontally centered over its optional anchor — the composer card, so it sits over the chat column — `role="alert"`, `pointer-events: none`, three-second hold then one-second fade, `onDone` unmount, keyed per show so identical repeated messages re-announce). `InputBar` routes both intake rejections (`addImages`'s returned reason) and `promptError` through it, replacing the inline strips, and `ModelSelect` routes rejected model selections through the same atom while its in-menu strip with Retry stays the catalog-load surface; the machine-notice strip is untouched. DeepSeek Chat's source (a local reference copy) provided the target behaviors: its `ImageThumbnailInInput` (64px cards, opacity-transition delete), `ScrollArrows` (sentinel-driven paging), and `useToast` usage. + +## Alternatives considered + +**Keep the components inside `ui-conversation` and only restyle.** Rejected by the user: the attachment surface is expected to grow (file cards, upload progress), and the repo's plugin discipline forbids other plugins importing `ui-conversation` internals, so growth inside the plugin builds an unreusable pile. The atoms package gives the same components a sanctioned import path. + +**A `ui-attachment` client plugin registering slots.** Rejected: the rail renders inside the composer the machine owns and the gallery inside chat nodes; neither is a composition hole another plugin should fill, and a plugin would force slot indirection for what are pure presentational components. + +**Toast inside `ui-conversation`.** Rejected: nothing about a transient banner is conversation-specific, and `ui-primitives` is the established home for zero-cordis atoms other surfaces may reuse. + +**Keep inline error strips and only add the toast for image intake.** Rejected: `promptError` (the `attachment-error` screenshot in the issue) is the surface users actually complained about, and two error presentations in one composer would leave the strip as the odd survivor. + +## Consequences + +The composer and history image surfaces now match DeepSeek Chat's interaction model, and the label-prop seam means the atoms render under any locale without reaching for one. The cost is a real package boundary: `ui-attachment` carries the standard scaffolding (invariant companion, bilingual README, tsconfig face, per-file 100% coverage) and item strings must be resolved by every future consumer rather than inherited. Error banners are now transient — a user who looks away for four seconds misses the message, the trade DeepSeek Chat itself makes. Non-image attachments remain unsupported; the rail's card model is ready for them but the composer's intake is image-only (tracked in the package README's limitations). diff --git a/.agents/notes/implemented/feature/2026-08-11-web-attachment-display-alignment.zh.md b/.agents/notes/implemented/feature/2026-08-11-web-attachment-display-alignment.zh.md new file mode 100644 index 0000000000..8a4222c31c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-08-11-web-attachment-display-alignment.zh.md @@ -0,0 +1,33 @@ +# Agent Note: Web 附件展示经附件原子组件对齐 DeepSeek Chat + +Status: implemented + +[English](2026-08-11-web-attachment-display-alignment.md) | 中文 + +## 问题 + +Web 输入框的图片界面缺乏基本可用性(用户反馈,issue #2248)。删除按钮以 `top/right: -6px` 挂在 72px 缩略图外侧,被附件栏的 `overflow-x` 盒子裁切,点击经常落空;预览只能双击打开,除了 tooltip 没有任何提示这个操作;附件栏超出输入框宽度时在胶囊内部直接出现原生横向滚动条;图片接收被拒和发送失败(例如所选模型不支持图片输入时的 `attachment-error`)以常驻的内联红条显示在卡片上方。这些界面在 DeepSeek Chat 里都有用户熟悉的既定设计:单击预览、卡片内部悬停显示的删除按钮、隐藏滚动条的箭头翻页、顶部居中的短时 toast。 + +首个多模态版本把这些界面记录在[Web 多模态 Note](2026-07-22-web-multimodal-image-input-and-durable-attachments.md)中;本 Note 取代其中的展示与交互细节(缩略图几何、点击方式、错误呈现),其附件服务边界、准入与持久化决策继续有效。 + +这些 UI 还全部住在 `dsh-client-ui-conversation` 里——附件栏内联在 700 行的 `InputBar` 中,历史图片和灯箱分散在 `chat/` 与 `skeleton/`——没有其他界面可复用的接缝,纯 props 的纪律也无从约束。 + +## 决定 + +附件展示落位到新的零 cordis 原子组件包 `@deepseek-ai/dsh-client-ui-attachment`(`packages/client/ui-attachment`),模式照 `dsh-client-ui-primitives`:`AttachmentRail`(64px、16px 圆角缩略图,单击 `onOpen`,卡片内部的删除按钮悬停或聚焦显示、`pointer: coarse` 下常显,隐藏滚动条配两端圆形箭头并依滚动几何重算,纵向滚轮转横向平移且单次钳制 60px,新增条目滚到栏尾),`MessageImage`/`ImageGallery`(单击预览),以及 `ImageLightbox`。文案经 label props 传入;`ui-conversation` 通过 `src/client/image-labels.ts` 桥接 `conversation` 词典,并保留状态机接线(草稿 id、预览状态、接收回调)。跨包 import 之所以是被允许的路径,正因为它是原子组件库而非 client 插件:插件之间仍禁止互相 import 组件,且附件栏是输入框自有的渲染,不是插槽。 + +两个浮层都 portal 到 body:从聊天消息打开的灯箱位于带 transform 的祖先之下,`position: fixed` 会被困在祖先的盒子里(遮罩只盖住聊天列),因此 `ImageLightbox` 与 `Toast` 经 `createPortal(document.body)` 渲染,从任何打开位置都覆盖整个视口。短时横幅是 `ui-primitives` 的 `Toast` 原子(距视口顶部 120px,水平中心跟随可选锚点——composer 卡片,因此横幅在聊天列上居中——`role="alert"`、`pointer-events: none`,停留三秒再一秒淡出,`onDone` 卸载,按展示序号作 key 使相同文案重新播报)。`InputBar` 把接收拒绝(`addImages` 返回的原因)和 `promptError` 都改走 toast,替换内联红条,`ModelSelect` 的模型选择被拒也走同一原子,其菜单内带 Retry 的错误条仍是目录加载的呈现面;状态机 notice 条不受影响。DeepSeek Chat 源码(本地参考副本)提供了目标行为:其 `ImageThumbnailInInput`(64px 卡片、透明度过渡的删除钮)、`ScrollArrows`(哨兵驱动的翻页)与 `useToast` 用法。 + +## 备选方案 + +**组件留在 `ui-conversation` 里只改样式。** 被用户否决:附件面预期还会长(文件卡片、上传进度),而仓库的插件纪律禁止其他插件 import `ui-conversation` 内部实现,在插件里生长只会堆出无法复用的一坨。原子组件包给了同样的组件一条被允许的 import 路径。 + +**做成注册插槽的 `ui-attachment` client 插件。** 否决:附件栏渲染在状态机持有的输入框里,画廊渲染在聊天节点里,二者都不是该由其他插件填充的组合孔位,插件形态会为纯展示组件强加插槽间接层。 + +**Toast 放在 `ui-conversation`。** 否决:短时横幅没有任何会话特有的东西,`ui-primitives` 是零 cordis 原子组件的既定归属,其他界面也可能复用。 + +**保留内联红条,只给图片接收加 toast。** 否决:`promptError`(issue 截图里的 `attachment-error`)恰是用户实际抱怨的界面,一个输入框里存在两种错误呈现会让红条成为孤例。 + +## 结果 + +输入框与历史图片界面的交互模型现已与 DeepSeek Chat 一致,label props 接缝让原子组件在任何语言环境下渲染而无需触达 locale。代价是一个真实的包边界:`ui-attachment` 背上标准脚手架(invariant 伴生、双语 README、tsconfig face、逐文件 100% 覆盖率),且每个未来消费者都要自行解析条目文案而非继承。错误横幅变为短时——用户移开视线四秒就会错过消息,这正是 DeepSeek Chat 自己做的取舍。非图片附件仍不支持;附件栏的卡片模型已就绪,但输入框的接收仍只认图片(记录于包 README 的限制一节)。 diff --git a/apps/cli/config/agent-presets/cordis/agent.cordis.yml b/apps/cli/config/agent-presets/cordis/agent.cordis.yml index 6fa6030c97..2cfb9edf28 100644 --- a/apps/cli/config/agent-presets/cordis/agent.cordis.yml +++ b/apps/cli/config/agent-presets/cordis/agent.cordis.yml @@ -24,7 +24,7 @@ Two planes decide where an edit belongs. The HOST composition holds the registries and anything shared across sessions — persistence, the sandbox and approval stack, the model route, the subagent registry and its backends. An AGENT PRESET holds what one session contributes to those registries: its tools, its persona, its prompt sections. A row that publishes a service belongs in the host composition, or inside an `isolate` realm if the preset genuinely owns that service and nothing outside one agent reads it. - Presets you author live under `${DSH_HOME:-$HOME/.dsh}/.agent-presets//`, one directory per preset. NEVER edit or delete the shipped preset install (the `agent-presets` directory beside the deployment's own config): it belongs to the deployment, an upgrade overwrites it, and corrupting the `cordis` preset would disable this very mode. To change what a shipped preset does, copy its composition into a new preset directory and edit the copy. + Presets you author live one directory per preset under `${DSH_HOME:-$HOME/.dsh}/.agent-presets//`; the roster reports each preset's real path, so take the one you edit from there. NEVER edit or delete the shipped preset install (the `agent-presets` directory beside the deployment's own config): it belongs to the deployment, an upgrade overwrites it, and corrupting the `cordis` preset would disable this very mode. To change what a shipped preset does, copy its composition into a new preset directory and edit the copy. Load the `editing-cordis-compositions` skill before writing or changing a composition. diff --git a/apps/cli/config/agent-presets/cordis/skills/editing-cordis-compositions/SKILL.md b/apps/cli/config/agent-presets/cordis/skills/editing-cordis-compositions/SKILL.md index ce751f039d..744d2f13c1 100644 --- a/apps/cli/config/agent-presets/cordis/skills/editing-cordis-compositions/SKILL.md +++ b/apps/cli/config/agent-presets/cordis/skills/editing-cordis-compositions/SKILL.md @@ -1,12 +1,18 @@ --- name: editing-cordis-compositions -description: Use when creating or changing a Cordis composition for this harness — writing or editing an agent preset, adding or removing a plugin row, deciding whether something belongs to the host composition or to one session, or diagnosing a row that mounted but contributed nothing. +description: Use when creating, changing, or validating a Cordis composition for this harness — writing or editing an agent preset, adding or removing a plugin row, deciding whether something belongs to the host composition or to one session, checking whether a preset you authored actually mounts, or diagnosing a row that mounted but contributed nothing. --- # Editing Cordis compositions Every capability in this harness is a plugin row in a `cordis.yml`. There is no separate configuration language: changing what an agent can do means changing which rows are composed for it. +## Off-limits + +**Never edit, delete, or overwrite a preset that ships with the deployment** — the `agent-presets` directory beside the deployment's own config, which supplies `standard`, `code`, `minimal`, and `cordis`. Never escalate the sandbox to reach it, even when a change there looks quicker. An upgrade overwrites that install, and corrupting `cordis` disables preset authoring itself. Reading a shipped composition is the intended way to start; writing to one is not, and neither is editing the host composition to work around a preset limitation. + +To change what a shipped preset does, copy it and edit the copy. Locally authored presets under the user root are yours to create, edit, and delete. + ## Decide the plane first Two planes, and the choice is not about how "agent-related" something feels — it is about whether the thing must be shared. @@ -17,16 +23,105 @@ Two planes, and the choice is not about how "agent-related" something feels — **A service with a consumer outside the agent plane cannot move into a preset.** `subagents` is the worked example: the registry answers cross-session queries for the host api-proxy, so a per-session copy both starves that host row — it waits forever for a service nothing provides — and collides on the second session, since a provider name registers once. The preset contributes the delegation *tools*; the registry and its backends stay host-side. -A preset is a directory holding one `agent.cordis.yml`, optionally beside a `preset.yml` carrying display metadata — `name` and `description` (and, for shipped presets, a roster `order`). Write the metadata too: a preset without it shows up in every picker as its bare directory name. The shipped presets live beside the deployment's composition; locally authored ones live under `${DSH_HOME:-$HOME/.dsh}/.agent-presets//`. +A preset is a directory holding one `agent.cordis.yml`, optionally beside a `preset.yml` carrying display metadata — `name` and `description` (and, for shipped presets, a roster `order`). Write the metadata too: a preset without it shows up in every picker as its bare directory name. + +Locally authored presets live one directory per preset under `${DSH_HOME:-$HOME/.dsh}/.agent-presets/`, and the shipped set sits beside the deployment's own config. Use those when the user asks where to look. Both roots are configuration rather than fixed locations, though, and no call reports them — `authorable` says only whether a writable one exists — so take the path you actually read or edit from `list()` or `resolve()`, which is also where `copy()` reports what it just created. + +## The roster service + +`ctx.agentPresets` owns discovery, authoring, and mounting. You reach it by mounting a temporary plugin that injects it and registers a tool for yourself — `cordis_mount` returns only the mount acknowledgement, so a registered tool is how a service answer gets back to you, and it becomes callable on your next step. + +Read `cordis_inspect what:"api" name:"agentPresets"` for the current signatures before writing the code. The four calls this skill relies on: + +- `list()` — every preset with its `id`, `trust` (`system` for the shipped set, `user` for authored ones), and the absolute `path` of its composition file. This is how you locate any composition without knowing the install layout; the directory is that path's parent. +- `read(id)` — one preset's composition text, without a file tool or a path. +- `copy(from, id, name?)` — the only authoring write (see below). +- `standingKeyFor(id)` — mount-validate one preset (see below). + +```js +return { + name: 'preset-tools', + inject: ['agentPresets', 'tools'], + apply(ctx) { + harness.registerTool(ctx, harness.defineTool({ + name: 'preset_check', + description: 'Mount-validate one preset by id.', + parameters: { id: { type: 'string', required: true } }, + output: { schema: { type: 'string' }, render(_a, v) { return [{ type: 'text', text: v }] } }, + async execute(args) { + try { + await ctx.agentPresets.standingKeyFor(args.id) + return 'mounted OK' + } catch (error) { + return error.message + } + }, + })) + }, +} +``` + +Unmount the plugin with `cordis_unmount` when you are done; it is a probe, not a capability to leave behind. ## Authoring a preset -1. **Start from a copy.** Read a shipped composition close to what you want (the `standard` preset is the full coding agent) and copy its whole directory into `${DSH_HOME:-$HOME/.dsh}/.agent-presets//` — the id must be lowercase letters, digits, and hyphens, because it becomes the directory name. A composition written from scratch usually forgets a group realm or a consumer row; a copy starts loadable. -2. **Expect the file sandbox.** The preset root lies outside the session workspace, so under the default `workspace-write` policy the first write is denied. Retry that exact command once with `sandbox_permissions` escalation and a short justification — the user sees and approves it. Batch your writes (one heredoc per file) rather than escalating many small commands. -3. **Rewrite `preset.yml`**: give the copy its own `name` and `description`, and drop any `order` the source declared — that field sorts the shipped roster. -4. **Edit `agent.cordis.yml`** row by row, keeping the plane rule and realm rule above. +1. **Start from a copy.** `copy(from, id, name)` copies a whole preset directory into the user root — composition, metadata, skill directories, assets. It validates the id against `[a-z0-9][a-z0-9-]*` (it becomes the directory name, so no leading hyphen), refuses an id any root already supplies, rolls a failed copy back, and rewrites the copy's `preset.yml` to keep the source's description while dropping its name and roster `order`. Prefer it over a shell copy: it needs no sandbox escalation, it lands the copy in whichever root this deployment made writable, and the copy is exactly as loadable as its source. `resolve(id)` then names the file it created — that path, not a guessed one, is what the following edits target. `standard` is the full coding agent and the usual source. +2. **Expect the file sandbox on every edit after the copy.** The user preset root lies outside the session workspace, so under the default `workspace-write` policy the first write there is denied. Only writes are: reading any composition by absolute path needs no escalation. Retry that exact command once with `sandbox_permissions` escalation and a short justification — the user sees and approves it. Batch your writes (one heredoc per file) rather than escalating many small commands. `copy()` itself runs host-side and needs none of this; the edits do. +3. **Write the copy's `description`** in `preset.yml`, and its `name` if you passed none to `copy()`. +4. **Edit `agent.cordis.yml`** row by row, keeping the plane rule and the realm rule. +5. **Mount-validate the result**, then hand off to the user for a real session — both under *Verifying a change*. -### Native product subagents +A composition written from scratch usually forgets a group realm or a consumer row; a copy starts loadable. + +## The rule that catches people + +**A row that publishes a service may not sit loose in a preset.** Registering a service without an isolate realm puts it in the process-global realm, so the second session mounting that preset collides with the first. The mount rejects it rather than letting the collision surface later. + +Whether a row publishes a service is not visible from its name, and package READMEs are absent from an installed deployment. Read it off the live runtime instead: `cordis_inspect what:"services"` lists every service with the fiber that owns it, so a service attributed to a fiber other than the row you are adding is one that row consumes rather than provides. For a row not in your current composition, mount-validate and read the rejection — it names the offending service. + +When a preset genuinely owns a service, wrap the provider **and every consumer that reaches it** in one group carrying an `isolate` realm. The shipped `standard` composition does this for `workflows`, which nothing outside an agent reads — its `delegation` group, with the delegation tools omitted here: + +```yaml +- id: delegation + name: cordis:group + group: true + isolate: + workflows: true + config: + - id: workflow-workerthread + name: '@deepseek-ai/dsh-workflow-workerthread' + config: + provider: spawn + - id: tool-workflow + name: '@deepseek-ai/dsh-tool-workflow' +``` + +`true` means a realm private to each mounting session. A string label instead joins subtrees into one shared realm; `provide()` still throws on the second registration under that symbol, so a label does not pool instances and is not what a preset needs. + +A consumer left outside the group resolves the host's registry, which the preset did not populate, and then contributes nothing. Mount-validation catches that as a row that never activated. + +Realms are for services a preset owns, not for every group. A host capability the preset only consumes must stay outside a realm, or the row cannot resolve it: `tool-bash`, `tool-tasks`, and `tool-goal` publish nothing and sit loose in `standard`, which explains in comments which host instance each one resolves and why a realm would break it. Wrapping a consumer row in a realm of its own is the same error as leaving one outside its provider's realm. + +## Verifying a change + +**`standingKeyFor(id)` is the check.** It composes the preset's plugin subtree for real — the same mount a session start performs, minus the agent — and rejects the four ways a composition fails: + +- a row whose package does not resolve (`Cannot find package …`); +- a row whose config is invalid (`invalid config: $. missing required value`); +- a row that never activated (`N row(s) did not activate: : waiting for `); +- a service published into the root realm, which arrives as one of two messages. A name the host does not supply lands in the root realm and the mount audit rejects it: `row(s) published process-global service(s) []; a preset service must sit behind an isolate realm or move to the host composition` — this is the shape a preset's own forgotten realm takes. A name the host already supplies collides before the audit: `service "" has been registered at `. Both name the offending service. + +It returns normally when the composition mounts. Run it as the final check on a finished edit rather than after every line: a successful mount installs a standing generation that lives until the process exits, while a failed one disposes its subtree and leaves nothing behind. + +**Do not treat the roster's `broken` field as validation.** `list()` reports `broken` from a shape check — the file parses in the loader's YAML dialect and holds named rows — which every failure above passes. It catches a damaged file, not an unusable composition. + +`cordis_inspect` reports THIS session's composition, so it confirms what a row does in the runtime you are already in, never what your new preset will do. + +After a clean mount-validation, ask the user to start a session on the new preset and confirm the tool list; the preset decides tool schemas and prompt sections, and only a real session shows the agent that composition produces. + +`cordis_mount` evaluates JavaScript against the live runtime and disappears on restart. It is for probing, not for shipping a capability: a capability belongs in a composition file. + +## Native product subagents Codex and Claude Code providers already live in the host composition. A preset chooses either product by contributing the same ordinary delegation-tool row used for spawn and fork; never move a product provider into the preset and never add a product-specific settings field. @@ -54,43 +149,6 @@ Copy these disabled templates from a shipped full preset and remove `disabled` o The two rows are independent. Leaving both disabled preserves the copied preset, enabling one exposes only that product tool, and enabling both exposes both. The host must provide `codex` or `claude` on `PATH`; the preset does not install, authenticate, select a model for, or probe either product. -The shipped preset directories are off-limits: never edit or delete them, and never escalate the sandbox to reach them, even when a change there looks quicker — an upgrade overwrites the install, and corrupting the `cordis` preset disables preset authoring itself. Locally authored presets under the user root are yours to create, edit, and delete. - -## The rule that catches people - -**A row that publishes a service may not sit loose in a preset.** Registering a service without an isolate realm puts it in the process-global realm, so the second session mounting that preset collides with the first. The mount rejects it rather than letting the collision surface later. - -Whether a row publishes a service is not visible from its name. `tool-bash` reads like a tool but provides `bashEnv`. Check the package's README, or mount the preset and read the rejection — it names the offending service. - -When a preset genuinely owns a service, wrap the provider **and every consumer that reaches it** in one group carrying an `isolate` realm: - -```yaml -- id: tasks - name: cordis:group - group: true - isolate: - tasks: true - config: - - id: tasks-local - name: '@deepseek-ai/dsh-tasks-local' - - id: tool-tasks - name: '@deepseek-ai/dsh-tool-tasks' -``` - -`true` means a realm private to each mounting session. A string label instead pools one instance across every subtree naming that label — use it only for something genuinely expensive to duplicate. - -A consumer left outside the group resolves the host's registry, which the preset did not populate, and then contributes nothing. That is the quietest failure here: the mount succeeds and a tool is simply missing. - -Host capabilities exposed through registries need no realm: the host `tools` and `skills` registries are layered per scope, so rows like `skill-local` and `tool-skill` sit loose in the preset and their registrations file into this preset's layer automatically — the agent's catalog merges them with whatever the deployment registered globally. - -## Verifying a change - -Read the live runtime with `cordis_inspect` — it reports the services, the plugin fibers, and the registered tools as they actually are, which is the only reliable check that a row did what its name suggests. Note it shows THIS session's composition: a preset you just wrote is not mounted anywhere until a session starts on it. - -To check a preset you authored, re-read the files and validate these fields: the top level is a YAML list, every row is a map with a `name`, every group carries its own list, and service-publishing rows sit behind an `isolate` realm. The settings page's preset roster validates the same fields and marks an unloadable preset broken in red — point the user there, and ask them to start a session on the new preset to confirm the tool list; you cannot start one yourself. - -`cordis_mount` evaluates JavaScript against the live runtime and disappears on restart. It is for probing, not for shipping a capability: a capability belongs in a composition file. - ## What not to move into a preset `agent-loop` registers the one agent factory and throws on a second. The registries own the per-session layering and cannot themselves be per-session. Session persistence must stay host-side or the session list fragments. The sandbox, approval, and permission rows are a deliberate boundary: a preset is exactly as privileged as the plugins it names, so letting one relax its own confinement would defeat the confinement. diff --git a/apps/web/tests/image-display.snapshot.ts b/apps/web/tests/image-display.snapshot.ts index df286ec1c3..2d2dda42d6 100644 --- a/apps/web/tests/image-display.snapshot.ts +++ b/apps/web/tests/image-display.snapshot.ts @@ -4,7 +4,7 @@ // Opens the fixture history session whose turn 72 carries an image in BOTH a // user message and an assistant message, and pins the product surfaces: the // history ImageGallery loading real fixture bytes through the authorized -// sessions.attachment route, the double-click ImageLightbox, and the composer +// sessions.attachment route, the single-click ImageLightbox, and the composer // intake chain (paste → ordered thumbnail rail → image-only send enablement → remove). import { fireEvent, screen, waitFor, within } from '@testing-library/react' import { expect, it } from 'vitest' @@ -66,10 +66,10 @@ it('renders the history image pair through the authorized attachment route and o `) const userImage = document.querySelector('[data-align="end"] img')! - // Double-click opens the original-size lightbox; Escape/close dismisses it. + // A single click opens the original-size lightbox; Escape/close dismisses it. const frame = userImage.closest('button') if (frame === null) throw new Error('image frame button missing') - fireEvent.doubleClick(frame) + fireEvent.click(frame) const lightbox = await screen.findByRole('dialog') expect(within(lightbox).getByRole('img').getAttribute('src')?.split(':')[0]).toBe('blob') fireEvent.click(within(lightbox).getByRole('button', { name: /Close/ })) @@ -133,4 +133,18 @@ it('accepts pasted images into the composer rail in order and removes them', asy await waitFor(() => { expect(document.querySelector('[role="group"][aria-label="Pending images"]')).toBeNull() }) + + // An unsupported file announces a transient toast (the inline strip is + // gone) and the banner dismisses itself after its hold-and-fade lifetime. + fireEvent.paste(textarea, { + clipboardData: { + items: [{ kind: 'file', type: 'text/plain', getAsFile: () => new File(['x'], 'notes.txt', { type: 'text/plain' }) }], + getData: () => '', + }, + }) + const toast = await screen.findByRole('alert') + expect(toast.textContent).toContain('Unsupported image format: text/plain') + await waitFor(() => { + expect(screen.queryByRole('alert')).toBeNull() + }, { timeout: 6_000 }) }) diff --git a/apps/web/tests/plugin-config.e2e.ts b/apps/web/tests/plugin-config.e2e.ts new file mode 100644 index 0000000000..bdad2083aa --- /dev/null +++ b/apps/web/tests/plugin-config.e2e.ts @@ -0,0 +1,176 @@ +// Web e2e scenario: the Plugins settings section — the cards a deployment's +// exposed host-plane namespaces produce, one field edited through the real +// wire down to `$DSH_HOME/settings.yaml`, and the override badge and reset +// that layering produces. Zero model calls: everything is client state plus +// the settings document on a blank frame, so there is no fixture and a stray +// stream would fail loud on the open llm seam. +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { join } from 'node:path' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/plugin-config', import.meta.url)) +const SECTION_EXPECTED = join(SNAPSHOT_DIR, 'section.expected.md') +const MODE = webSnapshotMode() + +describe('web e2e: plugin configuration section', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + browser = await chromium.launch() + // Chinese browser: the section asserts the localized copy the client + // derives from it, as the rest of the settings surface does. + page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + tripwire = watchConsole(page) + await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + /** + * Open the settings dialog on the Plugins section. The scenarios share one + * page so the settings document accumulates across them, so this leaves any + * dialog a previous scenario opened closed first — its mask would otherwise + * swallow the trigger click. + */ + async function openPlugins() { + if (await page.getByRole('dialog', { name: '设置' }).count() > 0) { + await page.keyboard.press('Escape') + await expect.poll(() => page.getByRole('dialog', { name: '设置' }).count(), { timeout: 5_000 }).toBe(0) + } + await page.getByRole('button', { name: '设置', exact: true }).click() + const dialog = page.getByRole('dialog', { name: '设置' }) + await dialog.waitFor({ timeout: 10_000 }) + await dialog.getByRole('button', { name: '插件' }).click() + await expect + .poll(() => dialog.getByRole('button', { name: '插件' }).getAttribute('aria-current'), { timeout: 5_000 }) + .toBe('true') + return dialog + } + + /** The settings document as the Host has written it so far. */ + async function settingsDocument(): Promise { + return readFile(join(scaffold.harnessHome, 'settings.yaml'), 'utf8').catch(() => '') + } + + it('shows one card per exposed host-plane namespace', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-config-cards')) + const dialog = await openPlugins() + + // Every card the shipped web composition exposes: the shell executor, the + // agent loop, and the DeepSeek search provider. + await dialog.getByText('终端', { exact: true }).waitFor({ timeout: 10_000 }) + expect(await dialog.getByText('Agent 循环', { exact: true }).count()).toBe(1) + expect(await dialog.getByText('网页搜索', { exact: true }).count()).toBe(1) + // Collapsed: a card's fields appear only once it is expanded. + expect(await dialog.getByLabel('命令超时(毫秒)').count()).toBe(0) + + const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(SECTION_EXPECTED, snapshot, MODE) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('stages an edit and writes it only when saved', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-config-write')) + const dialog = await openPlugins() + await dialog.getByText('终端', { exact: true }).click() + + const timeout = dialog.getByLabel('命令超时(毫秒)') + await timeout.waitFor({ timeout: 10_000 }) + // The composed default this deployment ships, before any user layer. + expect(await timeout.inputValue()).toBe('60000') + await timeout.fill('12000') + await timeout.blur() + + // Nothing crosses the wire until the user saves: leaving the control is + // not a decision to store the value. + expect(await settingsDocument()).not.toContain('timeoutMs') + const save = dialog.getByRole('button', { name: '保存', exact: true }) + await expect.poll(() => save.isEnabled(), { timeout: 5_000 }).toBe(true) + await save.click() + + await expect.poll(async () => (await settingsDocument()).includes('timeoutMs: 12000'), { timeout: 10_000 }) + .toBe(true) + // Presence in the user layer is what the badge reports, and the reset is + // offered only for a field that has one. + await expect.poll(() => dialog.getByText('已覆盖').count(), { timeout: 5_000 }).toBe(1) + expect(await dialog.getByRole('button', { name: '恢复默认' }).count()).toBe(1) + // A settled form offers no save to repeat. + await expect.poll(() => save.isDisabled(), { timeout: 5_000 }).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('drops a staged edit on discard without touching the document', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-config-discard')) + const dialog = await openPlugins() + await dialog.getByText('终端', { exact: true }).click() + const timeout = dialog.getByLabel('命令超时(毫秒)') + await timeout.waitFor({ timeout: 10_000 }) + + await timeout.fill('7000') + await dialog.getByRole('button', { name: '放弃修改' }).click() + + await expect.poll(() => timeout.inputValue(), { timeout: 5_000 }).toBe('12000') + expect(await settingsDocument()).toContain('timeoutMs: 12000') + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('refuses to save a draft that is not a number', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-config-invalid')) + const dialog = await openPlugins() + await dialog.getByText('终端', { exact: true }).click() + const timeout = dialog.getByLabel('命令超时(毫秒)') + await timeout.waitFor({ timeout: 10_000 }) + + await timeout.fill('soon') + + const save = dialog.getByRole('button', { name: '保存', exact: true }) + await expect.poll(() => save.isDisabled(), { timeout: 5_000 }).toBe(true) + expect(await dialog.getByText('请填数字;留空表示使用默认值。').count()).toBe(1) + await dialog.getByRole('button', { name: '放弃修改' }).click() + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('clears the field back to the composed default on reset', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-config-reset')) + const dialog = await openPlugins() + await dialog.getByText('终端', { exact: true }).click() + const timeout = dialog.getByLabel('命令超时(毫秒)') + await timeout.waitFor({ timeout: 10_000 }) + expect(await timeout.inputValue()).toBe('12000') + + // The reset stages the composed default; the document still carries the + // override until the save lands. + await dialog.getByRole('button', { name: '恢复默认' }).click() + await expect.poll(() => timeout.inputValue(), { timeout: 5_000 }).toBe('60000') + expect(await settingsDocument()).toContain('timeoutMs: 12000') + + await dialog.getByRole('button', { name: '保存', exact: true }).click() + + await expect.poll(async () => (await settingsDocument()).includes('timeoutMs'), { timeout: 10_000 }) + .toBe(false) + expect(await timeout.inputValue()).toBe('60000') + expect(await dialog.getByText('已覆盖').count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => { + expect(tripwire.warnings).toEqual([]) + await assertFixtureInventory(SNAPSHOT_DIR, ['section.expected.md']) + }) +}) diff --git a/apps/web/tests/snapshots/agent-preset-authoring/created.expected.md b/apps/web/tests/snapshots/agent-preset-authoring/created.expected.md index 0ddc4dd77b..fc96442a85 100644 --- a/apps/web/tests/snapshots/agent-preset-authoring/created.expected.md +++ b/apps/web/tests/snapshots/agent-preset-authoring/created.expected.md @@ -10,6 +10,9 @@ - button "Agent 预设": - img - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 - button "打开配置文件" - button "关闭": - img diff --git a/apps/web/tests/snapshots/agent-preset-authoring/damaged.expected.md b/apps/web/tests/snapshots/agent-preset-authoring/damaged.expected.md index f853cacf24..b8136ec702 100644 --- a/apps/web/tests/snapshots/agent-preset-authoring/damaged.expected.md +++ b/apps/web/tests/snapshots/agent-preset-authoring/damaged.expected.md @@ -10,6 +10,9 @@ - button "Agent 预设": - img - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 - button "打开配置文件" - button "关闭": - img diff --git a/apps/web/tests/snapshots/agent-preset-authoring/section.expected.md b/apps/web/tests/snapshots/agent-preset-authoring/section.expected.md index ad2bf86389..9bc3d8db4d 100644 --- a/apps/web/tests/snapshots/agent-preset-authoring/section.expected.md +++ b/apps/web/tests/snapshots/agent-preset-authoring/section.expected.md @@ -10,6 +10,9 @@ - button "Agent 预设": - img - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 - button "打开配置文件" - button "关闭": - img diff --git a/apps/web/tests/snapshots/models-settings/configured.expected.md b/apps/web/tests/snapshots/models-settings/configured.expected.md index 02746c7f76..e4fb6e13e8 100644 --- a/apps/web/tests/snapshots/models-settings/configured.expected.md +++ b/apps/web/tests/snapshots/models-settings/configured.expected.md @@ -10,6 +10,9 @@ - button "Agent 预设": - img - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 - button "打开配置文件" - button "关闭": - img diff --git a/apps/web/tests/snapshots/models-settings/declared-edit.expected.md b/apps/web/tests/snapshots/models-settings/declared-edit.expected.md index e36c7ff2e8..1acd03b4aa 100644 --- a/apps/web/tests/snapshots/models-settings/declared-edit.expected.md +++ b/apps/web/tests/snapshots/models-settings/declared-edit.expected.md @@ -10,6 +10,9 @@ - button "Agent 预设": - img - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 - button "打开配置文件" - button "关闭": - img diff --git a/apps/web/tests/snapshots/models-settings/declared.expected.md b/apps/web/tests/snapshots/models-settings/declared.expected.md index 857bfaf13e..b126a5025b 100644 --- a/apps/web/tests/snapshots/models-settings/declared.expected.md +++ b/apps/web/tests/snapshots/models-settings/declared.expected.md @@ -10,6 +10,9 @@ - button "Agent 预设": - img - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 - button "打开配置文件" - button "关闭": - img diff --git a/apps/web/tests/snapshots/models-settings/empty.expected.md b/apps/web/tests/snapshots/models-settings/empty.expected.md index 03169f8e72..5a1dba54ee 100644 --- a/apps/web/tests/snapshots/models-settings/empty.expected.md +++ b/apps/web/tests/snapshots/models-settings/empty.expected.md @@ -10,6 +10,9 @@ - button "Agent 预设": - img - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 - button "打开配置文件" - button "关闭": - img diff --git a/apps/web/tests/snapshots/onboarding-deepseek-config/models.expected.md b/apps/web/tests/snapshots/onboarding-deepseek-config/models.expected.md index e50c347966..2624f4db70 100644 --- a/apps/web/tests/snapshots/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/snapshots/onboarding-deepseek-config/models.expected.md @@ -10,6 +10,9 @@ - button "Agent 预设": - img - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 - button "打开配置文件" - button "关闭": - img diff --git a/apps/web/tests/snapshots/plugin-config/section.expected.md b/apps/web/tests/snapshots/plugin-config/section.expected.md new file mode 100644 index 0000000000..7d10d05cd1 --- /dev/null +++ b/apps/web/tests/snapshots/plugin-config/section.expected.md @@ -0,0 +1,34 @@ +- dialog "设置": + - navigation: + - text: 设置 + - button "通用设置": + - img + - text: 通用设置 + - button "模型": + - img + - text: 模型 + - button "Agent 预设": + - img + - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 + - button "打开配置文件" + - button "关闭": + - img + - text: 关闭 + - heading "插件配置" [level=2] + - paragraph: 配置本部署已安装的插件。 + - list: + - listitem: + - 'button "展开设置: 终端"': + - text: 终端 限制 agent 运行的每一条命令。 + - img + - listitem: + - 'button "展开设置: Agent 循环"': + - text: Agent 循环 Agent 如何派发工具调用。 + - img + - listitem: + - 'button "展开设置: 网页搜索"': + - text: 网页搜索 DeepSeek 搜索提供方。 + - img diff --git a/apps/web/tests/snapshots/settings-chrome/dialog.expected.md b/apps/web/tests/snapshots/settings-chrome/dialog.expected.md index cf87f5acbd..914293aee3 100644 --- a/apps/web/tests/snapshots/settings-chrome/dialog.expected.md +++ b/apps/web/tests/snapshots/settings-chrome/dialog.expected.md @@ -10,6 +10,9 @@ - button "Agent 预设": - img - text: Agent 预设 + - button "插件配置": + - img + - text: 插件配置 - button "打开配置文件" - button "关闭": - img diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 45218c165b..99e6f906f7 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -36,6 +36,7 @@ "tests/trajectory-virtualization.e2e.ts", "tests/lifecycle-chrome.e2e.ts", "tests/details-session-lifecycle.e2e.ts", + "tests/plugin-config.e2e.ts", "tests/settings-chrome.e2e.ts", "tests/models-settings.e2e.ts", "tests/default-model.e2e.ts", diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 08e12b2e97..7b9ef7a15b 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -143,6 +143,7 @@ export default defineConfig({ { find: /^@deepseek-ai\/dsh-client-web-react$/, replacement: src('../../packages/client/web-react/src/index.ts') }, { find: /^@deepseek-ai\/dsh-client-ui-slots$/, replacement: src('../../packages/client/ui-slots/src/index.ts') }, { find: /^@deepseek-ai\/dsh-client-ui-primitives$/, replacement: src('../../packages/client/ui-primitives/src/index.ts') }, + { find: /^@deepseek-ai\/dsh-client-ui-attachment$/, replacement: src('../../packages/client/ui-attachment/src/index.ts') }, { find: /^@deepseek-ai\/dsh-client-schema-form$/, replacement: src('../../packages/client/schema-form/src/index.ts') }, { find: /^@deepseek-ai\/dsh-client-modules\/client$/, replacement: src('../../packages/client/modules/src/client/index.ts') }, ], diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 56590143db..2b0f494ca6 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: b6e27b0915b09430dd22dcc9054e43e62728a1d3 -config-catalog.zh.md: c1ae11dca2389eb8cd3d2f109aa3b31e14199aac +config-catalog.md: 01c942493ad81eb978ff269bee544bbb1560c819 +config-catalog.zh.md: 4be30ea40432e71e2fc53fd17fae107fd631fa06 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index b6e27b0915..01c942493a 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -122,7 +122,7 @@ export interface Config { Depends on: [`AgentOptions`](subsystems/core.md) · [`SessionId`](subsystems/core.md) -Source: [`packages/core/agent-loop/src/index.ts:236`](../packages/core/agent-loop/src/index.ts) +Source: [`packages/core/agent-loop/src/index.ts:255`](../packages/core/agent-loop/src/index.ts) ## `@deepseek-ai/dsh-agent-presets` @@ -315,7 +315,7 @@ export interface Config { } ``` -Source: [`packages/bash/bash-local/src/index.ts:40`](../packages/bash/bash-local/src/index.ts) +Source: [`packages/bash/bash-local/src/index.ts:41`](../packages/bash/bash-local/src/index.ts) ## `@deepseek-ai/dsh-bash-sandbox` @@ -1292,7 +1292,7 @@ export interface Config { } ``` -Source: [`packages/bash/pwsh-local/src/index.ts:54`](../packages/bash/pwsh-local/src/index.ts) +Source: [`packages/bash/pwsh-local/src/index.ts:58`](../packages/bash/pwsh-local/src/index.ts) ## `@deepseek-ai/dsh-pwsh-sandbox` @@ -2625,7 +2625,7 @@ export interface Config { } ``` -Source: [`packages/web/web-search-deepseek/src/index.ts:44`](../packages/web/web-search-deepseek/src/index.ts) +Source: [`packages/web/web-search-deepseek/src/index.ts:46`](../packages/web/web-search-deepseek/src/index.ts) ## `@deepseek-ai/dsh-web-search-exa` @@ -2747,6 +2747,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-client-ui-models` ([`packages/client/ui-models/src/index.ts`](../packages/client/ui-models/src/index.ts)) - `@deepseek-ai/dsh-client-ui-permission` ([`packages/client/ui-permission/src/index.ts`](../packages/client/ui-permission/src/index.ts)) - `@deepseek-ai/dsh-client-ui-plan` ([`packages/client/ui-plan/src/index.ts`](../packages/client/ui-plan/src/index.ts)) +- `@deepseek-ai/dsh-client-ui-plugin-config` ([`packages/client/ui-plugin-config/src/index.ts`](../packages/client/ui-plugin-config/src/index.ts)) - `@deepseek-ai/dsh-client-ui-question` ([`packages/client/ui-question/src/index.ts`](../packages/client/ui-question/src/index.ts)) - `@deepseek-ai/dsh-client-ui-settings` ([`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts)) - `@deepseek-ai/dsh-client-ui-settings-general` ([`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts)) @@ -2818,6 +2819,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. - `@deepseek-ai/dsh-brand` ([`packages/util/brand/src/index.ts`](../packages/util/brand/src/index.ts)) - `@deepseek-ai/dsh-client-schema-form` ([`packages/client/schema-form/src/index.ts`](../packages/client/schema-form/src/index.ts)) - `@deepseek-ai/dsh-client-test-runtime` ([`packages/client/test-runtime/src/index.ts`](../packages/client/test-runtime/src/index.ts)) +- `@deepseek-ai/dsh-client-ui-attachment` ([`packages/client/ui-attachment/src/index.ts`](../packages/client/ui-attachment/src/index.ts)) - `@deepseek-ai/dsh-client-ui-primitives` ([`packages/client/ui-primitives/src/index.ts`](../packages/client/ui-primitives/src/index.ts)) - `@deepseek-ai/dsh-client-ui-slots` ([`packages/client/ui-slots/src/index.ts`](../packages/client/ui-slots/src/index.ts)) - `@deepseek-ai/dsh-client-web` ([`packages/client/web/src/index.ts`](../packages/client/web/src/index.ts)) diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index c1ae11dca2..4be30ea404 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2748,6 +2748,7 @@ export interface Config { - `@deepseek-ai/dsh-client-ui-models`([`packages/client/ui-models/src/index.ts`](../packages/client/ui-models/src/index.ts)) - `@deepseek-ai/dsh-client-ui-permission`([`packages/client/ui-permission/src/index.ts`](../packages/client/ui-permission/src/index.ts)) - `@deepseek-ai/dsh-client-ui-plan`([`packages/client/ui-plan/src/index.ts`](../packages/client/ui-plan/src/index.ts)) +- `@deepseek-ai/dsh-client-ui-plugin-config`([`packages/client/ui-plugin-config/src/index.ts`](../packages/client/ui-plugin-config/src/index.ts)) - `@deepseek-ai/dsh-client-ui-question`([`packages/client/ui-question/src/index.ts`](../packages/client/ui-question/src/index.ts)) - `@deepseek-ai/dsh-client-ui-settings`([`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts)) - `@deepseek-ai/dsh-client-ui-settings-general`([`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts)) @@ -2818,6 +2819,7 @@ export interface Config { - `@deepseek-ai/dsh-brand`([`packages/util/brand/src/index.ts`](../packages/util/brand/src/index.ts)) - `@deepseek-ai/dsh-client-schema-form`([`packages/client/schema-form/src/index.ts`](../packages/client/schema-form/src/index.ts)) - `@deepseek-ai/dsh-client-test-runtime`([`packages/client/test-runtime/src/index.ts`](../packages/client/test-runtime/src/index.ts)) +- `@deepseek-ai/dsh-client-ui-attachment`([`packages/client/ui-attachment/src/index.ts`](../packages/client/ui-attachment/src/index.ts)) - `@deepseek-ai/dsh-client-ui-primitives`([`packages/client/ui-primitives/src/index.ts`](../packages/client/ui-primitives/src/index.ts)) - `@deepseek-ai/dsh-client-ui-slots`([`packages/client/ui-slots/src/index.ts`](../packages/client/ui-slots/src/index.ts)) - `@deepseek-ai/dsh-client-web`([`packages/client/web/src/index.ts`](../packages/client/web/src/index.ts)) diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml index d56a4dcd28..9ce7b9c983 100644 --- a/docs/event-producer-consumer.i18n.yaml +++ b/docs/event-producer-consumer.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/event-producer-consumer.md -event-producer-consumer.md: 05f0ebfeba307cd4bf5f9fa061bc728593960424 +event-producer-consumer.md: d3c02ec849c73314da05697921a4fd1adac8fcb2 event-producer-consumer.zh.md: c75dda333a2064b76ea35477d9f5be2583fd5238 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 05f0ebfeba..d3c02ec849 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -7,7 +7,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:182`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | +| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:183`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-presets/src/types.ts:13`](../packages/preset/agent-presets/src/types.ts) | [`agent-presets`](../packages/preset/agent-presets) (`emit`) | `apiproxy` | | `agent/created` | `emit` | [`packages/core/agent/src/runtime-types.ts:159`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-presets`](../packages/preset/agent-presets), [`goal-session`](../packages/goal/goal-session) | | `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:168`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), [`goal-session`](../packages/goal/goal-session), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/module-graph.i18n.yaml b/docs/module-graph.i18n.yaml index e4459fed5e..e898eb7bda 100644 --- a/docs/module-graph.i18n.yaml +++ b/docs/module-graph.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/module-graph.md -module-graph.md: 6a8ca06626c5c2604bfb4b0d8b9db2020cc8f78c -module-graph.zh.md: d62f8cd071af392693a08a3a1cd266fed33cc796 +module-graph.md: 994d7add39d2cf2f82d0fcfb745d2745aa4428e6 +module-graph.zh.md: d5176cb71e8ff7e29e8442bdd7e2724712977610 diff --git a/docs/module-graph.md b/docs/module-graph.md index 6a8ca06626..994d7add39 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -149,6 +149,7 @@ flowchart TD pkg_client_schema_form["client-schema-form"] pkg_client_test_runtime["client-test-runtime"] pkg_client_ui_agent_preset["client-ui-agent-preset"] + pkg_client_ui_attachment["client-ui-attachment"] pkg_client_ui_command["client-ui-command"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -158,6 +159,7 @@ flowchart TD pkg_client_ui_models["client-ui-models"] pkg_client_ui_permission["client-ui-permission"] pkg_client_ui_plan["client-ui-plan"] + pkg_client_ui_plugin_config["client-ui-plugin-config"] pkg_client_ui_primitives["client-ui-primitives"] pkg_client_ui_question["client-ui-question"] pkg_client_ui_settings["client-ui-settings"] @@ -318,6 +320,7 @@ flowchart TD pkg_base --> pkg_invariants pkg_client_modules --> pkg_invariants pkg_client_schema_form --> pkg_invariants + pkg_client_ui_attachment --> pkg_invariants pkg_client_ui_primitives --> pkg_invariants pkg_client_ui_slots --> pkg_invariants pkg_client_web --> pkg_invariants @@ -478,6 +481,7 @@ flowchart TD pkg_goal --> pkg_type_meta pkg_bash --> pkg_invariants pkg_bash --> pkg_sandbox + pkg_bash --> pkg_settings pkg_bash --> pkg_subprocess pkg_fs --> pkg_brand pkg_fs --> pkg_invariants @@ -488,6 +492,7 @@ flowchart TD pkg_web_search_deepseek --> pkg_environment pkg_web_search_deepseek --> pkg_invariants pkg_web_search_deepseek --> pkg_session + pkg_web_search_deepseek --> pkg_settings pkg_web_search_deepseek --> pkg_web pkg_spill_local --> pkg_invariants pkg_spill_local --> pkg_spill @@ -592,10 +597,12 @@ flowchart TD pkg_goal_session --> pkg_session pkg_bash_local --> pkg_bash pkg_bash_local --> pkg_invariants + pkg_bash_local --> pkg_settings pkg_bash_local --> pkg_subprocess pkg_bash_local --> pkg_timeout pkg_pwsh_local --> pkg_bash pkg_pwsh_local --> pkg_invariants + pkg_pwsh_local --> pkg_settings pkg_pwsh_local --> pkg_subprocess pkg_pwsh_local --> pkg_timeout pkg_fs_local --> pkg_fs @@ -699,6 +706,7 @@ flowchart TD pkg_agent_loop --> pkg_scope pkg_agent_loop --> pkg_session pkg_agent_loop --> pkg_session_persistence + pkg_agent_loop --> pkg_settings pkg_agent_loop --> pkg_system_prompt pkg_agent_loop --> pkg_tools pkg_agent_tool_mode --> pkg_invariants @@ -1062,6 +1070,15 @@ flowchart TD pkg_subagent_spawn --> pkg_invariants pkg_subagent_spawn --> pkg_subagent pkg_subagent_spawn --> pkg_subagent_inprocess + pkg_client_ui_plugin_config --> pkg_api_remotes + pkg_client_ui_plugin_config --> pkg_client_connection + pkg_client_ui_plugin_config --> pkg_client_locale + pkg_client_ui_plugin_config --> pkg_client_runtime + pkg_client_ui_plugin_config --> pkg_client_ui_primitives + pkg_client_ui_plugin_config --> pkg_client_ui_settings + pkg_client_ui_plugin_config --> pkg_client_ui_slots + pkg_client_ui_plugin_config --> pkg_client_web_react + pkg_client_ui_plugin_config --> pkg_invariants pkg_client_ui_question --> pkg_client_locale pkg_client_ui_question --> pkg_invariants pkg_client_ui_sidebar --> pkg_client_locale @@ -1143,6 +1160,7 @@ flowchart TD pkg_client_ui_conversation --> pkg_client_connection pkg_client_ui_conversation --> pkg_client_locale pkg_client_ui_conversation --> pkg_client_runtime + pkg_client_ui_conversation --> pkg_client_ui_attachment pkg_client_ui_conversation --> pkg_client_ui_primitives pkg_client_ui_conversation --> pkg_client_ui_settings pkg_client_ui_conversation --> pkg_client_ui_slash @@ -1312,6 +1330,7 @@ flowchart TD | [`base`](../packages/bundle/base) | `bundle` | [`invariants`](../packages/support/invariants) | | [`client-modules`](../packages/client/modules) | `client` | [`invariants`](../packages/support/invariants) | | [`client-schema-form`](../packages/client/schema-form) | `client` | [`invariants`](../packages/support/invariants) | +| [`client-ui-attachment`](../packages/client/ui-attachment) | `client` | [`invariants`](../packages/support/invariants) | | [`client-ui-primitives`](../packages/client/ui-primitives) | `client` | [`invariants`](../packages/support/invariants) | | [`client-ui-slots`](../packages/client/ui-slots) | `client` | [`invariants`](../packages/support/invariants) | | [`client-web`](../packages/client/web) | `client` | [`invariants`](../packages/support/invariants) | @@ -1369,9 +1388,9 @@ flowchart TD | [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | | [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`settings`](../packages/settings/settings) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`type-meta`](../packages/typert/type-meta) | -| [`bash`](../packages/bash/bash) | `bash` | [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`subprocess`](../packages/subprocess/subprocess) | +| [`bash`](../packages/bash/bash) | `bash` | [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | -| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`environment`](../packages/util/environment), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`web`](../packages/web/web) | +| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`environment`](../packages/util/environment), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`invariants`](../packages/support/invariants), [`spill`](../packages/spill/spill) | | [`loader-smoke`](../packages/support/loader-smoke) | `support` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session) | @@ -1394,8 +1413,8 @@ flowchart TD | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants) | | [`goal-session`](../packages/goal/goal-session) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`bash-local`](../packages/bash/bash-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | -| [`pwsh-local`](../packages/bash/pwsh-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`bash-local`](../packages/bash/bash-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`pwsh-local`](../packages/bash/pwsh-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants) | | [`fs-policy`](../packages/fs/fs-policy) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants) | | [`skill-local`](../packages/skill/skill-local) | `skill` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`skill`](../packages/skill/skill) | @@ -1415,7 +1434,7 @@ flowchart TD | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`tasks-local`](../packages/tasks/tasks-local) | `tasks` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`scope`](../packages/core/scope), [`tasks`](../packages/tasks/tasks), [`timeout`](../packages/util/timeout) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | -| [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`agent-tool-mode`](../packages/core/agent-tool-mode) | `core` | [`invariants`](../packages/support/invariants), [`tools`](../packages/core/tools) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`bash-env`](../packages/bash/bash-env) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | @@ -1475,6 +1494,7 @@ flowchart TD | [`subagent-codex`](../packages/subagent/subagent-codex) | `subagent` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-fork`](../packages/subagent/subagent-fork) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | | [`subagent-spawn`](../packages/subagent/subagent-spawn) | `subagent` | [`invariants`](../packages/support/invariants), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | +| [`client-ui-plugin-config`](../packages/client/ui-plugin-config) | `client` | [`api-remotes`](../packages/api/remotes), [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web-react`](../packages/client/web-react), [`invariants`](../packages/support/invariants) | | [`client-ui-question`](../packages/client/ui-question) | `client` | [`client-locale`](../packages/client/locale), [`invariants`](../packages/support/invariants) | | [`client-ui-sidebar`](../packages/client/ui-sidebar) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-slash`](../packages/client/ui-slash) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | @@ -1485,7 +1505,7 @@ flowchart TD | [`jsonrpc`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | -| [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | [`agent`](../packages/core/agent), [`api-remotes`](../packages/api/remotes), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`commands`](../packages/interaction/commands), [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm-retry`](../packages/llm/llm-retry), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | +| [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | [`agent`](../packages/core/agent), [`api-remotes`](../packages/api/remotes), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-attachment`](../packages/client/ui-attachment), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`commands`](../packages/interaction/commands), [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm-retry`](../packages/llm/llm-retry), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | | [`client-ui-layout`](../packages/client/ui-layout) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-theme`](../packages/client/ui-theme), [`invariants`](../packages/support/invariants) | | [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | [`api-remotes`](../packages/api/remotes), [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-sidebar`](../packages/client/ui-sidebar), [`client-ui-slots`](../packages/client/ui-slots), [`client-web-react`](../packages/client/web-react), [`invariants`](../packages/support/invariants) | | [`acp-demo`](../packages/examples/acp-demo) | `examples` | [`acp`](../packages/acp/acp), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/boot/app-boot), [`invariants`](../packages/support/invariants), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index d62f8cd071..d5176cb71e 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -151,6 +151,7 @@ flowchart TD pkg_client_schema_form["client-schema-form"] pkg_client_test_runtime["client-test-runtime"] pkg_client_ui_agent_preset["client-ui-agent-preset"] + pkg_client_ui_attachment["client-ui-attachment"] pkg_client_ui_command["client-ui-command"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] @@ -160,6 +161,7 @@ flowchart TD pkg_client_ui_models["client-ui-models"] pkg_client_ui_permission["client-ui-permission"] pkg_client_ui_plan["client-ui-plan"] + pkg_client_ui_plugin_config["client-ui-plugin-config"] pkg_client_ui_primitives["client-ui-primitives"] pkg_client_ui_question["client-ui-question"] pkg_client_ui_settings["client-ui-settings"] @@ -320,6 +322,7 @@ flowchart TD pkg_base --> pkg_invariants pkg_client_modules --> pkg_invariants pkg_client_schema_form --> pkg_invariants + pkg_client_ui_attachment --> pkg_invariants pkg_client_ui_primitives --> pkg_invariants pkg_client_ui_slots --> pkg_invariants pkg_client_web --> pkg_invariants @@ -480,6 +483,7 @@ flowchart TD pkg_goal --> pkg_type_meta pkg_bash --> pkg_invariants pkg_bash --> pkg_sandbox + pkg_bash --> pkg_settings pkg_bash --> pkg_subprocess pkg_fs --> pkg_brand pkg_fs --> pkg_invariants @@ -490,6 +494,7 @@ flowchart TD pkg_web_search_deepseek --> pkg_environment pkg_web_search_deepseek --> pkg_invariants pkg_web_search_deepseek --> pkg_session + pkg_web_search_deepseek --> pkg_settings pkg_web_search_deepseek --> pkg_web pkg_spill_local --> pkg_invariants pkg_spill_local --> pkg_spill @@ -594,10 +599,12 @@ flowchart TD pkg_goal_session --> pkg_session pkg_bash_local --> pkg_bash pkg_bash_local --> pkg_invariants + pkg_bash_local --> pkg_settings pkg_bash_local --> pkg_subprocess pkg_bash_local --> pkg_timeout pkg_pwsh_local --> pkg_bash pkg_pwsh_local --> pkg_invariants + pkg_pwsh_local --> pkg_settings pkg_pwsh_local --> pkg_subprocess pkg_pwsh_local --> pkg_timeout pkg_fs_local --> pkg_fs @@ -701,6 +708,7 @@ flowchart TD pkg_agent_loop --> pkg_scope pkg_agent_loop --> pkg_session pkg_agent_loop --> pkg_session_persistence + pkg_agent_loop --> pkg_settings pkg_agent_loop --> pkg_system_prompt pkg_agent_loop --> pkg_tools pkg_agent_tool_mode --> pkg_invariants @@ -1064,6 +1072,15 @@ flowchart TD pkg_subagent_spawn --> pkg_invariants pkg_subagent_spawn --> pkg_subagent pkg_subagent_spawn --> pkg_subagent_inprocess + pkg_client_ui_plugin_config --> pkg_api_remotes + pkg_client_ui_plugin_config --> pkg_client_connection + pkg_client_ui_plugin_config --> pkg_client_locale + pkg_client_ui_plugin_config --> pkg_client_runtime + pkg_client_ui_plugin_config --> pkg_client_ui_primitives + pkg_client_ui_plugin_config --> pkg_client_ui_settings + pkg_client_ui_plugin_config --> pkg_client_ui_slots + pkg_client_ui_plugin_config --> pkg_client_web_react + pkg_client_ui_plugin_config --> pkg_invariants pkg_client_ui_question --> pkg_client_locale pkg_client_ui_question --> pkg_invariants pkg_client_ui_sidebar --> pkg_client_locale @@ -1145,6 +1162,7 @@ flowchart TD pkg_client_ui_conversation --> pkg_client_connection pkg_client_ui_conversation --> pkg_client_locale pkg_client_ui_conversation --> pkg_client_runtime + pkg_client_ui_conversation --> pkg_client_ui_attachment pkg_client_ui_conversation --> pkg_client_ui_primitives pkg_client_ui_conversation --> pkg_client_ui_settings pkg_client_ui_conversation --> pkg_client_ui_slash @@ -1314,6 +1332,7 @@ flowchart TD | [`base`](../packages/bundle/base) | `bundle` | [`invariants`](../packages/support/invariants) | | [`client-modules`](../packages/client/modules) | `client` | [`invariants`](../packages/support/invariants) | | [`client-schema-form`](../packages/client/schema-form) | `client` | [`invariants`](../packages/support/invariants) | +| [`client-ui-attachment`](../packages/client/ui-attachment) | `client` | [`invariants`](../packages/support/invariants) | | [`client-ui-primitives`](../packages/client/ui-primitives) | `client` | [`invariants`](../packages/support/invariants) | | [`client-ui-slots`](../packages/client/ui-slots) | `client` | [`invariants`](../packages/support/invariants) | | [`client-web`](../packages/client/web) | `client` | [`invariants`](../packages/support/invariants) | @@ -1371,9 +1390,9 @@ flowchart TD | [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | | [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`settings`](../packages/settings/settings) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`type-meta`](../packages/typert/type-meta) | -| [`bash`](../packages/bash/bash) | `bash` | [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`subprocess`](../packages/subprocess/subprocess) | +| [`bash`](../packages/bash/bash) | `bash` | [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) | | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | -| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`environment`](../packages/util/environment), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`web`](../packages/web/web) | +| [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`environment`](../packages/util/environment), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`web`](../packages/web/web) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`invariants`](../packages/support/invariants), [`spill`](../packages/spill/spill) | | [`loader-smoke`](../packages/support/loader-smoke) | `support` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session) | @@ -1396,8 +1415,8 @@ flowchart TD | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | | [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants) | | [`goal-session`](../packages/goal/goal-session) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | -| [`bash-local`](../packages/bash/bash-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | -| [`pwsh-local`](../packages/bash/pwsh-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`bash-local`](../packages/bash/bash-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`pwsh-local`](../packages/bash/pwsh-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`fs-local`](../packages/fs/fs-local) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants) | | [`fs-policy`](../packages/fs/fs-policy) | `fs` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants) | | [`skill-local`](../packages/skill/skill-local) | `skill` | [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`skill`](../packages/skill/skill) | @@ -1417,7 +1436,7 @@ flowchart TD | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`tasks-local`](../packages/tasks/tasks-local) | `tasks` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`scope`](../packages/core/scope), [`tasks`](../packages/tasks/tasks), [`timeout`](../packages/util/timeout) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | -| [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | +| [`agent-loop`](../packages/core/agent-loop) | `core` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`settings`](../packages/settings/settings), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`agent-tool-mode`](../packages/core/agent-tool-mode) | `core` | [`invariants`](../packages/support/invariants), [`tools`](../packages/core/tools) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`bash-env`](../packages/bash/bash-env) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | @@ -1477,6 +1496,7 @@ flowchart TD | [`subagent-codex`](../packages/subagent/subagent-codex) | `subagent` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`subagent-fork`](../packages/subagent/subagent-fork) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | | [`subagent-spawn`](../packages/subagent/subagent-spawn) | `subagent` | [`invariants`](../packages/support/invariants), [`subagent`](../packages/subagent/subagent), [`subagent-inprocess`](../packages/subagent/subagent-inprocess) | +| [`client-ui-plugin-config`](../packages/client/ui-plugin-config) | `client` | [`api-remotes`](../packages/api/remotes), [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web-react`](../packages/client/web-react), [`invariants`](../packages/support/invariants) | | [`client-ui-question`](../packages/client/ui-question) | `client` | [`client-locale`](../packages/client/locale), [`invariants`](../packages/support/invariants) | | [`client-ui-sidebar`](../packages/client/ui-sidebar) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-slash`](../packages/client/ui-slash) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | @@ -1487,7 +1507,7 @@ flowchart TD | [`jsonrpc`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | -| [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | [`agent`](../packages/core/agent), [`api-remotes`](../packages/api/remotes), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`commands`](../packages/interaction/commands), [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm-retry`](../packages/llm/llm-retry), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | +| [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | [`agent`](../packages/core/agent), [`api-remotes`](../packages/api/remotes), [`attachment`](../packages/attachment/attachment), [`brand`](../packages/util/brand), [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-attachment`](../packages/client/ui-attachment), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`commands`](../packages/interaction/commands), [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm-retry`](../packages/llm/llm-retry), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) | | [`client-ui-layout`](../packages/client/ui-layout) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-theme`](../packages/client/ui-theme), [`invariants`](../packages/support/invariants) | | [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | [`api-remotes`](../packages/api/remotes), [`client-connection`](../packages/client/connection), [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-sidebar`](../packages/client/ui-sidebar), [`client-ui-slots`](../packages/client/ui-slots), [`client-web-react`](../packages/client/web-react), [`invariants`](../packages/support/invariants) | | [`acp-demo`](../packages/examples/acp-demo) | `examples` | [`acp`](../packages/acp/acp), [`agent-spine-demo`](../packages/examples/agent-spine-demo), [`app-boot`](../packages/boot/app-boot), [`invariants`](../packages/support/invariants), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`tools`](../packages/core/tools), [`workspace-context`](../packages/context/workspace-context) | diff --git a/docs/subsystems/bash.i18n.yaml b/docs/subsystems/bash.i18n.yaml index b3cd579b22..7f73736655 100644 --- a/docs/subsystems/bash.i18n.yaml +++ b/docs/subsystems/bash.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/subsystems/bash.md -bash.md: 50e2051778dc0aca5c7b80e1a8b330ae62d4d309 -bash.zh.md: 40ab5b7eea04aeb7c85ab550a8d93ce352fe116e +bash.md: 1f85dc1a0e570b403c5f20c398520eda9ea845e0 +bash.zh.md: 13d382299cc46e00975619dcf3042bea32420222 diff --git a/docs/subsystems/bash.md b/docs/subsystems/bash.md index 50e2051778..1f85dc1a0e 100644 --- a/docs/subsystems/bash.md +++ b/docs/subsystems/bash.md @@ -266,7 +266,7 @@ abstract run(spec: BashExecSpec): Promise abstract start(spec: BashExecSpec): BashProcess ``` -Source: [`packages/bash/bash/src/index.ts:53`](../../packages/bash/bash/src/index.ts) +Source: [`packages/bash/bash/src/index.ts:65`](../../packages/bash/bash/src/index.ts) diff --git a/docs/subsystems/bash.zh.md b/docs/subsystems/bash.zh.md index 40ab5b7eea..13d382299c 100644 --- a/docs/subsystems/bash.zh.md +++ b/docs/subsystems/bash.zh.md @@ -266,7 +266,7 @@ abstract run(spec: BashExecSpec): Promise abstract start(spec: BashExecSpec): BashProcess ``` -Source: [`packages/bash/bash/src/index.ts:53`](../../packages/bash/bash/src/index.ts) +Source: [`packages/bash/bash/src/index.ts:65`](../../packages/bash/bash/src/index.ts) diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 5653d2de4a..ff6ed9b466 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.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/subsystems/core.md -core.md: d3b7f4d3ad9ff4a99383f132b316f64c426f0c59 -core.zh.md: 7a5372b0982e4dbb9dcf83d844ae3a82554664aa +core.md: e52a7619085b2956496be6234f711441902fc259 +core.zh.md: e9cfe19129e33a1c17e87561397b13139a6d7537 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index d3b7f4d3ad..e52a761908 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -375,7 +375,7 @@ async resume(ownerCtx: Context, options: ResumeAgentOptions): Promise @@ -1041,7 +1041,7 @@ A declarative agent entry failed before it could publish a live agent. Consumers 'agent-loop/config-start-failed'(payload: { sessionId: SessionId; error: unknown }): void ``` -Source: [`packages/core/agent-loop/src/index.ts:182`](../../packages/core/agent-loop/src/index.ts) +Source: [`packages/core/agent-loop/src/index.ts:183`](../../packages/core/agent-loop/src/index.ts) diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 7a5372b098..e9cfe19129 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -383,7 +383,7 @@ async resume(ownerCtx: Context, options: ResumeAgentOptions): Promise @@ -1049,7 +1049,7 @@ A declarative agent entry failed before it could publish a live agent. Consumers 'agent-loop/config-start-failed'(payload: { sessionId: SessionId; error: unknown }): void ``` -Source: [`packages/core/agent-loop/src/index.ts:182`](../../packages/core/agent-loop/src/index.ts) +Source: [`packages/core/agent-loop/src/index.ts:183`](../../packages/core/agent-loop/src/index.ts) diff --git a/packages/bash/bash-local/README.i18n.yaml b/packages/bash/bash-local/README.i18n.yaml index ee5a635a16..e826cd5e6c 100644 --- a/packages/bash/bash-local/README.i18n.yaml +++ b/packages/bash/bash-local/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/bash/bash-local/README.md -README.md: 253d1c9efb518ca204956f062b2f529f4e83531b -README.zh.md: 5a0d943a08d1da6c73ad07f469c056180b476ff3 +README.md: 386ffc00466108ab14352b6d39d3a20da3321e1c +README.zh.md: 39d37bededa72ec96911bb1ce055ed105fdd7082 diff --git a/packages/bash/bash-local/README.md b/packages/bash/bash-local/README.md index 253d1c9efb..386ffc0046 100644 --- a/packages/bash/bash-local/README.md +++ b/packages/bash/bash-local/README.md @@ -23,6 +23,7 @@ The package root exports the default and named `LocalBashExecutor` plugin plus i ## Behavior - **Spawn per call, no shell state** — every call is a fresh non-login `bash -c` with no rc files. +- **The composition entry is a layer, not the last word** — when a settings provider is composed, this executor registers the capability's [`bash` namespace](../bash/README.md) with the entry above as its base, so a user section in `settings.yaml` layers over it and the next command runs with the new budgets. Values the schema cannot judge (positive and finite, the `graceMs` timer bound) are refused at the write, leaving the running executor on its last good section; without a provider, or after one detaches, the composition entry is what runs. - **Configured budgets over managed groups** — `resolve()` fills `workdir`/`timeoutMs`/`stdoutMaxBytes` from config, and every spawn hands the service explicit byte caps, spill cap, and `graceMs`. The grace must be positive, finite, and no greater than [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md), so Node can represent it with one timer. Process-group kills, post-exit pipe draining, tail retention, and bounded spill files are [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) mechanics. A foreground `BashExecRequest.stdoutMaxBytes` can raise stdout's capture budget for one trusted caller; stderr and background runs still use `maxOutputBytes`. - **Timeout and cancel classification** — `run()` fuses its config-clamped timeout with the caller's signal through one deadline; only the executor's own timeout reports `timedOut`, an upstream cancel reports `aborted`, and a self-signaled command reports neither ([timeout-library Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md)). - **Model-friendly terminal env** — `NO_COLOR=1 TERM=dumb PAGER=cat GIT_PAGER=cat` prevents pagers and ANSI color from garbling results. These values merge as ordinary env under the service's credential scrub and `DSH_*` channel rules; an explicit caller entry still wins. See the [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.md) and [managed environment Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md). diff --git a/packages/bash/bash-local/README.zh.md b/packages/bash/bash-local/README.zh.md index 5a0d943a08..39d37beded 100644 --- a/packages/bash/bash-local/README.zh.md +++ b/packages/bash/bash-local/README.zh.md @@ -23,6 +23,7 @@ ## 行为 - **每次调用都 spawn,不保留 shell 状态**:每次调用都启动新的非登录 `bash -c`,且不读取 rc 文件。 +- **组装条目是一层,而不是最终值**:当组装中存在 settings 提供方时,本执行器以上面的条目为 base 注册该能力的 [`bash` 命名空间](../bash/README.md),因此 `settings.yaml` 中的用户段会叠加其上,下一条命令即按新预算运行。schema 无法判定的值(正有限、`graceMs` 的定时器上界)会在写入时被拒绝,运行中的执行器保持它最后一份可用的段;没有提供方、或提供方脱离之后,运行的就是组装条目。 - **在受管进程组之上应用配置预算**:`resolve()` 从配置补全 `workdir`/`timeoutMs`/`stdoutMaxBytes`,每次 spawn 都向服务传入显式的字节上限、spill 上限与 `graceMs`。该宽限期须为正有限值,且不得大于 [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md),这样 Node 就能用一个定时器表示它。进程组终止、退出后管道排空、尾部保留与有界 spill 文件是 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 的机制。前台 `BashExecRequest.stdoutMaxBytes` 可为某个受信任调用方提高单次 stdout 捕获预算;stderr 和后台运行仍使用 `maxOutputBytes`。 - **超时与取消分类**:`run()` 通过同一个 deadline 把经配置钳位的超时与调用方的信号融合;只有执行器自身的超时报告 `timedOut`,上游取消报告 `aborted`,自身因信号终止的命令两者皆不报告(见[超时库 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md))。 - **适合模型的终端环境**:`NO_COLOR=1 TERM=dumb PAGER=cat GIT_PAGER=cat` 防止分页器与 ANSI 颜色破坏结果。这些值作为普通 env 合并,遵循服务的凭据清除与 `DSH_*` 通道规则;调用方的显式条目依旧优先。详见 [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-api.md) 与 [受管环境 Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md)。 diff --git a/packages/bash/bash-local/package.json b/packages/bash/bash-local/package.json index a46c5b6502..4b1b831c55 100644 --- a/packages/bash/bash-local/package.json +++ b/packages/bash/bash-local/package.json @@ -36,7 +36,8 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-subprocess": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:^" @@ -47,6 +48,7 @@ "@deepseek-ai/dsh-subprocess": "workspace:^", "@deepseek-ai/dsh-subprocess-local": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" } } diff --git a/packages/bash/bash-local/src/index.ts b/packages/bash/bash-local/src/index.ts index 2c8e200fc3..025f86a8b3 100644 --- a/packages/bash/bash-local/src/index.ts +++ b/packages/bash/bash-local/src/index.ts @@ -11,9 +11,10 @@ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { BashExecutor } from '@deepseek-ai/dsh-bash' +import { BASH_SETTINGS_NAMESPACE, BashExecutor } from '@deepseek-ai/dsh-bash' import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult, CollectedOutput } from '@deepseek-ai/dsh-bash' import type { SubprocessCollect, SubprocessHandle, SubprocessOutputReader, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { installSettingsSection } from '@deepseek-ai/dsh-settings' import { clampTimeout, deadline, MAX_TIMER_DELAY_MS, timeoutOf } from '@deepseek-ai/dsh-timeout' /** @@ -71,6 +72,26 @@ function assertPositiveFinite(name: string, value: number): void { } } +/** + * Reject a resolved section this executor could not run with. The schema + * expresses neither "positive and finite" nor the timer bound `graceMs` has to + * fit, so a stored value is refused where it is written instead of failing at + * the next command. + * @param config - the resolved section, schema-valid by construction. + * @throws Error naming the field that cannot be used. + */ +export function assertServiceableBashConfig(config: Config): void { + const resolved = config as ResolvedConfig + assertPositiveFinite('timeoutMs', resolved.timeoutMs) + assertPositiveFinite('maxTimeoutMs', resolved.maxTimeoutMs) + assertPositiveFinite('maxOutputBytes', resolved.maxOutputBytes) + assertPositiveFinite('maxSpillBytes', resolved.maxSpillBytes) + assertPositiveFinite('graceMs', resolved.graceMs) + if (resolved.graceMs > MAX_TIMER_DELAY_MS) { + throw new Error(`bash-local: graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`) + } +} + /** * Local bash executor over `ctx.subprocess`. Bounded output, spill files, and * process-group SIGTERM→SIGKILL escalation are the subprocess service's @@ -90,21 +111,29 @@ export class LocalBashExecutor extends BashExecutor { graceMs: z.number().default(DEFAULT_GRACE_MS), }) + /** The currently authoritative config: the settings section, or the composition entry. */ + private source: () => ResolvedConfig + /** Validated config (schemastery applied the defaults before construction). */ - readonly config: ResolvedConfig + get config(): ResolvedConfig { + return this.source() + } constructor(ctx: Context, config: Config) { super(ctx) // Schemastery fills these fields before construction; the type does not encode that step. - this.config = config as ResolvedConfig - assertPositiveFinite('timeoutMs', this.config.timeoutMs) - assertPositiveFinite('maxTimeoutMs', this.config.maxTimeoutMs) - assertPositiveFinite('maxOutputBytes', this.config.maxOutputBytes) - assertPositiveFinite('maxSpillBytes', this.config.maxSpillBytes) - assertPositiveFinite('graceMs', this.config.graceMs) - if (this.config.graceMs > MAX_TIMER_DELAY_MS) { - throw new Error(`bash-local: graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`) - } + const entry = config as ResolvedConfig + assertServiceableBashConfig(entry) + this.source = () => entry + installSettingsSection(ctx, BASH_SETTINGS_NAMESPACE, LocalBashExecutor.Config, entry, { + validate: assertServiceableBashConfig, + setSource: (current) => { + this.source = current as () => ResolvedConfig + }, + // Every field is read through the getter at each command, so nothing + // derived from the source needs rebuilding when the document changes. + onChange: () => {}, + }) } /** diff --git a/packages/bash/bash-local/tests/settings.spec.ts b/packages/bash/bash-local/tests/settings.spec.ts new file mode 100644 index 0000000000..f0bcd8e113 --- /dev/null +++ b/packages/bash/bash-local/tests/settings.spec.ts @@ -0,0 +1,115 @@ +/** The `bash` settings section layered over the executor's composition entry. */ + +import { describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Fiber } from '@deepseek-ai/cordis' +import { Settings } from '@deepseek-ai/dsh-settings' +import type { SettingsNamespace } from '@deepseek-ai/dsh-settings' +import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' +import { BASH_SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-bash' +import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' + +/** The smallest real provider: one in-memory document, always writable. */ +class MemorySettings extends Settings { + doc: Record = {} + + get writable(): boolean { + return true + } + + protected load(): Promise> { + return Promise.resolve(structuredClone(this.doc)) + } + + protected persist(ns: SettingsNamespace, section: Record): Promise { + this.doc = { ...this.doc, [ns]: structuredClone(section) } + return Promise.resolve() + } +} + +async function boot(config: ConstructorParameters[1] = {}): Promise<{ + ctx: Context + settingsFiber: Fiber + executorFiber: Fiber + bash: LocalBashExecutor +}> { + const ctx = new Context() + await ctx.plugin(LocalSubprocessService) + const settingsFiber = ctx.plugin(MemorySettings) + await settingsFiber.await() + const executorFiber = ctx.plugin(LocalBashExecutor, { timeoutMs: 60_000, ...config }) + await executorFiber.await() + return { ctx, settingsFiber, executorFiber, bash: ctx.bash as LocalBashExecutor } +} + +describe('bash settings section', () => { + it('resolves the user layer over the composition entry', async () => { + const bench = await boot() + expect(bench.bash.config.timeoutMs).toBe(60_000) + + await bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { timeoutMs: 5_000 }) + + expect(bench.bash.config.timeoutMs).toBe(5_000) + await bench.ctx.fiber.dispose() + }) + + it('refuses a stored value the constructor would have rejected', async () => { + const bench = await boot() + + await expect(bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { timeoutMs: 0 })) + .rejects.toThrow(/positive finite/) + + expect(bench.bash.config.timeoutMs).toBe(60_000) + await bench.ctx.fiber.dispose() + }) + + it('refuses a grace period longer than a timer can carry', async () => { + const bench = await boot() + + await expect(bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { graceMs: Number.MAX_SAFE_INTEGER })) + .rejects.toThrow(/graceMs must be no greater than/) + + await bench.ctx.fiber.dispose() + }) + + it('serves the stored section to every later read', async () => { + const bench = await boot() + await bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { maxOutputBytes: 1_024, cwd: '/tmp' }) + + const spec = bench.bash.resolve({ command: 'true' }) + + expect(spec.stdoutMaxBytes).toBe(1_024) + expect(spec.workdir).toBe('/tmp') + await bench.ctx.fiber.dispose() + }) + + it('falls back to the composition entry when the settings provider detaches', async () => { + const bench = await boot() + await bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { timeoutMs: 5_000 }) + expect(bench.bash.config.timeoutMs).toBe(5_000) + + await bench.settingsFiber.dispose() + + expect(bench.bash.config.timeoutMs).toBe(60_000) + await bench.ctx.fiber.dispose() + }) + + it('keeps the composition entry when no settings provider is mounted', async () => { + const ctx = new Context() + await ctx.plugin(LocalSubprocessService) + await ctx.plugin(LocalBashExecutor, { timeoutMs: 1_234 }) + + expect((ctx.bash as LocalBashExecutor).config.timeoutMs).toBe(1_234) + await ctx.fiber.dispose() + }) + + it('releases the namespace when the executor unloads', async () => { + const bench = await boot() + expect(bench.ctx.settings.describe().map(row => String(row.ns))).toContain('bash') + + await bench.executorFiber.dispose() + + expect(bench.ctx.settings.describe().map(row => String(row.ns))).not.toContain('bash') + await bench.ctx.fiber.dispose() + }) +}) diff --git a/packages/bash/bash-local/tsconfig.json b/packages/bash/bash-local/tsconfig.json index 53ccc94926..80015bf539 100644 --- a/packages/bash/bash-local/tsconfig.json +++ b/packages/bash/bash-local/tsconfig.json @@ -29,6 +29,9 @@ { "path": "../../subprocess/subprocess" }, + { + "path": "../../settings/settings" + }, { "path": "../../support/invariants" } diff --git a/packages/bash/bash/README.i18n.yaml b/packages/bash/bash/README.i18n.yaml index 3ac95f32c5..42bb31cd52 100644 --- a/packages/bash/bash/README.i18n.yaml +++ b/packages/bash/bash/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/bash/bash/README.md -README.md: a076c6ef3150de86c251f0501b18de01c4491c67 -README.zh.md: 1be9f817a8379b2974fb4cfd63c197c320934f00 +README.md: ef873dfb87cb330847274be59d5f2a0c3a5bc0b9 +README.zh.md: 4047765f248a25ff700ba62bf87636c0e8bfe7ac diff --git a/packages/bash/bash/README.md b/packages/bash/bash/README.md index a076c6ef31..ef873dfb87 100644 --- a/packages/bash/bash/README.md +++ b/packages/bash/bash/README.md @@ -27,6 +27,8 @@ The split is a standard capability seam ([capability-seams Agent Note](../../../ Implementations subclass `BashExecutor` and implement the abstract methods. Disposal must kill every running process and await its exit. +`BASH_SETTINGS_NAMESPACE` (`bash`) is exported here rather than by a provider because it names the capability, not an implementation. A host composes exactly one provider of `ctx.bash` — the win32 layer swaps the POSIX rows for the pwsh ones, and mounting both fails loud on a duplicate service registration — so every provider can register this one namespace with its own schema and composition entry without two of them ever colliding, and a `settings.yaml` carried between platforms keeps resolving on both. + ## Vocabulary `BashExecRequest` (command, workdir?, timeoutMs?, stdoutMaxBytes?, signal?, stdin?, env?, dshEnv?, sandboxPolicy?) resolves to `BashExecSpec` (command, workdir, timeoutMs, stdoutMaxBytes, signal?, stdin?, env?, dshEnv?, sandboxPolicy) before execution. `stdoutMaxBytes` is a trusted foreground-run capture budget for consumers that must parse complete bounded stdout; the model-facing bash tool does not expose it. `sandboxPolicy` is optional on the request and required-but-nullable on the resolved spec: it carries the complete per-call mode and workspace root. The sandbox tool path resolves it from the calling session through `ctx.sandboxPolicy`; a direct sandbox-executor caller falls back to deployment policy, while a non-sandboxing executor carries the field and confines nothing. diff --git a/packages/bash/bash/README.zh.md b/packages/bash/bash/README.zh.md index 1be9f817a8..4047765f24 100644 --- a/packages/bash/bash/README.zh.md +++ b/packages/bash/bash/README.zh.md @@ -27,6 +27,8 @@ 实现会继承 `BashExecutor` 并实现抽象方法。dispose(资源释放)必须终止每个运行中的进程并等待其退出。 +`BASH_SETTINGS_NAMESPACE`(`bash`)由此处导出而非由某个提供方导出,因为它命名的是能力而不是实现。一个宿主只组装一个 `ctx.bash` 提供方——win32 层会把 POSIX 行换成 pwsh 行,同时挂载两者会因服务重复注册而在加载期失败——所以每个提供方都能用自己的 schema 与组装条目注册这同一个命名空间,两者永不相撞;在平台间携带的 `settings.yaml` 也能在两边继续解析。 + ## 词汇 `BashExecRequest`(command、workdir?、timeoutMs?、stdoutMaxBytes?、signal?、stdin?、env?、dshEnv?、sandboxPolicy?)在执行前解析为 `BashExecSpec`(command、workdir、timeoutMs、stdoutMaxBytes、signal?、stdin?、env?、dshEnv?、sandboxPolicy)。`stdoutMaxBytes` 是受信任前台运行的捕获预算,用于必须解析完整有界 stdout 的消费方;面向模型的 bash 工具不公开该字段。`sandboxPolicy` 在请求上可选,在已解析 spec 上必填但可为 null:它携带完整的每次调用模式与工作区根目录。沙箱工具路径通过 `ctx.sandboxPolicy` 从调用会话解析它;沙箱执行器的直接调用方回退到部署策略,非沙箱执行器则携带该字段但不作限制。 diff --git a/packages/bash/bash/package.json b/packages/bash/bash/package.json index 0821a526c8..f97d4b1f74 100644 --- a/packages/bash/bash/package.json +++ b/packages/bash/bash/package.json @@ -35,12 +35,14 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-subprocess": "workspace:^", "@deepseek-ai/dsh-sandbox": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" }, "devDependencies": { "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-subprocess": "workspace:^", "@deepseek-ai/dsh-sandbox": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" } } diff --git a/packages/bash/bash/src/index.ts b/packages/bash/bash/src/index.ts index 30d5840052..b27e2ff5ea 100644 --- a/packages/bash/bash/src/index.ts +++ b/packages/bash/bash/src/index.ts @@ -6,9 +6,21 @@ */ import { Context, Service } from '@deepseek-ai/cordis' +import { settingsNamespace } from '@deepseek-ai/dsh-settings' import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from './types.ts' +/** + * Settings namespace of this capability, owned here rather than by either + * executor family because it names the capability, not an implementation: a + * host composes exactly one provider of `ctx.bash` (the win32 layer swaps the + * POSIX rows for the pwsh ones, and mounting both fails loud on a duplicate + * service registration), so the providers share one namespace without ever + * registering it twice, and a settings document carried between platforms + * keeps resolving on both. + */ +export const BASH_SETTINGS_NAMESPACE = settingsNamespace('bash') + export { DSH_ENV_PREFIX } from './types.ts' export type { BashExecRequest, diff --git a/packages/bash/bash/tsconfig.json b/packages/bash/bash/tsconfig.json index 3f611c80e0..dac354f18a 100644 --- a/packages/bash/bash/tsconfig.json +++ b/packages/bash/bash/tsconfig.json @@ -20,6 +20,9 @@ { "path": "../../sandbox/sandbox" }, + { + "path": "../../settings/settings" + }, { "path": "../../support/invariants" } diff --git a/packages/bash/pwsh-local/README.i18n.yaml b/packages/bash/pwsh-local/README.i18n.yaml index 1d26227716..46929dd0f2 100644 --- a/packages/bash/pwsh-local/README.i18n.yaml +++ b/packages/bash/pwsh-local/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/bash/pwsh-local/README.md -README.md: eb3365b009e3595230e5fb0f616079bd73c55840 -README.zh.md: d79201c756a26bbc343e2b284a803b0cf9aee69b +README.md: 76f3071dc1049e2ea5929d5990ee0cb526ef702e +README.zh.md: e773e0e83e81ffa311bd555b7a75433ba22dfd22 diff --git a/packages/bash/pwsh-local/README.md b/packages/bash/pwsh-local/README.md index eb3365b009..76f3071dc1 100644 --- a/packages/bash/pwsh-local/README.md +++ b/packages/bash/pwsh-local/README.md @@ -28,8 +28,9 @@ The package root exports the default and named `PwshLocalExecutor` plugin, its ` The Windows counterpart of `dsh-bash-local`, deliberately mirroring its semantics call-for-call: - **Spawn per call, no shell state** — every call is a fresh non-interactive `pwsh -Command` (deterministic; no profile files). The `-NoLogo -NoProfile -NonInteractive` flags disable startup banners, profile loading, and prompts that would garble tool output. +- **The composition entry is a layer, not the last word** — when a settings provider is composed, this executor registers the capability's [`bash` namespace](../bash/README.md) with the entry above as its base, so a user section in `settings.yaml` layers over it and the next command runs with the new budgets. The namespace is shared with the POSIX family because a host composes exactly one provider of `ctx.bash`; a document written on either platform keeps resolving on the other. Values the schema cannot judge (positive and finite, the `graceMs` timer bound) are refused at the write, leaving the running executor on its last good section. - **UTF-8 output pinned** — every command runs with `[Console]::OutputEncoding` and `$OutputEncoding` set to UTF-8 first, so the Windows PowerShell 5.1 fallback (or any host whose console code page is not UTF-8) cannot garble non-ASCII output: the subprocess collector decodes bytes as UTF-8. Input encoding is left at the host default; pwsh 7 defaults to UTF-8 and is unaffected. -- **Executable resolution** — `resolvePwshPath` prefers an explicit `pwshPath`, then on Windows probes PowerShell 7's install location, every PATH entry (Microsoft Store installs; surrounding quotes stripped), and Windows PowerShell 5.1 as a legacy last resort, checking `existsSync` on each; elsewhere it falls back to a bare `pwsh` resolved through PATH. Resolution is a pure function of `(configured, env, platform)` and happens once at construction. +- **Executable resolution** — `resolvePwshPath` prefers an explicit `pwshPath`, then on Windows probes PowerShell 7's install location, every PATH entry (Microsoft Store installs; surrounding quotes stripped), and Windows PowerShell 5.1 as a legacy last resort, checking `existsSync` on each; elsewhere it falls back to a bare `pwsh` resolved through PATH. Resolution is a pure function of `(configured, env, platform)`; it runs at construction and again only when a stored `pwshPath` differs from the one the current executable was resolved from, so an unrelated settings change never re-probes the filesystem. - **Configured budgets over managed groups** — `resolve()` fills `workdir`/`timeoutMs`/`stdoutMaxBytes` from config, and every spawn hands the service explicit byte caps, spill cap, and `graceMs`. The grace must be positive, finite, and no greater than [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md), so Node can represent it with one timer. Tree termination (taskkill on Windows, process-group signals on POSIX), the post-exit pipe-drain grace, tail-keep truncation, and bounded spill files are [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) mechanics. A foreground `BashExecRequest.stdoutMaxBytes` can raise stdout's capture budget for one trusted caller; stderr and background runs still use `maxOutputBytes`. - **Timeout and cancel classification** — `run()` fuses its config-clamped timeout with the caller's signal through one deadline; only the executor's own timeout reports `timedOut`, an upstream cancel reports `aborted`, and a self-terminated command reports neither ([timeout-library Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md)). Windows reports forced termination as exit 1 without a signal, so signal-stamped facts (`signal`, `killed` status) are POSIX-only there; the timeout/abort classification is platform-independent. - **Model-friendly terminal env** — `NO_COLOR=1 PAGER=cat GIT_PAGER=cat` (no `TERM=dumb`: that is a POSIX concept; `NO_COLOR` is honored by modern PowerShell renderers) merged as ordinary env under the service's credential scrub and `DSH_*` channel rules; an explicit caller entry still wins. diff --git a/packages/bash/pwsh-local/README.zh.md b/packages/bash/pwsh-local/README.zh.md index d79201c756..e773e0e83e 100644 --- a/packages/bash/pwsh-local/README.zh.md +++ b/packages/bash/pwsh-local/README.zh.md @@ -28,8 +28,9 @@ 作为 `dsh-bash-local` 的 Windows 对应物,逐调用地镜像其语义: - **每次调用新建进程,无 shell 状态**——每次调用都是全新的非交互 `pwsh -Command`(确定性;不加载 profile 文件)。`-NoLogo -NoProfile -NonInteractive` 关闭启动横幅、profile 加载与会干扰工具输出的提示符。 +- **组装条目是一层,而不是最终值**——当组装中存在 settings 提供方时,本执行器以上面的条目为 base 注册该能力的 [`bash` 命名空间](../bash/README.md),因此 `settings.yaml` 中的用户段会叠加其上,下一条命令即按新预算运行。该命名空间与 POSIX 家族共用,因为一个宿主只组装一个 `ctx.bash` 提供方;在任一平台写下的文档在另一平台仍能解析。schema 无法判定的值(正有限、`graceMs` 的定时器上界)会在写入时被拒绝,运行中的执行器保持它最后一份可用的段。 - **UTF-8 输出固定**——每条命令都先以 UTF-8 设置 `[Console]::OutputEncoding` 与 `$OutputEncoding`,因此 Windows PowerShell 5.1 兜底(或任何控制台代码页非 UTF-8 的主机)不会破坏非 ASCII 输出:subprocess collector 以 UTF-8 解码字节。输入编码保持宿主默认;pwsh 7 默认为 UTF-8,不受影响。 -- **可执行文件解析**——`resolvePwshPath` 优先显式 `pwshPath`,然后在 Windows 上依次探测 PowerShell 7 安装位置、每个 PATH 条目(Microsoft Store 安装;剥离两端引号)以及作为遗留兜底的 Windows PowerShell 5.1,逐一检查 `existsSync`;其他平台回退为通过 PATH 解析的裸 `pwsh`。解析是 `(configured, env, platform)` 的纯函数,在构造时执行一次。 +- **可执行文件解析**——`resolvePwshPath` 优先显式 `pwshPath`,然后在 Windows 上依次探测 PowerShell 7 安装位置、每个 PATH 条目(Microsoft Store 安装;剥离两端引号)以及作为遗留兜底的 Windows PowerShell 5.1,逐一检查 `existsSync`;其他平台回退为通过 PATH 解析的裸 `pwsh`。解析是 `(configured, env, platform)` 的纯函数;它在构造时执行,此后仅当存储的 `pwshPath` 与当前可执行文件所依据的值不同才再次执行,因此无关的设置变更绝不会重新探测文件系统。 - **受管进程组之上的配置预算**——`resolve()` 从配置填充 `workdir`/`timeoutMs`/`stdoutMaxBytes`,每次 spawn 都向服务提供显式字节上限、spill 上限与 `graceMs`。该宽限期须为正有限值,且不得大于 [`MAX_TIMER_DELAY_MS`](../../util/timeout/README.md),这样 Node 就能用一个定时器表示它。进程树终止(Windows 用 taskkill,POSIX 用进程组信号)、退出后管道排空宽限、保尾截断与有界 spill 文件是 [`dsh-subprocess-local`](../../subprocess/subprocess-local/README.md) 的机制。前台 `BashExecRequest.stdoutMaxBytes` 可为单个受信调用方提高 stdout 捕获预算;stderr 与后台运行仍使用 `maxOutputBytes`。 - **超时与取消分类**——`run()` 通过一个 deadline 融合按配置上限截取的超时与调用方信号;只有执行器自身超时报告 `timedOut`,上游取消报告 `aborted`,自我终止的命令两者都不报告(见 [timeout 库 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-06-timeout-deadline-library.md))。Windows 将强制终止报告为退出码 1 且无信号,因此带信号标记的事实(`signal`、`killed` 状态)在那里仅限 POSIX;超时/取消分类与平台无关。 - **面向模型的终端环境**——`NO_COLOR=1 PAGER=cat GIT_PAGER=cat`(没有 `TERM=dumb`:那是 POSIX 概念;现代 PowerShell 渲染器遵循 `NO_COLOR`),作为普通 env 在服务的凭据清理与 `DSH_*` 通道规则之下合并;显式调用方条目仍然优先。 diff --git a/packages/bash/pwsh-local/package.json b/packages/bash/pwsh-local/package.json index 59e8714608..aac75796a7 100644 --- a/packages/bash/pwsh-local/package.json +++ b/packages/bash/pwsh-local/package.json @@ -36,7 +36,8 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-subprocess": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:^" @@ -47,6 +48,7 @@ "@deepseek-ai/dsh-subprocess": "workspace:^", "@deepseek-ai/dsh-subprocess-local": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" } } diff --git a/packages/bash/pwsh-local/src/index.ts b/packages/bash/pwsh-local/src/index.ts index 16f5c4479f..fa63abc955 100644 --- a/packages/bash/pwsh-local/src/index.ts +++ b/packages/bash/pwsh-local/src/index.ts @@ -13,12 +13,16 @@ * @module @deepseek-ai/dsh-pwsh-local */ +/* jscpd:ignore-start -- this executor mirrors dsh-bash-local call-for-call by + design (see this package's README), so the two import the same seam surface */ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { BashExecutor } from '@deepseek-ai/dsh-bash' +import { BASH_SETTINGS_NAMESPACE, BashExecutor } from '@deepseek-ai/dsh-bash' import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult, CollectedOutput } from '@deepseek-ai/dsh-bash' import type { SubprocessCollect, SubprocessHandle, SubprocessOutputReader, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { installSettingsSection } from '@deepseek-ai/dsh-settings' import { clampTimeout, deadline, MAX_TIMER_DELAY_MS, timeoutOf } from '@deepseek-ai/dsh-timeout' +/* jscpd:ignore-end */ import { resolvePwshPath } from './resolve.ts' /* jscpd:ignore-start -- deliberate call-for-call mirror of dsh-bash-local (Agent Note: pwsh-tool-and-executor). */ @@ -96,6 +100,26 @@ function assertPositiveFinite(name: string, value: number): void { } } +/** + * Reject a resolved section this executor could not run with. The schema + * expresses neither "positive and finite" nor the timer bound `graceMs` has to + * fit, so a stored value is refused where it is written instead of failing at + * the next command. + * @param config - the resolved section, schema-valid by construction. + * @throws Error naming the field that cannot be used. + */ +export function assertServiceablePwshConfig(config: Config): void { + const resolved = config as ResolvedConfig + assertPositiveFinite('timeoutMs', resolved.timeoutMs) + assertPositiveFinite('maxTimeoutMs', resolved.maxTimeoutMs) + assertPositiveFinite('maxOutputBytes', resolved.maxOutputBytes) + assertPositiveFinite('maxSpillBytes', resolved.maxSpillBytes) + assertPositiveFinite('graceMs', resolved.graceMs) + if (resolved.graceMs > MAX_TIMER_DELAY_MS) { + throw new Error(`pwsh-local: graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`) + } +} + /** * Local PowerShell executor over `ctx.subprocess`. Bounded output, spill * files, and process-tree termination are the subprocess service's mechanics; @@ -114,25 +138,47 @@ export class PwshLocalExecutor extends BashExecutor { pwshPath: z.string(), }) - /** Validated config (schemastery applied the defaults before construction). */ - readonly config: ResolvedConfig + /** The currently authoritative config: the settings section, or the composition entry. */ + private source: () => ResolvedConfig - /** The pwsh executable resolved once at construction. */ - readonly pwshPath: string + /** The declared executable the current {@link pwshPath} was resolved from. */ + private declaredPwshPath: string | undefined + + /** The pwsh executable resolved from the current config. */ + private resolvedPwshPath: string + + /** Validated config (schemastery applied the defaults before construction). */ + get config(): ResolvedConfig { + return this.source() + } + + /** The pwsh executable every command runs through. */ + get pwshPath(): string { + return this.resolvedPwshPath + } constructor(ctx: Context, config: Config) { super(ctx) // Schemastery fills these fields before construction; the type does not encode that step. - this.config = config as ResolvedConfig - assertPositiveFinite('timeoutMs', this.config.timeoutMs) - assertPositiveFinite('maxTimeoutMs', this.config.maxTimeoutMs) - assertPositiveFinite('maxOutputBytes', this.config.maxOutputBytes) - assertPositiveFinite('maxSpillBytes', this.config.maxSpillBytes) - assertPositiveFinite('graceMs', this.config.graceMs) - if (this.config.graceMs > MAX_TIMER_DELAY_MS) { - throw new Error(`pwsh-local: graceMs must be no greater than ${MAX_TIMER_DELAY_MS}`) - } - this.pwshPath = resolvePwshPath(this.config.pwshPath) + const entry = config as ResolvedConfig + assertServiceablePwshConfig(entry) + this.source = () => entry + this.declaredPwshPath = entry.pwshPath + this.resolvedPwshPath = resolvePwshPath(entry.pwshPath) + installSettingsSection(ctx, BASH_SETTINGS_NAMESPACE, PwshLocalExecutor.Config, entry, { + validate: assertServiceablePwshConfig, + setSource: (current) => { + this.source = current as () => ResolvedConfig + }, + // Probing the filesystem is the one fact derived from the source: every + // other field is read through the getter at each command. + onChange: () => { + const declared = this.source().pwshPath + if (declared === this.declaredPwshPath) return + this.declaredPwshPath = declared + this.resolvedPwshPath = resolvePwshPath(declared) + }, + }) } /** diff --git a/packages/bash/pwsh-local/tests/settings.spec.ts b/packages/bash/pwsh-local/tests/settings.spec.ts new file mode 100644 index 0000000000..f211369d5a --- /dev/null +++ b/packages/bash/pwsh-local/tests/settings.spec.ts @@ -0,0 +1,108 @@ +/** The shared `bash` settings section as the pwsh executor family resolves it. */ + +import { describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Fiber } from '@deepseek-ai/cordis' +import { Settings } from '@deepseek-ai/dsh-settings' +import type { SettingsNamespace } from '@deepseek-ai/dsh-settings' +import { BASH_SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-bash' +import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local' +import { PwshLocalExecutor } from '@deepseek-ai/dsh-pwsh-local' + +/** The smallest real provider: one in-memory document, always writable. */ +class MemorySettings extends Settings { + doc: Record = {} + + get writable(): boolean { + return true + } + + protected load(): Promise> { + return Promise.resolve(structuredClone(this.doc)) + } + + protected persist(ns: SettingsNamespace, section: Record): Promise { + this.doc = { ...this.doc, [ns]: structuredClone(section) } + return Promise.resolve() + } +} + +async function boot(config: ConstructorParameters[1] = {}): Promise<{ + ctx: Context + settingsFiber: Fiber + executorFiber: Fiber + pwsh: PwshLocalExecutor +}> { + const ctx = new Context() + await ctx.plugin(LocalSubprocessService) + const settingsFiber = ctx.plugin(MemorySettings) + await settingsFiber.await() + const executorFiber = ctx.plugin(PwshLocalExecutor, { timeoutMs: 60_000, ...config }) + await executorFiber.await() + return { ctx, settingsFiber, executorFiber, pwsh: ctx.bash as PwshLocalExecutor } +} + +describe('pwsh executor over the bash settings section', () => { + it('resolves the user layer over the composition entry', async () => { + const bench = await boot() + expect(bench.pwsh.config.timeoutMs).toBe(60_000) + + await bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { timeoutMs: 5_000 }) + + expect(bench.pwsh.config.timeoutMs).toBe(5_000) + await bench.ctx.fiber.dispose() + }) + + it('refuses a stored value the constructor would have rejected', async () => { + const bench = await boot() + + await expect(bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { timeoutMs: 0 })) + .rejects.toThrow(/pwsh-local: timeoutMs must be a positive finite number/) + + expect(bench.pwsh.config.timeoutMs).toBe(60_000) + await bench.ctx.fiber.dispose() + }) + + it('re-resolves the executable when the stored path changes', async () => { + const bench = await boot({ pwshPath: '/opt/first/pwsh' }) + expect(bench.pwsh.pwshPath).toBe('/opt/first/pwsh') + + await bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { pwshPath: '/opt/second/pwsh' }) + + expect(bench.pwsh.pwshPath).toBe('/opt/second/pwsh') + await bench.ctx.fiber.dispose() + }) + + it('keeps the resolved executable when an unrelated field changes', async () => { + const bench = await boot({ pwshPath: '/opt/first/pwsh' }) + const before = bench.pwsh.pwshPath + + await bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { timeoutMs: 5_000 }) + + expect(bench.pwsh.pwshPath).toBe(before) + await bench.ctx.fiber.dispose() + }) + + it('falls back to the composition entry when the settings provider detaches', async () => { + const bench = await boot({ pwshPath: '/opt/first/pwsh' }) + await bench.ctx.settings.update(BASH_SETTINGS_NAMESPACE, { timeoutMs: 5_000, pwshPath: '/opt/second/pwsh' }) + expect(bench.pwsh.config.timeoutMs).toBe(5_000) + expect(bench.pwsh.pwshPath).toBe('/opt/second/pwsh') + + await bench.settingsFiber.dispose() + + expect(bench.pwsh.config.timeoutMs).toBe(60_000) + expect(bench.pwsh.pwshPath).toBe('/opt/first/pwsh') + await bench.ctx.fiber.dispose() + }) + + it('releases the namespace when the executor unloads', async () => { + const bench = await boot() + expect(bench.ctx.settings.describe().map(row => String(row.ns))).toContain('bash') + + await bench.executorFiber.dispose() + + expect(bench.ctx.settings.describe().map(row => String(row.ns))).not.toContain('bash') + await bench.ctx.fiber.dispose() + }) +}) diff --git a/packages/bash/pwsh-local/tsconfig.json b/packages/bash/pwsh-local/tsconfig.json index 53ccc94926..80015bf539 100644 --- a/packages/bash/pwsh-local/tsconfig.json +++ b/packages/bash/pwsh-local/tsconfig.json @@ -29,6 +29,9 @@ { "path": "../../subprocess/subprocess" }, + { + "path": "../../settings/settings" + }, { "path": "../../support/invariants" } diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index c0750ddf95..535386579f 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -227,6 +227,11 @@ - id: ui-agent-preset name: '@deepseek-ai/dsh-client-ui-agent-preset' + # Plugin configuration: the host-plane sections a user owns, as expandable + # cards. A namespace this deployment does not expose renders nothing. + - id: ui-plugin-config + name: '@deepseek-ai/dsh-client-ui-plugin-config' + # Plan control: the composer plan seat over the plan projection + /plan channel. - id: ui-plan name: '@deepseek-ai/dsh-client-ui-plan' diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index c1f93343fc..51de2e02fd 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -45,12 +45,12 @@ }, "dependencies": { "@deepseek-ai/dsh-agent-presets": "workspace:^", + "@deepseek-ai/dsh-api-remotes": "workspace:^", "@deepseek-ai/dsh-app-boot": "workspace:^", "@deepseek-ai/dsh-client-connection": "workspace:^", "@deepseek-ai/dsh-client-hmr": "workspace:^", "@deepseek-ai/dsh-client-locale": "workspace:^", "@deepseek-ai/dsh-client-modules": "workspace:^", - "@deepseek-ai/dsh-api-remotes": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-agent-preset": "workspace:^", "@deepseek-ai/dsh-client-ui-command": "workspace:^", @@ -62,6 +62,7 @@ "@deepseek-ai/dsh-client-ui-models": "workspace:^", "@deepseek-ai/dsh-client-ui-permission": "workspace:^", "@deepseek-ai/dsh-client-ui-plan": "workspace:^", + "@deepseek-ai/dsh-client-ui-plugin-config": "workspace:^", "@deepseek-ai/dsh-client-ui-question": "workspace:^", "@deepseek-ai/dsh-client-ui-settings": "workspace:^", "@deepseek-ai/dsh-client-ui-settings-general": "workspace:^", diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index 254fefeac9..c5da6b743a 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/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/README.md -README.md: 42258a961b522271cf61367856c162a7312c79f2 -README.zh.md: 5ecebbfd1e3c8aaa294e3bfd1bf943600ab3366e +README.md: 75abe408952ed66dcc237ce489e417f61159bcc3 +README.zh.md: 5432efcb0a5ebc410093da4c3ec6c2e07c4520ca diff --git a/packages/client/README.md b/packages/client/README.md index 42258a961b..75abe40895 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -18,6 +18,7 @@ The browser side of the dsh web GUI: shell boot, browser-host communication, sha | [`ui-slots/`](ui-slots/README.md) | Defines how UI features register and compose extension slots. | | [`ui-theme/`](ui-theme/README.md) | Applies the selected color theme. | | [`ui-primitives/`](ui-primitives/README.md) | Provides shared React controls, icons, and content renderers. | +| [`ui-attachment/`](ui-attachment/README.md) | Provides attachment display atoms: draft-image rail, message gallery, and lightbox. | | [`ui-layout/`](ui-layout/README.md) | Arranges the main application regions. | | [`ui-sidebar/`](ui-sidebar/README.md) | Presents workspace and session navigation. | | [`ui-workspace/`](ui-workspace/README.md) | Provides workspace selection and creation surfaces. | @@ -34,6 +35,7 @@ The browser side of the dsh web GUI: shell boot, browser-host communication, sha | [`ui-model/`](ui-model/README.md) | Provides model selection in conversation surfaces. | | [`ui-permission/`](ui-permission/README.md) | Configures default permissions and switches the current session's access. | | [`ui-plan/`](ui-plan/README.md) | Presents active plan-mode status and its exit control. | +| [`ui-plugin-config/`](ui-plugin-config/README.md) | The Plugins settings section: host-plane plugin configuration as expandable cards. | | [`ui-question/`](ui-question/README.md) | Presents interactive questions requested by the agent. | | [`ui-agent-preset/`](ui-agent-preset/README.md) | Selects a session's agent preset and authors preset compositions. | | [`ui-settings/`](ui-settings/README.md) | Hosts the settings interface and its extension areas. | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index 5ecebbfd1e..5432efcb0a 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -18,6 +18,7 @@ dsh web GUI 的浏览器侧:shell 启动、浏览器与宿主通信、共享 U | [`ui-slots/`](ui-slots/README.md) | 定义 UI 功能注册和组合扩展 slot 的方式。 | | [`ui-theme/`](ui-theme/README.md) | 应用所选颜色主题。 | | [`ui-primitives/`](ui-primitives/README.md) | 提供共享 React 控件、图标和内容渲染器。 | +| [`ui-attachment/`](ui-attachment/README.md) | 提供附件展示原子组件:草稿图片栏、消息画廊与灯箱。 | | [`ui-layout/`](ui-layout/README.md) | 排列应用的主要区域。 | | [`ui-sidebar/`](ui-sidebar/README.md) | 展示 Workspace 与会话导航。 | | [`ui-workspace/`](ui-workspace/README.md) | 提供 Workspace 选择与创建界面。 | @@ -34,6 +35,7 @@ dsh web GUI 的浏览器侧:shell 启动、浏览器与宿主通信、共享 U | [`ui-model/`](ui-model/README.md) | 在会话界面中提供模型选择。 | | [`ui-permission/`](ui-permission/README.md) | 配置默认权限并切换当前会话的访问模式。 | | [`ui-plan/`](ui-plan/README.md) | 展示生效中的 plan mode 状态及其退出控件。 | +| [`ui-plugin-config/`](ui-plugin-config/README.md) | 插件设置分区:把宿主平面的插件配置呈现为可展开卡片。 | | [`ui-question/`](ui-question/README.md) | 展示 agent 请求的交互式问题。 | | [`ui-agent-preset/`](ui-agent-preset/README.md) | 选择会话的 agent 预设,并创作预设组装。 | | [`ui-settings/`](ui-settings/README.md) | 承载设置界面及其扩展区域。 | diff --git a/packages/client/runtime/README.i18n.yaml b/packages/client/runtime/README.i18n.yaml index 0cbdbb5294..e57f1a9be8 100644 --- a/packages/client/runtime/README.i18n.yaml +++ b/packages/client/runtime/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/runtime/README.md -README.md: be04f56ac5151c756aa6d4e2233461cc173fe261 -README.zh.md: 372922b8b02f694512505c97bf08b9ab480912a5 +README.md: bcc1b070535046ab2af1878f763c806aada49ba0 +README.zh.md: 7a5d651c862d9f9682688f71a9bdf7d6b22f3e63 diff --git a/packages/client/runtime/README.md b/packages/client/runtime/README.md index be04f56ac5..bcc1b07053 100644 --- a/packages/client/runtime/README.md +++ b/packages/client/runtime/README.md @@ -4,7 +4,8 @@ English | [中文](README.zh.md) Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects, list and scope state, and the shared event window and history paging used by registered conversation view targets. WorkspacesService depends on SessionsService and owns Workspace objects, list/actions, default-target derivation, and the New Session blank-reuse entry (`connectWorkspace`). The runtime fans the shared Host stream into Session and Workspace owners and hands each generic `host/remote-event` frame to `ctx.remote.$dispatch`; domain packages subscribe to their owner events through `ctx.remote.$on` and decide which caches or session rows they invalidate. Client sessions are always Host-born (Session+Agent+cwd in one `session.create`); the client holds no pre-entity session state — a session's Agent scope (the client mirror of host dsh-scope, keyed by the shared agent/session id) is born when its row enters the list mirror and dies with the prune. Contract: api-contracts v3 §4. Each `Session` holds a generic `ProjectionValueStore` seeded from the history-tail `projections` block and updated by `session/projection` frames under higher-seq-wins; domain keys (including `todos`) are read via `projections.faceOf` / `useProjection`, not via `ConversationSnapshot`. The store also publishes one reference-stable whole-value map through `SessionSummary.projectionValues`, allowing global list consumers to reuse the same projections without creating per-session subscriptions. -`bindSettingsScope` is the browser mirror of the Host-side settings owner seam for one domain-owned namespace. It subscribes before starting a nonblocking initial read, publishes a uSES snapshot (status, section value, revision, writability, host/memory mode), serializes `set` writes with the latest known namespace revision, suppresses stale publications, recovers a rejected latest write from Host state, and reaches quiescence on plugin disposal. The default decoder validates each section against the namespace's own serialized wire schema (rehydrated through dsh-client-schema-form), so a domain adds a decoder only to narrow beyond that schema. Loopback pages use the Host settings API; remote pages stay in memory mode. Domain packages own the namespace schema, default, and live service rather than putting product policy in runtime. +`bindSettingsScope` is the browser mirror of the Host-side settings owner seam for one domain-owned namespace. It subscribes before starting a nonblocking initial read, publishes a uSES snapshot (status, section value, the composition `base` and raw `user` layers, revision, writability, host/memory mode), serializes `set` and `unset` writes with the latest known namespace revision, suppresses stale publications, recovers a rejected latest write from Host state, and reaches quiescence on plugin disposal. The default decoder validates each section against the namespace's own serialized wire schema (rehydrated through dsh-client-schema-form), so a domain adds a decoder only to narrow beyond that schema. Loopback pages use the Host settings API; remote pages stay in memory mode. A field is overridden when it is PRESENT in `user` — an override equal to the composition default is still an override, which comparing values could not see — and `unset` is how a form clears one back to `base`. Domain packages own the namespace schema, default, and live service rather than putting product policy in runtime. + ## Slot declaration injection `ctx.slots.inject(name, callback)` makes a full `SlotMap` key the dependency for a contribution whose plugin can activate independently from the declaring entry. It runs `callback` synchronously when the declaration exists, otherwise waits; declaration collapse disposes the callback effect, and redeclaration reruns it. The controller belongs to the caller's plugin fiber, so unloading the contributor cancels either the wait or its active registrations. A direct `slots.register()` into an undeclared slot still throws. diff --git a/packages/client/runtime/README.zh.md b/packages/client/runtime/README.zh.md index 372922b8b0..7a5d651c86 100644 --- a/packages/client/runtime/README.zh.md +++ b/packages/client/runtime/README.zh.md @@ -4,7 +4,8 @@ 客户端 cordis 启动与不依赖 React 的对象服务:SlotsService 包装 SlotCore 并提供 renderer 数据源;SessionsService 拥有 Session 对象、列表与 scope 状态,以及供已注册 conversation view target 共用的事件窗口与历史分页。WorkspacesService 依赖 SessionsService,拥有 Workspace 对象、列表/操作、默认目标派生,以及 New Session 空会话复用入口(`connectWorkspace`)。运行时把共享 Host 流分发给 Session 与 Workspace 所有者,并把每个通用 `host/remote-event` 帧交给 `ctx.remote.$dispatch`;各领域包通过 `ctx.remote.$on` 订阅自身 owner 事件,并自行决定使哪些缓存或会话行失效。客户端会话一律由 Host 创建(一次 `session.create` 同时产生 Session、agent(智能体)和 cwd);客户端不持有任何实体化之前的会话状态——agent scope(host dsh-scope 的客户端镜像,以 agent/session 共用 id 为键)在会话行进入列表镜像时创建,并随 prune 销毁。约定:api-contracts v3 §4。每个 `Session` 持有一个通用的 `ProjectionValueStore`,由历史记录尾部的 `projections` 块播种,并经 `session/projection` 帧按 seq 高者胜更新;领域键(含 `todos`)经 `projections.faceOf`/`useProjection` 读取,不经 `ConversationSnapshot`。该 store 还会通过 `SessionSummary.projectionValues` 发布一份引用稳定的完整值映射,使全局列表消费方无需为每个会话创建订阅,即可复用同一组投影。 -`bindSettingsScope` 面向单个由领域持有的 namespace,是 Host 侧 settings owner seam 的浏览器镜像。它在开始非阻塞初始读取前建立订阅,发布 uSES 快照(状态、分节值、revision、可写性、host/内存模式),使用已知最新 namespace revision 串行执行 `set` 写入,抑制陈旧发布,并在最新写入被拒时从 Host 状态恢复;插件释放时,它会达到完全停稳。默认解码器会对照该 namespace 自身的序列化 wire schema(经 dsh-client-schema-form 还原)校验每个分节,因此领域只有在需要比该 schema 进一步收窄时才添加解码器。回环页面使用 Host settings API,远程页面则停留在内存模式。namespace schema、默认值与实时服务归领域包所有,而非把产品政策放入运行时。 +`bindSettingsScope` 面向单个由领域持有的 namespace,是 Host 侧 settings owner seam 的浏览器镜像。它在开始非阻塞初始读取前建立订阅,发布 uSES 快照(状态、分节值、组装 `base` 层与原始 `user` 层、revision、可写性、host/内存模式),使用已知最新 namespace revision 串行执行 `set` 与 `unset` 写入,抑制陈旧发布,并在最新写入被拒时从 Host 状态恢复;插件释放时,它会达到完全停稳。默认解码器会对照该 namespace 自身的序列化 wire schema(经 dsh-client-schema-form 还原)校验每个分节,因此领域只有在需要比该 schema 进一步收窄时才添加解码器。回环页面使用 Host settings API,远程页面则停留在内存模式。字段是否被覆盖,取决于它是否**出现**在 `user` 中——与组装默认值相同的覆盖仍然是覆盖,比较值是看不出来的——而 `unset` 就是表单把某个字段清回 `base` 的方式。namespace schema、默认值与实时服务归领域包所有,而非把产品政策放入运行时。 + ## Slot 声明注入 `ctx.slots.inject(name, callback)` 将完整的 `SlotMap` key 作为贡献项的依赖,适用于贡献方插件可独立于声明条目激活的情形。声明存在时,它会同步运行 `callback`,否则等待;声明折叠会 dispose(资源释放)回调 effect,重新声明则会再次运行回调。控制器归调用方的插件 fiber 所有,因此卸载贡献方会取消等待或移除其活跃注册项。直接调用 `slots.register()` 向未声明 slot 注册仍会抛出异常。 diff --git a/packages/client/runtime/src/client/contract/settings-scope.ts b/packages/client/runtime/src/client/contract/settings-scope.ts index 4e4f583d87..cb22cb15ed 100644 --- a/packages/client/runtime/src/client/contract/settings-scope.ts +++ b/packages/client/runtime/src/client/contract/settings-scope.ts @@ -17,6 +17,17 @@ export interface SettingsScopeSnapshot { status: 'loading' | 'ready' | 'unavailable' /** Last accepted schema-resolved section; undefined before the first acceptance. */ value: T | undefined + /** + * Composition layer the Host resolved {@link value} over, when the owning + * plugin declared one. What a field reverts to once cleared. + */ + base: unknown + /** + * Raw user layer as stored, when one exists. A field's PRESENCE here is what + * marks it overridden — an override whose value equals the composition + * default is still an override, and comparing values could not see it. + */ + user: unknown /** Namespace revision fencing the next write; undefined before the first Host view. */ revision: number | undefined /** Whether the Host document accepts writes; memory mode never does. */ @@ -60,4 +71,11 @@ export interface SettingsScope { * @returns settlement after the write and any latest-write recovery read. */ set(field: string, value: unknown): Promise + /** + * Queue one field clear, so the field re-inherits the composition layer. + * Shares {@link set}'s ordering, revision, and recovery contract. + * @param field - scalar field inside the namespace section. + * @returns settlement after the clear and any latest-write recovery read. + */ + unset(field: string): Promise } diff --git a/packages/client/test-runtime/src/settings-scope.ts b/packages/client/test-runtime/src/settings-scope.ts index c901221018..377ed84210 100644 --- a/packages/client/test-runtime/src/settings-scope.ts +++ b/packages/client/test-runtime/src/settings-scope.ts @@ -8,6 +8,8 @@ export interface StubSettingsScope { scope: SettingsScope /** Spy behind `scope.set`; resolves immediately. */ set: ReturnType + /** Spy behind `scope.unset`; resolves immediately. */ + unset: ReturnType /** @returns how many listeners are currently subscribed (disposal assertions). */ listenerCount(): number /** @@ -25,10 +27,12 @@ export interface StubSettingsScope { */ export function stubSettingsScope(): StubSettingsScope { let snapshot: SettingsScopeSnapshot = { - status: 'loading', value: undefined, revision: undefined, writable: false, mode: 'host', + status: 'loading', value: undefined, base: undefined, user: undefined, + revision: undefined, writable: false, mode: 'host', } const listeners = new Set<() => void>() const set = vi.fn(() => Promise.resolve()) + const unset = vi.fn(() => Promise.resolve()) return { scope: { getSnapshot: () => snapshot, @@ -37,8 +41,10 @@ export function stubSettingsScope(): StubSettingsScope { return () => { listeners.delete(listener) } }, set, + unset, }, set, + unset, listenerCount: () => listeners.size, publish: (next) => { snapshot = { ...snapshot, ...next } diff --git a/packages/client/test-runtime/tests/runtime.spec.tsx b/packages/client/test-runtime/tests/runtime.spec.tsx index 23320387c5..9c012bce6d 100644 --- a/packages/client/test-runtime/tests/runtime.spec.tsx +++ b/packages/client/test-runtime/tests/runtime.spec.tsx @@ -7,6 +7,7 @@ * stack — this suite is the fixture the migrated feature specs rely on. */ import { afterEach, describe, expect, it, vi } from 'vitest' +import { stubSettingsScope } from '../src/settings-scope.ts' import { cleanup } from '@testing-library/react' import { defineStore } from '@deepseek-ai/dsh-client-runtime/client' import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' @@ -635,3 +636,32 @@ describe('single-slot mounting edge arms', () => { await runtime.dispose() }) }) + +describe('stubbed settings scope', () => { + it('records both write kinds and publishes a Host acceptance to its listeners', async () => { + const host = stubSettingsScope<{ preference: string }>() + let notified = 0 + const stop = host.scope.subscribe(() => { notified += 1 }) + expect(host.listenerCount()).toBe(1) + expect(host.scope.getSnapshot()).toMatchObject({ + status: 'loading', base: undefined, user: undefined, + }) + + await host.scope.set('preference', 'dark') + await host.scope.unset('preference') + host.publish({ + status: 'ready', + value: { preference: 'system' }, + base: { preference: 'system' }, + revision: 2, + writable: true, + }) + + expect(host.set).toHaveBeenCalledWith('preference', 'dark') + expect(host.unset).toHaveBeenCalledWith('preference') + expect(notified).toBe(1) + expect(host.scope.getSnapshot()).toMatchObject({ status: 'ready', revision: 2, writable: true }) + stop() + expect(host.listenerCount()).toBe(0) + }) +}) diff --git a/packages/client/ui-attachment/README.i18n.yaml b/packages/client/ui-attachment/README.i18n.yaml new file mode 100644 index 0000000000..faea84bfdb --- /dev/null +++ b/packages/client/ui-attachment/README.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 packages/client/ui-attachment/README.md +README.md: 9fab9c23b958606030b1e87fcbfa45130c980947 +README.zh.md: 668dba11154538f52a9a87692020868c1b8a63d5 diff --git a/packages/client/ui-attachment/README.md b/packages/client/ui-attachment/README.md new file mode 100644 index 0000000000..9fab9c23b9 --- /dev/null +++ b/packages/client/ui-attachment/README.md @@ -0,0 +1,27 @@ +# @deepseek-ai/dsh-client-ui-attachment + +English | [中文](README.zh.md) + +Pure React attachment atoms (zero cordis): the composer draft-image rail (`AttachmentRail`), the chat-history image gallery (`MessageImage`/`ImageGallery`), and the original-image lightbox (`ImageLightbox`). Every string arrives through label props resolved by the owning plugin's own locale namespace, and nothing here reads application state; `@deepseek-ai/dsh-client-ui-conversation` is the current consumer, bridging its `conversation` dictionary through its `image-labels` module. + +## Attachment rail + +`AttachmentRail` renders pending draft images as fixed 64px thumbnails (16px radius) in one horizontally scrolling row whose scrollbar stays hidden. Overflow is announced by circular edge arrows instead: each pages one viewport (minus one card of context, floored at 200px) with smooth scrolling (instant under `prefers-reduced-motion: reduce`), and arrow visibility is recomputed from scroll geometry on scroll, item-count changes, and rail size changes (a ResizeObserver on the rail element, so sidebar and panel resizes count, not only window resizes). The rail scrolls horizontally only: a non-passive listener consumes every wheel tick with a vertical component — nothing scrolls the conversation behind the composer — converting a pure vertical wheel to a horizontal step (LINE/PAGE deltas normalized to pixels, per-tick travel clamped to 60px) and keeping a diagonal pan's horizontal intent, while purely horizontal pans stay native. A newly added item is revealed at the rail's end; removal keeps the scroll position, and a rail that mounts over an already-populated draft keeps its start position. Each thumbnail opens its original through `onOpen` on a single click, and its remove control sits inside the card's top-right corner, hidden until the card is hovered or the control keyboard-focused; coarse-pointer (touch) surfaces show it permanently because they have no hover. The owner decides mounting and renders the rail only while items exist. + +## Message images and the lightbox + +`MessageImage` renders one durable history image bounded to 240px on its longer edge, loading a session-authorized URL through the owner's `ImageLoader`; a failed load renders an explicit retry control, and a settled load answers a single click by opening `ImageLightbox` (clicks during loading are ignored). `ImageGallery` wraps a message's images in one aligned flex group (`end` for user messages, `start` for assistant messages) and renders nothing for an empty list. `ImageLightbox` is a document-level modal preview that closes on Escape, a backdrop press, or its close control, and restores focus to its opener on unmount. + +## Model Experience + +None, as the package renders pure React atoms in the browser; nothing here reaches a model request. + +#### KV Cache effect + +None; this package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + +- **Images only** — non-image files have no rail card or history renderer yet; DeepSeek Chat-style file cards and upload-progress states wait until the composer accepts non-image attachments. +- **No zoom or download in the lightbox** — the preview renders the original at fit-to-viewport size only. +- **The lightbox does not trap focus** — it sets `aria-modal` and restores focus on close, but Tab can reach the page behind it (behavior carried over from the pre-package component). diff --git a/packages/client/ui-attachment/README.zh.md b/packages/client/ui-attachment/README.zh.md new file mode 100644 index 0000000000..668dba1115 --- /dev/null +++ b/packages/client/ui-attachment/README.zh.md @@ -0,0 +1,27 @@ +# @deepseek-ai/dsh-client-ui-attachment + +[English](README.md) | 中文 + +纯 React 附件原子组件(零 cordis):输入框草稿图片栏(`AttachmentRail`)、聊天历史图片画廊(`MessageImage`/`ImageGallery`)与原图灯箱(`ImageLightbox`)。所有文案都由持有方插件在自己的语言命名空间中解析后经 label props 传入,此包不读取任何应用状态;当前消费者是 `@deepseek-ai/dsh-client-ui-conversation`,经其 `image-labels` 模块桥接 `conversation` 词典。 + +## 附件栏 + +`AttachmentRail` 将待发送草稿图片渲染为固定 64px(16px 圆角)的缩略图横排,滚动条始终隐藏,溢出改由两端的圆形箭头提示:每次翻页滚动一个视口宽度(减去一张卡片作为上下文,下限 200px)并平滑滚动(`prefers-reduced-motion: reduce` 下瞬时完成),箭头的显隐在滚动、条目数量变化和栏自身尺寸变化时依据滚动几何重算(rail 元素上的 ResizeObserver,因此侧栏、面板的宽度变化也计入,不只是窗口尺寸变化)。附件栏只允许横向滚动:非 passive 监听器消费所有带纵向分量的滚轮事件——不会滚动输入框背后的会话记录——纯纵向滚轮转为横向步进(LINE/PAGE 单位先归一化为像素,单次行程钳制在 60px 内),对角平移保留其横向分量,纯横向平移保持原生滚动。新增条目会滚动到栏尾展示,删除则保持原位,带着已有草稿重新挂载的栏保持起始位置。每张缩略图单击经 `onOpen` 打开原图,删除按钮位于卡片内部右上角,悬停卡片或键盘聚焦时才显示;粗指针(触屏)设备没有悬停,因此常显。是否挂载由持有方决定,仅在有条目时渲染。 + +## 消息图片与灯箱 + +`MessageImage` 渲染一张持久化历史图片,长边收敛到 240px,经持有方的 `ImageLoader` 加载会话授权 URL;加载失败渲染显式重试按钮,加载完成后单击打开 `ImageLightbox`(加载中的点击被忽略)。`ImageGallery` 将一条消息的图片包为一个对齐的弹性分组(用户消息 `end`,助手消息 `start`),空列表不渲染。`ImageLightbox` 是文档级模态预览,按 Escape、按下遮罩或点关闭按钮均可关闭,卸载时将焦点还给打开者。 + +## 模型体验 + +无。该包(package)在浏览器中渲染纯 React 原子组件;这里没有任何内容进入模型请求。 + +#### KV Cache 影响 + +无;该包既不组装也不发送提供方请求。 + +## 已知限制与暂缓事项 + +- **仅支持图片** — 非图片文件尚无附件栏卡片与历史渲染;DeepSeek Chat 风格的文件卡片和上传进度状态等输入框接受非图片附件后再做。 +- **灯箱无缩放与下载** — 预览仅以适配视口的尺寸渲染原图。 +- **灯箱不锁定焦点** — 它设置 `aria-modal` 并在关闭时归还焦点,但 Tab 仍可移动到背后的页面(沿袭入包前组件的行为)。 diff --git a/packages/client/ui-attachment/package.json b/packages/client/ui-attachment/package.json new file mode 100644 index 0000000000..e894a42196 --- /dev/null +++ b/packages/client/ui-attachment/package.json @@ -0,0 +1,51 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-attachment", + "description": "Pure React attachment atoms for the dsh web UI: draft-image rail, message image gallery, and original-image lightbox (zero cordis)", + "version": "0.0.1-rc.1", + "publishConfig": { + "access": "restricted" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-attachment" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "license": "BSD-3-Clause", + "dependencies": { + "@deepseek-ai/dsh-attachment": "workspace:^", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", + "clsx": "^2.0.0", + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@types/react": "~18.3.1", + "@types/react-dom": "~18.3.0" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts" + ], + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^" + } +} diff --git a/packages/client/ui-attachment/src/AttachmentRail.module.css b/packages/client/ui-attachment/src/AttachmentRail.module.css new file mode 100644 index 0000000000..ac8968f777 --- /dev/null +++ b/packages/client/ui-attachment/src/AttachmentRail.module.css @@ -0,0 +1,118 @@ +/* Thumbnail geometry mirrors DeepSeek Chat's composer rail: 64px cards with a + 16px radius, remove control fully inside the card, arrows overlaid at the + edges instead of a scrollbar. */ + +.root { + position: relative; + min-width: 0; +} + +.rail { + display: flex; + gap: 10px; + overflow-x: auto; + overflow-y: hidden; + /* Edge arrows page the overflow; the scrollbar stays hidden (both engines). */ + scrollbar-width: none; + /* The rail scrolls on the composer's elevated input surface: bind the l2 + pair (ui-theme styles/scrollbar.css rebinding contract) so anything that + does draw a thumb here matches the surface. */ + --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); + --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); +} + +.rail::-webkit-scrollbar { + display: none; +} + +.item { + position: relative; + flex: 0 0 64px; + width: 64px; + height: 64px; +} + +.thumbnail { + width: 64px; + height: 64px; + padding: 0; + overflow: hidden; + border: 1px solid var(--dsw-alias-border-l2-darkmode-thin); + border-radius: 16px; + background: var(--dsw-alias-interactive-bg-hover); + cursor: zoom-in; +} + +.thumbnail img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; +} + +.remove { + position: absolute; + top: 4px; + right: 4px; + z-index: 1; + display: grid; + place-items: center; + width: 18px; + height: 18px; + padding: 0; + border: none; + border-radius: 50%; + background: var(--dsw-alias-button-contrast-fill); + color: var(--dsw-alias-label-primary-inverted); + cursor: pointer; + opacity: 0; + transition: opacity 0.2s ease-in-out; +} + +.item:hover .remove, +.remove:focus-visible { + opacity: 1; +} + +/* Touch surfaces have no hover to reveal the control. */ +@media (pointer: coarse) { + .remove { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .remove { + transition: none; + } +} + +.arrow { + position: absolute; + top: 50%; + z-index: 2; + display: grid; + place-items: center; + width: 24px; + height: 24px; + padding: 0; + border: 1px solid var(--dsw-alias-border-l2-darkmode-thin); + border-radius: 999px; + background: var(--dsw-specific-input-major); + color: var(--dsw-alias-label-secondary); + box-shadow: var(--dsw-shadow-lv2); + cursor: pointer; + transform: translateY(-50%); +} + +.arrow:hover { + background: var(--dsw-alias-interactive-bg-hover-solid); +} + +.arrowLeft { + left: 4px; +} + +.arrowRight { + right: 4px; +} diff --git a/packages/client/ui-attachment/src/AttachmentRail.tsx b/packages/client/ui-attachment/src/AttachmentRail.tsx new file mode 100644 index 0000000000..65e2df109b --- /dev/null +++ b/packages/client/ui-attachment/src/AttachmentRail.tsx @@ -0,0 +1,200 @@ +/** Draft-attachment thumbnail rail: scrollbar-less horizontal overflow paged + * by edge arrows, hover-revealed per-item remove, single-click open. */ + +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' +import clsx from 'clsx' +import { + IconChevronLeftOutline14, IconChevronRightOutline14, IconCloseFill14, +} from '@deepseek-ai/dsh-client-ui-primitives' +import css from './AttachmentRail.module.css' + +/** One rail thumbnail; strings arrive resolved (zero-cordis atom). */ +export interface AttachmentRailItem { + /** Stable identity for the React key. */ + id: string + /** Object or data URL rendered as the thumbnail. */ + previewUrl: string + /** Image alt text (display name with the owner's fallback applied). */ + alt: string + /** Accessible label of the item's remove control. */ + removeLabel: string +} + +/** Rail-level strings the owner resolves from its own locale namespace. */ +export interface AttachmentRailLabels { + /** Accessible name of the rail group. */ + group: string + /** Thumbnail tooltip inviting the original-image preview. */ + open: string + /** Accessible label of the left paging arrow. */ + scrollLeft: string + /** Accessible label of the right paging arrow. */ + scrollRight: string +} + +/** Approximate pixels per wheel step for `deltaMode` LINE deltas (Firefox + * notch wheels report lines, not pixels). */ +const WHEEL_LINE_PX = 16 + +/** Smooth paging unless the user asked for reduced motion. */ +function pageBehavior(): ScrollBehavior { + // jsdom (the unit lane) implements no matchMedia despite lib.dom's + // non-optional typing; the optional call keeps that lane on the default. + // oxlint-disable-next-line typescript/no-unnecessary-condition + return window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' +} + +/** + * Horizontal thumbnail rail over the caller's draft attachments. + * + * The rail scrolls with its scrollbar hidden; overflow is announced by edge + * arrows recomputed from scroll geometry on scroll, item-count changes, and + * rail size changes (a ResizeObserver on the rail element, so sidebar or + * panel resizes count, not only window resizes). A vertical wheel pans the + * rail horizontally and is consumed exclusively (non-passive listener), a + * newly added item is revealed at the rail's end while a rail that mounts + * over an existing draft keeps its start position, and each thumbnail opens + * on a single click while its remove control sits inside the card and + * reveals on hover or focus. The owner decides mounting; it renders the rail + * only while items exist. + * + * @param props.items - resolved thumbnails in draft order. + * @param props.labels - rail-level strings (group name, open tooltip, arrows). + * @param props.onOpen - single-click open of one item's original image. + * @param props.onRemove - remove one item from the draft. + * @returns the rail group with its paging arrows. + */ +export function AttachmentRail({ items, labels, onOpen, onRemove }: { + items: readonly T[] + labels: AttachmentRailLabels + onOpen: (item: T) => void + onRemove: (item: T) => void +}) { + const railRef = useRef(null) + // null marks the first layout pass: a rail that MOUNTS over an existing + // draft (session switch back to held images) is initial display, not + // growth, and must not jump to the end. + const countRef = useRef(null) + const [edges, setEdges] = useState({ left: false, right: false }) + const updateEdges = useCallback(() => { + const el = railRef.current + /* v8 ignore next -- defensive: every caller runs while the rail element is mounted. */ + if (el === null) return + // 1px slack: engines report fractional scroll positions at the edges. + const left = el.scrollLeft > 1 + const right = el.scrollLeft < el.scrollWidth - el.clientWidth - 1 + setEdges(prev => prev.left === left && prev.right === right ? prev : { left, right }) + }, []) + useLayoutEffect(() => { + const grew = countRef.current !== null && items.length > countRef.current + countRef.current = items.length + const el = railRef.current + /* v8 ignore next -- defensive: the rail div renders unconditionally, so the layout effect always finds it. */ + if (el === null) return + // A newly added attachment lands at the rail's end: reveal it. + if (grew) el.scrollLeft = el.scrollWidth - el.clientWidth + updateEdges() + }, [items.length, updateEdges]) + useEffect(() => { + const el = railRef.current + /* v8 ignore next -- defensive: the rail div renders unconditionally, so the mount effect always finds it. */ + if (el === null) return + // The rail's width follows the composer, which resizes with sidebars and + // panels, not only the window — observe the element itself. jsdom (the + // unit lane) implements no ResizeObserver; every browser gets the + // subscription. + let disconnect = (): void => {} + if (typeof ResizeObserver !== 'undefined') { + const observer = new ResizeObserver(updateEdges) + observer.observe(el) + disconnect = () => { observer.disconnect() } + } + // The rail scrolls horizontally ONLY: any wheel tick with a vertical + // component is consumed — without preventDefault it would also scroll the + // conversation behind the composer, and React's root wheel listener is + // passive, so the exclusion needs this manually attached non-passive + // listener. A diagonal trackpad pan keeps its horizontal intent; a pure + // vertical wheel converts to a horizontal step, with LINE and PAGE deltas + // (Firefox notch wheels) normalized to pixels before the per-tick clamp + // that keeps a fast wheel followable. A purely horizontal pan stays + // native. + const onWheel = (event: globalThis.WheelEvent): void => { + if (event.deltaY === 0) return + const scale = event.deltaMode === WheelEvent.DOM_DELTA_LINE + ? WHEEL_LINE_PX + : event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? el.clientWidth : 1 + event.preventDefault() + el.scrollBy({ + left: event.deltaX !== 0 + ? event.deltaX * scale + : Math.sign(event.deltaY) * Math.min(Math.abs(event.deltaY) * scale, 60), + behavior: 'auto', + }) + } + el.addEventListener('wheel', onWheel, { passive: false }) + return () => { + disconnect() + el.removeEventListener('wheel', onWheel) + } + }, [updateEdges]) + const page = (direction: -1 | 1): void => { + const el = railRef.current + /* v8 ignore next -- defensive: the arrows render only while the rail is mounted, so a click cannot find a null ref. */ + if (el === null) return + // One viewport minus a card keeps the last visible thumbnail as context; + // the floor keeps narrow rails paging a useful distance. + el.scrollBy({ left: direction * Math.max(el.clientWidth - 64, 200), behavior: pageBehavior() }) + } + return ( +
+ {edges.left && ( + + )} +
+ {items.map(item => ( +
+ + +
+ ))} +
+ {edges.right && ( + + )} +
+ ) +} diff --git a/packages/client/ui-conversation/src/client/skeleton/ImageLightbox.module.css b/packages/client/ui-attachment/src/ImageLightbox.module.css similarity index 100% rename from packages/client/ui-conversation/src/client/skeleton/ImageLightbox.module.css rename to packages/client/ui-attachment/src/ImageLightbox.module.css diff --git a/packages/client/ui-attachment/src/ImageLightbox.tsx b/packages/client/ui-attachment/src/ImageLightbox.tsx new file mode 100644 index 0000000000..0207ee5a53 --- /dev/null +++ b/packages/client/ui-attachment/src/ImageLightbox.tsx @@ -0,0 +1,61 @@ +import { useEffect, useRef } from 'react' +import { createPortal } from 'react-dom' +import css from './ImageLightbox.module.css' + +/** Lightbox strings the owner resolves from its own locale namespace. */ +export interface ImageLightboxLabels { + /** Accessible name of the preview dialog. */ + dialog: string + /** Accessible label of the close control. */ + close: string +} + +/** + * Document-level original-image preview opened by clicking a thumbnail. + * Closes on Escape, backdrop press, or the close control, and restores focus + * to the opener on unmount. Rendered through a body portal: an opener inside + * a transformed or filtered ancestor would otherwise trap the fixed backdrop + * in that ancestor's box instead of covering the viewport. + * + * @param props.src - the original image URL. + * @param props.alt - the image's alt text. + * @param props.labels - dialog and close-control strings. + * @param props.onClose - dismiss callback owned by the opener. + * @returns the modal preview dialog. + */ +export function ImageLightbox({ src, alt, labels, onClose }: { + src: string + alt: string + labels: ImageLightboxLabels + onClose: () => void +}) { + const closeRef = useRef(null) + const restoreRef = useRef(null) + + useEffect(() => { + restoreRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null + closeRef.current?.focus() + const onKeyDown = (event: globalThis.KeyboardEvent): void => { + if (event.key === 'Escape') onClose() + } + window.addEventListener('keydown', onKeyDown) + return () => { + window.removeEventListener('keydown', onKeyDown) + restoreRef.current?.focus() + } + }, [onClose]) + + return createPortal( +
{ if (event.target === event.currentTarget) onClose() }} + > + {alt} + +
, + document.body, + ) +} diff --git a/packages/client/ui-conversation/src/client/chat/MessageImage.module.css b/packages/client/ui-attachment/src/MessageImage.module.css similarity index 97% rename from packages/client/ui-conversation/src/client/chat/MessageImage.module.css rename to packages/client/ui-attachment/src/MessageImage.module.css index e05a6fc625..17ac423640 100644 --- a/packages/client/ui-conversation/src/client/chat/MessageImage.module.css +++ b/packages/client/ui-attachment/src/MessageImage.module.css @@ -24,7 +24,7 @@ padding: 0; overflow: hidden; border: 1px solid var(--dsw-alias-border-l2-darkmode-thin); - border-radius: 12px; + border-radius: 16px; background: var(--dsw-alias-interactive-bg-hover); cursor: zoom-in; } diff --git a/packages/client/ui-attachment/src/MessageImage.tsx b/packages/client/ui-attachment/src/MessageImage.tsx new file mode 100644 index 0000000000..15420c9569 --- /dev/null +++ b/packages/client/ui-attachment/src/MessageImage.tsx @@ -0,0 +1,95 @@ +import { useCallback, useEffect, useMemo, useState } from 'react' +import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' +import { ImageLightbox } from './ImageLightbox.tsx' +import type { ImageLightboxLabels } from './ImageLightbox.tsx' +import css from './MessageImage.module.css' + +/** Loads a session-authorized durable image URL. */ +export type ImageLoader = (attachment: ImageAttachmentRef) => Promise + +/** Message-image strings the owner resolves from its own locale namespace. */ +export interface MessageImageLabels { + /** Fallback display name for an unnamed image. */ + image: string + /** Thumbnail tooltip inviting the original-image preview. */ + open: string + /** Accessible thumbnail label; receives the image's display name. */ + openNamed: (label: string) => string + /** Loading placeholder shown until bytes resolve. */ + loading: string + /** Retry-control label shown when the load fails. */ + loadFailed: string + /** Lightbox strings forwarded to the opened preview. */ + lightbox: ImageLightboxLabels +} + +/** + * Compact history renderer with retryable loading and click-to-open original + * preview. + * + * @param props.attachment - the durable image reference to load and bound. + * @param props.load - session-authorized URL loader. + * @param props.labels - resolved strings (tooltip, loading, retry, lightbox). + * @returns the bounded thumbnail button, or the retry control on failure. + */ +export function MessageImage({ attachment, load, labels }: { + attachment: ImageAttachmentRef + load: ImageLoader + labels: MessageImageLabels +}) { + const [src, setSrc] = useState(null) + const [error, setError] = useState(false) + const [open, setOpen] = useState(false) + // Retry re-arms the one load effect below, so every attempt — first load or + // retry — runs under the same liveness guard and the same reset. + const [attempt, setAttempt] = useState(0) + const request = useCallback(() => { setAttempt(a => a + 1) }, []) + const close = useCallback(() => { setOpen(false) }, []) + const size = useMemo(() => { + const scale = Math.min(1, 240 / attachment.width, 240 / attachment.height) + return { width: Math.max(1, Math.round(attachment.width * scale)), height: Math.max(1, Math.round(attachment.height * scale)) } + }, [attachment.height, attachment.width]) + + useEffect(() => { + let live = true + setError(false) + setSrc(null) + void load(attachment).then((url) => { if (live) setSrc(url) }).catch(() => { if (live) setError(true) }) + return () => { live = false } + }, [attachment, load, attempt]) + + const label = attachment.name ?? labels.image + if (error) return + return ( + <> + + {open && src !== null && } + + ) +} + +/** Wrapping image group shared by user and assistant history. */ +export function ImageGallery({ images, load, align, labels }: { + images: readonly { attachment: ImageAttachmentRef }[] + load: ImageLoader + align: 'start' | 'end' + labels: MessageImageLabels +}) { + if (images.length === 0) return null + return ( +
+ {images.map((image, index) => ( + + ))} +
+ ) +} diff --git a/packages/client/ui-attachment/src/css-modules.d.ts b/packages/client/ui-attachment/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-attachment/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-attachment/src/index.ts b/packages/client/ui-attachment/src/index.ts new file mode 100644 index 0000000000..8757915fee --- /dev/null +++ b/packages/client/ui-attachment/src/index.ts @@ -0,0 +1,14 @@ +/** + * Pure React attachment atoms (zero cordis): the composer draft-image rail, + * the chat-history image gallery, and the original-image lightbox. Owners + * resolve every string through their own locale namespace and pass it down; + * nothing here reads application state. + * @module @deepseek-ai/dsh-client-ui-attachment + */ + +export { AttachmentRail } from './AttachmentRail.tsx' +export type { AttachmentRailItem, AttachmentRailLabels } from './AttachmentRail.tsx' +export { ImageLightbox } from './ImageLightbox.tsx' +export type { ImageLightboxLabels } from './ImageLightbox.tsx' +export { ImageGallery, MessageImage } from './MessageImage.tsx' +export type { ImageLoader, MessageImageLabels } from './MessageImage.tsx' diff --git a/packages/client/ui-attachment/src/invariant.ts b/packages/client/ui-attachment/src/invariant.ts new file mode 100644 index 0000000000..47d18f97b8 --- /dev/null +++ b/packages/client/ui-attachment/src/invariant.ts @@ -0,0 +1,31 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-attachment`. + * @module @deepseek-ai/dsh-client-ui-attachment/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from '@deepseek-ai/cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-attachment' + +/** Cordis companion plugin name. */ +export const name = 'client-ui-attachment-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: pure props-in React atoms with no Cordis API — + * no events, no services, no mutable cross-plugin state; rendering contracts + * are asserted directly by this package's component specs. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/client/ui-attachment/tests/attachment-rail.spec.tsx b/packages/client/ui-attachment/tests/attachment-rail.spec.tsx new file mode 100644 index 0000000000..a373464b61 --- /dev/null +++ b/packages/client/ui-attachment/tests/attachment-rail.spec.tsx @@ -0,0 +1,173 @@ +// @vitest-environment jsdom +// AttachmentRail behavior in the jsdom lane: item rendering and callbacks, +// arrow paging over stubbed scroll geometry (jsdom lays nothing out), the +// exclusive vertical-wheel pan, and the new-item end reveal. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render } from '@testing-library/react' +import { AttachmentRail } from '../src/AttachmentRail.tsx' +import type { AttachmentRailItem, AttachmentRailLabels } from '../src/AttachmentRail.tsx' + +afterEach(cleanup) + +// jsdom implements no ResizeObserver; the stub records instances so a test +// can drive the size-change recompute path. +const observers: { callback: ResizeObserverCallback; observed: Element[] }[] = [] +beforeEach(() => { + observers.length = 0 + vi.stubGlobal('ResizeObserver', class { + observed: Element[] = [] + constructor(callback: ResizeObserverCallback) { + observers.push({ callback, observed: this.observed }) + } + + observe(el: Element) { this.observed.push(el) } + disconnect() { this.observed.length = 0 } + }) +}) +afterEach(() => { vi.unstubAllGlobals() }) + +const labels: AttachmentRailLabels = { + group: '待发送图片', + open: '查看原图', + scrollLeft: '向左滚动图片', + scrollRight: '向右滚动图片', +} + +function item(id: string): AttachmentRailItem { + return { id, previewUrl: `blob:${id}`, alt: `${id}.png`, removeLabel: `移除图片 ${id}.png` } +} + +/** Stub the rail's scroll geometry (jsdom reports 0 for every metric). */ +function stubGeometry(rail: HTMLElement, { scrollWidth, clientWidth }: { scrollWidth: number; clientWidth: number }) { + Object.defineProperty(rail, 'scrollWidth', { value: scrollWidth, configurable: true }) + Object.defineProperty(rail, 'clientWidth', { value: clientWidth, configurable: true }) + let scrollLeft = 0 + Object.defineProperty(rail, 'scrollLeft', { + configurable: true, + get: () => scrollLeft, + set: (value: number) => { scrollLeft = value }, + }) + const scrollBy = vi.fn((options: { left: number }) => { + scrollLeft = Math.max(0, Math.min(scrollWidth - clientWidth, scrollLeft + options.left)) + }) + rail.scrollBy = scrollBy as unknown as typeof rail.scrollBy + return { scrollBy, setScrollLeft: (value: number) => { scrollLeft = value } } +} + +describe('AttachmentRail', () => { + it('renders thumbnails in order and routes open and remove clicks', () => { + const onOpen = vi.fn() + const onRemove = vi.fn() + const items = [item('a'), item('b')] + const view = render() + const rail = view.getByRole('group', { name: '待发送图片' }) + expect([...rail.querySelectorAll('img')].map(img => img.getAttribute('alt'))).toEqual(['a.png', 'b.png']) + fireEvent.click(view.getAllByTitle('查看原图')[0]!) + expect(onOpen).toHaveBeenCalledWith(items[0]) + fireEvent.click(view.getByRole('button', { name: '移除图片 b.png' })) + expect(onRemove).toHaveBeenCalledWith(items[1]) + }) + + it('shows edge arrows from scroll geometry and pages a viewport at a time', () => { + const view = render( + , + ) + const rail = view.getByRole('group', { name: '待发送图片' }) + const { scrollBy } = stubGeometry(rail, { scrollWidth: 400, clientWidth: 200 }) + // No arrows until geometry is observed (mount saw jsdom's zero metrics). + expect(view.queryByLabelText('向右滚动图片')).toBeNull() + fireEvent.scroll(rail) + // Same-edges scroll takes the memoized-state path. + fireEvent.scroll(rail) + expect(view.queryByLabelText('向左滚动图片')).toBeNull() + const right = view.getByLabelText('向右滚动图片') + // clientWidth 200 - 64 < the 200 floor: pages by the floor. + fireEvent.click(right) + expect(scrollBy).toHaveBeenCalledWith({ left: 200, behavior: 'smooth' }) + fireEvent.scroll(rail) + // Scrolled to the far edge: only the left arrow remains. + expect(view.queryByLabelText('向右滚动图片')).toBeNull() + fireEvent.click(view.getByLabelText('向左滚动图片')) + expect(scrollBy).toHaveBeenCalledWith({ left: -200, behavior: 'smooth' }) + fireEvent.scroll(rail) + expect(view.queryByLabelText('向左滚动图片')).toBeNull() + expect(view.getByLabelText('向右滚动图片')).toBeTruthy() + }) + + it('shows both arrows mid-scroll and recomputes when the rail itself resizes', () => { + const view = render( + , + ) + const rail = view.getByRole('group', { name: '待发送图片' }) + const { setScrollLeft } = stubGeometry(rail, { scrollWidth: 400, clientWidth: 200 }) + setScrollLeft(100) + // The component observes the rail element, not the window: a sidebar or + // panel resize reaches it through the ResizeObserver callback. + expect(observers.at(-1)?.observed).toContain(rail) + act(() => { observers.at(-1)!.callback([], undefined as never) }) + expect(view.getByLabelText('向左滚动图片')).toBeTruthy() + expect(view.getByLabelText('向右滚动图片')).toBeTruthy() + }) + + it('pans horizontally on a vertical wheel, consuming the event, with clamped normalized travel', () => { + const view = render( + , + ) + const rail = view.getByRole('group', { name: '待发送图片' }) + const { scrollBy } = stubGeometry(rail, { scrollWidth: 400, clientWidth: 200 }) + // Converted ticks are consumed (preventDefault): fireEvent returns false. + expect(fireEvent.wheel(rail, { deltaY: 30 })).toBe(false) + expect(scrollBy).toHaveBeenCalledWith({ left: 30, behavior: 'auto' }) + fireEvent.wheel(rail, { deltaY: 500 }) + expect(scrollBy).toHaveBeenCalledWith({ left: 60, behavior: 'auto' }) + fireEvent.wheel(rail, { deltaY: -500 }) + expect(scrollBy).toHaveBeenCalledWith({ left: -60, behavior: 'auto' }) + // Firefox notch wheels report lines; a page-mode wheel reports viewports. + fireEvent.wheel(rail, { deltaY: 2, deltaMode: WheelEvent.DOM_DELTA_LINE }) + expect(scrollBy).toHaveBeenCalledWith({ left: 32, behavior: 'auto' }) + fireEvent.wheel(rail, { deltaY: -1, deltaMode: WheelEvent.DOM_DELTA_PAGE }) + expect(scrollBy).toHaveBeenCalledWith({ left: -60, behavior: 'auto' }) + // A diagonal pan is consumed too — nothing vertical may escape the rail — + // and keeps its horizontal intent. + expect(fireEvent.wheel(rail, { deltaX: 12, deltaY: 30 })).toBe(false) + expect(scrollBy).toHaveBeenCalledWith({ left: 12, behavior: 'auto' }) + // A purely horizontal pan and a zero-delta wheel keep native behavior. + expect(fireEvent.wheel(rail, { deltaX: 12, deltaY: 0 })).toBe(true) + fireEvent.wheel(rail, { deltaY: 0 }) + expect(scrollBy).toHaveBeenCalledTimes(6) + }) + + it('pages instantly under a reduced-motion preference, smoothly otherwise', () => { + for (const [matches, behavior] of [[true, 'auto'], [false, 'smooth']] as const) { + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches }) as MediaQueryList)) + const view = render( + , + ) + const rail = view.getByRole('group', { name: '待发送图片' }) + const { scrollBy } = stubGeometry(rail, { scrollWidth: 400, clientWidth: 200 }) + fireEvent.scroll(rail) + fireEvent.click(view.getByLabelText('向右滚动图片')) + expect(scrollBy).toHaveBeenCalledWith({ left: 200, behavior }) + view.unmount() + } + }) + + it('reveals the rail end when an item is added, not when one is removed', () => { + const first = [item('a'), item('b')] + const view = render( + , + ) + const rail = view.getByRole('group', { name: '待发送图片' }) + stubGeometry(rail, { scrollWidth: 400, clientWidth: 200 }) + view.rerender( + , + ) + expect(rail.scrollLeft).toBe(200) + view.rerender( + , + ) + // Removal keeps the position; only growth jumps to the end. + expect(rail.scrollLeft).toBe(200) + }) +}) diff --git a/packages/client/ui-attachment/tests/image-lightbox.spec.tsx b/packages/client/ui-attachment/tests/image-lightbox.spec.tsx new file mode 100644 index 0000000000..6152fc5ec2 --- /dev/null +++ b/packages/client/ui-attachment/tests/image-lightbox.spec.tsx @@ -0,0 +1,50 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { ImageLightbox } from '../src/ImageLightbox.tsx' + +afterEach(cleanup) + +const labels = { dialog: '原图预览', close: '关闭原图预览' } + +describe('ImageLightbox', () => { + it('focuses its close control, closes by button and Escape, and restores focus', () => { + const opener = document.createElement('button') + document.body.appendChild(opener) + opener.focus() + const onClose = vi.fn() + const view = render() + const close = view.getByRole('button', { name: '关闭原图预览' }) + expect(document.activeElement).toBe(close) + fireEvent.keyDown(window, { key: 'a' }) + expect(onClose).not.toHaveBeenCalled() + fireEvent.keyDown(window, { key: 'Escape' }) + fireEvent.click(close) + expect(onClose).toHaveBeenCalledTimes(2) + view.unmount() + expect(document.activeElement).toBe(opener) + opener.remove() + }) + + it('tolerates a focus owner it cannot restore (no active element at mount)', () => { + // jsdom always reports body as the fallback active element; stub the + // element-less state a detached focus can leave. + Object.defineProperty(document, 'activeElement', { configurable: true, get: () => null }) + try { + const view = render() + view.unmount() + } finally { + delete (document as { activeElement?: unknown }).activeElement + } + }) + + it('closes on a backdrop press but not on a press over the image', () => { + const onClose = vi.fn() + const view = render() + fireEvent.mouseDown(view.getByRole('img')) + expect(onClose).not.toHaveBeenCalled() + fireEvent.mouseDown(view.getByRole('dialog', { name: '原图预览' })) + expect(onClose).toHaveBeenCalledTimes(1) + }) +}) diff --git a/packages/client/ui-attachment/tests/invariant.spec.ts b/packages/client/ui-attachment/tests/invariant.spec.ts new file mode 100644 index 0000000000..4e76b3776f --- /dev/null +++ b/packages/client/ui-attachment/tests/invariant.spec.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import * as AttachmentInvariant from '@deepseek-ai/dsh-client-ui-attachment/invariant' +import InvariantService from '@deepseek-ai/dsh-invariants' + +describe('invariant companion', () => { + it('registers under the package name with an empty installer', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService, { enabled: true }) + await expect(ctx.plugin(AttachmentInvariant).await()).resolves.toBeDefined() + }) +}) diff --git a/packages/client/ui-attachment/tests/message-image.spec.tsx b/packages/client/ui-attachment/tests/message-image.spec.tsx new file mode 100644 index 0000000000..6dbf4cd746 --- /dev/null +++ b/packages/client/ui-attachment/tests/message-image.spec.tsx @@ -0,0 +1,103 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, waitFor } from '@testing-library/react' +import { AttachmentId } from '@deepseek-ai/dsh-attachment' +import { ImageGallery, MessageImage } from '../src/MessageImage.tsx' +import type { MessageImageLabels } from '../src/MessageImage.tsx' + +afterEach(cleanup) + +const labels: MessageImageLabels = { + image: '图片', + open: '查看原图', + openNamed: label => `${label},点击查看原图`, + loading: '图片加载中…', + loadFailed: '图片加载失败,点击重试', + lightbox: { dialog: '原图预览', close: '关闭原图预览' }, +} + +const attachment = { + attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png' as const, + bytes: 68, + width: 640, + height: 320, + name: 'history.png', +} + +describe('MessageImage', () => { + it('loads a session-authorized URL, bounds the thumbnail, and clicks into the original', async () => { + const load = vi.fn().mockResolvedValue('blob:history') + const view = render() + const frame = view.getByRole('button', { name: 'history.png,点击查看原图' }) + expect(frame.getAttribute('style')).toContain('width: 240px') + expect(frame.getAttribute('style')).toContain('height: 120px') + expect(frame.getAttribute('title')).toBe('查看原图') + await waitFor(() => { expect(view.getByAltText('history.png')).toBeTruthy() }) + expect(load).toHaveBeenCalledWith(attachment) + fireEvent.click(frame) + expect(view.getByRole('dialog', { name: '原图预览' })).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: '关闭原图预览' })) + expect(view.queryByRole('dialog', { name: '原图预览' })).toBeNull() + }) + + it('ignores a click while the thumbnail is still loading', () => { + const load = vi.fn(() => new Promise(() => {})) + const view = render() + const frame = view.getByRole('button', { name: 'history.png,点击查看原图' }) + expect(view.getByText('图片加载中…')).toBeTruthy() + fireEvent.click(frame) + expect(view.queryByRole('dialog')).toBeNull() + }) + + it('falls back to the image label for an unnamed attachment', async () => { + const { name: _named, ...unnamed } = attachment + const load = vi.fn().mockResolvedValue('blob:unnamed') + const view = render() + await waitFor(() => { expect(view.getByAltText('图片')).toBeTruthy() }) + expect(view.getByRole('button', { name: '图片,点击查看原图' })).toBeTruthy() + }) + + it('surfaces a retry control when durable bytes cannot be read, including a failed retry', async () => { + const load = vi.fn() + .mockRejectedValueOnce(new Error('offline')) + .mockRejectedValueOnce(new Error('still offline')) + .mockResolvedValueOnce('blob:retry') + const view = render() + const retry = await view.findByRole('button', { name: '图片加载失败,点击重试' }) + fireEvent.click(retry) + const retryAgain = await view.findByRole('button', { name: '图片加载失败,点击重试' }) + fireEvent.click(retryAgain) + await waitFor(() => { expect(view.getByAltText('history.png')).toBeTruthy() }) + expect(load).toHaveBeenCalledTimes(3) + }) + + it('ignores a load settling after unmount', async () => { + let resolve: ((url: string) => void) | undefined + const load = vi.fn(() => new Promise((r) => { resolve = r })) + const view = render() + view.unmount() + resolve?.('blob:late') + await Promise.resolve() + let reject: ((error: Error) => void) | undefined + const failing = vi.fn(() => new Promise((_r, rej) => { reject = rej })) + const second = render() + second.unmount() + reject?.(new Error('late failure')) + await Promise.resolve() + }) +}) + +describe('ImageGallery', () => { + it('renders nothing without images and an aligned wrapping group with them', async () => { + const load = vi.fn().mockResolvedValue('blob:gallery') + const empty = render() + expect(empty.container.firstChild).toBeNull() + const view = render( + , + ) + expect(view.container.querySelector('[data-align="end"]')).not.toBeNull() + await waitFor(() => { expect(view.getAllByAltText('history.png')).toHaveLength(2) }) + }) +}) diff --git a/packages/client/ui-attachment/tsconfig.json b/packages/client/ui-attachment/tsconfig.json new file mode 100644 index 0000000000..e034eef4e3 --- /dev/null +++ b/packages/client/ui-attachment/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../attachment/attachment" + }, + { + "path": "../../support/invariants" + }, + { + "path": "../ui-primitives" + } + ] +} diff --git a/packages/client/ui-attachment/tsdown.config.ts b/packages/client/ui-attachment/tsdown.config.ts new file mode 100644 index 0000000000..d8c37d8a2c --- /dev/null +++ b/packages/client/ui-attachment/tsdown.config.ts @@ -0,0 +1,35 @@ +import { clientOnly } from '../tsdown.client.ts' + +// TODO(client-atoms): verbatim copy of ui-primitives/tsdown.config.ts (only +// the package differs). On a third atoms package, extract a shared css-stub +// client-library preset in packages/client/tsdown.client.ts instead of a +// fourth copy. +/** + * ui-attachment is browser-only, but its lib bundle IS imported under plain + * Node because the web shell is a lib (dsh-client-web's lib chain reaches + * this package). CSS imports are therefore stubbed to empty modules instead + * of externalized — the hashed class maps only matter in bundler contexts + * (loader module table / vite source paths), which compile src directly and + * never read lib. + */ +export default clientOnly([{ + entry: ['lib/types/index.js', 'lib/types/invariant.js'], + outDir: 'lib', + format: ['esm'], + platform: 'neutral', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + plugins: [{ + name: 'dsh-css-stub', + resolveId(source: string) { + if (!source.endsWith('.css')) return null + return `\0dsh-css-stub:${source}.mjs` + }, + load(id: string) { + if (!id.startsWith('\0dsh-css-stub:')) return null + return 'export default {};' + }, + }], +}]) diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index 710cfa81bb..2f4258639b 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -61,6 +61,7 @@ "@deepseek-ai/dsh-client-connection": "workspace:^", "@deepseek-ai/dsh-client-locale": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", + "@deepseek-ai/dsh-client-ui-attachment": "workspace:^", "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-settings": "workspace:^", "@deepseek-ai/dsh-client-ui-slash": "workspace:^", @@ -84,6 +85,7 @@ "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-test-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-layout": "workspace:^", + "@deepseek-ai/dsh-client-ui-attachment": "workspace:^", "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-settings": "workspace:^", "@deepseek-ai/dsh-client-ui-slash": "workspace:^", diff --git a/packages/client/ui-conversation/src/client/chat/AssistantMarkdown.tsx b/packages/client/ui-conversation/src/client/chat/AssistantMarkdown.tsx index 7a8590c2b8..4365f4c453 100644 --- a/packages/client/ui-conversation/src/client/chat/AssistantMarkdown.tsx +++ b/packages/client/ui-conversation/src/client/chat/AssistantMarkdown.tsx @@ -13,8 +13,9 @@ import { memo, useMemo } from 'react' import type { AssistantBlock } from '@deepseek-ai/dsh-client-runtime/client' import { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' import type { MarkdownFileMentions } from '@deepseek-ai/dsh-client-ui-primitives' +import { ImageGallery, type ImageLoader } from '@deepseek-ai/dsh-client-ui-attachment' import type { ChatViewSlotProps } from '../contract/slots.ts' -import { ImageGallery, type ImageLoader } from './MessageImage.tsx' +import { messageImageLabels } from '../image-labels.ts' import { ReasoningRow } from './ReasoningRow.tsx' import css from './AssistantMarkdown.module.css' @@ -62,7 +63,7 @@ export const AssistantMarkdown = memo(function AssistantMarkdown({ /> ) case 'reasoning': return - case 'image': return + case 'image': return // Grouped into tool rows by ChatView; hasVisible above skips an empty shell. case 'tool-call': return null default: return ( diff --git a/packages/client/ui-conversation/src/client/chat/MessageImage.tsx b/packages/client/ui-conversation/src/client/chat/MessageImage.tsx deleted file mode 100644 index 3f22ff72b8..0000000000 --- a/packages/client/ui-conversation/src/client/chat/MessageImage.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { useCallback, useEffect, useMemo, useState } from 'react' -import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' -import type { ChatViewSlotProps } from '../contract/slots.ts' -import { ImageLightbox } from '../skeleton/ImageLightbox.tsx' -import css from './MessageImage.module.css' - -/** Loads a session-authorized durable image URL. */ -export type ImageLoader = (attachment: ImageAttachmentRef) => Promise - -/** Compact history renderer with retryable loading and double-click original preview. */ -export function MessageImage({ attachment, load, t }: { - attachment: ImageAttachmentRef - load: ImageLoader - t: ChatViewSlotProps['t'] -}) { - const [src, setSrc] = useState(null) - const [error, setError] = useState(false) - const [open, setOpen] = useState(false) - const close = useCallback(() => { setOpen(false) }, []) - const size = useMemo(() => { - const scale = Math.min(1, 240 / attachment.width, 240 / attachment.height) - return { width: Math.max(1, Math.round(attachment.width * scale)), height: Math.max(1, Math.round(attachment.height * scale)) } - }, [attachment.height, attachment.width]) - - const request = useCallback(() => { - setError(false) - setSrc(null) - void load(attachment).then(setSrc).catch(() => { setError(true) }) - }, [attachment, load]) - - useEffect(() => { - let live = true - setError(false) - void load(attachment).then((url) => { if (live) setSrc(url) }).catch(() => { if (live) setError(true) }) - return () => { live = false } - }, [attachment, load]) - - const label = attachment.name ?? t('image.label') - if (error) return - return ( - <> - - {open && src !== null && } - - ) -} - -/** Wrapping image group shared by user and assistant history. */ -export function ImageGallery({ images, load, align, t }: { - images: readonly { attachment: ImageAttachmentRef }[] - load: ImageLoader - align: 'start' | 'end' - t: ChatViewSlotProps['t'] -}) { - if (images.length === 0) return null - return ( -
- {images.map((image, index) => ( - - ))} -
- ) -} diff --git a/packages/client/ui-conversation/src/client/chat/MessageItem.tsx b/packages/client/ui-conversation/src/client/chat/MessageItem.tsx index f7c451ce8a..d2bfe8868f 100644 --- a/packages/client/ui-conversation/src/client/chat/MessageItem.tsx +++ b/packages/client/ui-conversation/src/client/chat/MessageItem.tsx @@ -10,10 +10,11 @@ import type { } from '@deepseek-ai/dsh-client-runtime/client' import { JsonBlock, MessageText, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' import type { ChatNodeViewProps, ChatViewSlotProps } from '../contract/slots.ts' +import { ImageGallery, type ImageLoader } from '@deepseek-ai/dsh-client-ui-attachment' +import { messageImageLabels } from '../image-labels.ts' import { CompactionItem } from './CompactionItem.tsx' import { ContextInjectionRow } from './ContextInjectionRow.tsx' import { MessageIconActions } from './MessageIconActions.tsx' -import { ImageGallery, type ImageLoader } from './MessageImage.tsx' import css from './MessageItem.module.css' type UserImage = Extract @@ -177,7 +178,7 @@ function UserStyleBubble({ return (
- + {showBubble &&
{projectUserText(text)} {rest.map((block, i) => )} diff --git a/packages/client/ui-conversation/src/client/image-labels.ts b/packages/client/ui-conversation/src/client/image-labels.ts new file mode 100644 index 0000000000..493ddbbbbe --- /dev/null +++ b/packages/client/ui-conversation/src/client/image-labels.ts @@ -0,0 +1,48 @@ +/** Bridges the `conversation` locale namespace to the zero-cordis attachment + * atoms' label props (`@deepseek-ai/dsh-client-ui-attachment` reads no + * application state; owners resolve every string). */ + +import type { + AttachmentRailLabels, ImageLightboxLabels, MessageImageLabels, +} from '@deepseek-ai/dsh-client-ui-attachment' +import type { Translate } from '@deepseek-ai/dsh-client-ui-slots' +import type { ConversationKey } from './locales.ts' + +/** + * Resolve the original-image lightbox strings. + * @param t - the conversation-namespace translate. + * @returns the lightbox dialog and close-control labels. + */ +export function lightboxLabels(t: Translate): ImageLightboxLabels { + return { dialog: t('image.preview'), close: t('image.closePreview') } +} + +/** + * Resolve the chat-history image strings. + * @param t - the conversation-namespace translate. + * @returns the message-image labels including the forwarded lightbox strings. + */ +export function messageImageLabels(t: Translate): MessageImageLabels { + return { + image: t('image.label'), + open: t('image.openOriginal'), + openNamed: label => t('image.openOriginalLabel', { label }), + loading: t('image.loading'), + loadFailed: t('image.loadFailed'), + lightbox: lightboxLabels(t), + } +} + +/** + * Resolve the composer draft-image rail strings. + * @param t - the conversation-namespace translate. + * @returns the rail group, open-tooltip, and paging-arrow labels. + */ +export function attachmentRailLabels(t: Translate): AttachmentRailLabels { + return { + group: t('image.pending'), + open: t('image.openOriginal'), + scrollLeft: t('image.scrollLeft'), + scrollRight: t('image.scrollRight'), + } +} diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index dcf04264e8..080bb9b67b 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -27,9 +27,11 @@ export const zh = { 'input.accessMode': '访问模式,当前:{name}', 'image.dropHint': '松开以添加图片', 'image.pending': '待发送图片', - 'image.openOriginal': '双击查看原图', - 'image.openOriginalLabel': '{label},双击查看原图', + 'image.openOriginal': '查看原图', + 'image.openOriginalLabel': '{label},点击查看原图', 'image.remove': '移除图片 {name}', + 'image.scrollLeft': '向左滚动图片', + 'image.scrollRight': '向右滚动图片', 'image.original': '原图', 'image.label': '图片', 'image.loadFailed': '图片加载失败,点击重试', @@ -184,9 +186,11 @@ export const en = { 'input.accessMode': 'Access mode, current: {name}', 'image.dropHint': 'Drop to add images', 'image.pending': 'Pending images', - 'image.openOriginal': 'Double-click to view original', - 'image.openOriginalLabel': '{label}, double-click to view original', + 'image.openOriginal': 'View original', + 'image.openOriginalLabel': '{label}, click to view original', 'image.remove': 'Remove image {name}', + 'image.scrollLeft': 'Scroll images left', + 'image.scrollRight': 'Scroll images right', 'image.original': 'Original image', 'image.label': 'Image', 'image.loadFailed': 'Image failed to load; click to retry', diff --git a/packages/client/ui-conversation/src/client/skeleton/ImageLightbox.tsx b/packages/client/ui-conversation/src/client/skeleton/ImageLightbox.tsx deleted file mode 100644 index 43cbc441a5..0000000000 --- a/packages/client/ui-conversation/src/client/skeleton/ImageLightbox.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { useEffect, useRef } from 'react' -import type { ChatViewSlotProps } from '../contract/slots.ts' -import css from './ImageLightbox.module.css' - -/** Document-level original-image preview opened by an explicit double-click. */ -export function ImageLightbox({ src, alt, onClose, t }: { - src: string - alt: string - onClose: () => void - t: ChatViewSlotProps['t'] -}) { - const closeRef = useRef(null) - const restoreRef = useRef(null) - - useEffect(() => { - restoreRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null - closeRef.current?.focus() - const onKeyDown = (event: globalThis.KeyboardEvent): void => { - if (event.key === 'Escape') onClose() - } - window.addEventListener('keydown', onKeyDown) - return () => { - window.removeEventListener('keydown', onKeyDown) - restoreRef.current?.focus() - } - }, [onClose]) - - return ( -
{ if (event.target === event.currentTarget) onClose() }} - > - {alt} - -
- ) -} diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css b/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css index ad1a6ed275..751e253e22 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css @@ -35,22 +35,6 @@ padding: 0 var(--dsh-composer-side-clearance); } -.error, -.status { - width: 100%; - max-width: var(--dsh-composer-card-max-width); - margin-bottom: 6px; - padding: 4px 8px; - border-radius: 8px; - font-size: 12px; - line-height: 18px; -} - -.status { - background: var(--dsw-alias-interactive-bg-hover); - color: var(--dsw-alias-label-secondary); -} - .notice { width: 100%; max-width: var(--dsh-composer-card-max-width); @@ -68,11 +52,6 @@ color: var(--dsw-alias-state-error-primary); } -.error { - background: var(--dsw-alias-interactive-bg-hover-danger); - color: var(--dsw-alias-state-error-primary); -} - .card { box-sizing: border-box; position: relative; /* overlay anchor positioning context */ @@ -162,55 +141,13 @@ padding: 10px 12px 0; } +/* Rail seat: the card's top padding (10px) plus this 4px matches DeepSeek + Chat's spacing above the thumbnails; the card's 12px flex gap owns the space + below. The rail itself (arrows, hidden scrollbar, card geometry) is the + ui-attachment atom's. */ .attachments { - display: flex; - gap: 8px; min-width: 0; - padding: 12px 12px 0; - overflow-x: auto; - overflow-y: hidden; -} - -.attachment { - position: relative; - flex: 0 0 72px; - width: 72px; - height: 72px; -} - -.thumbnail { - width: 72px; - height: 72px; - padding: 0; - overflow: hidden; - border: 1px solid var(--dsw-alias-border-l2-darkmode-thin); - border-radius: 12px; - background: var(--dsw-alias-interactive-bg-hover); - cursor: zoom-in; -} - -.thumbnail img { - width: 100%; - height: 100%; - object-fit: cover; -} - -.remove { - position: absolute; - top: -6px; - right: -6px; - display: grid; - place-items: center; - width: 22px; - height: 22px; - padding: 0; - border: 1px solid var(--dsw-specific-input-major); - border-radius: 999px; - background: var(--dsw-alias-label-primary); - color: var(--dsw-specific-input-major); - font-size: 16px; - line-height: 1; - cursor: pointer; + padding: 4px 12px 0; } /* Floating overlay anchor (menu / popupSelect shell): entries position diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 5423a2bac6..901bdc4682 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -9,7 +9,11 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { ChangeEvent, DragEvent, KeyboardEvent, MouseEvent, ReactNode } from 'react' import clsx from 'clsx' -import { IconPlusOutline16, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import { + IconPlusOutline16, IconWarningOutline16, Toast, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import { AttachmentRail, ImageLightbox } from '@deepseek-ai/dsh-client-ui-attachment' +import type { AttachmentRailItem } from '@deepseek-ai/dsh-client-ui-attachment' // Type-only: the `plan` projection key merge (the TodoDock posture — the // composer reads a host-computed value; the domain owns the key). import type {} from '@deepseek-ai/dsh-plan-mode/client' @@ -19,18 +23,17 @@ import type { Translate } from '@deepseek-ai/dsh-client-ui-slots' import type { ComposerAttachment, ComposerBarProps } from '../contract/slots.ts' import { deriveDecorations } from '../input/decorations.ts' import type { DraftDecorations } from '../input/decorations.ts' +import { attachmentRailLabels, lightboxLabels } from '../image-labels.ts' import { ContextMeter } from './ContextMeter.tsx' -import { ImageLightbox } from './ImageLightbox.tsx' import { PermissionSelect } from './PermissionSelect.tsx' import css from './InputBar.module.css' /** Decoration product of the no-session state (no machine, empty draft). */ const INERT_DECORATIONS: DraftDecorations = { token: null, chips: [], textRefs: [], hint: null } -/** Prompt failure surface (derived from promptError). */ -export interface InputBarError { - op: 'send' | 'stop' - message: string +/** Rail thumbnail carrying its source attachment for the open/remove callbacks. */ +interface ComposerRailItem extends AttachmentRailItem { + attachment: ComposerAttachment } export type InputBarProps = ComposerBarProps @@ -56,12 +59,6 @@ export function InputBar({ const planActive = useProjection('plan', plan => plan !== undefined && (plan.pending ? !plan.active : plan.active)) // Absent (undefined: no frame yet) and cleared (null) both mean no goal. const hasGoal = useProjection('goal', goal => goal != null) - // Prompt failures are ordinary failures (no create/attach transaction - // exists anymore): the strip renders promptError, the draft stays in the - // machine, and the user resubmits. - const error: InputBarError | null = promptError === null - ? null - : { op: promptError.op, message: `${promptError.error.message} (${promptError.error.code})` } // Session-maybe: the machine faces are absent together while no session is // current; the bar renders the same DOM inert instead of a parallel tree. const live = input !== undefined && keyboard !== undefined && inputActions !== undefined @@ -73,8 +70,26 @@ export function InputBar({ const empty = draft.trim() === '' && attachments.length === 0 const [preview, setPreview] = useState(null) const [dragActive, setDragActive] = useState(false) - const [dropError, setDropError] = useState(null) + // Transient error banner (image-intake rejections and prompt failures): the + // seq keys the Toast so an identical repeated message restarts the + // hold-then-fade cycle instead of silently reusing the faded one. + const [toast, setToast] = useState<{ seq: number; text: string } | null>(null) + const toastSeq = useRef(0) + const showToast = useCallback((text: string) => { + toastSeq.current += 1 + setToast({ seq: toastSeq.current, text }) + }, []) + const dismissToast = useCallback(() => { setToast(null) }, []) + // Prompt failures are ordinary failures (no create/attach transaction exists + // anymore): the toast announces promptError, the draft stays in the machine, + // and the user resubmits. A remount over a session whose machine still holds + // an unresolved promptError deliberately re-announces it once — the failure + // is still pending, and a transient banner is its only surface. + useEffect(() => { + if (promptError !== null) showToast(`${promptError.error.message} (${promptError.error.code})`) + }, [promptError, showToast]) const inputRef = useRef(null) + const cardRef = useRef(null) const dragDepthRef = useRef(0) const scrollRef = useRef(null) const mirrorRef = useRef(null) @@ -369,7 +384,10 @@ export function InputBar({ .filter(item => item.kind === 'file') .map(item => item.getAsFile()) .filter((file): file is File => file !== null) - if (files.length > 0 && addImages !== undefined) setDropError(addImages(files)) + if (files.length > 0 && addImages !== undefined) { + const rejected = addImages(files) + if (rejected !== null) showToast(rejected) + } const text = e.clipboardData.getData('text/plain') if (text === '') { if (files.length > 0) e.preventDefault() @@ -393,7 +411,6 @@ export function InputBar({ event.preventDefault() if (locked || machineBusy || addImages === undefined) return dragDepthRef.current += 1 - setDropError(null) setDragActive(true) } @@ -416,11 +433,24 @@ export function InputBar({ setDragActive(false) if (locked || machineBusy || addImages === undefined) return const dropped = [...event.dataTransfer.files] - if (dropped.length > 0) setDropError(addImages(dropped)) + if (dropped.length > 0) { + const rejected = addImages(dropped) + if (rejected !== null) showToast(rejected) + } } const closePreview = useCallback(() => { setPreview(null) }, []) + // Rail thumbnails with their strings resolved here: the attachment atoms are + // zero-cordis and read no locale. + const railItems = useMemo(() => attachments.map(attachment => ({ + id: attachment.id, + previewUrl: attachment.previewUrl, + alt: attachment.file.name || t('image.pending'), + removeLabel: t('image.remove', { name: attachment.file.name }), + attachment, + })), [attachments, t]) + const onSelect = (e: React.SyntheticEvent): void => { // Any caret/selection gesture ends a live paste attempt (the machine // cannot observe DOM selection). Cheap no-op when none is live. @@ -543,10 +573,14 @@ export function InputBar({ return (
- {error !== null && ( -
- {error.message} -
+ {toast !== null && ( + } + anchor={cardRef.current} + onDone={dismissToast} + /> )} {notice !== null && (
@@ -558,8 +592,8 @@ export function InputBar({ their pointer events), so the WHOLE capsule is the pick target. pointerdown stops here so the Menu's outside-close cannot race the click's reopen (close-then-open flickers the chip's open echo). */} - {dropError !== null &&
{dropError}
}
{t('image.dropHint')}
} {overlay !== undefined &&
{overlay}
} {accessory !== undefined &&
{accessory}
} - {attachments.length > 0 && ( -
- {attachments.map(attachment => ( -
- - -
- ))} + {railItems.length > 0 && ( +
+ { setPreview(item.attachment) }} + onRemove={(item) => { removeImage?.(item.attachment.id) }} + />
)} {/* One scrollport, two text layers. The hidden mirror renders draft+'\n' and stretches the @@ -628,10 +647,7 @@ export function InputBar({ ? t('placeholder.steerQueue') : planActive ? t('placeholder.plan') : t('placeholder.default'))} rows={2} - onChange={(event) => { - setDropError(null) - onChange(event) - }} + onChange={onChange} onKeyDown={onKeyDown} onSelect={onSelect} onCopy={(e) => { onCopyOrCut(e, false) }} @@ -712,8 +728,8 @@ export function InputBar({ )} {footer} diff --git a/packages/client/ui-conversation/tests/image-labels.spec.tsx b/packages/client/ui-conversation/tests/image-labels.spec.tsx new file mode 100644 index 0000000000..6aa5810e38 --- /dev/null +++ b/packages/client/ui-conversation/tests/image-labels.spec.tsx @@ -0,0 +1,82 @@ +// @vitest-environment jsdom +// The conversation-side bridge to the ui-attachment atoms: dictionary strings +// flow through image-labels into the gallery, and assistant images keep their +// block position between text blocks. + +import { afterEach, describe, expect, it } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { AttachmentId } from '@deepseek-ai/dsh-attachment' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' +import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx' +import { en, zh } from '../src/client/locales.ts' + +afterEach(cleanup) + +const t = makeTranslate(zh, commonZh) +const enT = makeTranslate(en, commonZh) + +const attachment = { + attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png' as const, + bytes: 68, + width: 640, + height: 320, + name: 'history.png', +} + +describe('assistant images through the label bridge', () => { + it('resolves zh dictionary strings and opens the lightbox on a single click', async () => { + const view = render( + Promise.resolve('blob:history')} + />, + ) + const frame = await view.findByRole('button', { name: 'history.png,点击查看原图' }) + expect(frame.getAttribute('title')).toBe('查看原图') + await view.findByAltText('history.png') + fireEvent.click(frame) + expect(view.getByRole('dialog', { name: '原图预览' })).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: '关闭原图预览' })) + expect(view.queryByRole('dialog', { name: '原图预览' })).toBeNull() + }) + + it('resolves the active English dictionary', async () => { + const view = render( + Promise.resolve('blob:history')} + />, + ) + const frame = await view.findByRole('button', { name: 'history.png, click to view original' }) + await view.findByAltText('history.png') + fireEvent.click(frame) + expect(view.getByRole('dialog', { name: 'Original image preview' })).toBeTruthy() + expect(view.getByRole('button', { name: 'Close original image preview' })).toBeTruthy() + }) + + it('keeps assistant images at their original position between text blocks', async () => { + const view = render( + Promise.resolve('blob:middle')} + />, + ) + const image = await view.findByAltText('history.png') + const before = view.getByText('before') + const after = view.getByText('after') + expect(before.compareDocumentPosition(image) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0) + expect(image.compareDocumentPosition(after) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0) + }) +}) diff --git a/packages/client/ui-conversation/tests/input-bar.spec.tsx b/packages/client/ui-conversation/tests/input-bar.spec.tsx index f7b0669e3e..a766781b5f 100644 --- a/packages/client/ui-conversation/tests/input-bar.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.spec.tsx @@ -237,15 +237,49 @@ describe('image draft rail', () => { expect(removeImage).toHaveBeenCalledWith('draft-1') }) - it('opens the original image on double-click and closes it with Escape', () => { + it('opens the original image on a single click and closes it with Escape', () => { const file = new File([Uint8Array.of(1)], 'pixel.png', { type: 'image/png' }) const attachment = { kind: 'image' as const, id: 'draft-1' as DraftAttachmentId, file, previewUrl: 'blob:draft-1' } const { view } = bench({ attachments: [attachment] }) - fireEvent.doubleClick(view.getByTitle('双击查看原图')) + fireEvent.click(view.getByTitle('查看原图')) expect(view.getByRole('dialog', { name: '原图预览' })).toBeTruthy() fireEvent.keyDown(window, { key: 'Escape' }) expect(view.queryByRole('dialog', { name: '原图预览' })).toBeNull() }) + + it('announces an image-intake rejection as a fading toast, repeatable for the same reason', () => { + vi.useFakeTimers() + try { + const addImages = vi.fn(() => '不支持的图片格式:text/plain') + const { view, textarea } = bench({ addImages }) + const paste = () => { + fireEvent.paste(textarea, { + clipboardData: { + items: [{ kind: 'file', type: 'text/plain', getAsFile: () => new File(['x'], 'note.txt', { type: 'text/plain' }) }], + getData: () => '', + }, + }) + } + paste() + expect(view.getByRole('alert').textContent).toContain('不支持的图片格式:text/plain') + act(() => { vi.advanceTimersByTime(4000) }) + expect(view.queryByRole('alert')).toBeNull() + // The identical rejection re-announces: the toast is keyed per show. + paste() + expect(view.getByRole('alert').textContent).toContain('不支持的图片格式:text/plain') + } finally { + vi.useRealTimers() + } + }) + + it('announces a rejected drop through the same toast', () => { + const addImages = vi.fn(() => '图片读取服务不可用') + const { view } = bench({ addImages }) + const card = view.container.querySelector('[class*="card"]')! + const dataTransfer = { types: ['Files'], files: [new File([Uint8Array.of(1)], 'x.png', { type: 'image/png' })], dropEffect: 'none' } + fireEvent.drop(card, { dataTransfer }) + expect(view.getByRole('alert').textContent).toContain('图片读取服务不可用') + }) }) describe('Enter semantics', () => { @@ -941,10 +975,19 @@ describe('insertText (scoped event body)', () => { }) describe('strips and variants', () => { - it('derives the failure strip from promptError (ordinary failure — no transaction UI, no Retry)', () => { - const send = bench({ promptError: { op: 'send', error: { code: 'agent-busy', message: 'boom', details: { reason: 'boom' } } } }) - expect(send.view.container.querySelector('[role="alert"]')?.textContent).toBe('boom (agent-busy)') - expect(send.view.queryByRole('button', { name: 'Retry' })).toBeNull() + it('announces promptError as a fading toast (ordinary failure — no transaction UI, no Retry)', () => { + vi.useFakeTimers() + try { + const send = bench({ promptError: { op: 'send', error: { code: 'agent-busy', message: 'boom', details: { reason: 'boom' } } } }) + // The toast body-portals (transformed ancestors must not trap it), so + // queries go through the view's document-bound helpers. + expect(send.view.getByRole('alert').textContent).toContain('boom (agent-busy)') + expect(send.view.queryByRole('button', { name: 'Retry' })).toBeNull() + act(() => { vi.advanceTimersByTime(4000) }) + expect(send.view.queryByRole('alert')).toBeNull() + } finally { + vi.useRealTimers() + } }) it('renders the notice strip from the machine notice store', () => { diff --git a/packages/client/ui-conversation/tests/message-image.spec.tsx b/packages/client/ui-conversation/tests/message-image.spec.tsx deleted file mode 100644 index 6da4d42f12..0000000000 --- a/packages/client/ui-conversation/tests/message-image.spec.tsx +++ /dev/null @@ -1,81 +0,0 @@ -// @vitest-environment jsdom - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, fireEvent, render, waitFor } from '@testing-library/react' -import { AttachmentId } from '@deepseek-ai/dsh-attachment' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' -import { MessageImage } from '../src/client/chat/MessageImage.tsx' -import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx' -import { en, zh } from '../src/client/locales.ts' - -afterEach(cleanup) - -const t = makeTranslate(zh, commonZh) -const enT = makeTranslate(en, commonZh) - -const attachment = { - attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), - mediaType: 'image/png' as const, - bytes: 68, - width: 640, - height: 320, - name: 'history.png', -} - -describe('MessageImage', () => { - it('loads a session-authorized URL, bounds the thumbnail, and double-clicks into the original', async () => { - const load = vi.fn().mockResolvedValue('blob:history') - const view = render() - const frame = view.getByRole('button', { name: 'history.png,双击查看原图' }) - expect(frame.getAttribute('style')).toContain('width: 240px') - expect(frame.getAttribute('style')).toContain('height: 120px') - await waitFor(() => { expect(view.getByAltText('history.png')).toBeTruthy() }) - expect(load).toHaveBeenCalledWith(attachment) - fireEvent.doubleClick(frame) - expect(view.getByRole('dialog', { name: '原图预览' })).toBeTruthy() - fireEvent.click(view.getByRole('button', { name: '关闭原图预览' })) - expect(view.queryByRole('dialog', { name: '原图预览' })).toBeNull() - }) - - it('surfaces a retry control when durable bytes cannot be read', async () => { - const load = vi.fn() - .mockRejectedValueOnce(new Error('offline')) - .mockResolvedValueOnce('blob:retry') - const view = render() - const retry = await view.findByRole('button', { name: '图片加载失败,点击重试' }) - fireEvent.click(retry) - await waitFor(() => { expect(view.getByAltText('history.png')).toBeTruthy() }) - expect(load).toHaveBeenCalledTimes(2) - }) - - it('renders image controls from the active English dictionary', async () => { - const load = vi.fn().mockResolvedValue('blob:history') - const view = render() - const frame = view.getByRole('button', { name: 'history.png, double-click to view original' }) - await waitFor(() => { expect(view.getByAltText('history.png')).toBeTruthy() }) - fireEvent.doubleClick(frame) - expect(view.getByRole('dialog', { name: 'Original image preview' })).toBeTruthy() - expect(view.getByRole('button', { name: 'Close original image preview' })).toBeTruthy() - }) - - it('keeps assistant images at their original position between text blocks', async () => { - const view = render( - Promise.resolve('blob:middle')} - />, - ) - const image = await view.findByAltText('history.png') - const before = view.getByText('before') - const after = view.getByText('after') - expect(before.compareDocumentPosition(image) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0) - expect(image.compareDocumentPosition(after) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0) - }) -}) diff --git a/packages/client/ui-conversation/tsconfig.json b/packages/client/ui-conversation/tsconfig.json index b6190dc3ae..58af4f794f 100644 --- a/packages/client/ui-conversation/tsconfig.json +++ b/packages/client/ui-conversation/tsconfig.json @@ -23,6 +23,9 @@ { "path": "../ui-slots" }, + { + "path": "../ui-attachment" + }, { "path": "../ui-primitives" }, diff --git a/packages/client/ui-model/src/client/ModelSelect.tsx b/packages/client/ui-model/src/client/ModelSelect.tsx index 6b7bfd19b9..7be74a90d7 100644 --- a/packages/client/ui-model/src/client/ModelSelect.tsx +++ b/packages/client/ui-model/src/client/ModelSelect.tsx @@ -7,7 +7,9 @@ * ToggleButton) shows both: model name + effort in the caption tone. * Data and submission ride the SAME per-session ModelDirectory as the * /model popup; exact-model reasoning metadata and the selected effort come - * from the Host rather than a client-owned vocabulary. + * from the Host rather than a client-owned vocabulary. A rejected selection + * announces through the shared transient Toast anchored to the composer + * card; the in-menu strip with Retry remains the catalog-load surface. */ import { useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, @@ -17,6 +19,7 @@ import clsx from 'clsx' import type { ModelReasoningEffort, ModelSelection } from '@deepseek-ai/dsh-client-connection/client' import { IconCheckOutline16, IconChevronDownOutline14, IconChevronRightOutline14, + IconWarningOutline16, Toast, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ModelSelectInjected } from './slots.ts' @@ -49,6 +52,13 @@ export function ModelSelect( ) const [open, setOpen] = useState(false) const [pane, setPane] = useState('root') + // The in-menu error strip serves catalog loads (its Retry re-runs the + // load); a rejected SELECTION announces through the transient toast + // instead, so the strip renders only while the latest failure-capable + // action was a load. + const lastActionRef = useRef<'load' | 'select'>('load') + const [toast, setToast] = useState<{ seq: number; text: string } | null>(null) + const toastSeq = useRef(0) const rootRef = useRef(null) const triggerRef = useRef(null) const itemRefs = useRef<(HTMLButtonElement | null)[]>([]) @@ -92,9 +102,17 @@ export function ModelSelect( ], [reasoning, t]) const busy = state.status === 'selecting' + const reload = (): void => { + lastActionRef.current = 'load' + load() + } + // Mount-time load resolves the trigger label; every open refreshes. useEffect(() => { - if (available) load() + if (available) { + lastActionRef.current = 'load' + load() + } }, [available, load]) useEffect(() => { @@ -111,7 +129,7 @@ export function ModelSelect( const show = (): void => { setPane('root') setOpen(true) - load() + reload() } const close = (restoreFocus = false): void => { @@ -148,14 +166,25 @@ export function ModelSelect( close() } + const settleSelection = (accepted: boolean): void => { + if (accepted) { + if (rootRef.current !== null) close(true) + return + } + const message = directory.getSnapshot().error + if (message !== null) { + toastSeq.current += 1 + setToast({ seq: toastSeq.current, text: t('error.action', { message }) }) + } + } + const choose = (selection: ModelSelection): void => { if (state.current?.provider === selection.provider && state.current.model === selection.model) { close(true) return } - void select(selection).then((accepted) => { - if (accepted && rootRef.current !== null) close(true) - }) + lastActionRef.current = 'select' + void select(selection).then(settleSelection) } const chooseEffort = (effort: string | undefined): void => { @@ -169,9 +198,8 @@ export function ModelSelect( model: state.current.model, ...effort === undefined ? {} : { reasoningEffort: effort }, } - void select(selection).then((accepted) => { - if (accepted && rootRef.current !== null) close(true) - }) + lastActionRef.current = 'select' + void select(selection).then(settleSelection) } const modelLabel = currentChoice?.model.name ?? t('trigger.fallback') @@ -243,16 +271,16 @@ export function ModelSelect( {state.status === 'loading' && (
{t('status.loading')}
)} - {state.error !== null && ( + {state.error !== null && lastActionRef.current === 'load' && (
{t('error.action', { message: state.error })} - +
)} {state.failures.map(failure => (
{t('warning.groupLoad', { name: failure.name, message: failure.message })} - +
))}
@@ -299,10 +327,10 @@ export function ModelSelect( {pane === 'effort' && ( <> - {state.error !== null && ( + {state.error !== null && lastActionRef.current === 'load' && (
{t('error.action', { message: state.error })} - +
)} {effortChoices.length === 0 @@ -333,6 +361,15 @@ export function ModelSelect( )}
)} + {toast !== null && ( + } + anchor={rootRef.current?.closest('[data-composer-card]') ?? null} + onDone={() => { setToast(null) }} + /> + )}
) } diff --git a/packages/client/ui-model/tests/model-select.spec.tsx b/packages/client/ui-model/tests/model-select.spec.tsx index 1b1e1ef17c..4f6a37d151 100644 --- a/packages/client/ui-model/tests/model-select.spec.tsx +++ b/packages/client/ui-model/tests/model-select.spec.tsx @@ -135,6 +135,38 @@ describe('ModelSelect reasoning effort', () => { expect(screen.getByRole('menuitemradio', { name: 'DeepSeek-V4-Flash' })).toBeTruthy() }) + it('announces a rejected selection as a transient toast and keeps the in-menu strip for loads', async () => { + const groups = [{ + id: 'deepseek-official', + name: 'DeepSeek', + models: [ + { id: 'deepseek-v4-flash', name: 'DeepSeek-V4-Flash', reasoning }, + { id: 'deepseek-v4-pro', name: 'DeepSeek-V4-Pro' }, + ], + }] + const directory = createSnapshotStore(state({ groups })) + const select = vi.fn(async () => { + directory.set(state({ groups, status: 'error', error: 'model-unavailable: session already contains images' })) + return false + }) + render() + + fireEvent.click(screen.getByRole('button', { name: /选择模型|当前/ })) + fireEvent.click(screen.getByRole('menuitem', { name: /模型/ })) + fireEvent.click(screen.getByRole('menuitemradio', { name: /DeepSeek-V4-Pro/ })) + const toast = await screen.findByRole('alert') + expect(toast.textContent).toContain('模型操作失败:model-unavailable: session already contains images') + // The selection failure does not render the in-menu load strip (no Retry). + expect(screen.queryByRole('button', { name: '重试' })).toBeNull() + }) + it('renders no Agent-bound control for an addressed subagent session', () => { const load = vi.fn() render( + & PropsLocale<'settings.pluginConfig'> + & InjectFace + +/** + * Render the agent-loop card. + * @param props - locale copy, the card snapshot, and its form actions. + * @returns the card. + */ +export function AgentLoopCard(props: AgentLoopCardProps) { + const { t } = props + const state = props.useAgentLoopCard(snapshot => snapshot) + return ( + + { props.edit('maxParallelToolCalls', text) }} + onReset={() => { props.resetField('maxParallelToolCalls') }} + /> + + ) +} diff --git a/packages/client/ui-plugin-config/src/client/BashCard.tsx b/packages/client/ui-plugin-config/src/client/BashCard.tsx new file mode 100644 index 0000000000..d7f9918a39 --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/BashCard.tsx @@ -0,0 +1,61 @@ +/** The shell plugin's card: the limits every command the agent runs is bound by. */ + +import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import { ValueField } from './fields.tsx' +import { PluginCard } from './PluginCard.tsx' +import type { BashCardFace } from './bash-store.ts' +import type {} from './slot-contract.ts' + +/** Props the renderer binds for the shell card. */ +export type BashCardProps = + PropsRuntime<'settings.plugin.item'> + & PropsLocale<'settings.pluginConfig'> + & InjectFace + +/** + * Render the shell card. + * @param props - locale copy, the card snapshot, and its form actions. + * @returns the card. + */ +export function BashCard(props: BashCardProps) { + const { t } = props + const state = props.useBashCard(snapshot => snapshot) + const disabled = !state.writable + return ( + + { props.edit('timeoutMs', text) }} + onReset={() => { props.resetField('timeoutMs') }} + /> + { props.edit('maxOutputBytes', text) }} + onReset={() => { props.resetField('maxOutputBytes') }} + /> + + ) +} diff --git a/packages/client/ui-plugin-config/src/client/PluginCard.module.css b/packages/client/ui-plugin-config/src/client/PluginCard.module.css new file mode 100644 index 0000000000..091273cd5b --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/PluginCard.module.css @@ -0,0 +1,157 @@ +/* Plugin card: a header that names the plugin, disclosing its controls in place. */ + +.card { + list-style: none; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 12px; + background: var(--dsw-alias-bg-layer-3); + transition: border-color .16s, background .16s; +} + +.card:hover { + border-color: var(--dsw-alias-label-dimmed); +} + +/* An open card reads as the one being worked on, not merely taller. */ +.cardOpen { + background: var(--dsw-alias-bg-layer-2); + border-color: var(--dsw-alias-label-dimmed); +} + +.header { + width: 100%; + appearance: none; + border: 0; + background: none; + font: inherit; + color: inherit; + text-align: left; + cursor: pointer; + display: flex; + align-items: center; + gap: 12px; + padding: 14px 16px; + border-radius: 12px; +} + +.header:focus-visible { + outline: 2px solid var(--dsw-alias-brand-primary); + outline-offset: -2px; +} + +/* Name over description: the description is what tells two plugins apart, so + it gets its own line rather than trailing the name. */ +.headText { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 4px; +} + +.name { + font-size: 15px; + font-weight: 600; + line-height: 1.4; + color: var(--dsw-alias-label-primary); +} + +.description { + font-size: 13px; + line-height: 1.5; + color: var(--dsw-alias-label-tertiary); +} + +.chevron { + flex: none; + color: var(--dsw-alias-label-tertiary); + transition: transform .16s; +} + +.chevronOpen { + transform: rotate(180deg); +} + +.body { + border-top: 1px solid var(--dsw-alias-border-l2); + margin: 0 16px; + padding-bottom: 8px; +} + +.readOnly { + margin: 12px 0 0; + font-size: 12px; + line-height: 1.5; + color: var(--dsw-alias-label-tertiary); +} + +/* Carried on the header so a collapsed card still says it holds edits. */ +.pending { + flex: none; + border-radius: 999px; + padding: 1px 8px; + font-size: 11px; + line-height: 17px; + font-weight: 500; + white-space: nowrap; + background: var(--dsw-alias-bg-module-platform); + color: var(--dsw-alias-label-secondary); +} + +.footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + padding: 12px 0 4px; + border-top: 1px solid var(--dsw-alias-border-l2); +} + +.failed { + flex: 1; + min-width: 0; + margin: 0; + font-size: 12px; + line-height: 1.5; + color: var(--dsw-alias-label-error); +} + +.discard, +.save { + appearance: none; + border: 1px solid transparent; + border-radius: 8px; + padding: 5px 14px; + font: inherit; + font-size: 13px; + line-height: 1.5; + cursor: pointer; +} + +.discard { + border-color: var(--dsw-alias-border-l2); + background: none; + color: var(--dsw-alias-label-secondary); +} + +.discard:hover:not(:disabled) { + color: var(--dsw-alias-label-primary); + border-color: var(--dsw-alias-label-dimmed); +} + +.save { + background: var(--dsw-alias-label-primary); + color: var(--dsw-alias-bg-layer-3); +} + +.discard:disabled, +.save:disabled { + opacity: 0.4; + cursor: default; +} + +.discard:focus-visible, +.save:focus-visible { + outline: 2px solid var(--dsw-alias-brand-primary); + outline-offset: 1px; +} diff --git a/packages/client/ui-plugin-config/src/client/PluginCard.tsx b/packages/client/ui-plugin-config/src/client/PluginCard.tsx new file mode 100644 index 0000000000..459fd627c1 --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/PluginCard.tsx @@ -0,0 +1,98 @@ +/** + * One plugin's card: a header naming the plugin and what its settings govern, + * disclosing that plugin's controls in place, with the save that writes them. + * + * The header is its own button rather than a shared disclosure row because a + * card stacks its name over its description, while that row lays the two side + * by side — the layout, not the behavior, is what differs. Disclosure is + * card-local state: which card a user has open is a reading gesture, not + * something the Host or the section has any stake in. Staged edits outlive + * collapsing, so the header marks a card holding unsaved edits. + * + * A card renders nothing while its namespace is unavailable: a deployment that + * does not compose the owning plugin should show no trace of it, rather than a + * disabled card the user cannot act on. + */ + +import { useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives' +import type { CardShell } from './card-store.ts' +import type { PluginConfigKey } from './locales.ts' +import css from './PluginCard.module.css' + +/** Card chrome shared by every plugin section. */ +export interface PluginCardProps { + /** Locale reader for this section's copy. */ + t: (key: PluginConfigKey) => string + /** Locale key of the plugin's name. */ + titleKey: PluginConfigKey + /** Locale key of the line describing what this plugin's settings govern. */ + descriptionKey: PluginConfigKey + /** The card's form state: availability, writability, and what a save would do. */ + state: CardShell + /** Write every staged edit. */ + onSave: () => void + /** Drop every staged edit. */ + onDiscard: () => void + /** The plugin's controls. */ + children: ReactNode +} + +/** + * Render one plugin card. + * @param props - the plugin's copy keys, its form state, and its controls. + * @returns the card, or nothing when the namespace is unavailable. + */ +export function PluginCard(props: PluginCardProps) { + const [open, setOpen] = useState(false) + const { state } = props + if (!state.available) return null + const title = props.t(props.titleKey) + const blocked = !state.dirty || state.invalid || state.saving + return ( +
  • + + {open + ? ( +
    + {!state.writable ?

    {props.t('readOnly')}

    : null} + {props.children} +
    + {state.failed ?

    {props.t('saveFailed')}

    : null} + + +
    +
    + ) + : null} +
  • + ) +} diff --git a/packages/client/ui-plugin-config/src/client/PluginConfigSection.module.css b/packages/client/ui-plugin-config/src/client/PluginConfigSection.module.css new file mode 100644 index 0000000000..45c9a78f00 --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/PluginConfigSection.module.css @@ -0,0 +1,36 @@ +/* Plugin configuration section: heading, intro, and the card list. */ + +.section { + display: flex; + flex-direction: column; + gap: 12px; + max-width: 720px; + color: var(--dsw-alias-label-primary); +} + +.heading { + margin: 0; + font-size: 18px; + font-weight: 600; +} + +.intro { + margin: 0; + font-size: 13px; + color: var(--dsw-alias-label-tertiary); +} + +.cards { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 10px; +} + +.empty { + margin: 0; + font-size: 13px; + color: var(--dsw-alias-label-tertiary); +} diff --git a/packages/client/ui-plugin-config/src/client/PluginConfigSection.tsx b/packages/client/ui-plugin-config/src/client/PluginConfigSection.tsx new file mode 100644 index 0000000000..68de45eff3 --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/PluginConfigSection.tsx @@ -0,0 +1,49 @@ +/** + * Plugin configuration section: the shell around the per-plugin cards. It + * enumerates nothing itself — cards arrive through the `settings.plugin.item` + * slot it declares, so a plugin that ships a browser half owns its own card + * and this section never learns what a namespace means. + */ + +import type { InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from './slot-contract.ts' +import type { PluginConfigKey } from './locales.ts' +import css from './PluginConfigSection.module.css' + +/** Registration-side business face for the section. */ +export interface PluginConfigSectionInjected { + /** How many cards the slot ledger currently holds; zero renders the empty line. */ + cardCount: number +} + +/** Props the renderer binds for the section. */ +export type PluginConfigSectionProps = + PropsRuntime<'settings.section'> + & PropsLocale<'settings.pluginConfig'> + & PropsRenderSlots<'settings.plugin.item'> + & InjectFace + +/** + * Render the plugin configuration section. + * @param props - runtime slot rendering, locale copy, and the card count. + * @returns the section. + */ +export function PluginConfigSection(props: PluginConfigSectionProps) { + const { t, renderSlot, cardCount } = props + return ( +
    +

    {t('title')}

    +

    {t('intro')}

    + {cardCount === 0 + ?

    {t('empty')}

    + :
      {renderSlot('settings.plugin.item', {})}
    } +
    + ) +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + /** Plugin configuration section and card copy. */ + 'settings.pluginConfig': PluginConfigKey + } +} diff --git a/packages/client/ui-plugin-config/src/client/WebSearchCard.tsx b/packages/client/ui-plugin-config/src/client/WebSearchCard.tsx new file mode 100644 index 0000000000..02762a802f --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/WebSearchCard.tsx @@ -0,0 +1,78 @@ +/** + * The web-search provider's card: its endpoint, its per-request search budget, + * and the key — which is written through the credentials domain, never into + * the settings section, so the literal never rides a response. + */ + +import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import { SecretField, ValueField } from './fields.tsx' +import { PluginCard } from './PluginCard.tsx' +import type { WebSearchCardFace } from './web-search-store.ts' +import type {} from './slot-contract.ts' + +/** Props the renderer binds for the web-search card. */ +export type WebSearchCardProps = + PropsRuntime<'settings.plugin.item'> + & PropsLocale<'settings.pluginConfig'> + & InjectFace + +/** + * Render the web-search card. + * @param props - locale copy, the card snapshot, and its form actions. + * @returns the card. + */ +export function WebSearchCard(props: WebSearchCardProps) { + const { t } = props + const state = props.useWebSearchCard(snapshot => snapshot) + const disabled = !state.writable + return ( + + { props.edit('apiKey', text) }} + /> + { props.edit('baseURL', text) }} + onReset={() => { props.resetField('baseURL') }} + /> + { props.edit('maxUses', text) }} + onReset={() => { props.resetField('maxUses') }} + /> + + ) +} diff --git a/packages/client/ui-plugin-config/src/client/agent-loop-store.ts b/packages/client/ui-plugin-config/src/client/agent-loop-store.ts new file mode 100644 index 0000000000..2bed0d1def --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/agent-loop-store.ts @@ -0,0 +1,57 @@ +/** The agent-loop card's staged form over the `agent-loop` settings namespace. */ + +import type { SettingsScope, SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import { CardForm, numberField, type CardActions, type CardFieldState, type CardShell } from './card-store.ts' + +/** + * Namespace of the agent loop's user-owned settings. Spelled here rather than + * imported: a client package must not depend on a Host package. + */ +export const AGENT_LOOP_NS = 'agent-loop' + +/** + * The agent-loop fields this card edits. The Host section carries only this + * field — the composed `agents` array is deliberately not part of it. + */ +export interface AgentLoopSettings { + /** Upper bound on parallel-safe tool calls in flight per step. */ + maxParallelToolCalls?: number +} + +/** What the agent-loop card renders. */ +export interface AgentLoopCardState extends CardShell { + /** Parallel tool-call cap. */ + maxParallelToolCalls: CardFieldState +} + +/** The registration-side face the agent-loop card's slot entry injects. */ +export interface AgentLoopCardFace extends CardActions { + hooks: { + /** Card snapshot bound by the renderer as useAgentLoopCard. */ + agentLoopCard: SnapshotStore + } +} + +/** Bridges the `agent-loop` scope onto the card's staged form. */ +export class AgentLoopCardController { + private readonly form: CardForm + private readonly store: SnapshotStore + + /** @param scope - the bound settings scope for the `agent-loop` namespace. */ + constructor(scope: SettingsScope) { + this.form = new CardForm(scope, [numberField('maxParallelToolCalls')]) + this.store = this.form.bind(() => this.projection()) + } + + private projection(): AgentLoopCardState { + return { ...this.form.shell(), maxParallelToolCalls: this.form.field('maxParallelToolCalls') } + } + + /** + * Build the face the card's slot registration injects. + * @returns the card's snapshot and its form actions. + */ + inject(): AgentLoopCardFace { + return { hooks: { agentLoopCard: this.store }, ...this.form.actions() } + } +} diff --git a/packages/client/ui-plugin-config/src/client/bash-store.ts b/packages/client/ui-plugin-config/src/client/bash-store.ts new file mode 100644 index 0000000000..c107ebc225 --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/bash-store.ts @@ -0,0 +1,63 @@ +/** The shell card's staged form over the `bash` settings namespace. */ + +import type { SettingsScope, SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import { CardForm, numberField, type CardActions, type CardFieldState, type CardShell } from './card-store.ts' + +/** + * Namespace of the shell capability. Spelled here rather than imported: a + * client package must not depend on a Host package, and the executor families + * that own it spell the same value. + */ +export const BASH_NS = 'bash' + +/** The shell fields this card edits — a subset of the served schema by design. */ +export interface BashSettings { + /** Foreground command timeout in milliseconds. */ + timeoutMs?: number + /** Per-stream in-memory output cap in bytes. */ + maxOutputBytes?: number +} + +/** What the shell card renders. */ +export interface BashCardState extends CardShell { + /** Command timeout in milliseconds. */ + timeoutMs: CardFieldState + /** Per-stream output cap in bytes. */ + maxOutputBytes: CardFieldState +} + +/** The registration-side face the shell card's slot entry injects. */ +export interface BashCardFace extends CardActions { + hooks: { + /** Card snapshot bound by the renderer as useBashCard. */ + bashCard: SnapshotStore + } +} + +/** Bridges the `bash` scope onto the shell card's staged form. */ +export class BashCardController { + private readonly form: CardForm + private readonly store: SnapshotStore + + /** @param scope - the bound settings scope for the `bash` namespace. */ + constructor(scope: SettingsScope) { + this.form = new CardForm(scope, [numberField('timeoutMs'), numberField('maxOutputBytes')]) + this.store = this.form.bind(() => this.projection()) + } + + private projection(): BashCardState { + return { + ...this.form.shell(), + timeoutMs: this.form.field('timeoutMs'), + maxOutputBytes: this.form.field('maxOutputBytes'), + } + } + + /** + * Build the face the card's slot registration injects. + * @returns the card's snapshot and its form actions. + */ + inject(): BashCardFace { + return { hooks: { bashCard: this.store }, ...this.form.actions() } + } +} diff --git a/packages/client/ui-plugin-config/src/client/card-store.ts b/packages/client/ui-plugin-config/src/client/card-store.ts new file mode 100644 index 0000000000..255450bdb9 --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/card-store.ts @@ -0,0 +1,351 @@ +/** + * Shared form model behind every plugin card. + * + * A card stages what the user types and writes it only when they save. Each + * settings write is a durable, revision-fenced document mutation, so a control + * that committed as it settled turned one edit into a write the user never + * asked for and could not preview; staged text makes what is on screen exactly + * what a save would store. + * + * A field shows its effective value — the user layer over the composition + * layer over the schema default — and whether the user layer carries it. That + * presence, not a value comparison, is what marks a field overridden: an + * override equal to the composition default is still an override. + */ + +import type { SettingsScope, SettingsScopeSnapshot } from '@deepseek-ai/dsh-client-runtime/client' +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' + +/** The write one field's staged text performs when the card is saved. */ +export type FieldWrite = + | { kind: 'set'; value: unknown } + | { kind: 'clear' } + +/** How one section field converts between its stored value and its draft text. */ +export interface CardFieldSpec { + /** Field name inside the namespace section. */ + field: string + /** Render a stored value as draft text; the empty string when the section carries none. */ + format: (value: unknown) => string + /** + * The write this draft text stages, or undefined when the text is not a + * value this field accepts — which blocks the save rather than discarding it. + */ + parse: (text: string) => FieldWrite | undefined +} + +/** + * A control whose value is written outside the settings section. A credential + * literal never rides a response, so its draft has nothing to seed from: it is + * blank until typed, and a blank draft writes nothing. + */ +export interface CardSecretSpec { + /** Field name addressing this control inside the card's form. */ + field: string + /** Write the staged text; resolves to whether the Host accepted it. */ + write: (text: string) => Promise +} + +/** One field as a card's control renders it. */ +export interface CardFieldState { + /** Draft text the control renders. */ + text: string + /** + * Whether saving would leave a user-layer entry for this field. A staged + * edit answers for itself, so the badge previews the save rather than + * reporting a state the pending edit already contradicts. + */ + overridden: boolean + /** Whether the draft is not a value this field accepts, which blocks saving. */ + invalid: boolean +} + +/** Form state every plugin card shares. */ +export interface CardShell { + /** False while the namespace is not served to this client; the card renders nothing. */ + available: boolean + /** Whether the Host document accepts writes. */ + writable: boolean + /** Whether the form holds edits that a save would write. */ + dirty: boolean + /** Whether any staged draft is invalid, which blocks the save. */ + invalid: boolean + /** Whether a save is crossing the wire. */ + saving: boolean + /** Whether the last save did not land as staged; cleared by the next edit or save. */ + failed: boolean +} + +/** The write actions every plugin card's slot entry injects. */ +export interface CardActions { + /** Stage draft text for one field. */ + edit: (field: string, text: string) => void + /** Stage a clear, so saving lets the field re-inherit the composition layer. */ + resetField: (field: string) => void + /** Write every staged edit, then re-seed from what the Host accepted. */ + save: () => void + /** Drop every staged edit. */ + discard: () => void +} + +/** One field's staged edit. */ +interface StagedEdit { + /** Draft text the control renders. */ + text: string + /** True when this edit clears the field whatever text it shows. */ + clear: boolean +} + +/** One staged edit resolved into the write a save performs. */ +interface PlannedWrite { + /** Field this entry writes. */ + field: string + /** + * Perform the write and report whether the Host holds the staged value + * afterwards; undefined when the draft is not a value the field accepts. + */ + run: (() => Promise) | undefined +} + +/** + * A whole-number field. An empty draft clears the field; any other draft that + * is not a finite number blocks the save. + * @param field - field name inside the namespace section. + * @returns the field's conversion spec. + */ +export function numberField(field: string): CardFieldSpec { + return { + field, + // A section that carries no number for this field renders empty rather + // than as a value nobody chose. + format: value => typeof value === 'number' ? String(value) : '', + parse: (text) => { + const trimmed = text.trim() + if (trimmed === '') return { kind: 'clear' } + const parsed = Number(trimmed) + return Number.isFinite(parsed) ? { kind: 'set', value: parsed } : undefined + }, + } +} + +/** + * A free-text field. An empty draft clears the field, so emptying the control + * and saving is the same gesture as resetting it. + * @param field - field name inside the namespace section. + * @returns the field's conversion spec. + */ +export function textField(field: string): CardFieldSpec { + return { + field, + format: value => typeof value === 'string' ? value : '', + parse: (text) => { + const trimmed = text.trim() + return trimmed === '' ? { kind: 'clear' } : { kind: 'set', value: trimmed } + }, + } +} + +/** + * Stages one card's edits over one settings namespace and writes them on save. + * + * The form publishes through a snapshot store because slot components read + * through a snapshot selector, while both the scope and the local drafts + * change underneath; every projection is rebuilt from the two together. + */ +export class CardForm { + private readonly specs: Map + private readonly secretSpecs: Map + private readonly staged = new Map() + private readonly listeners = new Set<() => void>() + private saving = false + private failed = false + + /** + * @param scope - the bound settings scope for this card's namespace. + * @param specs - the section fields this card edits. + * @param secrets - the card's write-only controls, written outside the section. + */ + constructor( + private readonly scope: SettingsScope, + specs: CardFieldSpec[], + secrets: CardSecretSpec[] = [], + ) { + this.specs = new Map(specs.map(spec => [spec.field, spec])) + this.secretSpecs = new Map(secrets.map(spec => [spec.field, spec])) + scope.subscribe(() => { this.publish() }) + } + + /** + * Publish a projection of this form, rebuilt whenever the scope or a draft changes. + * @param project - build the card's state from the form's current reads. + * @returns the store the card's component reads through its bound selector. + */ + bind(project: () => S): SnapshotStore { + const store = createSnapshotStore(project()) + this.listeners.add(() => { store.set(project()) }) + return store + } + + /** + * Read the card-level state: what the Host serves, and what a save would do. + * @returns the form state every card shares. + */ + shell(): CardShell { + const snapshot = this.scope.getSnapshot() + const plan = this.plan() + return { + available: snapshot.status === 'ready', + writable: snapshot.writable, + dirty: plan.length > 0, + invalid: plan.some(item => item.run === undefined), + saving: this.saving, + failed: this.failed, + } + } + + /** + * Read one control's state. + * @param field - field name of a section field or of a write-only control. + * @returns the draft text, whether a save would leave an override, and whether it is invalid. + */ + field(field: string): CardFieldState { + const staged = this.staged.get(field) + if (this.secretSpecs.has(field)) { + return { text: staged?.text ?? '', overridden: false, invalid: false } + } + const spec = this.spec(field) + if (staged === undefined) { + return { text: spec.format(this.sectionValue(field)), overridden: this.stored(field), invalid: false } + } + const write = staged.clear ? { kind: 'clear' as const } : spec.parse(staged.text) + return { + text: staged.text, + overridden: write?.kind === 'set', + invalid: write === undefined, + } + } + + /** + * Build the edit, reset, save, and discard actions bound to this form. + * @returns the actions a card's slot entry injects. + */ + actions(): CardActions { + return { + edit: (field, text) => { this.stage(field, { text, clear: false }) }, + resetField: (field) => { + this.stage(field, { text: this.spec(field).format(this.baseValue(field)), clear: true }) + }, + save: () => { void this.save() }, + discard: () => { + if (this.staged.size === 0 && !this.failed) return + this.staged.clear() + this.failed = false + this.publish() + }, + } + } + + /** + * Write every staged edit, then re-seed from what the Host accepted. + * + * The Host is the only authority on whether a value was accepted — its + * validators own the constraints no schema can express — so the outcome is + * read back from the section rather than predicted here. A save that did not + * land keeps its drafts, so the user can correct them instead of retyping. + * @returns settlement after every write and the read-back. + */ + async save(): Promise { + const plan = this.plan() + const writes = plan.flatMap(item => item.run === undefined ? [] : [item.run]) + if (plan.length === 0 || this.saving || writes.length !== plan.length) return + this.saving = true + this.failed = false + this.publish() + let landed = true + for (const write of writes) { + landed = await write() && landed + } + if (landed) this.staged.clear() + this.saving = false + this.failed = !landed + this.publish() + } + + /** + * Every staged edit a save would write. An entry whose draft is not a value + * its field accepts carries no write: the form is still dirty, and the save + * refuses rather than dropping the edit. + * @returns the planned writes, in the order the fields were staged. + */ + private plan(): PlannedWrite[] { + const plan: PlannedWrite[] = [] + for (const [field, staged] of this.staged) { + const secret = this.secretSpecs.get(field) + if (secret !== undefined) { + const value = staged.text.trim() + if (value !== '') plan.push({ field, run: () => secret.write(value) }) + continue + } + const spec = this.spec(field) + if (staged.clear) { + if (this.stored(field)) plan.push({ field, run: () => this.clear(field) }) + continue + } + if (staged.text === spec.format(this.sectionValue(field))) continue + const write = spec.parse(staged.text) + if (write === undefined) plan.push({ field, run: undefined }) + else if (write.kind === 'clear') plan.push({ field, run: () => this.clear(field) }) + else plan.push({ field, run: () => this.store(field, write.value) }) + } + return plan + } + + private async clear(field: string): Promise { + await this.scope.unset(field) + return !this.stored(field) + } + + private async store(field: string, value: unknown): Promise { + await this.scope.set(field, value) + return this.userLayer()?.[field] === value + } + + private stage(field: string, edit: StagedEdit): void { + this.staged.set(field, edit) + this.failed = false + this.publish() + } + + private spec(field: string): CardFieldSpec { + const spec = this.specs.get(field) + // Every call site names a field this card declared; a missing one is a + // wiring mistake that must not degrade into a silently inert control. + if (spec === undefined) throw new Error(`plugin card has no field ${field}`) + return spec + } + + private snapshotOf(): SettingsScopeSnapshot { + return this.scope.getSnapshot() + } + + private sectionValue(field: string): unknown { + return (this.snapshotOf().value as Record | undefined)?.[field] + } + + private baseValue(field: string): unknown { + return (this.snapshotOf().base as Record | undefined)?.[field] + } + + private userLayer(): Record | undefined { + return this.snapshotOf().user as Record | undefined + } + + private stored(field: string): boolean { + const user = this.userLayer() + return user !== undefined && Object.hasOwn(user, field) + } + + private publish(): void { + for (const listener of this.listeners) listener() + } +} diff --git a/packages/client/ui-plugin-config/src/client/fields.module.css b/packages/client/ui-plugin-config/src/client/fields.module.css new file mode 100644 index 0000000000..261dcb0fe9 --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/fields.module.css @@ -0,0 +1,113 @@ +/* Plugin configuration fields: label, control, override badge, and hint. */ + +.field { + display: flex; + flex-direction: column; + gap: 6px; + padding: 12px 0; +} + +.field + .field { + border-top: 1px solid var(--dsw-alias-border-l2); +} + +.head { + display: flex; + align-items: center; + gap: 8px; +} + +.label { + flex: 1; + min-width: 0; + font-size: 13px; + font-weight: 500; + line-height: 1.5; + color: var(--dsw-alias-label-primary); +} + +.badges { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.badge { + border-radius: 999px; + padding: 1px 8px; + font-size: 11px; + line-height: 17px; + white-space: nowrap; + font-weight: 500; + background: var(--dsw-alias-bg-module-platform); + color: var(--dsw-alias-label-secondary); +} + +.badgeMuted { + border-radius: 999px; + padding: 1px 8px; + font-size: 11px; + line-height: 17px; + white-space: nowrap; + color: var(--dsw-alias-label-tertiary); +} + +.reset { + border: none; + background: none; + padding: 0; + font: inherit; + font-size: 12px; + line-height: 1.5; + color: var(--dsw-alias-label-secondary); + cursor: pointer; +} + +.reset:hover:not(:disabled) { + color: var(--dsw-alias-label-primary); +} + +.reset:disabled { + cursor: default; +} + +.input { + height: 34px; + padding: 0 12px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 8px; + background: var(--dsw-alias-bg-layer-3); + font: inherit; + font-size: 13px; + line-height: 1.5; + color: var(--dsw-alias-label-primary); +} + +.input:focus-visible { + outline: none; + border-color: var(--dsw-alias-brand-primary); +} + +.input:disabled { + color: var(--dsw-alias-label-tertiary); + cursor: default; +} + +.inputInvalid { + composes: input; + border-color: var(--dsw-alias-label-error); +} + +.invalid { + margin: 0; + font-size: 12px; + line-height: 1.5; + color: var(--dsw-alias-label-error); +} + +.hint { + margin: 0; + font-size: 12px; + line-height: 1.5; + color: var(--dsw-alias-label-tertiary); +} diff --git a/packages/client/ui-plugin-config/src/client/fields.tsx b/packages/client/ui-plugin-config/src/client/fields.tsx new file mode 100644 index 0000000000..a30998ddad --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/fields.tsx @@ -0,0 +1,123 @@ +/** + * Hand-written controls for the plugin configuration forms. Each renders one + * field's label, its staged text, whether saving would leave an override, and + * — when one stands — the reset that stages a clear back to the composition + * layer. Nothing here writes: a control reports what the user typed, and the + * card's save is the single point where a draft becomes a document mutation. + */ + +import css from './fields.module.css' + +/** What every field control needs regardless of its value type. */ +export interface FieldProps { + /** Stable id associating the label with its control. */ + id: string + /** Visible label. */ + label: string + /** One-line explanation rendered under the control. */ + hint: string + /** Draft text this control renders. */ + text: string + /** True when saving would leave a user-layer entry for this field. */ + overridden: boolean + /** True when the draft is not a value this field accepts. */ + invalid: boolean + /** Copy for the overridden badge. */ + overriddenLabel: string + /** Copy for the reset control. */ + resetLabel: string + /** Copy shown in place of the hint while the draft is invalid. */ + invalidLabel: string + /** Disables every control (read-only document, or an unavailable namespace). */ + disabled: boolean + /** Stage draft text. */ + onEdit: (text: string) => void + /** Stage a clear so the field re-inherits the composition layer. */ + onReset: () => void +} + +/** + * A staged value field. `numeric` only hints the keypad: which drafts a field + * accepts is decided by its spec, so the control never silently rewrites what + * the user typed. + * @param props - the field's copy, its staged text, and the edit actions. + * @returns the labelled control. + */ +export function ValueField(props: FieldProps & { + /** Hints a numeric keypad without narrowing what the control accepts. */ + numeric?: boolean + /** Placeholder shown while the draft is empty. */ + placeholder?: string +}) { + return ( +
    +
    + + {props.overridden + ? ( + + {props.overriddenLabel} + + + ) + : null} +
    + { props.onEdit(event.target.value) }} + /> +

    + {props.invalid ? props.invalidLabel : props.hint} +

    +
    + ) +} + +/** + * A write-only credential control. The value never rides a response, so the + * control reports only whether one is configured and starts blank; a blank + * draft writes nothing, which keeps the stored key rather than clearing it. + * @param props - the field's copy, its staged text, and the configured state. + * @returns the labelled control. + */ +export function SecretField(props: Pick & { + /** Whether the Host reports a configured credential for this reference. */ + configured: boolean + /** Copy describing the configured state. */ + stateLabel: string +}) { + return ( +
    +
    + + + {props.stateLabel} + +
    + { props.onEdit(event.target.value) }} + /> +

    {props.hint}

    +
    + ) +} diff --git a/packages/client/ui-plugin-config/src/client/index.ts b/packages/client/ui-plugin-config/src/client/index.ts new file mode 100644 index 0000000000..f3425634ef --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/index.ts @@ -0,0 +1,110 @@ +/** + * Plugin configuration surface, browser half — one settings section holding + * an expandable card per Host plugin whose configuration a user owns. + * + * The section owns no knowledge of any namespace: it declares the + * `settings.plugin.item` slot and renders whatever cards were registered into + * it, so a plugin that ships a browser half contributes its own card and its + * own controls. The three cards this package registers are the host-plane + * sections the deployment already exposes; each binds its namespace through + * the client settings scope, which keeps them unaware of one another. + */ + +import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client' +// Type-only: pulls the locale plugin's Context merge (ctx.locale). +import type {} from '@deepseek-ai/dsh-client-locale/client' +// Type-only: the settings shell's SlotMap merge (the 'settings.section' entry) +// and the ctx.settingsScope Context merge. Cross-plugin collaboration goes +// through the service, never a value import (client bundle purity gate). +import type {} from '@deepseek-ai/dsh-client-ui-settings/client' +import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +// Type-only: the ctx.remote Context merge and the forwarded-event key face. +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import { AgentLoopCard } from './AgentLoopCard.tsx' +import { BashCard } from './BashCard.tsx' +import { PluginConfigSection } from './PluginConfigSection.tsx' +import { WebSearchCard } from './WebSearchCard.tsx' +import { AGENT_LOOP_NS, AgentLoopCardController } from './agent-loop-store.ts' +import { BASH_NS, BashCardController } from './bash-store.ts' +import { WEB_SEARCH_NS, WebSearchCardController } from './web-search-store.ts' +import { en, zh } from './locales.ts' + +export type { PluginConfigSectionInjected, PluginConfigSectionProps } from './PluginConfigSection.tsx' +export type { PluginCardProps } from './PluginCard.tsx' +export type { SettingsPluginItemOwnerProps } from './slot-contract.ts' +export type { FieldProps } from './fields.tsx' +export type { + CardActions, CardFieldSpec, CardFieldState, CardSecretSpec, CardShell, +} from './card-store.ts' +export type { AgentLoopCardFace, AgentLoopCardState } from './agent-loop-store.ts' +export type { BashCardFace, BashCardState } from './bash-store.ts' +export type { WebSearchCardFace, WebSearchCardState } from './web-search-store.ts' + +/** Dictionary namespace owned by this plugin. */ +const NS = 'settings.pluginConfig' + +/** Required services (cordis fiber inject). */ +export const inject = ['slots', 'locale', 'connection', 'remote', 'settingsScope'] + +/** + * Mount the plugin configuration section and the cards this package ships. + * @param ctx - the browser plugin context. + */ +export function apply(ctx: ClientContext): void { + const { api } = ctx.get('connection') as ConnectionHandle + const t = ctx.locale.bind(NS) + ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-plugin-config: section dictionaries') + + const bash = new BashCardController(ctx.settingsScope.bind({ namespace: BASH_NS })) + const agentLoop = new AgentLoopCardController(ctx.settingsScope.bind({ namespace: AGENT_LOOP_NS })) + const webSearch = new WebSearchCardController(ctx.settingsScope.bind({ namespace: WEB_SEARCH_NS }), api) + + // The credential a card reports is not part of any settings section, so its + // scope publishes nothing when one is written. This is the only signal that + // a key written on another surface reached the Host. + ctx.effect( + () => ctx.remote.$on('credentials/updated', (ref) => { webSearch.refreshCredential(ref) }), + 'ui-plugin-config: credential invalidations', + ) + + // The section renders the empty line rather than an empty list when no plugin + // contributed a card. The count is read once: the renderer caches a root + // entry's inject face per registration, so this reports what was registered + // when the section mounted, not what is visible now. Both gaps are bounded by + // this deployment always registering the three cards below — a card that + // arrives later would not raise the count, and a namespace this deployment + // does not expose leaves its card rendering nothing inside a non-empty list. + ctx.slots.inject('settings.section', () => ctx.slots.register({ + name: 'settings.section', + id: 'plugins', + order: 30, + label: () => t('nav'), + locale: NS, + inject: () => ({ cardCount: ctx.slots.entries('settings.plugin.item').length }), + children: { 'settings.plugin.item': { kind: 'list', scope: 'root' } }, + }, PluginConfigSection)) + + ctx.slots.inject('settings.plugin.item', function* () { + yield ctx.slots.register({ + name: 'settings.plugin.item', + id: 'bash', + order: 0, + locale: NS, + inject: () => bash.inject(), + }, BashCard) + yield ctx.slots.register({ + name: 'settings.plugin.item', + id: 'agent-loop', + order: 10, + locale: NS, + inject: () => agentLoop.inject(), + }, AgentLoopCard) + yield ctx.slots.register({ + name: 'settings.plugin.item', + id: 'web-search', + order: 20, + locale: NS, + inject: () => webSearch.inject(), + }, WebSearchCard) + }) +} diff --git a/packages/client/ui-plugin-config/src/client/locales.ts b/packages/client/ui-plugin-config/src/client/locales.ts new file mode 100644 index 0000000000..18fc943f7b --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/locales.ts @@ -0,0 +1,91 @@ +/** Locale bundles for the plugin configuration section and its plugin cards. */ + +/** Locale keys these surfaces render. */ +export type PluginConfigKey = + | 'nav' | 'title' | 'intro' | 'empty' + | 'overridden' | 'reset' | 'readOnly' | 'expand' | 'collapse' + | 'save' | 'saving' | 'discard' | 'unsaved' | 'saveFailed' | 'invalidNumber' + | 'bashTitle' | 'bashDescription' | 'bashTimeoutMs' | 'bashTimeoutMsHint' + | 'bashMaxOutputBytes' | 'bashMaxOutputBytesHint' + | 'agentLoopTitle' | 'agentLoopDescription' | 'agentLoopMaxParallel' | 'agentLoopMaxParallelHint' + | 'webSearchTitle' | 'webSearchDescription' + | 'webSearchApiKey' | 'webSearchApiKeyHint' | 'webSearchApiKeySet' | 'webSearchApiKeyUnset' + | 'webSearchBaseUrl' | 'webSearchBaseUrlHint' | 'webSearchMaxUses' | 'webSearchMaxUsesHint' + +/** English copy. */ +export const en: Record = { + nav: 'Plugin config', + title: 'Plugin configuration', + intro: 'Configure the plugins this deployment installed.', + empty: 'This deployment exposes no plugin settings.', + overridden: 'Overridden', + reset: 'Reset to default', + readOnly: 'This deployment stores settings read-only.', + expand: 'Show settings', + collapse: 'Hide settings', + save: 'Save', + saving: 'Saving…', + discard: 'Discard', + unsaved: 'Unsaved', + saveFailed: 'The deployment did not accept these values; they were left for you to correct.', + invalidNumber: 'Enter a number, or leave blank to use the default.', + bashTitle: 'Shell', + bashDescription: 'Limits every command the agent runs.', + bashTimeoutMs: 'Command timeout (ms)', + bashTimeoutMsHint: 'How long one command may run before it is terminated.', + bashMaxOutputBytes: 'Output cap per stream (bytes)', + bashMaxOutputBytesHint: 'Output beyond this spills to a temporary file rather than being lost.', + agentLoopTitle: 'Agent loop', + agentLoopDescription: 'How the agent dispatches tool calls.', + agentLoopMaxParallel: 'Parallel tool calls', + agentLoopMaxParallelHint: 'Upper bound on parallel-safe calls running at once within one step.', + webSearchTitle: 'Web search', + webSearchDescription: 'The DeepSeek search provider.', + webSearchApiKey: 'API key', + webSearchApiKeyHint: 'Stored outside the settings file. Leave blank to keep the current key.', + webSearchApiKeySet: 'A key is configured.', + webSearchApiKeyUnset: 'No key is configured; search is unavailable until one is.', + webSearchBaseUrl: 'Endpoint', + webSearchBaseUrlHint: 'Leave blank to use the provider default.', + webSearchMaxUses: 'Max searches per request', + webSearchMaxUsesHint: 'How many times one request may search before it must answer.', +} + +/** Simplified Chinese copy. */ +export const zh: Record = { + nav: '插件配置', + title: '插件配置', + intro: '配置本部署已安装的插件。', + empty: '本部署没有开放任何插件设置。', + overridden: '已覆盖', + reset: '恢复默认', + readOnly: '本部署的设置为只读。', + expand: '展开设置', + collapse: '收起设置', + save: '保存', + saving: '保存中…', + discard: '放弃修改', + unsaved: '未保存', + saveFailed: '本部署没有接受这些值,已保留供你修改。', + invalidNumber: '请填数字;留空表示使用默认值。', + bashTitle: '终端', + bashDescription: '限制 agent 运行的每一条命令。', + bashTimeoutMs: '命令超时(毫秒)', + bashTimeoutMsHint: '单条命令允许运行多久,超时即终止。', + bashMaxOutputBytes: '单流输出上限(字节)', + bashMaxOutputBytesHint: '超出部分会转存到临时文件,而不是被丢弃。', + agentLoopTitle: 'Agent 循环', + agentLoopDescription: 'Agent 如何派发工具调用。', + agentLoopMaxParallel: '并行工具调用数', + agentLoopMaxParallelHint: '同一步内最多同时运行多少个可并行的调用。', + webSearchTitle: '网页搜索', + webSearchDescription: 'DeepSeek 搜索提供方。', + webSearchApiKey: 'API Key', + webSearchApiKeyHint: '不写入设置文件。留空表示保持当前密钥。', + webSearchApiKeySet: '已配置密钥。', + webSearchApiKeyUnset: '未配置密钥;配置之前搜索不可用。', + webSearchBaseUrl: '接口地址', + webSearchBaseUrlHint: '留空则使用提供方默认地址。', + webSearchMaxUses: '单次请求最多搜索次数', + webSearchMaxUsesHint: '一次请求在必须作答前最多可以搜索多少次。', +} diff --git a/packages/client/ui-plugin-config/src/client/slot-contract.ts b/packages/client/ui-plugin-config/src/client/slot-contract.ts new file mode 100644 index 0000000000..02b00ea35b --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/slot-contract.ts @@ -0,0 +1,24 @@ +/** + * The `settings.plugin.item` slot type — one plugin's card inside the plugin + * configuration section. Options: `id` (card key), `order` (card position). + * A card draws its own internals; the section only stacks them and reports + * how many there are. + * + * TYPE HOME RATIONALE: unlike `settings.general.item`, whose registrants span + * packages that cannot reference its declarer, every current registrant of + * this slot ships in this package, and a plugin registering its own card + * already depends on this package for the card chrome. The type therefore + * lives with the section that declares it at runtime. + */ +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** One plugin's card inside the plugin configuration section (see module JSDoc). */ + 'settings.plugin.item': { kind: 'list'; scope: 'root'; owner: SettingsPluginItemOwnerProps } + } +} + +/** Owner share of a plugin card (the section supplies nothing). */ +export interface SettingsPluginItemOwnerProps { + /** Marker field: card owner props are intentionally empty. */ + children?: never +} diff --git a/packages/client/ui-plugin-config/src/client/web-search-store.ts b/packages/client/ui-plugin-config/src/client/web-search-store.ts new file mode 100644 index 0000000000..5b6907d464 --- /dev/null +++ b/packages/client/ui-plugin-config/src/client/web-search-store.ts @@ -0,0 +1,192 @@ +/** + * The web-search card's staged form over the `web-search-deepseek` settings + * namespace. + * + * The key is the one control that does not live in the section: its literal + * never rides a response, so the card learns only whether one is configured + * and writes it through the credentials domain, addressed by the reference the + * section names. It is still staged with the rest of the form, so one save + * covers everything the card shows. + */ + +import type { IApiClient } from '@deepseek-ai/dsh-client-connection/client' +import type { SettingsScope, SettingsScopeSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import { + CardForm, numberField, textField, + type CardActions, type CardFieldState, type CardShell, +} from './card-store.ts' + +/** + * Namespace of the DeepSeek search provider. Spelled here rather than + * imported: a client package must not depend on a Host package. + */ +export const WEB_SEARCH_NS = 'web-search-deepseek' + +/** Credential reference the provider resolves when the section names none. */ +const DEFAULT_API_KEY_REF = 'DEEPSEEK_API_KEY' + +/** Form field the credential control stages under. */ +const API_KEY_FIELD = 'apiKey' + +/** The search-provider fields this card edits. */ +export interface WebSearchSettings { + /** Credential reference naming the environment key. */ + apiKeyEnv?: string + /** Provider endpoint; blank inherits the provider default. */ + baseURL?: string + /** Maximum searches served within one request. */ + maxUses?: number +} + +/** What the credentials domain last reported, and for which reference. */ +interface CredentialState { + /** Reference this answer describes; a stale response for another one is dropped. */ + ref: string + /** Whether any layer supplies a value for it. */ + configured: boolean + /** Whether `credentials.set` can affect it; false disables the control. */ + writable: boolean +} + +/** What the web-search card renders. */ +export interface WebSearchCardState extends CardShell { + /** Provider endpoint. */ + baseURL: CardFieldState + /** Searches allowed per request. */ + maxUses: CardFieldState + /** The staged credential, which starts blank on every load. */ + apiKey: CardFieldState + /** Whether the Host reports a credential configured for the referenced key. */ + apiKeyConfigured: boolean + /** Whether the credentials domain accepts a write for it; false disables the control. */ + apiKeyWritable: boolean +} + +/** The registration-side face the web-search card's slot entry injects. */ +export interface WebSearchCardFace extends CardActions { + hooks: { + /** Card snapshot bound by the renderer as useWebSearchCard. */ + webSearchCard: SnapshotStore + } +} + +/** Bridges the `web-search-deepseek` scope and the credentials domain onto the card. */ +export class WebSearchCardController { + private readonly form: CardForm + private readonly store: SnapshotStore + private credential: CredentialState = { ref: '', configured: false, writable: true } + + /** + * @param scope - the bound settings scope for the `web-search-deepseek` namespace. + * @param api - wire face used for the credential the section references. + */ + constructor( + private readonly scope: SettingsScope, + private readonly api: Pick, + ) { + this.form = new CardForm( + scope, + [textField('baseURL'), numberField('maxUses')], + [{ field: API_KEY_FIELD, write: text => this.writeKey(text) }], + ) + this.store = this.form.bind(() => this.projection()) + scope.subscribe(() => { void this.readCredential() }) + void this.readCredential() + } + + private projection(): WebSearchCardState { + return { + ...this.form.shell(), + baseURL: this.form.field('baseURL'), + maxUses: this.form.field('maxUses'), + apiKey: this.form.field(API_KEY_FIELD), + apiKeyConfigured: this.credential.configured, + apiKeyWritable: this.credential.writable, + } + } + + /** + * Ask the credentials domain about the reference the section currently names. + * + * The answer is stored with the reference it describes: `apiKeyEnv` can + * change between the request and its response, and two reads can settle out + * of order, so a response is published only while it still answers for the + * reference in force. + */ + private async readCredential(): Promise { + const ref = refOf(this.scope.getSnapshot()) + if (ref !== this.credential.ref) { + // A new reference knows nothing yet; keeping the old answer would claim + // the key is configured under a name nobody has checked. + this.credential = { ref, configured: false, writable: true } + this.store.set(this.projection()) + } + let response: Awaited> + try { + response = await this.api.credentials.describe({ refs: [ref] }) + } catch (_credentialReadFailure) { + // The card stays usable without this: the key control simply reports the + // last state it knew, and a write still reaches the Host. + return + } + if (!response.result.ok || ref !== refOf(this.scope.getSnapshot())) return + const view = response.result.value.credentials[ref] + const next: CredentialState = { + ref, + configured: view?.configured ?? false, + // An unknown reference is treated as writable: the control stays usable + // and the Host is what refuses, rather than the card guessing a refusal. + writable: view?.writable ?? true, + } + if (next.configured === this.credential.configured && next.writable === this.credential.writable) return + this.credential = next + this.store.set(this.projection()) + } + + /** + * Re-read after the Host reports a change to the reference this card watches. + * + * A key can be written from somewhere else — the Models page addresses the + * same reference — and the settings section does not change when it is, so + * without this the badge keeps reporting a state the Host already replaced. + * @param ref - the reference the Host reports as changed. + */ + refreshCredential(ref: string): void { + if (ref !== this.credential.ref) return + void this.readCredential() + } + + /** + * Build the face the card's slot registration injects. + * @returns the card's snapshot and its form actions. + */ + inject(): WebSearchCardFace { + return { hooks: { webSearchCard: this.store }, ...this.form.actions() } + } + + /** + * Write the staged key, then re-read whether the Host now holds one. + * @param value - the staged credential literal. + * @returns whether the Host reports a configured credential afterwards. + */ + private async writeKey(value: string): Promise { + try { + await this.api.credentials.set({ ref: refOf(this.scope.getSnapshot()), value }) + } catch (_credentialWriteFailure) { + // Refusals surface through the re-read below: the Host is the only + // authority on whether the key now exists. + } + await this.readCredential() + return this.credential.configured + } +} + +/** + * The credential reference the section names, or the provider's default. + * @param snapshot - the current scope snapshot. + * @returns the reference to address. + */ +function refOf(snapshot: SettingsScopeSnapshot): string { + const declared = snapshot.value?.apiKeyEnv + return declared !== undefined && declared.length > 0 ? declared : DEFAULT_API_KEY_REF +} diff --git a/packages/client/ui-plugin-config/src/css-modules.d.ts b/packages/client/ui-plugin-config/src/css-modules.d.ts new file mode 100644 index 0000000000..8811db1264 --- /dev/null +++ b/packages/client/ui-plugin-config/src/css-modules.d.ts @@ -0,0 +1,4 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} diff --git a/packages/client/ui-plugin-config/src/index.ts b/packages/client/ui-plugin-config/src/index.ts new file mode 100644 index 0000000000..0bb50fba35 --- /dev/null +++ b/packages/client/ui-plugin-config/src/index.ts @@ -0,0 +1,11 @@ +/** + * Plugin configuration surface, node half. The empty apply exists so the + * plugin appears in the host cordis.yml / Loader; the browser half ships the + * settings section through exports["./client"], discovered from the + * package.json dsh.client declaration. Every section this page edits is owned + * by the Host plugin that registered it, so this package registers no + * namespace of its own. + */ + +/** Host plugin body — no host-side behavior for this surface plugin. */ +export function apply(): void {} diff --git a/packages/client/ui-plugin-config/src/invariant.ts b/packages/client/ui-plugin-config/src/invariant.ts new file mode 100644 index 0000000000..b65c7f8757 --- /dev/null +++ b/packages/client/ui-plugin-config/src/invariant.ts @@ -0,0 +1,31 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-plugin-config`. + * @module @deepseek-ai/dsh-client-ui-plugin-config/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from '@deepseek-ai/cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-plugin-config' + +/** Cordis companion plugin name. */ +export const name = 'client-ui-plugin-config-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: this is a browser-side settings surface whose node half owns no event + * stream or mutable runtime data; the layering, write refusals, and exposure boundary are Host + * contracts covered by the owning plugins and the api-proxy. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/client/ui-plugin-config/tests/apply.spec.ts b/packages/client/ui-plugin-config/tests/apply.spec.ts new file mode 100644 index 0000000000..a880446e8c --- /dev/null +++ b/packages/client/ui-plugin-config/tests/apply.spec.ts @@ -0,0 +1,134 @@ +/** What the browser half registers, and that it all leaves with the fiber. */ + +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, vi } from 'vitest' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' +import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' +import { TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime' +import { SettingsScopeService } from '@deepseek-ai/dsh-client-ui-settings/client' +import { apply, inject } from '@deepseek-ai/dsh-client-ui-plugin-config/client' + +// The service reads its initial locale from the browser; these specs assert +// the shipped Chinese copy, so they state the browser they assume. +usePinnedBrowserLanguages('zh-CN') + +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotsService).await() + const locale = new LocaleService(ctx) + ctx.provide('locale', locale) + const describeCredentials = vi.fn(() => Promise.resolve({ rpcId: 'c', result: { ok: false, error: {} } })) + // The section binds its scopes through the Settings surface's service, and + // forwarded Host events reach it through the same `$dispatch` handoff the + // connection sink makes. + new TestRemote(ctx) + ctx.provide('connection', { + isLoopback: true, + api: { + settings: { describe: vi.fn(() => Promise.resolve({ rpcId: 's', result: { ok: false, error: {} } })) }, + credentials: { describe: describeCredentials }, + }, + } as never) + await ctx.plugin(SettingsScopeService).await() + return { ctx, slots: ctx.get('slots') as SlotsService, describeCredentials } +} + +function declareRoot(slots: SlotsService): () => void { + return slots.register({ + name: 'root', + children: { 'settings.section': { kind: 'list', scope: 'root' } }, + } as never, () => null) +} + +describe('ui-plugin-config apply', () => { + it('declares the services it uses', () => { + expect(inject).toEqual(['slots', 'locale', 'connection', 'remote', 'settingsScope']) + }) + + it('registers the section and declares the per-plugin card slot', async () => { + const { ctx, slots } = await bench() + declareRoot(slots) + + await ctx.plugin({ inject: [...inject], apply }).await() + + const section = slots.entries('settings.section')[0]! + expect(section.options).toMatchObject({ id: 'plugins', order: 30 }) + // The nav label is a locale-following thunk; owners resolve it at read time. + expect(resolveSlotLabel(section.options.label)).toBe('插件配置') + expect(slots.spec('settings.plugin.item')).toMatchObject({ kind: 'list', scope: 'root' }) + }) + + it('registers one card per host-plane section it ships, in a stable order', async () => { + const { ctx, slots } = await bench() + declareRoot(slots) + + await ctx.plugin({ inject: [...inject], apply }).await() + + expect(slots.entries('settings.plugin.item').map(entry => entry.options.id)) + .toEqual(['bash', 'agent-loop', 'web-search']) + }) + + it('injects a live card count and one business face per card', async () => { + const { ctx, slots } = await bench() + declareRoot(slots) + await ctx.plugin({ inject: [...inject], apply }).await() + + const section = slots.entries('settings.section')[0]! + expect((section as { inject?: () => unknown }).inject?.()).toEqual({ cardCount: 3 }) + for (const entry of slots.entries('settings.plugin.item')) { + const face = (entry as { inject?: () => unknown }).inject?.() as { hooks: Record } + // Each card injects exactly one snapshot store plus its own actions. + expect(Object.keys(face.hooks)).toHaveLength(1) + } + }) + + it('re-reads the credential when the Host reports the watched reference changed', async () => { + const { ctx, slots, describeCredentials } = await bench() + declareRoot(slots) + await ctx.plugin({ inject: [...inject], apply }).await() + await vi.waitFor(() => { expect(describeCredentials).toHaveBeenCalled() }) + describeCredentials.mockClear() + + // A key written on another surface changes no settings section, so this + // event is the only thing that reaches the card. + ctx.remote.$dispatch('credentials/updated', ['DEEPSEEK_API_KEY']) + + await vi.waitFor(() => { expect(describeCredentials).toHaveBeenCalledTimes(1) }) + }) + + it('ignores a credential change for a reference no card watches', async () => { + const { ctx, slots, describeCredentials } = await bench() + declareRoot(slots) + await ctx.plugin({ inject: [...inject], apply }).await() + await vi.waitFor(() => { expect(describeCredentials).toHaveBeenCalled() }) + describeCredentials.mockClear() + + ctx.remote.$dispatch('credentials/updated', ['SOME_OTHER_KEY']) + await Promise.resolve() + + expect(describeCredentials).not.toHaveBeenCalled() + }) + + it('registers into a declaration that arrives after apply', async () => { + const { ctx, slots } = await bench() + await ctx.plugin({ inject: [...inject], apply }).await() + + declareRoot(slots) + + await vi.waitFor(() => { expect(slots.entries('settings.section')).toHaveLength(1) }) + }) + + it('collapses every contribution on teardown', async () => { + const { ctx, slots } = await bench() + declareRoot(slots) + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(slots.entries('settings.plugin.item')).toHaveLength(3) + + await fiber.dispose() + + expect(slots.entries('settings.section')).toHaveLength(0) + expect(slots.spec('settings.plugin.item')).toBeUndefined() + }) +}) diff --git a/packages/client/ui-plugin-config/tests/fields.spec.tsx b/packages/client/ui-plugin-config/tests/fields.spec.tsx new file mode 100644 index 0000000000..f9370106e0 --- /dev/null +++ b/packages/client/ui-plugin-config/tests/fields.spec.tsx @@ -0,0 +1,156 @@ +// @vitest-environment jsdom +/** + * Field-control behavior: what a control renders for a staged draft, how an + * overridden field offers its reset, and that a control never writes on its own. + */ + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { SecretField, ValueField } from '../src/client/fields.tsx' + +afterEach(cleanup) + +const frame = { + id: 'field', + label: 'Command timeout', + hint: 'How long one command may run.', + overriddenLabel: 'Overridden', + resetLabel: 'Reset to default', + invalidLabel: 'Enter a number.', + disabled: false, + overridden: false, + invalid: false, +} + +describe('ValueField', () => { + it('stages every keystroke without writing', () => { + const onEdit = vi.fn() + render() + + fireEvent.change(screen.getByLabelText('Command timeout'), { target: { value: '9000' } }) + + expect(onEdit).toHaveBeenCalledWith('9000') + }) + + it('renders the staged text it is given rather than a draft of its own', () => { + const { rerender } = render() + expect(screen.getByLabelText('Command timeout')).toHaveProperty('value', '60000') + + rerender() + + expect(screen.getByLabelText('Command timeout')).toHaveProperty('value', '9000') + }) + + it('offers the reset only while an override would stand', () => { + const onReset = vi.fn() + const { rerender } = render() + expect(screen.queryByRole('button', { name: 'Reset to default' })).toBeNull() + + rerender() + fireEvent.click(screen.getByRole('button', { name: 'Reset to default' })) + + expect(screen.getByText('Overridden')).toBeTruthy() + expect(onReset).toHaveBeenCalledOnce() + }) + + it('replaces the hint with the reason an invalid draft cannot be saved', () => { + render() + + expect(screen.getByText('Enter a number.')).toBeTruthy() + expect(screen.queryByText('How long one command may run.')).toBeNull() + expect(screen.getByLabelText('Command timeout').getAttribute('aria-invalid')).toBe('true') + }) + + it('hints a numeric keypad and renders a placeholder when asked', () => { + render( + , + ) + const input = screen.getByLabelText('Command timeout') + + expect(input.getAttribute('inputmode')).toBe('numeric') + expect(input).toHaveProperty('placeholder', 'https://api.deepseek.com') + }) + + it('disables the control and its reset while the document is read-only', () => { + render() + + expect(screen.getByLabelText('Command timeout')).toHaveProperty('disabled', true) + expect(screen.getByRole('button', { name: 'Reset to default' })).toHaveProperty('disabled', true) + }) +}) + +describe('SecretField', () => { + const secret = { + id: 'key', + label: 'API key', + hint: 'Stored outside the settings file.', + disabled: false, + } + + it('stages the draft and never renders it', () => { + const onEdit = vi.fn() + render( + , + ) + const input = screen.getByLabelText('API key') + + fireEvent.change(input, { target: { value: 'ds-secret' } }) + + expect(onEdit).toHaveBeenCalledWith('ds-secret') + expect(input).toHaveProperty('type', 'password') + }) + + it('reports the configured state the Host holds', () => { + const { rerender } = render( + , + ) + expect(screen.getByText('No key is configured.')).toBeTruthy() + + rerender( + , + ) + + expect(screen.getByText('A key is configured.')).toBeTruthy() + expect(screen.getByLabelText('API key')).toHaveProperty('value', 'ds-secret') + }) + + it('disables the control when it is told to', () => { + render( + , + ) + + expect(screen.getByLabelText('API key')).toHaveProperty('disabled', true) + }) +}) diff --git a/packages/client/ui-plugin-config/tests/invariant.spec.ts b/packages/client/ui-plugin-config/tests/invariant.spec.ts new file mode 100644 index 0000000000..2b41fb7a51 --- /dev/null +++ b/packages/client/ui-plugin-config/tests/invariant.spec.ts @@ -0,0 +1,25 @@ +/** The package's node half: an empty host body and an explained empty invariant companion. */ + +import { describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import InvariantService from '@deepseek-ai/dsh-invariants' +import * as PluginConfigInvariant from '@deepseek-ai/dsh-client-ui-plugin-config/invariant' + +describe('invariant companion', () => { + it('reserves package ownership with an empty installer', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService, { enabled: true }) + + await expect(ctx.plugin(PluginConfigInvariant).await()).resolves.toBeDefined() + }) + + it('has an empty node half', async () => { + const { apply } = await import('@deepseek-ai/dsh-client-ui-plugin-config') + + // The host body exists only so the plugin appears in the host cordis.yml; + // every surface this package ships lives in the browser half. + apply() + + expect(typeof apply).toBe('function') + }) +}) diff --git a/packages/client/ui-plugin-config/tests/section.spec.tsx b/packages/client/ui-plugin-config/tests/section.spec.tsx new file mode 100644 index 0000000000..3945092587 --- /dev/null +++ b/packages/client/ui-plugin-config/tests/section.spec.tsx @@ -0,0 +1,325 @@ +// @vitest-environment jsdom +/** + * What the section and its cards show: the empty line when no plugin + * contributed one, a card that renders nothing while its namespace is + * unavailable, and the save footer that decides when staged edits are written. + */ + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' +import { AgentLoopCard } from '../src/client/AgentLoopCard.tsx' +import type { AgentLoopCardProps } from '../src/client/AgentLoopCard.tsx' +import { BashCard } from '../src/client/BashCard.tsx' +import type { BashCardProps } from '../src/client/BashCard.tsx' +import { PluginConfigSection } from '../src/client/PluginConfigSection.tsx' +import type { PluginConfigSectionProps } from '../src/client/PluginConfigSection.tsx' +import { WebSearchCard } from '../src/client/WebSearchCard.tsx' +import type { WebSearchCardProps } from '../src/client/WebSearchCard.tsx' +import type { AgentLoopCardState } from '../src/client/agent-loop-store.ts' +import type { BashCardState } from '../src/client/bash-store.ts' +import type { CardFieldState, CardShell } from '../src/client/card-store.ts' +import type { WebSearchCardState } from '../src/client/web-search-store.ts' +import { en } from '../src/client/locales.ts' + +afterEach(cleanup) + +const t = (key: keyof typeof en) => en[key] + +/** A settled form: nothing staged, everything served. */ +const settled: CardShell = { + available: true, + writable: true, + dirty: false, + invalid: false, + saving: false, + failed: false, +} + +/** One control's state, defaulting to an inherited value. */ +function field(text: string, rest: Partial = {}): CardFieldState { + return { text, overridden: false, invalid: false, ...rest } +} + +function cardActions() { + return { edit: vi.fn(), resetField: vi.fn(), save: vi.fn(), discard: vi.fn() } +} + +function renderSection(cardCount: number, cards = 'cards') { + const props = { + t, + cardCount, + renderSlot: () =>
  • {cards}
  • , + } as unknown as PluginConfigSectionProps + render() +} + +function renderBash(state: Partial = {}) { + const store = createSnapshotStore({ + ...settled, + timeoutMs: field('60000'), + maxOutputBytes: field('64000'), + ...state, + }) + const actions = cardActions() + const props = { ...actions, t, useBashCard: bindSnapshotSelector(store) } as unknown as BashCardProps + render() + return actions +} + +describe('PluginConfigSection', () => { + it('says so when no plugin contributed a card', () => { + renderSection(0) + + expect(screen.getByText(en.empty)).toBeTruthy() + expect(screen.queryByText('cards')).toBeNull() + }) + + it('renders the card list once a plugin contributed one', () => { + renderSection(1) + + expect(screen.getByText('cards')).toBeTruthy() + expect(screen.queryByText(en.empty)).toBeNull() + }) + + it('leads with its own heading and intro', () => { + renderSection(1) + + expect(screen.getByRole('heading', { name: en.title })).toBeTruthy() + expect(screen.getByText(en.intro)).toBeTruthy() + }) +}) + +describe('BashCard', () => { + it('renders nothing while its namespace is unavailable', () => { + const { container } = render(
    ) + renderBash({ available: false }) + + expect(container.textContent).toBe('') + expect(screen.queryByText(en.bashTitle)).toBeNull() + }) + + it('shows the plugin and reveals its fields only once expanded', () => { + renderBash() + expect(screen.getByText(en.bashTitle)).toBeTruthy() + expect(screen.queryByLabelText(en.bashTimeoutMs)).toBeNull() + + fireEvent.click(screen.getByText(en.bashTitle)) + + expect(screen.getByLabelText(en.bashTimeoutMs)).toBeTruthy() + expect(screen.getByLabelText(en.bashMaxOutputBytes)).toBeTruthy() + }) + + it('stages an edit instead of writing it', () => { + const actions = renderBash() + fireEvent.click(screen.getByText(en.bashTitle)) + + fireEvent.change(screen.getByLabelText(en.bashTimeoutMs), { target: { value: '9000' } }) + + expect(actions.edit).toHaveBeenCalledWith('timeoutMs', '9000') + expect(actions.save).not.toHaveBeenCalled() + }) + + it('offers the reset for an overridden field only', () => { + const actions = renderBash({ timeoutMs: field('9000', { overridden: true }) }) + fireEvent.click(screen.getByText(en.bashTitle)) + + // One badge and one reset: the output cap is still inherited. + expect(screen.getAllByText(en.overridden)).toHaveLength(1) + fireEvent.click(screen.getByRole('button', { name: en.reset })) + + expect(actions.resetField).toHaveBeenCalledWith('timeoutMs') + }) + + it('addresses each of its two fields separately', () => { + const actions = renderBash({ maxOutputBytes: field('64000', { overridden: true }) }) + fireEvent.click(screen.getByText(en.bashTitle)) + + fireEvent.change(screen.getByLabelText(en.bashMaxOutputBytes), { target: { value: '1024' } }) + fireEvent.click(screen.getByRole('button', { name: en.reset })) + + expect(actions.edit).toHaveBeenCalledWith('maxOutputBytes', '1024') + expect(actions.resetField).toHaveBeenCalledWith('maxOutputBytes') + }) + + it('keeps save and discard inert until something is staged', () => { + renderBash() + fireEvent.click(screen.getByText(en.bashTitle)) + + expect(screen.getByRole('button', { name: en.save })).toHaveProperty('disabled', true) + expect(screen.getByRole('button', { name: en.discard })).toHaveProperty('disabled', true) + expect(screen.queryByText(en.unsaved)).toBeNull() + }) + + it('writes the staged edits when saved, and drops them when discarded', () => { + const actions = renderBash({ dirty: true, timeoutMs: field('9000', { overridden: true }) }) + fireEvent.click(screen.getByText(en.bashTitle)) + + fireEvent.click(screen.getByRole('button', { name: en.save })) + fireEvent.click(screen.getByRole('button', { name: en.discard })) + + expect(actions.save).toHaveBeenCalledOnce() + expect(actions.discard).toHaveBeenCalledOnce() + }) + + it('marks a card holding unsaved edits, collapsed or not', () => { + renderBash({ dirty: true }) + + expect(screen.getByText(en.unsaved)).toBeTruthy() + }) + + it('blocks the save while a draft is invalid, and says why', () => { + renderBash({ dirty: true, invalid: true, timeoutMs: field('soon', { invalid: true }) }) + fireEvent.click(screen.getByText(en.bashTitle)) + + expect(screen.getByRole('button', { name: en.save })).toHaveProperty('disabled', true) + expect(screen.getByRole('button', { name: en.discard })).toHaveProperty('disabled', false) + expect(screen.getByText(en.invalidNumber)).toBeTruthy() + }) + + it('reports a save in flight and refuses another', () => { + renderBash({ dirty: true, saving: true }) + fireEvent.click(screen.getByText(en.bashTitle)) + + expect(screen.getByRole('button', { name: en.saving })).toHaveProperty('disabled', true) + expect(screen.getByRole('button', { name: en.discard })).toHaveProperty('disabled', true) + }) + + it('reports a save the deployment did not accept', () => { + renderBash({ dirty: true, failed: true }) + fireEvent.click(screen.getByText(en.bashTitle)) + + expect(screen.getByText(en.saveFailed)).toBeTruthy() + }) + + it('says the document is read-only and disables its controls', () => { + renderBash({ writable: false }) + fireEvent.click(screen.getByText(en.bashTitle)) + + expect(screen.getByRole('status')).toHaveProperty('textContent', en.readOnly) + expect(screen.getByLabelText(en.bashTimeoutMs)).toHaveProperty('disabled', true) + }) + + it('collapses again on a second click', () => { + renderBash() + fireEvent.click(screen.getByText(en.bashTitle)) + expect(screen.getByLabelText(en.bashTimeoutMs)).toBeTruthy() + + fireEvent.click(screen.getByText(en.bashTitle)) + + expect(screen.queryByLabelText(en.bashTimeoutMs)).toBeNull() + }) +}) + +describe('AgentLoopCard', () => { + it('stages and saves the only field it owns', () => { + const store = createSnapshotStore({ + ...settled, + dirty: true, + maxParallelToolCalls: field('10'), + }) + const actions = cardActions() + const props = { + ...actions, + t, + useAgentLoopCard: bindSnapshotSelector(store), + } as unknown as AgentLoopCardProps + render() + + fireEvent.click(screen.getByText(en.agentLoopTitle)) + fireEvent.change(screen.getByLabelText(en.agentLoopMaxParallel), { target: { value: '2' } }) + fireEvent.click(screen.getByRole('button', { name: en.save })) + + expect(actions.edit).toHaveBeenCalledWith('maxParallelToolCalls', '2') + expect(actions.save).toHaveBeenCalledOnce() + }) + + it('stages a reset for the field it owns', () => { + const store = createSnapshotStore({ + ...settled, + maxParallelToolCalls: field('2', { overridden: true }), + }) + const actions = cardActions() + const props = { + ...actions, + t, + useAgentLoopCard: bindSnapshotSelector(store), + } as unknown as AgentLoopCardProps + render() + + fireEvent.click(screen.getByText(en.agentLoopTitle)) + fireEvent.click(screen.getByRole('button', { name: en.reset })) + + expect(actions.resetField).toHaveBeenCalledWith('maxParallelToolCalls') + }) +}) + +describe('WebSearchCard', () => { + function renderWebSearch(state: Partial = {}) { + const store = createSnapshotStore({ + ...settled, + baseURL: field(''), + maxUses: field('5'), + apiKey: field(''), + apiKeyConfigured: false, + apiKeyWritable: true, + ...state, + }) + const actions = cardActions() + const props = { ...actions, t, useWebSearchCard: bindSnapshotSelector(store) } as unknown as WebSearchCardProps + render() + return actions + } + + it('reports whether a key is configured without ever showing one', () => { + renderWebSearch({ apiKeyConfigured: true }) + fireEvent.click(screen.getByText(en.webSearchTitle)) + + expect(screen.getByText(en.webSearchApiKeySet)).toBeTruthy() + expect(screen.getByLabelText(en.webSearchApiKey)).toHaveProperty('type', 'password') + }) + + it('keeps the key control usable while the settings document is read-only', () => { + const actions = renderWebSearch({ writable: false }) + fireEvent.click(screen.getByText(en.webSearchTitle)) + + const key = screen.getByLabelText(en.webSearchApiKey) + expect(key).toHaveProperty('disabled', false) + expect(screen.getByLabelText(en.webSearchBaseUrl)).toHaveProperty('disabled', true) + + fireEvent.change(key, { target: { value: 'ds-secret' } }) + + expect(actions.edit).toHaveBeenCalledWith('apiKey', 'ds-secret') + }) + + it('disables the key control when the reference itself is not writable', () => { + // A key coming from the process environment: the settings document is + // writable, the credential is not. + renderWebSearch({ apiKeyConfigured: true, apiKeyWritable: false }) + fireEvent.click(screen.getByText(en.webSearchTitle)) + + expect(screen.getByLabelText(en.webSearchApiKey)).toHaveProperty('disabled', true) + expect(screen.getByLabelText(en.webSearchBaseUrl)).toHaveProperty('disabled', false) + }) + + it('stages the endpoint, the search budget, and their resets', () => { + const actions = renderWebSearch({ + baseURL: field('https://search.test/v1', { overridden: true }), + maxUses: field('3', { overridden: true }), + }) + fireEvent.click(screen.getByText(en.webSearchTitle)) + + fireEvent.change(screen.getByLabelText(en.webSearchBaseUrl), { target: { value: 'https://other.test' } }) + fireEvent.change(screen.getByLabelText(en.webSearchMaxUses), { target: { value: '4' } }) + const resets = screen.getAllByRole('button', { name: en.reset }) + expect(resets).toHaveLength(2) + for (const reset of resets) fireEvent.click(reset) + + expect(actions.edit.mock.calls).toEqual([ + ['baseURL', 'https://other.test'], + ['maxUses', '4'], + ]) + expect(actions.resetField.mock.calls).toEqual([['baseURL'], ['maxUses']]) + }) +}) diff --git a/packages/client/ui-plugin-config/tests/stores.spec.ts b/packages/client/ui-plugin-config/tests/stores.spec.ts new file mode 100644 index 0000000000..78e1ee90c7 --- /dev/null +++ b/packages/client/ui-plugin-config/tests/stores.spec.ts @@ -0,0 +1,540 @@ +/** + * The staged card form: what a draft shows before it is written, which wire + * call a save reaches, and what happens to drafts the Host did not accept. + */ + +import { describe, expect, it, vi } from 'vitest' +import { stubSettingsScope, type StubSettingsScope } from '@deepseek-ai/dsh-client-test-runtime' +import { CardForm, numberField, textField } from '../src/client/card-store.ts' +import { AgentLoopCardController, type AgentLoopSettings } from '../src/client/agent-loop-store.ts' +import { BashCardController, type BashSettings } from '../src/client/bash-store.ts' +import { WebSearchCardController, type WebSearchSettings } from '../src/client/web-search-store.ts' + +/** Make the stub behave like a Host that accepts every write. */ +function acceptWrites(host: StubSettingsScope): void { + const section = (): Record => ({ ...host.scope.getSnapshot().value as object }) + const layer = (): Record => ({ ...host.scope.getSnapshot().user as object }) + host.set.mockImplementation((field: string, value: unknown) => { + host.publish({ value: { ...section(), [field]: value } as T, user: { ...layer(), [field]: value } }) + }) + host.unset.mockImplementation((field: string) => { + const user = Object.fromEntries(Object.entries(layer()).filter(([key]) => key !== field)) + const base = host.scope.getSnapshot().base as Record | undefined + host.publish({ value: { ...section(), [field]: base?.[field] } as T, user }) + }) +} + +function credentialsApi(configured: boolean) { + const describe = vi.fn(() => Promise.resolve({ + rpcId: 'c-1' as never, + result: { ok: true as const, value: { credentials: { DEEPSEEK_API_KEY: { configured, writable: true } } } }, + })) + const set = vi.fn(() => Promise.resolve({ rpcId: 'c-2' as never, result: { ok: true as const, value: {} } })) + return { api: { credentials: { describe, set } } as never, describe, set } +} + +describe('CardForm', () => { + function form() { + const host = stubSettingsScope>() + const subject = new CardForm(host.scope, [numberField('timeoutMs'), textField('baseURL')]) + host.publish({ + status: 'ready', + writable: true, + value: { timeoutMs: 60_000, baseURL: 'https://search.test/v1' }, + base: { timeoutMs: 60_000, baseURL: 'https://search.test/v1' }, + user: {}, + }) + return { host, subject } + } + + it('shows the effective value and stays clean until something is staged', () => { + const { subject } = form() + + expect(subject.field('timeoutMs')).toEqual({ text: '60000', overridden: false, invalid: false }) + expect(subject.shell()).toMatchObject({ available: true, writable: true, dirty: false, invalid: false }) + }) + + it('marks a field the user layer carries as overridden', () => { + const { host, subject } = form() + + host.publish({ value: { timeoutMs: 60_000 }, user: { timeoutMs: 60_000 } }) + + // An override equal to the composition default is still an override. + expect(subject.field('timeoutMs').overridden).toBe(true) + }) + + it('writes nothing until the form is saved', async () => { + const { host, subject } = form() + acceptWrites(host) + + subject.actions().edit('timeoutMs', '9000') + + expect(subject.field('timeoutMs')).toEqual({ text: '9000', overridden: true, invalid: false }) + expect(subject.shell().dirty).toBe(true) + expect(host.set).not.toHaveBeenCalled() + + await subject.save() + + expect(host.set.mock.calls).toEqual([['timeoutMs', 9_000]]) + expect(subject.shell()).toMatchObject({ dirty: false, failed: false, saving: false }) + }) + + it('drops a draft that settles back on the value already shown', async () => { + const { host, subject } = form() + + subject.actions().edit('timeoutMs', '9000') + subject.actions().edit('timeoutMs', '60000') + + expect(subject.shell().dirty).toBe(false) + await subject.save() + + expect(host.set).not.toHaveBeenCalled() + }) + + it('refuses to save while a draft is not a value the field accepts', async () => { + const { host, subject } = form() + + subject.actions().edit('timeoutMs', 'soon') + + expect(subject.field('timeoutMs')).toEqual({ text: 'soon', overridden: false, invalid: true }) + expect(subject.shell()).toMatchObject({ dirty: true, invalid: true }) + + await subject.save() + + expect(host.set).not.toHaveBeenCalled() + expect(subject.field('timeoutMs').text).toBe('soon') + }) + + it('stages a reset that clears the field only once saved', async () => { + const { host, subject } = form() + acceptWrites(host) + host.publish({ value: { timeoutMs: 9_000 }, user: { timeoutMs: 9_000 } }) + + subject.actions().resetField('timeoutMs') + + // The badge previews the save: the field will no longer be overridden. + expect(subject.field('timeoutMs')).toEqual({ text: '60000', overridden: false, invalid: false }) + expect(host.unset).not.toHaveBeenCalled() + + await subject.save() + + expect(host.unset.mock.calls).toEqual([['timeoutMs']]) + expect(subject.shell()).toMatchObject({ dirty: false, failed: false }) + }) + + it('treats resetting an inherited field as no change at all', async () => { + const { host, subject } = form() + + subject.actions().resetField('timeoutMs') + + expect(subject.shell().dirty).toBe(false) + await subject.save() + + expect(host.unset).not.toHaveBeenCalled() + }) + + it('clears a number field by emptying it', async () => { + const { host, subject } = form() + acceptWrites(host) + host.publish({ user: { timeoutMs: 9_000 } }) + + subject.actions().edit('timeoutMs', '') + + expect(subject.field('timeoutMs')).toEqual({ text: '', overridden: false, invalid: false }) + await subject.save() + + expect(host.unset.mock.calls).toEqual([['timeoutMs']]) + }) + + it('clears a text field by emptying it', async () => { + const { host, subject } = form() + acceptWrites(host) + host.publish({ user: { baseURL: 'https://search.test/v1' } }) + + subject.actions().edit('baseURL', ' ') + await subject.save() + + expect(host.unset.mock.calls).toEqual([['baseURL']]) + }) + + it('writes the trimmed text of a text field', async () => { + const { host, subject } = form() + acceptWrites(host) + + subject.actions().edit('baseURL', ' https://other.test ') + await subject.save() + + expect(host.set.mock.calls).toEqual([['baseURL', 'https://other.test']]) + }) + + it('keeps the drafts a save did not land, and reports the failure', async () => { + const { host, subject } = form() + + subject.actions().edit('timeoutMs', '9000') + await subject.save() + + // The stub Host accepted the call without storing it, exactly as a + // validator that refuses the value does. + expect(host.set).toHaveBeenCalledWith('timeoutMs', 9_000) + expect(subject.shell()).toMatchObject({ dirty: true, failed: true, saving: false }) + expect(subject.field('timeoutMs').text).toBe('9000') + }) + + it('reports a reset the Host did not apply as a failure', async () => { + const { host, subject } = form() + host.publish({ user: { timeoutMs: 9_000 } }) + + subject.actions().resetField('timeoutMs') + await subject.save() + + expect(host.unset).toHaveBeenCalledWith('timeoutMs') + expect(subject.shell().failed).toBe(true) + }) + + it('clears the failure as soon as the user edits again', async () => { + const { subject } = form() + + subject.actions().edit('timeoutMs', '9000') + await subject.save() + expect(subject.shell().failed).toBe(true) + + subject.actions().edit('timeoutMs', '9001') + + expect(subject.shell().failed).toBe(false) + }) + + it('discards every staged edit', async () => { + const { host, subject } = form() + + subject.actions().edit('timeoutMs', '9000') + subject.actions().discard() + + expect(subject.field('timeoutMs').text).toBe('60000') + expect(subject.shell()).toMatchObject({ dirty: false, failed: false }) + + // A discard with nothing staged publishes nothing. + const before = subject.shell() + subject.actions().discard() + expect(subject.shell()).toEqual(before) + + await subject.save() + expect(host.set).not.toHaveBeenCalled() + }) + + it('refuses a second save while one is in flight', async () => { + const { host, subject } = form() + acceptWrites(host) + + subject.actions().edit('timeoutMs', '9000') + const first = subject.save() + expect(subject.shell().saving).toBe(true) + const second = subject.save() + await Promise.all([first, second]) + + expect(host.set).toHaveBeenCalledTimes(1) + }) + + it('publishes a projection whenever the scope or a draft changes', () => { + const { host, subject } = form() + const store = subject.bind(() => subject.field('timeoutMs').text) + expect(store.getSnapshot()).toBe('60000') + + host.publish({ value: { timeoutMs: 1_000 } }) + expect(store.getSnapshot()).toBe('1000') + + subject.actions().edit('timeoutMs', '2000') + expect(store.getSnapshot()).toBe('2000') + }) + + it('refuses to address a field the card never declared', () => { + const { subject } = form() + + expect(() => subject.field('nope')).toThrow('plugin card has no field nope') + }) + + it('renders an absent section value as an empty draft', () => { + const host = stubSettingsScope>() + const subject = new CardForm(host.scope, [numberField('timeoutMs'), textField('baseURL')]) + + host.publish({ status: 'ready', writable: true, value: {}, base: {}, user: undefined }) + + expect(subject.field('timeoutMs').text).toBe('') + expect(subject.field('baseURL').text).toBe('') + expect(subject.shell().available).toBe(true) + }) + + it('stays unavailable while the namespace is not served', () => { + const host = stubSettingsScope>() + const subject = new CardForm(host.scope, [numberField('timeoutMs')]) + + host.publish({ status: 'unavailable' }) + + expect(subject.shell()).toMatchObject({ available: false, writable: false }) + }) +}) + +describe('BashCardController', () => { + it('projects both fields and saves them in one write pass', async () => { + const host = stubSettingsScope() + acceptWrites(host) + const controller = new BashCardController(host.scope) + host.publish({ + status: 'ready', + writable: true, + value: { timeoutMs: 5_000, maxOutputBytes: 64_000 }, + base: { timeoutMs: 60_000, maxOutputBytes: 64_000 }, + user: { timeoutMs: 5_000 }, + }) + const face = controller.inject() + + expect(face.hooks.bashCard.getSnapshot()).toMatchObject({ + available: true, + writable: true, + dirty: false, + timeoutMs: { text: '5000', overridden: true }, + maxOutputBytes: { text: '64000', overridden: false }, + }) + + face.edit('timeoutMs', '9000') + face.edit('maxOutputBytes', '1024') + expect(face.hooks.bashCard.getSnapshot().dirty).toBe(true) + + face.save() + await vi.waitFor(() => { expect(host.set).toHaveBeenCalledTimes(2) }) + + expect(host.set.mock.calls).toEqual([['timeoutMs', 9_000], ['maxOutputBytes', 1_024]]) + expect(face.hooks.bashCard.getSnapshot().dirty).toBe(false) + }) + + it('stages a reset and applies it on save', async () => { + const host = stubSettingsScope() + acceptWrites(host) + const controller = new BashCardController(host.scope) + host.publish({ + status: 'ready', + writable: true, + value: { timeoutMs: 5_000 }, + base: { timeoutMs: 60_000 }, + user: { timeoutMs: 5_000 }, + }) + const face = controller.inject() + + face.resetField('timeoutMs') + expect(face.hooks.bashCard.getSnapshot().timeoutMs.text).toBe('60000') + + face.save() + await vi.waitFor(() => { expect(host.unset).toHaveBeenCalledWith('timeoutMs') }) + + expect(face.hooks.bashCard.getSnapshot()).toMatchObject({ + dirty: false, + timeoutMs: { text: '60000', overridden: false }, + }) + }) + + it('discards staged edits without writing', () => { + const host = stubSettingsScope() + const controller = new BashCardController(host.scope) + host.publish({ status: 'ready', writable: true, value: { timeoutMs: 5_000 }, user: {} }) + const face = controller.inject() + + face.edit('timeoutMs', '9000') + face.discard() + + expect(face.hooks.bashCard.getSnapshot().timeoutMs.text).toBe('5000') + expect(host.set).not.toHaveBeenCalled() + }) +}) + +describe('AgentLoopCardController', () => { + it('saves the only field it owns', async () => { + const host = stubSettingsScope() + acceptWrites(host) + const controller = new AgentLoopCardController(host.scope) + host.publish({ + status: 'ready', + writable: true, + value: { maxParallelToolCalls: 10 }, + base: { maxParallelToolCalls: 10 }, + user: {}, + }) + const face = controller.inject() + + face.edit('maxParallelToolCalls', '4') + face.save() + await vi.waitFor(() => { expect(host.set).toHaveBeenCalledWith('maxParallelToolCalls', 4) }) + + expect(face.hooks.agentLoopCard.getSnapshot()).toMatchObject({ + dirty: false, + maxParallelToolCalls: { text: '4', overridden: true }, + }) + }) + + it('reports a read-only document so the card can disable its controls', () => { + const host = stubSettingsScope() + const controller = new AgentLoopCardController(host.scope) + + host.publish({ status: 'ready', writable: false, value: { maxParallelToolCalls: 10 } }) + + expect(controller.inject().hooks.agentLoopCard.getSnapshot().writable).toBe(false) + }) +}) + +describe('WebSearchCardController', () => { + it('reads the credential state for the reference the section names', async () => { + const host = stubSettingsScope() + const credentials = credentialsApi(true) + const controller = new WebSearchCardController(host.scope, credentials.api) + const state = () => controller.inject().hooks.webSearchCard.getSnapshot() + await vi.waitFor(() => { expect(credentials.describe).toHaveBeenCalled() }) + + host.publish({ status: 'ready', writable: true, value: { baseURL: 'https://search.test/v1' }, user: {} }) + await vi.waitFor(() => { expect(state().apiKeyConfigured).toBe(true) }) + + expect(state()).toMatchObject({ + baseURL: { text: 'https://search.test/v1', overridden: false }, + apiKey: { text: '', overridden: false }, + }) + }) + + it('writes the staged key through the credentials domain, never the settings section', async () => { + const host = stubSettingsScope() + const credentials = credentialsApi(false) + const controller = new WebSearchCardController(host.scope, credentials.api) + host.publish({ status: 'ready', writable: true, value: {}, user: {} }) + const face = controller.inject() + + face.edit('apiKey', ' ds-secret ') + expect(face.hooks.webSearchCard.getSnapshot().dirty).toBe(true) + expect(credentials.set).not.toHaveBeenCalled() + + credentials.describe.mockImplementation(() => Promise.resolve({ + rpcId: 'c-1' as never, + result: { ok: true as const, value: { credentials: { DEEPSEEK_API_KEY: { configured: true, writable: true } } } }, + })) + face.save() + await vi.waitFor(() => { expect(credentials.set).toHaveBeenCalled() }) + + expect(credentials.set).toHaveBeenCalledWith({ ref: 'DEEPSEEK_API_KEY', value: 'ds-secret' }) + expect(host.set).not.toHaveBeenCalled() + await vi.waitFor(() => { + expect(face.hooks.webSearchCard.getSnapshot()).toMatchObject({ dirty: false, apiKeyConfigured: true }) + }) + }) + + it('keeps the stored key when the draft is left blank', () => { + const host = stubSettingsScope() + const credentials = credentialsApi(true) + const controller = new WebSearchCardController(host.scope, credentials.api) + host.publish({ status: 'ready', writable: true, value: {}, user: {} }) + const face = controller.inject() + + face.edit('apiKey', ' ') + + expect(face.hooks.webSearchCard.getSnapshot().dirty).toBe(false) + face.save() + + expect(credentials.set).not.toHaveBeenCalled() + }) + + it('re-reads when the Host reports the watched reference changed', async () => { + const host = stubSettingsScope() + const credentials = credentialsApi(false) + const controller = new WebSearchCardController(host.scope, credentials.api) + host.publish({ status: 'ready', writable: true, value: {}, user: {} }) + await vi.waitFor(() => { expect(credentials.describe).toHaveBeenCalled() }) + credentials.describe.mockClear() + + // Another reference is not this card's business. + controller.refreshCredential('OTHER_KEY') + expect(credentials.describe).not.toHaveBeenCalled() + + // A key written on another surface reaches this card only through this signal. + credentials.describe.mockImplementation(() => Promise.resolve({ + rpcId: 'c-1' as never, + result: { ok: true as const, value: { credentials: { DEEPSEEK_API_KEY: { configured: true, writable: true } } } }, + })) + controller.refreshCredential('DEEPSEEK_API_KEY') + + await vi.waitFor(() => { + expect(controller.inject().hooks.webSearchCard.getSnapshot().apiKeyConfigured).toBe(true) + }) + }) + + it('addresses the reference the section declares rather than the default', async () => { + const host = stubSettingsScope() + const credentials = credentialsApi(false) + const controller = new WebSearchCardController(host.scope, credentials.api) + host.publish({ status: 'ready', writable: true, value: { apiKeyEnv: 'SEARCH_KEY' }, user: {} }) + const face = controller.inject() + + face.edit('apiKey', 'ds-secret') + face.save() + await vi.waitFor(() => { expect(credentials.set).toHaveBeenCalled() }) + + expect(credentials.set).toHaveBeenCalledWith({ ref: 'SEARCH_KEY', value: 'ds-secret' }) + }) + + it('reports a key the Host did not store as a failed save', async () => { + const host = stubSettingsScope() + const credentials = credentialsApi(false) + const controller = new WebSearchCardController(host.scope, credentials.api) + host.publish({ status: 'ready', writable: true, value: {}, user: {} }) + const face = controller.inject() + + face.edit('apiKey', 'ds-secret') + face.save() + + await vi.waitFor(() => { + expect(face.hooks.webSearchCard.getSnapshot()).toMatchObject({ failed: true, dirty: true }) + }) + }) + + it('keeps the card usable when the credential read fails', async () => { + const host = stubSettingsScope() + const describe = vi.fn(() => Promise.reject(new Error('offline'))) + const set = vi.fn(() => Promise.reject(new Error('offline'))) + const controller = new WebSearchCardController(host.scope, { credentials: { describe, set } } as never) + const face = controller.inject() + await vi.waitFor(() => { expect(describe).toHaveBeenCalled() }) + + host.publish({ status: 'ready', writable: true, value: { baseURL: 'https://search.test/v1' }, user: {} }) + face.edit('apiKey', 'ds-secret') + face.save() + await vi.waitFor(() => { expect(set).toHaveBeenCalled() }) + + expect(face.hooks.webSearchCard.getSnapshot()).toMatchObject({ + available: true, + apiKeyConfigured: false, + baseURL: { text: 'https://search.test/v1' }, + }) + }) + + it('ignores a credential read the Host refused', async () => { + const host = stubSettingsScope() + const describe = vi.fn(() => Promise.resolve({ + rpcId: 'c-1' as never, + result: { ok: false as const, error: { code: 'credentials-unavailable', message: 'no provider' } }, + })) + const controller = new WebSearchCardController(host.scope, { credentials: { describe, set: vi.fn() } } as never) + await vi.waitFor(() => { expect(describe).toHaveBeenCalled() }) + + expect(controller.inject().hooks.webSearchCard.getSnapshot().apiKeyConfigured).toBe(false) + }) + + it('saves the endpoint and the search budget together', async () => { + const host = stubSettingsScope() + acceptWrites(host) + const credentials = credentialsApi(true) + const controller = new WebSearchCardController(host.scope, credentials.api) + host.publish({ status: 'ready', writable: true, value: {}, base: {}, user: {} }) + const face = controller.inject() + + face.edit('baseURL', 'https://other.test') + face.edit('maxUses', '3') + face.save() + await vi.waitFor(() => { expect(host.set).toHaveBeenCalledTimes(2) }) + + expect(host.set.mock.calls).toEqual([['baseURL', 'https://other.test'], ['maxUses', 3]]) + expect(credentials.set).not.toHaveBeenCalled() + }) +}) diff --git a/packages/client/ui-plugin-config/tsconfig.json b/packages/client/ui-plugin-config/tsconfig.json new file mode 100644 index 0000000000..3e03d647f2 --- /dev/null +++ b/packages/client/ui-plugin-config/tsconfig.json @@ -0,0 +1,45 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../connection" + }, + { + "path": "../locale" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../runtime" + }, + { + "path": "../test-runtime" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-settings" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../ui-slots" + }, + { + "path": "../web-react" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/client/ui-plugin-config/tsdown.config.ts b/packages/client/ui-plugin-config/tsdown.config.ts new file mode 100644 index 0000000000..5cda1844ab --- /dev/null +++ b/packages/client/ui-plugin-config/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle('@deepseek-ai/dsh-client-ui-plugin-config', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 06dfe45bd8..9ab67d0e43 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/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-primitives/README.md -README.md: a9c802c1e43cf06aa0492b39d5052e882a72d9e6 -README.zh.md: 9e67488ccc1d70263bd0b91d167c4c251ee95926 +README.md: f96e931472a0946bd023b97b034643f079a67e44 +README.zh.md: 0db2ac1bccbdc4793c488e1ce621ee5c674d9895 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index a9c802c1e4..f96e931472 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -2,12 +2,16 @@ English | [中文](README.zh.md) -Pure React atoms (zero cordis): StateDot, DisclosureRow, ic_ds_* icons, Button/Pill/Menu/Modal/Input, the OnboardingSurface first-run takeover (body-portaled mask + opaque stage that holds `#root` inert for exactly its own lifetime), the markdown family (MessageText/MarkdownText/JsonBlock), the read-only JsonTree inspector, the `useAnchoredMaxHeight` hook that clamps a bottom-anchored overlay to the viewport space above its anchor (re-measured on resize, scroll, and a caller-supplied dependency), TerminalBlock, DiffBlock, ReadBlock, SearchBlock, and WebBlock. +Pure React atoms (zero cordis): StateDot, DisclosureRow, ic_ds_* icons, Button/Pill/Menu/Modal/Input, the Toast transient banner, the OnboardingSurface first-run takeover (body-portaled mask + opaque stage that holds `#root` inert for exactly its own lifetime), the markdown family (MessageText/MarkdownText/JsonBlock), the read-only JsonTree inspector, the `useAnchoredMaxHeight` hook that clamps a bottom-anchored overlay to the viewport space above its anchor (re-measured on resize, scroll, and a caller-supplied dependency), TerminalBlock, DiffBlock, ReadBlock, SearchBlock, and WebBlock. ## Hover cards `HoverCard` keeps its portaled preview reachable across the anchor gap with a pointer-leave grace. A consumer may also pass `copyText`: the card then exposes button semantics for pointer and keyboard activation, includes that value after the `copyLabel` prefix in its accessible name, writes the exact value through the package clipboard helper, and temporarily replaces its content with `copiedLabel` only after the host accepts the write. A non-collapsed text selection intersecting the card suppresses pointer-click activation, while success feedback retains the original card height and clears when the card closes or after one second. `copyLabel` and `copiedLabel` are label props because this zero-cordis atom cannot read the application locale; omitting `copyText` preserves the read/select-only card. Historical rationale: [the archived hover-card copy note](../../../.agents/notes/archived/feature/2026-07-31-hover-card-click-copy.md). +## Toast + +`Toast` is the transient top banner: it slides in, holds at full opacity for three seconds, fades over one second, then calls `onDone` so the owner can unmount it. It renders `role="alert"` with an optional leading icon slot and takes its copy as a required prop (zero-cordis: the owner localizes). It body-portals with `pointer-events: none`, sits 120px from the viewport top, and centers horizontally over the optional `anchor` element (re-measured on window resizes) — the composer passes its card so the banner centers over the chat column rather than the whole window — falling back to the viewport center without one. Re-showing the same message requires a remount — owners key the element by a per-show sequence so an identical repeated message restarts the hold-and-fade cycle instead of silently reusing the faded banner. Under `prefers-reduced-motion: reduce` the slide-in is dropped and only the delayed fade remains. It layers above the ui-attachment image lightbox so a failure reported during a preview stays readable. + ## Markdown rendering `MarkdownText` renders GFM and `$…$`, `$$…$$`, `\(…\)`, and `\[…\]` TeX math from untrusted assistant output through React elements, with math typeset by KaTeX and trusted commands disabled; block-level same-line `$$…$$` is display math, including `\tag{}`. A narrow micromark extension lets asterisk strong emphasis ending in punctuation close before adjacent CJK text, where prose normally omits the whitespace CommonMark requires; single-asterisk emphasis, non-CJK adjacency, escapes, code, and math retain upstream parsing. It omits raw HTML, neutralizes relative and non-HTTP(S)/mailto links, opens HTTP(S) links with safe external-link attributes, and renders absolute HTTP(S) images without a referrer; relative paths, absolute local paths, `file:` URLs, and unsupported schemes retain their alt text. Inline code whose complete value is an absolute HTTP(S) URL keeps its code styling and gains the same safe external anchor; commands, partial URLs, other schemes, and fenced code remain inert. An optional `fileMentions` resolver lets the owning view link inline code that names a real file: the token keeps code styling and gains a button wired to the resolved opener, with the resolver's accessible label and full-path `title`. The renderer never guesses at what looks like a path — an unresolved token stays inert, mentions apply to settled renders only (the streaming cache must not bake in handlers that could go stale), and a token inside an anchor stays inert because a button cannot nest there. While a reply streams, `MarkdownText` parses incrementally: all but the trailing two blocks freeze as cached React elements and only the source tail behind them re-parses per chunk, so per-chunk work tracks the tail instead of the whole reply ([mechanism and DOM-parity contract](../../../.agents/notes/implemented/architecture/2026-08-06-web-markdown-incremental-ast-renderer.md)). `MessageText` remains the literal-text primitive for user-authored content. `extractMarkdownPlainText` removes Markdown presentation markup for compact labels while preserving raw HTML as literal text. Element spacing, responsive images, tables, links, and inline code use the same `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` tokens as deepsuite `@deepseek/md`. Fenced blocks render through `CodeBlock` (language banner, copy control, shiki for the registered grammars). diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 9e67488ccc..0db2ac1bcc 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -2,12 +2,16 @@ [English](README.md) | 中文 -纯 React 原子组件(零 cordis):StateDot、DisclosureRow、ic_ds_* 图标、Button/Pill/Menu/Modal/Input、OnboardingSurface 首次使用接管层(portal 到 body 的遮罩加不透明展示层,在且仅在自身生命周期内保持 `#root` 为 `inert`)、markdown 家族(MessageText/MarkdownText/JsonBlock)、只读 JsonTree 检查器、`useAnchoredMaxHeight` 钩子(把底部锚定的浮层高度收敛到锚点上方的视口空间,并在 resize、scroll 与调用方提供的依赖变化时重新测量)、TerminalBlock、DiffBlock、ReadBlock、SearchBlock,以及 WebBlock。 +纯 React 原子组件(零 cordis):StateDot、DisclosureRow、ic_ds_* 图标、Button/Pill/Menu/Modal/Input、Toast 短时横幅、OnboardingSurface 首次使用接管层(portal 到 body 的遮罩加不透明展示层,在且仅在自身生命周期内保持 `#root` 为 `inert`)、markdown 家族(MessageText/MarkdownText/JsonBlock)、只读 JsonTree 检查器、`useAnchoredMaxHeight` 钩子(把底部锚定的浮层高度收敛到锚点上方的视口空间,并在 resize、scroll 与调用方提供的依赖变化时重新测量)、TerminalBlock、DiffBlock、ReadBlock、SearchBlock,以及 WebBlock。 ## 悬浮卡片 `HoverCard` 通过指针离开宽限期,使采用 portal 渲染的预览在跨过与锚点之间的间隙时仍可触及。消费方还可传入 `copyText`:此时卡片为指针与键盘激活提供按钮语义,其无障碍名称会在 `copyLabel` 前缀后包含该值,通过包内剪贴板辅助函数原样写入该值,并且只有宿主接受写入后,才会临时将内容替换为 `copiedLabel`。与卡片相交的非折叠文本选区会阻止指针点击激活;成功反馈保持卡片原有高度,并随卡片关闭或在一秒后清除。`copyLabel` 和 `copiedLabel` 采用 label prop,是因为这个 zero-cordis 原子组件无法读取应用 locale;省略 `copyText` 时,卡片维持只读且可选择文本的行为。历史依据见[已归档的悬浮卡片复制 Agent Note](../../../.agents/notes/archived/feature/2026-07-31-hover-card-click-copy.md)。 +## Toast + +`Toast` 是顶部的短时横幅:滑入后满不透明度停留三秒,再用一秒淡出,随后调用 `onDone` 由持有方卸载。它渲染 `role="alert"`,带可选的前置图标插槽,文案是必填 prop(零 cordis,由持有方本地化)。它经 body portal 渲染且 `pointer-events: none`,距视口顶部 120px,水平中心跟随可选的 `anchor` 元素(窗口尺寸变化时重测)——composer 传入自己的卡片,横幅因此在聊天列而非整个窗口上居中——不传则回退到视口居中。重复展示同一条消息需要重新挂载,持有方用每次展示递增的序号作为 key,让相同文案重新走完停留与淡出,而不是静默复用已淡出的横幅。`prefers-reduced-motion: reduce` 下去掉滑入,只保留延迟淡出。它的层级高于 ui-attachment 的图片灯箱,预览打开时报出的失败仍然可读。 + ## Markdown 渲染 `MarkdownText` 通过 React 元素渲染来自不受信任 assistant 输出的 GFM 与 `$…$`、`$$…$$`、`\(…\)` 和 `\[…\]` TeX 公式,公式由 KaTeX 排版并禁用受信任命令;块级同一行 `$$…$$` 是显示公式并支持 `\tag{}`。一个小范围的 micromark 扩展允许由星号标记、以标点结尾的粗体在紧邻的 CJK 文本前闭合,以适应 CJK 文本通常省略 CommonMark 所要求空格的写法;单星号强调、紧邻非 CJK 文本的情况、转义、代码与数学公式仍沿用上游解析行为。它会省略原始 HTML,使相对链接及非 HTTP(S)/mailto 链接失效,以安全的外部链接属性打开 HTTP(S) 链接,并在不发送 referrer 的情况下渲染采用绝对 HTTP(S) URL 的图片;相对路径、绝对本地路径、`file:` URL 与不受支持的 scheme 会保留其 alt 文本。完整内容为绝对 HTTP(S) URL 的行内代码会保留代码样式,并获得同样安全的外部链接;命令、非完整 URL、其他 scheme 与围栏代码仍不会成为链接。可选的 `fileMentions` 解析器让持有该组件的视图为命名真实文件的行内代码添加可点击入口:token 保留代码样式,并获得一个连接到解析所得 opener 的按钮,按钮带有解析器提供的无障碍标签和以完整路径为值的 `title`。渲染器绝不猜测哪些内容像路径:未解析的 token 保持不可交互;文件提及仅应用于已定稿的渲染(流式缓存不得固化可能过期的 handler);锚点内的 token 也保持不可交互,因为按钮不能嵌套其中。回复流式输出期间,`MarkdownText` 增量解析:除末尾两个块外全部冻结为缓存的 React 元素,每个分片只重新解析其后的源文本尾部,因此每分片的工作量跟随尾部而非整个回复([机制与 DOM 一致性约定](../../../.agents/notes/implemented/architecture/2026-08-06-web-markdown-incremental-ast-renderer.md))。`MessageText` 仍是用户创作内容使用的字面文本原语。`extractMarkdownPlainText` 会移除 Markdown 呈现标记以用于紧凑标签,同时将原始 HTML 保留为字面文本。元素间距、响应式图片、表格、链接与行内代码使用与 deepsuite `@deepseek/md` 相同的 `--dsw-alias-markdown-*` / `--dsw-font-markdown-*` token。围栏代码块通过 `CodeBlock` 渲染(语言横幅、复制控件,以及对已注册语法使用 shiki)。 diff --git a/packages/client/ui-primitives/src/Toast.module.css b/packages/client/ui-primitives/src/Toast.module.css new file mode 100644 index 0000000000..458cce9221 --- /dev/null +++ b/packages/client/ui-primitives/src/Toast.module.css @@ -0,0 +1,70 @@ +/* Transient top-center banner (DeepSeek Chat toast look): contrast fill, + inverted label, slide-in, then hold-and-fade. The fade delay/duration MUST + agree with HOLD_MS/FADE_MS in Toast.tsx: the component unmounts at their + sum, so a mismatched sheet either cuts the fade or leaves an invisible + banner blocking nothing. */ + +.toast { + position: fixed; + top: 120px; + left: 50%; + /* Above the 1000 the image lightbox backdrop uses: a failure reported while + a preview is open must stay readable. */ + z-index: 1100; + /* Purely an announcement: it must never intercept clicks — in particular + after the CSS fade finished while a throttled background-tab timer has + not yet unmounted the still-hit-testable fixed element. */ + pointer-events: none; + display: flex; + align-items: center; + gap: 10px; + max-width: min(560px, calc(100vw - 48px)); + padding: 12px 16px; + border-radius: 14px; + background: var(--dsw-alias-button-contrast-fill); + color: var(--dsw-alias-label-primary-inverted); + font-size: 14px; + line-height: 22px; + box-shadow: var(--dsw-shadow-lv3); + transform: translateX(-50%); + animation: + dsh-toast-in 160ms ease-out, + dsh-toast-fade 1000ms ease 3000ms forwards; +} + +.icon { + display: grid; + place-items: center; + flex: none; + color: var(--dsw-alias-state-warn-label); +} + +.text { + min-width: 0; +} + +@keyframes dsh-toast-in { + from { + opacity: 0; + transform: translate(-50%, -6px); + } + + to { + opacity: 1; + transform: translate(-50%, 0); + } +} + +@keyframes dsh-toast-fade { + to { + opacity: 0; + } +} + +/* Reduced motion drops the slide-in; the delayed fade (an opacity change, + not movement) still ends the banner before the timed unmount. */ +@media (prefers-reduced-motion: reduce) { + .toast { + animation: dsh-toast-fade 1000ms ease 3000ms forwards; + } +} diff --git a/packages/client/ui-primitives/src/Toast.tsx b/packages/client/ui-primitives/src/Toast.tsx new file mode 100644 index 0000000000..acd02c4eb0 --- /dev/null +++ b/packages/client/ui-primitives/src/Toast.tsx @@ -0,0 +1,59 @@ +import { useEffect, useLayoutEffect, useState } from 'react' +import type { ReactNode } from 'react' +import { createPortal } from 'react-dom' +import css from './Toast.module.css' + +/** Full-opacity hold before the fade starts. Must agree with the stylesheet's + * toast-fade delay (Toast.module.css) or the banner unmounts mid-fade. */ +const HOLD_MS = 3000 +/** Fade duration. Must agree with the stylesheet's toast-fade duration. */ +const FADE_MS = 1000 + +/** + * Transient top-center banner: slides in, holds at full opacity, fades out, + * then reports done so the owner can unmount it. Re-showing the same text + * restarts the cycle when the owner remounts the component (key it by a + * per-show sequence). Rendered through a body portal so an owner inside a + * transformed or filtered ancestor cannot trap the fixed banner in that + * ancestor's box. + * + * @param props.text - resolved banner copy; the owner passes localized text. + * @param props.icon - optional leading glyph (e.g. a warning icon). + * @param props.anchor - optional element whose horizontal center the banner + * follows (e.g. the composer card, so the banner centers over the chat column + * rather than the whole window); omitted, it centers on the viewport. + * @param props.onDone - called once the fade completes; unmount the toast here. + * @returns the floating banner. + */ +export function Toast({ text, icon, anchor, onDone }: { + text: string + icon?: ReactNode + anchor?: HTMLElement | null + onDone: () => void +}) { + useEffect(() => { + const timer = setTimeout(onDone, HOLD_MS + FADE_MS) + return () => { clearTimeout(timer) } + }, [onDone]) + // Anchor-centered placement re-measures on window resizes; the banner lives + // four seconds, so sub-window layout drift within that span stays out of + // scope. + const [left, setLeft] = useState(null) + useLayoutEffect(() => { + if (anchor == null) return + const measure = (): void => { + const rect = anchor.getBoundingClientRect() + setLeft(rect.left + rect.width / 2) + } + measure() + window.addEventListener('resize', measure) + return () => { window.removeEventListener('resize', measure) } + }, [anchor]) + return createPortal( +
    + {icon !== undefined && {icon}} + {text} +
    , + document.body, + ) +} diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 18e5b2c7e9..05baf26f8d 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -23,6 +23,7 @@ export { FishLogo } from './FishLogo.tsx' export { BrandWordmark } from './BrandWordmark.tsx' export { Tooltip } from './Tooltip.tsx' export type { TooltipSide } from './Tooltip.tsx' +export { Toast } from './Toast.tsx' export { writeClipboard } from './clipboard.ts' export { JsonTree } from './JsonTree.tsx' export type { JsonTreeProps, JsonTreeLabels } from './JsonTree.tsx' diff --git a/packages/client/ui-primitives/tests/toast.spec.tsx b/packages/client/ui-primitives/tests/toast.spec.tsx new file mode 100644 index 0000000000..1e2bb35d51 --- /dev/null +++ b/packages/client/ui-primitives/tests/toast.spec.tsx @@ -0,0 +1,57 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { Toast } from '../src/Toast.tsx' + +afterEach(cleanup) + +describe('Toast', () => { + it('announces its text and reports done after the hold-and-fade lifetime', () => { + vi.useFakeTimers() + try { + const onDone = vi.fn() + const view = render(} onDone={onDone} />) + const banner = view.getByRole('alert') + expect(banner.textContent).toContain('最多添加 50 张图片') + expect(view.getByTestId('icon')).toBeTruthy() + vi.advanceTimersByTime(3999) + expect(onDone).not.toHaveBeenCalled() + vi.advanceTimersByTime(1) + expect(onDone).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } + }) + + it('centers over its anchor and re-measures on window resize', () => { + vi.useFakeTimers() + try { + const anchor = document.createElement('div') + document.body.appendChild(anchor) + anchor.getBoundingClientRect = () => ({ left: 100, width: 400 }) as DOMRect + const view = render() + expect(view.getByRole('alert').style.left).toBe('300px') + anchor.getBoundingClientRect = () => ({ left: 200, width: 400 }) as DOMRect + fireEvent(window, new Event('resize')) + expect(view.getByRole('alert').style.left).toBe('400px') + anchor.remove() + } finally { + vi.useRealTimers() + } + }) + + it('renders without an icon and cancels its timer on unmount', () => { + vi.useFakeTimers() + try { + const onDone = vi.fn() + const view = render() + expect(view.getByRole('alert').querySelector('[aria-hidden]')).toBeNull() + view.unmount() + vi.advanceTimersByTime(10_000) + expect(onDone).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx index 795b9f1308..fb14059f05 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx @@ -14,7 +14,8 @@ import { useCallback, useEffect, useId, useRef, useState } from 'react' import clsx from 'clsx' import { - IconAgentPresetOutline16, IconCloseOutline16, IconDataOutline16, IconSettingsOutline16, + IconAgentPresetOutline16, IconCloseOutline16, IconDataOutline16, + IconPersonalizationOutline16, IconSettingsOutline16, } from '@deepseek-ai/dsh-client-ui-primitives' import type { SettingsRootComponentProps, SettingsSectionRow } from './shell-contract.ts' import css from './SettingsRoot.module.css' @@ -23,6 +24,7 @@ import css from './SettingsRoot.module.css' function navIcon(id: string) { if (id === 'models') return if (id === 'agent-presets') return + if (id === 'plugins') return return } diff --git a/packages/client/ui-settings-general/tests/settings-root.spec.tsx b/packages/client/ui-settings-general/tests/settings-root.spec.tsx index a95e8e6533..430bb2daee 100644 --- a/packages/client/ui-settings-general/tests/settings-root.spec.tsx +++ b/packages/client/ui-settings-general/tests/settings-root.spec.tsx @@ -170,6 +170,28 @@ describe('SettingsPanel navigation', () => { expect(screen.getByTestId('section-general')).toBeTruthy() }) + it('gives every section a nav glyph, distinct for the ids the shell knows', () => { + mount({ + rows: [ + { id: 'general', order: 0, label: 'General' }, + { id: 'models', order: 10, label: 'Models' }, + { id: 'agent-presets', order: 20, label: 'Agent presets' }, + { id: 'plugins', order: 30, label: 'Plugins' }, + { id: 'contributed', order: 40, label: 'Contributed' }, + ], + }) + openPanel() + // Glyphs carry no id of their own, so the drawn paths are what tells them apart. + const glyphs = ['General', 'Models', 'Agent presets', 'Plugins', 'Contributed'] + .map(name => screen.getByRole('button', { name }).querySelector('svg')?.innerHTML) + + expect(glyphs.every(glyph => glyph !== undefined && glyph !== '')).toBe(true) + // The three ids the shell names get their own glyph; every other section — + // including one this package never heard of — shares the gear. + expect(new Set(glyphs.slice(0, 4)).size).toBe(4) + expect(glyphs[4]).toBe(glyphs[0]) + }) + it('switches the rendered section on nav click', () => { mount() openPanel() diff --git a/packages/client/ui-settings/src/client/contract/slots.ts b/packages/client/ui-settings/src/client/contract/slots.ts index a754570859..5255f9fb2f 100644 --- a/packages/client/ui-settings/src/client/contract/slots.ts +++ b/packages/client/ui-settings/src/client/contract/slots.ts @@ -117,4 +117,3 @@ export interface SettingsOnboardingOwnerProps { /** Open the settings panel directly on one registered section. */ openSection: (id: string) => void } - diff --git a/packages/client/ui-settings/src/client/settings-scope.ts b/packages/client/ui-settings/src/client/settings-scope.ts index 674b6ea517..84591802c1 100644 --- a/packages/client/ui-settings/src/client/settings-scope.ts +++ b/packages/client/ui-settings/src/client/settings-scope.ts @@ -8,7 +8,7 @@ import { Service } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' import type { - ConnectionHandle, IApiClient, SettingsNamespaceView, + ConnectionHandle, IApiClient, SettingsNamespaceView, SettingsPathOpView, } from '@deepseek-ai/dsh-client-connection/client' import { rehydrateSchema, validateDraft } from '@deepseek-ai/dsh-client-schema-form' import { @@ -59,6 +59,8 @@ export class SettingsScopeController implements SettingsScope { this.store = createSnapshotStore>({ status: persistence === 'host' ? 'loading' : 'unavailable', value: undefined, + base: undefined, + user: undefined, revision: undefined, writable: false, mode: persistence, @@ -96,6 +98,20 @@ export class SettingsScopeController implements SettingsScope { * @returns settlement after the write and any latest-write recovery read. */ set(field: string, value: unknown): Promise { + return this.write({ op: 'set', path: [field], value }) + } + + /** + * Queue one field clear; see {@link SettingsScope.unset} for the ordering, + * revision, and recovery contract. + * @param field - scalar field inside the namespace section. + * @returns settlement after the clear and any latest-write recovery read. + */ + unset(field: string): Promise { + return this.write({ op: 'unset', path: [field] }) + } + + private write(op: SettingsPathOpView): Promise { this.readGeneration += 1 const generation = ++this.writeGeneration return this.enqueue(async () => { @@ -104,7 +120,7 @@ export class SettingsScopeController implements SettingsScope { try { response = await this.api.settings.mutate({ ns: this.spec.namespace, - ops: [{ op: 'set', path: [field], value }], + ops: [op], ...(revision === undefined ? {} : { expectedRevision: revision }), }) } catch (_settingsWriteFailure) { @@ -169,6 +185,8 @@ export class SettingsScopeController implements SettingsScope { const decoded = publish ? this.decode(view) : undefined this.store.update((draft) => { draft.revision = view.revision + draft.base = view.base + draft.user = view.user if (writable !== undefined) draft.writable = writable if (decoded === undefined) return draft.status = 'ready' diff --git a/packages/client/ui-settings/tests/settings-scope.spec.ts b/packages/client/ui-settings/tests/settings-scope.spec.ts index e6b165e9f3..bce9d9c57b 100644 --- a/packages/client/ui-settings/tests/settings-scope.spec.ts +++ b/packages/client/ui-settings/tests/settings-scope.spec.ts @@ -293,6 +293,77 @@ describe('SettingsScopeController', () => { expect(describeCall).not.toHaveBeenCalled() expect(mutate).not.toHaveBeenCalled() }) + + it('carries the composition base and the user layer into the snapshot', async () => { + const layered: SettingsNamespaceView = { + ...view({ preference: 'dark' }, 3), + base: { preference: 'system' }, + user: { preference: 'dark' }, + } + const describeCall = vi.fn() + .mockResolvedValueOnce(ok({ writable: true, hasDocument: true, namespaces: [layered] })) + const scope = new SettingsScopeController( + { settings: { describe: describeCall } } as never, + { namespace: 'ui-test' }, + ) + + await scope.load() + + expect(scope.getSnapshot()).toMatchObject({ + value: { preference: 'dark' }, + base: { preference: 'system' }, + user: { preference: 'dark' }, + }) + }) + + it('reports an inherited field as absent from the user layer', async () => { + const inherited: SettingsNamespaceView = { ...view({ preference: 'system' }, 1), base: { preference: 'system' } } + const describeCall = vi.fn() + .mockResolvedValueOnce(ok({ writable: true, hasDocument: true, namespaces: [inherited] })) + const scope = new SettingsScopeController( + { settings: { describe: describeCall } } as never, + { namespace: 'ui-test' }, + ) + + await scope.load() + + expect(scope.getSnapshot().user).toBeUndefined() + }) + + it('clears one field through an unset op fenced by the held revision', async () => { + const mutate = vi.fn().mockResolvedValueOnce(ok(view({ preference: 'system' }, 4))) + const describeCall = vi.fn().mockResolvedValueOnce(described({ preference: 'dark' }, 3)) + const scope = new SettingsScopeController( + { settings: { describe: describeCall, mutate } } as never, + { namespace: 'ui-test' }, + ) + await scope.load() + + await scope.unset('preference') + + expect(mutate).toHaveBeenCalledWith({ + ns: 'ui-test', + ops: [{ op: 'unset', path: ['preference'] }], + expectedRevision: 3, + }) + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'system' }, revision: 4 }) + }) + + it('recovers the Host state when the latest clear is refused', async () => { + const mutate = vi.fn().mockResolvedValueOnce(rejected()) + const describeCall = vi.fn() + .mockResolvedValueOnce(described({ preference: 'dark' }, 3)) + .mockResolvedValueOnce(described({ preference: 'light' }, 5)) + const scope = new SettingsScopeController( + { settings: { describe: describeCall, mutate } } as never, + { namespace: 'ui-test' }, + ) + await scope.load() + + await scope.unset('preference') + + expect(scope.getSnapshot()).toMatchObject({ value: { preference: 'light' }, revision: 5 }) + }) }) describe('SettingsScopeService.bind', () => { @@ -354,4 +425,3 @@ describe('SettingsScopeService.bind', () => { expect(describeCall).not.toHaveBeenCalled() }) }) - diff --git a/packages/client/web/package.json b/packages/client/web/package.json index df5192e070..d23c343b3c 100644 --- a/packages/client/web/package.json +++ b/packages/client/web/package.json @@ -29,6 +29,7 @@ "dependencies": { "@deepseek-ai/dsh-client-modules": "workspace:^", "@deepseek-ai/dsh-client-schema-form": "workspace:^", + "@deepseek-ai/dsh-client-ui-attachment": "workspace:^", "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-client-ui-theme": "workspace:^", diff --git a/packages/client/web/src/platform.ts b/packages/client/web/src/platform.ts index e7997cf728..dd7248c117 100644 --- a/packages/client/web/src/platform.ts +++ b/packages/client/web/src/platform.ts @@ -10,6 +10,7 @@ export const PLATFORM_MODULES = [ '@deepseek-ai/dsh-client-ui-slots', '@deepseek-ai/dsh-client-web-react', '@deepseek-ai/dsh-client-ui-primitives', + '@deepseek-ai/dsh-client-ui-attachment', '@deepseek-ai/dsh-client-schema-form', ] as const diff --git a/packages/client/web/src/seed.ts b/packages/client/web/src/seed.ts index 78ed31099e..8299f225c7 100644 --- a/packages/client/web/src/seed.ts +++ b/packages/client/web/src/seed.ts @@ -14,6 +14,7 @@ import * as Cordis from '@deepseek-ai/cordis' import * as UiSlots from '@deepseek-ai/dsh-client-ui-slots' import * as WebReact from '@deepseek-ai/dsh-client-web-react' import * as UiPrimitives from '@deepseek-ai/dsh-client-ui-primitives' +import * as UiAttachment from '@deepseek-ai/dsh-client-ui-attachment' import * as SchemaForm from '@deepseek-ai/dsh-client-schema-form' import type { PlatformModule } from './platform.ts' @@ -34,6 +35,7 @@ export function getStaticModules(): Record { '@deepseek-ai/dsh-client-ui-slots': UiSlots, '@deepseek-ai/dsh-client-web-react': WebReact, '@deepseek-ai/dsh-client-ui-primitives': UiPrimitives, + '@deepseek-ai/dsh-client-ui-attachment': UiAttachment, '@deepseek-ai/dsh-client-schema-form': SchemaForm, } satisfies Record } diff --git a/packages/client/web/tsconfig.json b/packages/client/web/tsconfig.json index 9240c34891..db2e3b8ed8 100644 --- a/packages/client/web/tsconfig.json +++ b/packages/client/web/tsconfig.json @@ -20,6 +20,9 @@ { "path": "../ui-slots" }, + { + "path": "../ui-attachment" + }, { "path": "../ui-primitives" }, diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 49359b5f22..9812d570ac 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/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/core/agent-loop/README.md -README.md: 889fd74671eddc202b814cdf2749069ec3cea02c -README.zh.md: b65b5334d735a1e0b51fa517ce41c0c953f87cf7 +README.md: 13f79b9e70bfb658c459240c97acf39025df2ac0 +README.zh.md: ad8fc9478eb45620cee303eb7295b6b3fe8b0ed3 diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 889fd74671..13f79b9e70 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -49,7 +49,7 @@ interface Config { } ``` -Configured agents start automatically. A model call requires both `provider` and `model`; `agent/request` may supply a missing pair before dispatch. An optional positive `maxTokens` seeds each conversation request's output cap and is logged in its request header. `maxParallelToolCalls` bounds every agent's rolling pool for parallel-safe calls and defaults to `10`. `cwd` applies only to fresh sessions, while `resumeSessionId` retains persisted metadata. Configured agents use the deployment persona, and programmatic setup can shadow it per agent. This plugin supplies the per-agent `provider`, `model`, and `cwd` prompt variables; harness identity and deployment persona belong to `dsh-system-prompt`. +Configured agents start automatically. A model call requires both `provider` and `model`; `agent/request` may supply a missing pair before dispatch. An optional positive `maxTokens` seeds each conversation request's output cap and is logged in its request header. `maxParallelToolCalls` bounds every agent's rolling pool for parallel-safe calls and defaults to `10`; it is also the whole of the `agent-loop` Settings section, so a user layer over this entry caps the next tool group without a restart, and a value that is not a positive integer is refused at the write rather than at that group. `agents` is deliberately absent from that section — it is consumed once when the service starts, so a stored change could only look like it had an effect. `cwd` applies only to fresh sessions, while `resumeSessionId` retains persisted metadata. Configured agents use the deployment persona, and programmatic setup can shadow it per agent. This plugin supplies the per-agent `provider`, `model`, and `cwd` prompt variables; harness identity and deployment persona belong to `dsh-system-prompt`. ### Internal concrete driver diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index b65b5334d7..ad8fc9478e 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -49,7 +49,7 @@ interface Config { } ``` -通过配置创建的 agent 会自动启动。模型调用同时需要 `provider` 和 `model`;`agent/request` 可以在分发前补齐缺失的这一对值。可选的正数 `maxTokens` 会为每次对话请求提供初始输出上限,并记录在请求 header 中。`maxParallelToolCalls` 限制每个 agent 针对并行安全调用使用的滚动池,默认值为 `10`。`cwd` 仅应用于全新会话,而 `resumeSessionId` 保留持久化元数据。通过配置创建的 agent 使用部署 persona;编程式 setup 可以按 agent 遮蔽它。该插件为每个 agent 提供 `provider`、`model` 和 `cwd` 提示词变量;harness 身份与部署 persona 属于 `dsh-system-prompt`。 +通过配置创建的 agent 会自动启动。模型调用同时需要 `provider` 和 `model`;`agent/request` 可以在分发前补齐缺失的这一对值。可选的正数 `maxTokens` 会为每次对话请求提供初始输出上限,并记录在请求 header 中。`maxParallelToolCalls` 限制每个 agent 针对并行安全调用使用的滚动池,默认值为 `10`;它同时也是 `agent-loop` Settings 段的全部内容,因此叠加在该条目之上的用户层无需重启即可限制下一组工具调用,而非正整数的值会在写入时被拒绝,而不是到那一组时才失败。`agents` 刻意不在该段中——它在服务启动时被消费一次,所以存储的改动只会看起来生效。`cwd` 仅应用于全新会话,而 `resumeSessionId` 保留持久化元数据。通过配置创建的 agent 使用部署 persona;编程式 setup 可以按 agent 遮蔽它。该插件为每个 agent 提供 `provider`、`model` 和 `cwd` 提示词变量;harness 身份与部署 persona 属于 `dsh-system-prompt`。 ### 包内部具体驱动器 diff --git a/packages/core/agent-loop/package.json b/packages/core/agent-loop/package.json index 038822967a..8bfbe38cfe 100644 --- a/packages/core/agent-loop/package.json +++ b/packages/core/agent-loop/package.json @@ -39,7 +39,8 @@ "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:^" @@ -54,6 +55,7 @@ "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" } } diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index e492a21073..338c9a3541 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -20,6 +20,7 @@ import type { SessionStartSource, } from '@deepseek-ai/dsh-agent' import { errorChain } from '@deepseek-ai/dsh-llm' +import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings' import { SessionId, SessionPreparation } from '@deepseek-ai/dsh-session' import type { Session, SessionHeader } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-system-prompt' @@ -232,6 +233,24 @@ function applyLauncherIdentities( }) } +/** Settings namespace carrying the tool-call parallelism a user owns. */ +export const AGENT_LOOP_SETTINGS_NAMESPACE = settingsNamespace('agent-loop') + +/** + * The agent-loop fields a user owns. Deliberately a strict subset of + * {@link Config}: `agents` is a boot-time composition array consumed once when + * the service starts, so a stored change could only look like it had an effect. + */ +export interface AgentLoopSettings { + /** Maximum parallel-safe calls in flight per agent step. */ + maxParallelToolCalls: number +} + +/** Schema of the agent-loop settings section. */ +export const AGENT_LOOP_SETTINGS_SCHEMA: z = z.object({ + maxParallelToolCalls: z.number().step(1).min(1).default(DEFAULT_MAX_PARALLEL_TOOL_CALLS), +}) + /** Agent-loop plugin configuration. */ export interface Config { /** @@ -299,11 +318,31 @@ export class AgentLoop extends Service implements AgentFactory { constructor(ctx: Context, config: Config) { super(ctx, 'agentLoop') + const entry: AgentLoopSettings = { + maxParallelToolCalls: resolveMaxParallelToolCalls(config.maxParallelToolCalls), + } + let source: () => AgentLoopSettings = () => entry this.config = { ...config, agents: applyLauncherIdentities(config.agents, ctx.get(CONFIGURED_AGENT_IDENTITIES_KEY)), - maxParallelToolCalls: resolveMaxParallelToolCalls(config.maxParallelToolCalls), + // Read through on every scheduler decision: `tool-calls.ts` destructures + // this at the start of each group, so a committed change caps the next + // group without disturbing the one in flight. + get maxParallelToolCalls() { + return source().maxParallelToolCalls + }, } + installSettingsSection(ctx, AGENT_LOOP_SETTINGS_NAMESPACE, AGENT_LOOP_SETTINGS_SCHEMA, entry, { + // The schema admits any integer above zero; `resolveMaxParallelToolCalls` + // owns the whole rule, so refusing here keeps the running scheduler on + // its last good cap instead of failing at the next tool group. + validate: value => void resolveMaxParallelToolCalls(value.maxParallelToolCalls), + setSource: (current) => { + source = current + }, + // Nothing is derived from the cap: the getter above is the only reader. + onChange: () => {}, + }) validateConfiguredAgents(this.config.agents) this.ownership = new FactoryOwnership(ctx.fiber) this.runtime = { ctx } diff --git a/packages/core/agent-loop/tests/config-session-id.spec.ts b/packages/core/agent-loop/tests/config-session-id.spec.ts index 4ac477d42f..caf2e560b9 100644 --- a/packages/core/agent-loop/tests/config-session-id.spec.ts +++ b/packages/core/agent-loop/tests/config-session-id.spec.ts @@ -336,7 +336,10 @@ describe('config-driven session id', () => { const resumeEffect = loopFiber.getEffects().find(effect => effect.label === 'agentLoop.resume(main)') expect(resumeEffect?.children.map(child => child.label)).toEqual(['ctx.plugin()']) - expect(loopFiber.getEffects().filter(effect => effect.label === 'ctx.plugin()')).toEqual([]) + // Exactly one plugin effect sits at the fiber's own level — the optional + // settings wiring, whose `ctx.inject` cordis labels like any other plugin. + // A resumed agent joining it there is the regression this pins. + expect(loopFiber.getEffects().filter(effect => effect.label === 'ctx.plugin()')).toHaveLength(1) await loopFiber.dispose() }) diff --git a/packages/core/agent-loop/tests/settings.spec.ts b/packages/core/agent-loop/tests/settings.spec.ts new file mode 100644 index 0000000000..ea36236f68 --- /dev/null +++ b/packages/core/agent-loop/tests/settings.spec.ts @@ -0,0 +1,106 @@ +/** The `agent-loop` settings section layered over the composition entry. */ + +import { describe, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Fiber } from '@deepseek-ai/cordis' +import LlmService from '@deepseek-ai/dsh-llm' +import SessionStore from '@deepseek-ai/dsh-session' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry from '@deepseek-ai/dsh-tools' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import { Settings } from '@deepseek-ai/dsh-settings' +import type { SettingsNamespace } from '@deepseek-ai/dsh-settings' +import AgentLoop, { AGENT_LOOP_SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-agent-loop' + +/** The smallest real provider: one in-memory document, always writable. */ +class MemorySettings extends Settings { + doc: Record = {} + + get writable(): boolean { + return true + } + + protected load(): Promise> { + return Promise.resolve(structuredClone(this.doc)) + } + + protected persist(ns: SettingsNamespace, section: Record): Promise { + this.doc = { ...this.doc, [ns]: structuredClone(section) } + return Promise.resolve() + } +} + +async function boot(): Promise<{ ctx: Context; settingsFiber: Fiber; loopFiber: Fiber }> { + const ctx = new Context() + await ctx.plugin(LlmService) + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(AgentRegistry) + const settingsFiber = ctx.plugin(MemorySettings) + await settingsFiber.await() + const loopFiber = ctx.plugin(AgentLoop, { agents: [], maxParallelToolCalls: 4 }) + await loopFiber.await() + return { ctx, settingsFiber, loopFiber } +} + +describe('agent-loop settings section', () => { + it('layers the stored parallel cap over the composition entry', async () => { + const bench = await boot() + expect(bench.ctx.agentLoop.config.maxParallelToolCalls).toBe(4) + + await bench.ctx.settings.update(AGENT_LOOP_SETTINGS_NAMESPACE, { maxParallelToolCalls: 1 }) + + expect(bench.ctx.agentLoop.config.maxParallelToolCalls).toBe(1) + await bench.ctx.fiber.dispose() + }) + + it('refuses a non-positive cap at the write', async () => { + const bench = await boot() + + await expect(bench.ctx.settings.update(AGENT_LOOP_SETTINGS_NAMESPACE, { maxParallelToolCalls: 0 })) + .rejects.toThrow() + + expect(bench.ctx.agentLoop.config.maxParallelToolCalls).toBe(4) + await bench.ctx.fiber.dispose() + }) + + it('never offers the composed agents array to the settings document', async () => { + const bench = await boot() + + const descriptor = bench.ctx.settings.describe().find(row => String(row.ns) === 'agent-loop') + + expect(Object.keys(descriptor?.value as object)).toEqual(['maxParallelToolCalls']) + await bench.ctx.fiber.dispose() + }) + + it('keeps serving the composed agents array to its own consumers', async () => { + const bench = await boot() + + await bench.ctx.settings.update(AGENT_LOOP_SETTINGS_NAMESPACE, { maxParallelToolCalls: 2 }) + + expect(bench.ctx.agentLoop.config.agents).toEqual([]) + await bench.ctx.fiber.dispose() + }) + + it('falls back to the composition entry when the settings provider detaches', async () => { + const bench = await boot() + await bench.ctx.settings.update(AGENT_LOOP_SETTINGS_NAMESPACE, { maxParallelToolCalls: 1 }) + expect(bench.ctx.agentLoop.config.maxParallelToolCalls).toBe(1) + + await bench.settingsFiber.dispose() + + expect(bench.ctx.agentLoop.config.maxParallelToolCalls).toBe(4) + await bench.ctx.fiber.dispose() + }) + + it('releases the namespace when the service unloads', async () => { + const bench = await boot() + expect(bench.ctx.settings.describe().map(row => String(row.ns))).toContain('agent-loop') + + await bench.loopFiber.dispose() + + expect(bench.ctx.settings.describe().map(row => String(row.ns))).not.toContain('agent-loop') + await bench.ctx.fiber.dispose() + }) +}) diff --git a/packages/core/agent-loop/tsconfig.json b/packages/core/agent-loop/tsconfig.json index c3504e4eb4..724f0c6741 100644 --- a/packages/core/agent-loop/tsconfig.json +++ b/packages/core/agent-loop/tsconfig.json @@ -38,6 +38,9 @@ { "path": "../../core/scope" }, + { + "path": "../../settings/settings" + }, { "path": "../../support/invariants" } diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index cecfb064d9..1043b6c110 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/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/host/apiproxy/README.md -README.md: cc7af11e80518f77f5092c758b00f68cafa4d033 -README.zh.md: 1353f6c92ca20b9a229b06b843e2011e99337b7a +README.md: 8ade64849193df61a48effaea5739907fda901bf +README.zh.md: 5634100ff2a34f507f3e922729a6781ee5c508a5 diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index cc7af11e80..8ade648491 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -56,7 +56,7 @@ The `agentPreset.list` domain exposes the deployment's preset roster so a browse The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `skill.list` serves the composer's menu: it returns every user-invocable skill with its `modelInvocable` flag, so menus can mark user-only (`disable-model-invocation`) entries whose only invocation path is the slash gesture. Listing is the skill domain's only RPC — invocation itself is an ordinary `session.prompt` whose whitespace-bounded `/name` tokens `dsh-tool-skill` recognizes at the pre-step boundary and answers with injected `` context, so every entry point (Web, TUI, and ACP) shares one deterministic path—including for hand-typed text—with no dedicated invocation wire. `command.execute` runs a slash-command line host-side with pure admission semantics: the response reports whether the line resolved to a handler plus the minted lifecycle `commandId` when it did (correlating the acknowledgment with the flow node), while the outcome rides the durably logged `command/run`/`command/done` lifecycle pair broadcast on the mux stream. Command handlers may legitimately outlast the 30-second transport health deadline, so `command.execute` carries only caller/connection cancellation; that signal cancels the running handler. `commands/change` rides the forwarded-event frame as the registry-wide catalog invalidation signal: clients refetch `command.list` instead of diffing. Forwarded `agent-preset/selected` is its per-session counterpart, emitted from the logged selection commit: recomposing a blank session's agent re-parents its scope without registering anything, so both catalogs that session's composition decides (`command.list`, `skill.list`) go stale with no registry change to announce it. -The `settings.*`, `credentials.*`, and `llm.*` domains are the configuration-page wire. The settings domain serves the namespaces addressed by registered configurable providers (`ctx.llm.listConfigurableProviders()`) plus a small explicit allowlist — the Web preferences `locale`, `permission`, `ui-conversation`, and `ui-theme`, and the product-owned `ui-onboarding`; adding a Settings registration alone never makes it remotely readable or writable. Any other namespace answers `settings-not-exposed` — the same answer an unregistered namespace gets, so no caller can enumerate the registry by probing. `settings.describe` returns each exposed namespace's serialized schemastery schema, redacted layered values (resolved/`base`/`user` — a field's presence in `user` marks it user-overridden), the `secrets` slot list, the section's `revision`, and the boolean `hasDocument` capability flag. The browser receives no Host path: pathless `settings.openDocument` asks the provider to materialize its document and then hands the Host-resolved result to the native opener, so no browser payload can select any filesystem target. `settings.update`/`settings.replace` write the user layer; `settings.mutate` applies path ops (`set`/`unset`) against the section as stored, which is the removal path for a client holding the redacted view — rebuilding a section from it and replacing wholesale would delete the secrets the wire never returned. Any write may carry `expectedRevision`; a stale one answers `settings-conflict` with both revisions rather than overwriting the writer that landed first, and every other seam refusal folds into `settings-rejected`. Secret-role values never ride any response in any layer; a secret crosses the wire in exactly one direction — inside an `update`/`mutate` payload or `credentials.set`. `credentials.describe` returns value-free views (`configured`/`source`/`writable`), and `credentials.set`/`credentials.unset` map a shadowed-reference refusal onto `credential-rejected`. `llm.providers` merges the configurable-provider directory with live routes (dormant entries carry `active: false`; undeclared live routes append with no settings address) and `llm.models` is the session-independent catalog. `llm.discoverModels` interrogates a provider endpoint the page is still drafting: `settingsNs` selects the adapter family that knows how to read the listing, and the endpoint, protocol, and key come from the form rather than from storage. It writes nothing — the reply is candidates, and only a later `settings.mutate` decides what a route serves — so its `apiKey` is the third payload on which a secret may ride, alongside `settings.update`/`mutate` and `credentials.set`. The host never stores or returns it; like the other two it does ride the client's outgoing envelope, which `subscribeEnvelopes()` observers can see, and redacting that tap is a configuration-plane-wide change rather than this method's to make alone. Every refusal (an unserved namespace, a protocol with no readable listing, an unreachable endpoint, a rejected credential) folds into `model-discovery-failed`, whose message is the adapter's own text and whose details name the endpoint asked but never the credential offered. Invalidations keep every surface converged without polling. `settings/document-updated` and `credentials/updated` ride the verbatim forwarded-event frame (see below), so a raw settings change whose resolved value is unchanged still reaches clients, and a credential invalidation still carries reference names only, never values. `llm/adapters-updated` is forwarded beside `settings/document-updated`; concrete model consumers subscribe to both owner events directly because topology commits and settings documents can independently change their directories. The browser carrier restricts the whole configuration plane, reads and native actions included (`settings.describe`/`openDocument`/`update`/`replace`/`mutate`, `credentials.describe`/`set`/`unset`), to loopback same-origin requests — the `host.pickDirectory` privileged set. A composition without a settings or credential provider answers those domains with an actionable `internal` error naming the missing plugin. +The `settings.*`, `credentials.*`, and `llm.*` domains are the configuration-page wire. The settings domain serves the namespaces addressed by registered configurable providers (`ctx.llm.listConfigurableProviders()`) plus a small explicit allowlist — the Web preferences `locale`, `permission`, `ui-conversation`, and `ui-theme`, the host-plane plugin sections `agent-loop`, `bash`, and `web-search-deepseek` that the plugin configuration page edits, and the product-owned `ui-onboarding`; adding a Settings registration alone never makes it remotely readable or writable. Any other namespace answers `settings-not-exposed` — the same answer an unregistered namespace gets, so no caller can enumerate the registry by probing. `settings.describe` returns each exposed namespace's serialized schemastery schema, redacted layered values (resolved/`base`/`user` — a field's presence in `user` marks it user-overridden), the `secrets` slot list, the section's `revision`, and the boolean `hasDocument` capability flag. The browser receives no Host path: pathless `settings.openDocument` asks the provider to materialize its document and then hands the Host-resolved result to the native opener, so no browser payload can select any filesystem target. `settings.update`/`settings.replace` write the user layer; `settings.mutate` applies path ops (`set`/`unset`) against the section as stored, which is the removal path for a client holding the redacted view — rebuilding a section from it and replacing wholesale would delete the secrets the wire never returned. Any write may carry `expectedRevision`; a stale one answers `settings-conflict` with both revisions rather than overwriting the writer that landed first, and every other seam refusal folds into `settings-rejected`. Secret-role values never ride any response in any layer; a secret crosses the wire in exactly one direction — inside an `update`/`mutate` payload or `credentials.set`. `credentials.describe` returns value-free views (`configured`/`source`/`writable`), and `credentials.set`/`credentials.unset` map a shadowed-reference refusal onto `credential-rejected`. `llm.providers` merges the configurable-provider directory with live routes (dormant entries carry `active: false`; undeclared live routes append with no settings address) and `llm.models` is the session-independent catalog. `llm.discoverModels` interrogates a provider endpoint the page is still drafting: `settingsNs` selects the adapter family that knows how to read the listing, and the endpoint, protocol, and key come from the form rather than from storage. It writes nothing — the reply is candidates, and only a later `settings.mutate` decides what a route serves — so its `apiKey` is the third payload on which a secret may ride, alongside `settings.update`/`mutate` and `credentials.set`. The host never stores or returns it; like the other two it does ride the client's outgoing envelope, which `subscribeEnvelopes()` observers can see, and redacting that tap is a configuration-plane-wide change rather than this method's to make alone. Every refusal (an unserved namespace, a protocol with no readable listing, an unreachable endpoint, a rejected credential) folds into `model-discovery-failed`, whose message is the adapter's own text and whose details name the endpoint asked but never the credential offered. Invalidations keep every surface converged without polling. `settings/document-updated` and `credentials/updated` ride the verbatim forwarded-event frame (see below), so a raw settings change whose resolved value is unchanged still reaches clients, and a credential invalidation still carries reference names only, never values. `llm/adapters-updated` is forwarded beside `settings/document-updated`; concrete model consumers subscribe to both owner events directly because topology commits and settings documents can independently change their directories. The browser carrier restricts the whole configuration plane, reads and native actions included (`settings.describe`/`openDocument`/`update`/`replace`/`mutate`, `credentials.describe`/`set`/`unset`), to loopback same-origin requests — the `host.pickDirectory` privileged set. A composition without a settings or credential provider answers those domains with an actionable `internal` error naming the missing plugin. ## Carrier layer (`/client` + root) diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index 1353f6c92c..5634100ff2 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -56,7 +56,7 @@ Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.cr `command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和 skill(技能)目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`skill.list` 服务于 composer 的菜单:它返回每一个用户可调用的 skill 及其 `modelInvocable` 标志,让菜单能够标出仅限用户(`disable-model-invocation`)的条目——斜杠手势是这类条目唯一的调用路径。列表是 skill 领域唯一的 RPC——调用本身就是一次普通的 `session.prompt`,`dsh-tool-skill` 会在 pre-step 边界识别其中以空白为界的 `/name` token,并以注入的 `` 上下文作答,因此所有入口(Web、TUI 与 ACP(Agent Client Protocol))共享同一条确定性路径,手动键入的文本也走该路径,且没有专设的调用协议。`command.execute` 在宿主侧运行一条斜杠命令行,语义为纯准入:响应报告该行是否解析到处理器,并在解析到时回带铸造的生命周期 `commandId`(将本次确认与流节点关联);结局经由持久落账并在 mux 流广播的 `command/run`/`command/done` 生命周期事件对承载。命令处理器运行超过 30 秒的传输健康时限仍属正常,因此 `command.execute` 仅携带调用方/连接取消信号;该信号可取消正在运行的处理器。`commands/change` 搭乘转发事件帧作为注册表级目录失效信号:客户端重新拉取 `command.list` 而不是做差分。转发的 `agent-preset/selected` 是它按会话粒度的对应物,由落账的选择提交点发出:重组空会话的 agent 只是重新挂接其 scope,不产生任何注册,因此该会话组成所决定的两份目录(`command.list`、`skill.list`)都会失效,却没有任何注册表变化来宣告它。 -`settings.*`、`credentials.*` 与 `llm.*` 领域是配置页协议。settings 领域服务于已注册可配置提供方所指向的 namespace(`ctx.llm.listConfigurableProviders()`),并额外服务于一份小型、显式的 allowlist——Web 偏好 `locale`、`permission`、`ui-conversation` 与 `ui-theme`,以及产品持有的 `ui-onboarding`;仅新增一项 Settings 注册,绝不会使其可被远程读取或写入。其他任何 namespace 都只会得到 `settings-not-exposed`——未注册的 namespace 得到的是同一个答复,因此没有调用方能靠逐个探测把注册表枚举出来。`settings.describe` 为每个已暴露 namespace 提供其序列化 schemastery schema、脱敏后的分层值(resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表、该分节的 `revision`,以及布尔型 `hasDocument` 能力标志。浏览器不会收到 Host 路径:无路径参数的 `settings.openDocument` 会请求提供方准备文档,再把由 Host 解析出的结果交给原生打开器,因此任何浏览器载荷都无法选择任意文件系统目标。`settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op(`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;陈旧的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应;secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable`),`credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected`。`llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。`llm.discoverModels` 询问页面尚在起草的提供方端点:`settingsNs` 选出懂得读取该列表的适配器家族,端点、协议与密钥则来自表单而非存储。它什么都不写——回复是候选,只有随后的 `settings.mutate` 才决定路由服务什么——因此其 `apiKey` 是 secret 可以搭乘的第三个载荷(另两个是 `settings.update`/`mutate` 与 `credentials.set`),且绝不被存储或回显。host 从不存储或回传它;与另两者一样,它确实会搭乘客户端的出站信封,`subscribeEnvelopes()` 的观察者能看到——为该 tap 做脱敏是整个配置面的改动,而非本方法一家的事。每一种拒绝(无人服务的 namespace、没有可读列表的协议、不可达端点、被拒凭据)都折叠为 `model-discovery-failed`,其消息是适配器自己的文本,details 点名被询问的端点,绝不点名所提供的凭据。失效通知让每个面无需轮询即保持收敛。`settings/document-updated` 与 `credentials/updated` 搭乘原样转发事件帧(见下),因此解析值未变的原始设置变更同样能到达客户端,凭据失效通知也仍然只带引用名、绝不带值。`llm/adapters-updated` 与 `settings/document-updated` 一并原样转发;具体模型消费方直接订阅这两个 owner 事件,因为拓扑提交和设置文档都能独立改变其目录。浏览器载体把整个配置面(含读取与原生操作:`settings.describe`/`openDocument`/`update`/`replace`/`mutate` 与 `credentials.describe`/`set`/`unset`)限制为仅接受来自回环地址的同源请求——即 `host.pickDirectory` 所在的特权集合。未装 settings 或凭据 provider 的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。 +`settings.*`、`credentials.*` 与 `llm.*` 领域是配置页协议。settings 领域服务于已注册可配置提供方所指向的 namespace(`ctx.llm.listConfigurableProviders()`),并额外服务于一份小型、显式的 allowlist——Web 偏好 `locale`、`permission`、`ui-conversation` 与 `ui-theme`、插件配置页所编辑的宿主平面插件分节 `agent-loop`、`bash` 与 `web-search-deepseek`,以及产品持有的 `ui-onboarding`;仅新增一项 Settings 注册,绝不会使其可被远程读取或写入。其他任何 namespace 都只会得到 `settings-not-exposed`——未注册的 namespace 得到的是同一个答复,因此没有调用方能靠逐个探测把注册表枚举出来。`settings.describe` 为每个已暴露 namespace 提供其序列化 schemastery schema、脱敏后的分层值(resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表、该分节的 `revision`,以及布尔型 `hasDocument` 能力标志。浏览器不会收到 Host 路径:无路径参数的 `settings.openDocument` 会请求提供方准备文档,再把由 Host 解析出的结果交给原生打开器,因此任何浏览器载荷都无法选择任意文件系统目标。`settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op(`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;陈旧的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应;secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable`),`credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected`。`llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。`llm.discoverModels` 询问页面尚在起草的提供方端点:`settingsNs` 选出懂得读取该列表的适配器家族,端点、协议与密钥则来自表单而非存储。它什么都不写——回复是候选,只有随后的 `settings.mutate` 才决定路由服务什么——因此其 `apiKey` 是 secret 可以搭乘的第三个载荷(另两个是 `settings.update`/`mutate` 与 `credentials.set`),且绝不被存储或回显。host 从不存储或回传它;与另两者一样,它确实会搭乘客户端的出站信封,`subscribeEnvelopes()` 的观察者能看到——为该 tap 做脱敏是整个配置面的改动,而非本方法一家的事。每一种拒绝(无人服务的 namespace、没有可读列表的协议、不可达端点、被拒凭据)都折叠为 `model-discovery-failed`,其消息是适配器自己的文本,details 点名被询问的端点,绝不点名所提供的凭据。失效通知让每个面无需轮询即保持收敛。`settings/document-updated` 与 `credentials/updated` 搭乘原样转发事件帧(见下),因此解析值未变的原始设置变更同样能到达客户端,凭据失效通知也仍然只带引用名、绝不带值。`llm/adapters-updated` 与 `settings/document-updated` 一并原样转发;具体模型消费方直接订阅这两个 owner 事件,因为拓扑提交和设置文档都能独立改变其目录。浏览器载体把整个配置面(含读取与原生操作:`settings.describe`/`openDocument`/`update`/`replace`/`mutate` 与 `credentials.describe`/`set`/`unset`)限制为仅接受来自回环地址的同源请求——即 `host.pickDirectory` 所在的特权集合。未装 settings 或凭据 provider 的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。 ## 载体层(`/client` + 根路径) diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 76d5e91051..56f41ecf15 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -107,8 +107,19 @@ import { canOpenNativePath, openNativePath, openNativeTextFile } from './native- /** Page size when history is called without maxMessages. */ const DEFAULT_MAX_MESSAGES = 50 -/** Non-model settings namespaces intentionally served to the Web client. */ -const WEB_SETTINGS_NAMESPACES = ['locale', 'permission', 'ui-conversation', 'ui-theme'] as const +/** + * Non-model settings namespaces intentionally served to the Web client. The + * plugin-owned entries (`agent-loop`, `bash`, `web-search-deepseek`) are the + * host-plane sections the plugin configuration page edits; a namespace absent + * here answers `settings-not-exposed` even when its owner registered it, so + * adding a section to that page is a decision made here rather than by the + * registering plugin. Moving that declaration to `settings.register()`, so a + * plugin can expose its own configuration without a change in this package, + * is deferred work. + */ +const WEB_SETTINGS_NAMESPACES = [ + 'agent-loop', 'bash', 'locale', 'permission', 'ui-conversation', 'ui-theme', 'web-search-deepseek', +] as const /** Provider work budget: at most 100 calls and 2,000 inspected hits. */ const SESSION_SEARCH_PROVIDER_CALL_LIMIT = 100 diff --git a/packages/host/apiproxy/tests/api-proxy-config.spec.ts b/packages/host/apiproxy/tests/api-proxy-config.spec.ts index e748d3a38c..99e5796367 100644 --- a/packages/host/apiproxy/tests/api-proxy-config.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-config.spec.ts @@ -344,11 +344,21 @@ describe('settings domain', () => { ctx.settings.register(settingsNamespace('ui-conversation'), z.object({ busyEnter: z.union(['queue', 'steer']).default('queue'), })) + ctx.settings.register(settingsNamespace('bash'), z.object({ + timeoutMs: z.number().default(120_000), + })) + ctx.settings.register(settingsNamespace('agent-loop'), z.object({ + maxParallelToolCalls: z.number().default(10), + })) + ctx.settings.register(settingsNamespace('web-search-deepseek'), z.object({ + baseURL: z.string(), + })) const api = createApiProxy(ctx, DEFAULTS) const value = expectOk(await api.settings.describe(request({}))) expect(value.namespaces.map(view => view.ns)).toEqual([ 'llm-deepseek', 'permission', 'ui-theme', 'locale', 'ui-conversation', + 'bash', 'agent-loop', 'web-search-deepseek', ]) const permission = expectOk(await api.settings.mutate(request({ ns: 'permission', @@ -370,6 +380,21 @@ describe('settings domain', () => { ops: [{ op: 'set', path: ['busyEnter'], value: 'steer' }], }))) expect(conversation.value).toEqual({ busyEnter: 'steer' }) + const bash = expectOk(await api.settings.mutate(request({ + ns: 'bash', + ops: [{ op: 'set', path: ['timeoutMs'], value: 5_000 }], + }))) + expect(bash.value).toEqual({ timeoutMs: 5_000 }) + const agentLoop = expectOk(await api.settings.mutate(request({ + ns: 'agent-loop', + ops: [{ op: 'set', path: ['maxParallelToolCalls'], value: 2 }], + }))) + expect(agentLoop.value).toEqual({ maxParallelToolCalls: 2 }) + const webSearch = expectOk(await api.settings.mutate(request({ + ns: 'web-search-deepseek', + ops: [{ op: 'set', path: ['baseURL'], value: 'https://search.test/v1' }], + }))) + expect(webSearch.value).toEqual({ baseURL: 'https://search.test/v1' }) for (const response of [ await api.settings.update(request({ ns: 'some-other-plugin', patch: { secretPath: '/etc/shadow' } })), diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index 6763fb34d1..04f9199ea6 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/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/web/web-search-deepseek/README.md -README.md: 0ddd64827dde8a9f27937305fcb71d8c55e25ae6 -README.zh.md: 4e761aa6ef1a67ce17fbc1cabf595af7f24e15e6 +README.md: 25162a3e82a05bb17f31a69bc65f6552e42906ad +README.zh.md: 21962bcd390f253f899000be7273a79485821018 diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 0ddd64827d..25162a3e82 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -34,6 +34,8 @@ It reuses the `DEEPSEEK_API_KEY` credential reference (no new secret) but **not* baseURL: https://gateway.internal/anthropic/v1 ``` +The entry above is the base layer of the `web-search-deepseek` Settings section: a user layer over it reaches the NEXT search, because the provider projects the section per call rather than capturing it at registration. The seam's provider selection therefore never flickers when an endpoint or model changes. `apiKey` carries `role('secret')`, so it never rides a `describe()` response in any layer — a configuration surface learns only whether the credentials domain holds a value for the reference `apiKeyEnv` names, never whether a layer carries a literal key. + ## Mapping DeepSeek returns no provider-generated answer content this provider trusts as `content`, so `content` is omitted. `sources[]` comes from `web_search_result` items inside `web_search_tool_result` blocks: `url` ← `url`, `title` ← `title`, and `publishedAt` ← `page_age`. Snippets live separately as URL-keyed `cited_text` entries in a text block's `citations[]`; the provider joins them, leaving `snippet` absent when no excerpt exists. diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index 4e761aa6ef..21962bcd39 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -34,6 +34,8 @@ Exa 和 Perplexity 提供专用搜索端点,DeepSeek 则没有。该提供方 baseURL: https://gateway.internal/anthropic/v1 ``` +上面的条目是 `web-search-deepseek` Settings 段的 base 层:叠加其上的用户层会作用于**下一次**搜索,因为提供方是按次投影该段,而不是在注册时固化它。因此端点或模型变化时,seam 的提供方选择不会闪断。`apiKey` 带有 `role('secret')`,所以它在任何一层都不会出现在 `describe()` 响应中——配置表层只能知道 credentials 领域是否为 `apiKeyEnv` 所命名的引用持有值,而无从知道某一层是否带着字面密钥。 + ## 映射 DeepSeek 不返回该提供方可作为 `content` 信任的提供方生成答案表层,因此省略 `content`。`sources[]` 来自 `web_search_result` 配置项,这些配置项位于 `web_search_tool_result` 块内:`url` ← `url`、`title` ← `title`、`publishedAt` ← `page_age`。`cited_text` 配置项按 URL 标识,单独位于文本块的 `citations[]` 中;提供方会将其作为 snippet 连接,没有摘录时省略 `snippet`。 diff --git a/packages/web/web-search-deepseek/package.json b/packages/web/web-search-deepseek/package.json index c3d304678c..532b9d14bd 100644 --- a/packages/web/web-search-deepseek/package.json +++ b/packages/web/web-search-deepseek/package.json @@ -38,7 +38,8 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-web": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:^" @@ -51,6 +52,7 @@ "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-web": "workspace:^", - "@deepseek-ai/cordis": "workspace:^" + "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-settings": "workspace:^" } } diff --git a/packages/web/web-search-deepseek/src/index.ts b/packages/web/web-search-deepseek/src/index.ts index 8b465d9617..35d232af6c 100644 --- a/packages/web/web-search-deepseek/src/index.ts +++ b/packages/web/web-search-deepseek/src/index.ts @@ -9,6 +9,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' import { credentialRef } from '@deepseek-ai/dsh-credentials' +import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings' import { environmentOf } from '@deepseek-ai/dsh-environment' import type {} from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-web' @@ -20,6 +21,7 @@ import { DEEPSEEK_DEFAULT_MAX_USES, DEEPSEEK_DEFAULT_MODEL, } from './provider.ts' +import type { DeepSeekSearchProviderOptions } from './provider.ts' export { DeepSeekSearchProvider, @@ -61,11 +63,14 @@ export interface Config { export const Config: z = z.object({ apiKey: z.string().role('secret'), apiKeyEnv: z.string().role('credential-ref').default(DEFAULT_API_KEY_ENV), + // Declared here rather than only at the use site: a configuration surface + // renders the resolved section, so a default the schema does not carry reads + // there as no value at all. baseURL: z.string(), - model: z.string(), - apiVersion: z.string(), - maxTokens: z.number().step(1).min(1), - maxUses: z.number().step(1).min(1), + model: z.string().default(DEEPSEEK_DEFAULT_MODEL), + apiVersion: z.string().default(DEEPSEEK_DEFAULT_API_VERSION), + maxTokens: z.number().step(1).min(1).default(DEEPSEEK_DEFAULT_MAX_TOKENS), + maxUses: z.number().step(1).min(1).default(DEEPSEEK_DEFAULT_MAX_USES), }) /** @@ -76,15 +81,23 @@ export const Config: z = z.object({ */ const SEARCH_BASE_URL_ENV = 'DEEPSEEK_SEARCH_BASE_URL' -/** Register the DeepSeek search provider with `ctx.web`. */ -export function apply(ctx: Context, config: Config): void { - const maxTokens = config.maxTokens ?? DEEPSEEK_DEFAULT_MAX_TOKENS - const maxUses = config.maxUses ?? DEEPSEEK_DEFAULT_MAX_USES +/** Settings namespace carrying this provider's endpoint, model, and key reference. */ +export const WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE = settingsNamespace('web-search-deepseek') + +/** + * Project one resolved section into the options the provider serves its next + * search with. Environment fallbacks stay here rather than in the provider: + * every value it reads is already fully defaulted. + * @param ctx - plugin context supplying the credential and environment planes. + * @param config - the currently authoritative section. + * @returns options for one search. + */ +function resolveOptions(ctx: Context, config: Config): DeepSeekSearchProviderOptions { const apiKeyEnv = credentialRef(config.apiKeyEnv ?? DEFAULT_API_KEY_ENV) const literalApiKey = config.apiKey !== undefined && config.apiKey.length > 0 ? config.apiKey : undefined - ctx.web.registerSearchProvider(new DeepSeekSearchProvider({ + return { ...literalApiKey === undefined ? {} : { apiKey: literalApiKey }, resolveApiKey: async () => { const credentials = ctx.get('credentials') @@ -99,13 +112,27 @@ export function apply(ctx: Context, config: Config): void { ?? DEEPSEEK_DEFAULT_BASE_URL, model: config.model ?? DEEPSEEK_DEFAULT_MODEL, apiVersion: config.apiVersion ?? DEEPSEEK_DEFAULT_API_VERSION, - maxTokens, - maxUses, + maxTokens: config.maxTokens ?? DEEPSEEK_DEFAULT_MAX_TOKENS, + maxUses: config.maxUses ?? DEEPSEEK_DEFAULT_MAX_USES, recordRequest: (request) => { ctx.get('agents')?.currentInitiator()?.session.append( 'web/deepseek-search-llm-request', request, ) }, - })) + } +} + +/** Register the DeepSeek search provider with `ctx.web`. */ +export function apply(ctx: Context, config: Config): void { + let current: () => Config = () => config + installSettingsSection(ctx, WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE, Config, config, { + setSource: (source) => { + current = source + }, + // The registration carries no resolved value: the provider projects the + // section per search, so a committed change needs no re-registration. + onChange: () => {}, + }) + ctx.web.registerSearchProvider(new DeepSeekSearchProvider(() => resolveOptions(ctx, current()))) } diff --git a/packages/web/web-search-deepseek/src/provider.ts b/packages/web/web-search-deepseek/src/provider.ts index 73acd0284e..d6805bcacc 100644 --- a/packages/web/web-search-deepseek/src/provider.ts +++ b/packages/web/web-search-deepseek/src/provider.ts @@ -177,31 +177,43 @@ export function mapAnthropicResponse(response: AnthropicResponse): WebSearchResu export class DeepSeekSearchProvider implements WebSearchProvider { readonly id = DEEPSEEK_PROVIDER_ID - constructor(private readonly options: DeepSeekSearchProviderOptions) {} + /** + * @param resolveOptions - the options for the NEXT operation, snapshotted + * once at each operation's entry so one search never mixes two sections. A + * thunk rather than a value because the plugin's settings section can change + * between searches, and re-registering the provider to carry a new endpoint + * would make the seam's selection observable to the user as a flicker. + */ + constructor(private readonly resolveOptions: () => DeepSeekSearchProviderOptions) {} available(): boolean { - return ((this.options.apiKey?.length ?? 0) > 0 || this.options.resolveApiKey !== undefined) - && URL.canParse(this.options.baseURL) - && isPositiveInteger(this.options.maxTokens) - && isPositiveInteger(this.options.maxUses) + const options = this.resolveOptions() + return ((options.apiKey?.length ?? 0) > 0 || options.resolveApiKey !== undefined) + && URL.canParse(options.baseURL) + && isPositiveInteger(options.maxTokens) + && isPositiveInteger(options.maxUses) } async search(request: WebSearchRequest, signal?: AbortSignal): Promise { - const apiKey = await this.apiKey(signal) + // One snapshot for the whole operation: credential resolution awaits, and a + // settings write landing inside that await must not send the key resolved + // from the old section to the endpoint named by the new one. + const options = this.resolveOptions() + const apiKey = await this.apiKey(options, signal) throwIfSearchAborted(signal) - const endpoint = `${this.options.baseURL}/messages` + const endpoint = `${options.baseURL}/messages` const body: DeepSeekSearchLlmRequest['body'] = { - model: this.options.model, - max_tokens: this.options.maxTokens, + model: options.model, + max_tokens: options.maxTokens, messages: [{ role: 'user', content: [{ type: 'text', text: `Perform a web search for the query: ${request.query}` }], }], - tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: this.options.maxUses }], + tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: options.maxUses }], } - this.options.recordRequest?.({ + options.recordRequest?.({ endpoint, - apiVersion: this.options.apiVersion, + apiVersion: options.apiVersion, body, }) throwIfSearchAborted(signal) @@ -215,7 +227,7 @@ export class DeepSeekSearchProvider implements WebSearchProvider { // may expect `Authorization: Bearer` — send both so either resolves. 'x-api-key': apiKey, 'authorization': `Bearer ${apiKey}`, - 'anthropic-version': this.options.apiVersion, + 'anthropic-version': options.apiVersion, 'content-type': 'application/json', 'accept': 'application/json', 'user-agent': USER_AGENT, @@ -257,13 +269,18 @@ export class DeepSeekSearchProvider implements WebSearchProvider { } } - /** Resolve one operation's credential without retaining it on the provider. */ - private async apiKey(signal?: AbortSignal): Promise { + /** + * Resolve one operation's credential without retaining it on the provider. + * @param options - the caller's snapshot, so the key and the endpoint it is sent to come from one section. + * @param signal - abort signal for the surrounding search. + * @returns the resolved key. + */ + private async apiKey(options: DeepSeekSearchProviderOptions, signal?: AbortSignal): Promise { throwIfSearchAborted(signal) - if (this.options.apiKey !== undefined && this.options.apiKey.length > 0) return this.options.apiKey + if (options.apiKey !== undefined && options.apiKey.length > 0) return options.apiKey let resolved: string | undefined try { - resolved = await abortable(this.options.resolveApiKey?.() ?? Promise.resolve(undefined), signal) + resolved = await abortable(options.resolveApiKey?.() ?? Promise.resolve(undefined), signal) } catch (error: unknown) { if (signal?.aborted === true || isAbortError(error)) throw searchAborted(signal, error) throw new WebError( @@ -273,7 +290,7 @@ export class DeepSeekSearchProvider implements WebSearchProvider { ) } if (resolved !== undefined && resolved.length > 0) return resolved - const ref = this.options.apiKeyEnv ?? 'DEEPSEEK_API_KEY' + const ref = options.apiKeyEnv ?? 'DEEPSEEK_API_KEY' throw new WebError( `DeepSeek search has no API key for "${ref}"; store it through the credentials service` + ' (the web Models page writes it), export it in the launching environment, or set a literal' diff --git a/packages/web/web-search-deepseek/tests/deepseek.e2e.ts b/packages/web/web-search-deepseek/tests/deepseek.e2e.ts index e86be695b2..543b602786 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.e2e.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.e2e.ts @@ -8,6 +8,12 @@ import { DEEPSEEK_DEFAULT_MODEL, } from '@deepseek-ai/dsh-web-search-deepseek' +/** Construct the provider over a fixed options value; production passes a live thunk. */ +import type { DeepSeekSearchProviderOptions } from '@deepseek-ai/dsh-web-search-deepseek' + +const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchProvider => + new DeepSeekSearchProvider(() => options) + /** * Disabled real-API probe for the DeepSeek search provider. The live endpoint * can complete without structured source blocks, so this is not a reliable @@ -18,7 +24,7 @@ const maybe = apiKey !== undefined && apiKey.length > 0 ? describe : describe.sk maybe('DeepSeekSearchProvider real API', () => { it.skip('returns citeable sources for a live query via native web_search', async () => { - const provider = new DeepSeekSearchProvider({ + const provider = searchProvider({ apiKey: apiKey!, baseURL: process.env.DEEPSEEK_SEARCH_BASE_URL ?? DEEPSEEK_DEFAULT_BASE_URL, model: process.env.DEEPSEEK_SEARCH_MODEL ?? DEEPSEEK_DEFAULT_MODEL, diff --git a/packages/web/web-search-deepseek/tests/deepseek.spec.ts b/packages/web/web-search-deepseek/tests/deepseek.spec.ts index af51213660..c7eb156156 100644 --- a/packages/web/web-search-deepseek/tests/deepseek.spec.ts +++ b/packages/web/web-search-deepseek/tests/deepseek.spec.ts @@ -15,6 +15,12 @@ import * as deepseekPlugin from '@deepseek-ai/dsh-web-search-deepseek' import { citationSnippets, mapAnthropicResponse } from '../src/provider.ts' import type { AnthropicResponse } from '@deepseek-ai/dsh-web-search-deepseek/src/types.ts' +/** Construct the provider over a fixed options value; production passes a live thunk. */ +import type { DeepSeekSearchProviderOptions } from '@deepseek-ai/dsh-web-search-deepseek' + +const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchProvider => + new DeepSeekSearchProvider(() => options) + const options = { apiKey: 'ds-key', baseURL: 'https://api.deepseek.test/anthropic/v1', @@ -142,21 +148,21 @@ describe('mapAnthropicResponse', () => { describe('DeepSeekSearchProvider availability', () => { it('is unavailable without a key', () => { - expect(new DeepSeekSearchProvider({ ...options, apiKey: '' }).available()).toBe(false) + expect(searchProvider({ ...options, apiKey: '' }).available()).toBe(false) }) it('is available with a key', () => { - expect(new DeepSeekSearchProvider(options).available()).toBe(true) + expect(searchProvider(options).available()).toBe(true) }) it('is misconfigured when the base URL is unparseable', () => { - expect(new DeepSeekSearchProvider({ ...options, baseURL: 'not a url' }).available()).toBe(false) + expect(searchProvider({ ...options, baseURL: 'not a url' }).available()).toBe(false) }) it('is misconfigured when request limits are not positive integers', () => { - expect(new DeepSeekSearchProvider({ ...options, maxTokens: 0 }).available()).toBe(false) - expect(new DeepSeekSearchProvider({ ...options, maxUses: 0 }).available()).toBe(false) - expect(new DeepSeekSearchProvider({ ...options, maxUses: 1.5 }).available()).toBe(false) + expect(searchProvider({ ...options, maxTokens: 0 }).available()).toBe(false) + expect(searchProvider({ ...options, maxUses: 0 }).available()).toBe(false) + expect(searchProvider({ ...options, maxUses: 1.5 }).available()).toBe(false) }) }) @@ -165,7 +171,7 @@ describe('DeepSeekSearchProvider request mapping', () => { const fetchMock = vi.fn(async () => jsonResponse(searchResponse())) const recordRequest = vi.fn() vi.stubGlobal('fetch', fetchMock) - await new DeepSeekSearchProvider({ ...options, recordRequest }).search({ query: 'hello' }) + await searchProvider({ ...options, recordRequest }).search({ query: 'hello' }) const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit] expect(url).toBe('https://api.deepseek.test/anthropic/v1/messages') expect(init).toMatchObject({ method: 'POST', redirect: 'error' }) @@ -193,12 +199,40 @@ describe('DeepSeekSearchProvider request mapping', () => { const fetchMock = vi.fn(async () => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) const controller = new AbortController() - await new DeepSeekSearchProvider(options).search({ query: 'q' }, controller.signal) + await searchProvider(options).search({ query: 'q' }, controller.signal) const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit] expect(init.signal).toBe(controller.signal) }) }) +describe('DeepSeekSearchProvider settings changes mid-search', () => { + it('serves one search from one section even when settings land during credential resolution', async () => { + // The section the search starts on, and the one a user commits while the + // credential is still resolving. + const before = { ...options, apiKey: '', baseURL: 'https://before.test/v1', model: 'model-before', maxUses: 2 } + const after = { ...options, apiKey: '', baseURL: 'https://after.test/v1', model: 'model-after', maxUses: 9 } + let current = before + let commitSettings = () => {} + const resolveApiKey = () => new Promise((resolve) => { + commitSettings = () => { current = after; resolve('key-from-before') } + }) + const fetchMock = vi.fn(async () => jsonResponse(searchResponse())) + vi.stubGlobal('fetch', fetchMock) + + const provider = new DeepSeekSearchProvider(() => ({ ...current, resolveApiKey })) + const search = provider.search({ query: 'q' }) + await vi.waitFor(() => { expect(typeof commitSettings).toBe('function') }) + commitSettings() + await search + + const [endpoint, init] = fetchMock.mock.calls[0] as unknown as [string, { headers: Record; body: string }] + // The key resolved from `before` must never reach `after`'s origin. + expect(endpoint).toBe('https://before.test/v1/messages') + expect(init.headers['x-api-key']).toBe('key-from-before') + expect(JSON.parse(init.body)).toMatchObject({ model: 'model-before' }) + }) +}) + describe('DeepSeekSearchProvider error handling', () => { it('does not start credential resolution or dispatch for a pre-aborted call', async () => { const resolveApiKey = vi.fn(async () => 'late-key') @@ -207,7 +241,7 @@ describe('DeepSeekSearchProvider error handling', () => { vi.stubGlobal('fetch', fetchMock) const controller = new AbortController() controller.abort(new Error('caller stopped')) - await expect(new DeepSeekSearchProvider({ + await expect(searchProvider({ ...options, apiKey: '', resolveApiKey, @@ -225,7 +259,7 @@ describe('DeepSeekSearchProvider error handling', () => { const fetchMock = vi.fn() vi.stubGlobal('fetch', fetchMock) const controller = new AbortController() - const search = new DeepSeekSearchProvider({ + const search = searchProvider({ ...options, apiKey: '', resolveApiKey, @@ -242,7 +276,7 @@ describe('DeepSeekSearchProvider error handling', () => { const fetchMock = vi.fn(async () => jsonResponse(searchResponse())) vi.stubGlobal('fetch', fetchMock) const controller = new AbortController() - await expect(new DeepSeekSearchProvider({ + await expect(searchProvider({ ...options, apiKey: '', resolveApiKey: async () => 'resolved-key', @@ -253,7 +287,7 @@ describe('DeepSeekSearchProvider error handling', () => { it('maps a credential resolver rejection under an active signal to WEB_PROVIDER_ERROR', async () => { const controller = new AbortController() - await expect(new DeepSeekSearchProvider({ + await expect(searchProvider({ ...options, apiKey: '', resolveApiKey: () => Promise.reject(new Error('credential backend failed')), @@ -265,7 +299,7 @@ describe('DeepSeekSearchProvider error handling', () => { }) it('uses the default credential reference when no resolver is configured', async () => { - await expect(new DeepSeekSearchProvider({ ...options, apiKey: '' }).search({ query: 'q' })) + await expect(searchProvider({ ...options, apiKey: '' }).search({ query: 'q' })) .rejects.toThrow('DeepSeek search has no API key for "DEEPSEEK_API_KEY"') }) @@ -273,7 +307,7 @@ describe('DeepSeekSearchProvider error handling', () => { const controller = new AbortController() const fetchMock = vi.fn() vi.stubGlobal('fetch', fetchMock) - await expect(new DeepSeekSearchProvider({ + await expect(searchProvider({ ...options, apiKey: '', resolveApiKey: () => { @@ -287,31 +321,31 @@ describe('DeepSeekSearchProvider error handling', () => { it('maps an HTTP error to WEB_PROVIDER_ERROR with the provider message', async () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'rate limited' } }, { status: 429 }))) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', message: 'rate limited' })) }) it('handles a string-form error body', async () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'bad request' }, { status: 400 }))) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ message: 'bad request' })) }) it('keeps a status-line message when the error body is not JSON', async () => { vi.stubGlobal('fetch', vi.fn(async () => new Response('upstream error', { status: 503 }))) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ message: 'DeepSeek API error (HTTP 503)' })) }) it('keeps the status-line message when the JSON error body carries no detail', async () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 500 }))) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ message: 'DeepSeek API error (HTTP 500)' })) }) it('maps an abort to WEB_ABORTED', async () => { vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new DOMException('aborted', 'AbortError')))) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) }) @@ -321,46 +355,46 @@ describe('DeepSeekSearchProvider error handling', () => { await new Promise((_resolve, reject) => { init?.signal?.addEventListener('abort', () => { reject(new Error('custom abort reason')) }, { once: true }) }))) - const search = new DeepSeekSearchProvider(options).search({ query: 'q' }, controller.signal) + const search = searchProvider(options).search({ query: 'q' }, controller.signal) controller.abort(new Error('timeout reason')) await expect(search).rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) }) it('maps an unparseable success body to WEB_PROVIDER_ERROR', async () => { vi.stubGlobal('fetch', vi.fn(async () => new Response('not json', { status: 200 }))) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' })) }) it('maps a well-formed body of the wrong shape to WEB_PROVIDER_ERROR, not a raw TypeError', async () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ content: {} }, { status: 200 }))) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' })) }) it('surfaces an abort during success-body parse as WEB_ABORTED', async () => { const body = { json: () => Promise.reject(new DOMException('aborted', 'AbortError')), ok: true, status: 200 } vi.stubGlobal('fetch', vi.fn(async () => body as unknown as Response)) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) }) it('surfaces an abort during error-body parse as WEB_ABORTED', async () => { const body = { json: () => Promise.reject(new DOMException('aborted', 'AbortError')), ok: false, status: 500 } vi.stubGlobal('fetch', vi.fn(async () => body as unknown as Response)) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' })) }) it('maps a network failure to WEB_PROVIDER_ERROR', async () => { vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new TypeError('connection refused')))) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' })) }) it('strict mode flows through search(): a prose-only response throws WEB_PROVIDER_ERROR', async () => { vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ content: [{ type: 'text', text: 'no search happened' }] }))) - await expect(new DeepSeekSearchProvider(options).search({ query: 'q' })) + await expect(searchProvider(options).search({ query: 'q' })) .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' })) }) }) diff --git a/packages/web/web-search-deepseek/tests/redirect.spec.ts b/packages/web/web-search-deepseek/tests/redirect.spec.ts index 100d60f390..e42446e6ec 100644 --- a/packages/web/web-search-deepseek/tests/redirect.spec.ts +++ b/packages/web/web-search-deepseek/tests/redirect.spec.ts @@ -8,6 +8,12 @@ import { createServer, type IncomingMessage, type Server } from 'node:http' import type { AddressInfo } from 'node:net' import { DeepSeekSearchProvider } from '@deepseek-ai/dsh-web-search-deepseek' +/** Construct the provider over a fixed options value; production passes a live thunk. */ +import type { DeepSeekSearchProviderOptions } from '@deepseek-ai/dsh-web-search-deepseek' + +const searchProvider = (options: DeepSeekSearchProviderOptions): DeepSeekSearchProvider => + new DeepSeekSearchProvider(() => options) + const TEST_API_KEY = 'redirect-test-key' const TEST_QUERY = 'private redirect query' const targetRequests: ReceivedRequest[] = [] @@ -46,7 +52,7 @@ afterAll(async () => { describe('DeepSeekSearchProvider redirect policy', () => { it.each([301, 302, 303, 307, 308])('rejects HTTP %i before contacting Location', async (status) => { targetRequests.length = 0 - const provider = new DeepSeekSearchProvider({ + const provider = searchProvider({ apiKey: TEST_API_KEY, baseURL: `${redirectOrigin}/${status}`, model: 'deepseek-chat', diff --git a/packages/web/web-search-deepseek/tests/settings.spec.ts b/packages/web/web-search-deepseek/tests/settings.spec.ts new file mode 100644 index 0000000000..bd9eea4a15 --- /dev/null +++ b/packages/web/web-search-deepseek/tests/settings.spec.ts @@ -0,0 +1,124 @@ +/** The `web-search-deepseek` settings section layered over the composition entry. */ + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Fiber } from '@deepseek-ai/cordis' +import { Settings } from '@deepseek-ai/dsh-settings' +import type { SettingsNamespace } from '@deepseek-ai/dsh-settings' +import WebService from '@deepseek-ai/dsh-web' +import * as deepseekPlugin from '@deepseek-ai/dsh-web-search-deepseek' +import { WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE } from '@deepseek-ai/dsh-web-search-deepseek' + +/** The smallest real provider: one in-memory document, always writable. */ +class MemorySettings extends Settings { + doc: Record = {} + + get writable(): boolean { + return true + } + + protected load(): Promise> { + return Promise.resolve(structuredClone(this.doc)) + } + + protected persist(ns: SettingsNamespace, section: Record): Promise { + this.doc = { ...this.doc, [ns]: structuredClone(section) } + return Promise.resolve() + } +} + +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }) +} + +/** The smallest Anthropic-shaped answer the provider accepts — enough to observe the request. */ +const ONE_RESULT = { + content: [ + { type: 'text', text: 'ok' }, + { + type: 'web_search_tool_result', + content: [{ type: 'web_search_result', url: 'https://a.test', title: 'A' }], + }, + ], +} + +async function boot(): Promise<{ ctx: Context; settingsFiber: Fiber; pluginFiber: Fiber }> { + const ctx = new Context() + await ctx.plugin(WebService, {}) + const settingsFiber = ctx.plugin(MemorySettings) + await settingsFiber.await() + const pluginFiber = ctx.plugin(deepseekPlugin, { apiKey: 'ds-key', baseURL: 'https://search.entry.test/v1' }) + await pluginFiber.await() + return { ctx, settingsFiber, pluginFiber } +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +/** + * Run one search and answer the endpoint it reached. A fresh `Response` per + * call because a body can only be read once, and the call history is cleared + * because repeated `spyOn` returns the same spy. + * @param ctx - context whose `ctx.web` serves the search. + * @returns the URL the provider fetched. + */ +async function searchOnce(ctx: Context): Promise { + const fetchSpy = vi.spyOn(globalThis, 'fetch') + .mockImplementation(() => Promise.resolve(jsonResponse(ONE_RESULT))) + fetchSpy.mockClear() + await ctx.web.search({ query: 'anything' }) + return String((fetchSpy.mock.calls.at(-1)?.[0] as URL | string | undefined) ?? '') +} + +describe('web-search-deepseek settings section', () => { + it('serves a stored endpoint to the next search without re-registering the provider', async () => { + const bench = await boot() + expect(await searchOnce(bench.ctx)).toContain('https://search.entry.test/v1') + + await bench.ctx.settings.update(WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE, { + baseURL: 'https://search.stored.test/v1', + }) + + expect(await searchOnce(bench.ctx)).toContain('https://search.stored.test/v1') + await bench.ctx.fiber.dispose() + }) + + it('keeps the literal key out of every described layer', async () => { + const bench = await boot() + await bench.ctx.settings.update(WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE, { apiKey: 'ds-stored-secret' }) + + const [descriptor] = bench.ctx.settings.describe({ redactSecrets: true }) + .filter(row => String(row.ns) === 'web-search-deepseek') + + expect(JSON.stringify(descriptor)).not.toContain('ds-stored-secret') + expect(descriptor?.secrets).toEqual([{ path: ['apiKey'], set: true }]) + await bench.ctx.fiber.dispose() + }) + + it('falls back to the composition entry when the settings provider detaches', async () => { + const bench = await boot() + await bench.ctx.settings.update(WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE, { + baseURL: 'https://search.stored.test/v1', + }) + expect(await searchOnce(bench.ctx)).toContain('https://search.stored.test/v1') + + await bench.settingsFiber.dispose() + + expect(await searchOnce(bench.ctx)).toContain('https://search.entry.test/v1') + await bench.ctx.fiber.dispose() + }) + + it('releases the namespace when the plugin unloads', async () => { + const bench = await boot() + expect(bench.ctx.settings.describe().map(row => String(row.ns))).toContain('web-search-deepseek') + + await bench.pluginFiber.dispose() + + expect(bench.ctx.settings.describe().map(row => String(row.ns))).not.toContain('web-search-deepseek') + await bench.ctx.fiber.dispose() + }) +}) diff --git a/packages/web/web-search-deepseek/tsconfig.json b/packages/web/web-search-deepseek/tsconfig.json index b3d8e2ade6..28dbbc3b33 100644 --- a/packages/web/web-search-deepseek/tsconfig.json +++ b/packages/web/web-search-deepseek/tsconfig.json @@ -32,6 +32,9 @@ { "path": "../../credentials/credentials" }, + { + "path": "../../settings/settings" + }, { "path": "../../support/invariants" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 37062e020d..1a8247df74 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -901,6 +901,9 @@ importers: '@deepseek-ai/dsh-sandbox': specifier: workspace:^ version: link:../../sandbox/sandbox + '@deepseek-ai/dsh-settings': + specifier: workspace:^ + version: link:../../settings/settings '@deepseek-ai/dsh-subprocess': specifier: workspace:^ version: link:../../subprocess/subprocess @@ -951,6 +954,9 @@ importers: '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants + '@deepseek-ai/dsh-settings': + specifier: workspace:^ + version: link:../../settings/settings '@deepseek-ai/dsh-subprocess': specifier: workspace:^ version: link:../../subprocess/subprocess @@ -1006,6 +1012,9 @@ importers: '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants + '@deepseek-ai/dsh-settings': + specifier: workspace:^ + version: link:../../settings/settings '@deepseek-ai/dsh-subprocess': specifier: workspace:^ version: link:../../subprocess/subprocess @@ -1566,6 +1575,9 @@ importers: '@deepseek-ai/dsh-client-ui-plan': specifier: workspace:^ version: link:../../client/ui-plan + '@deepseek-ai/dsh-client-ui-plugin-config': + specifier: workspace:^ + version: link:../../client/ui-plugin-config '@deepseek-ai/dsh-client-ui-question': specifier: workspace:^ version: link:../../client/ui-question @@ -1961,6 +1973,37 @@ importers: specifier: ^18.2.0 version: 18.3.1 + packages/client/ui-attachment: + dependencies: + '@deepseek-ai/dsh-attachment': + specifier: workspace:^ + version: link:../../attachment/attachment + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:^ + version: link:../ui-primitives + clsx: + specifier: ^2.0.0 + version: 2.1.1 + react: + specifier: ^18.2.0 + version: 18.3.1 + react-dom: + specifier: ^18.2.0 + version: 18.3.1(react@18.3.1) + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:^ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + '@types/react-dom': + specifier: ~18.3.0 + version: 18.3.7(@types/react@18.3.31) + packages/client/ui-command: dependencies: clsx: @@ -2046,6 +2089,9 @@ importers: '@deepseek-ai/dsh-client-test-runtime': specifier: workspace:^ version: link:../test-runtime + '@deepseek-ai/dsh-client-ui-attachment': + specifier: workspace:^ + version: link:../ui-attachment '@deepseek-ai/dsh-client-ui-layout': specifier: workspace:^ version: link:../ui-layout @@ -2399,6 +2445,52 @@ importers: specifier: ^18.2.0 version: 18.3.1 + packages/client/ui-plugin-config: + dependencies: + clsx: + specifier: ^2.0.0 + version: 2.1.1 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:^ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:^ + version: link:../../api/remotes + '@deepseek-ai/dsh-client-connection': + specifier: workspace:^ + version: link:../connection + '@deepseek-ai/dsh-client-locale': + specifier: workspace:^ + version: link:../locale + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../runtime + '@deepseek-ai/dsh-client-test-runtime': + specifier: workspace:^ + version: link:../test-runtime + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:^ + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-settings': + specifier: workspace:^ + version: link:../ui-settings + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../ui-slots + '@deepseek-ai/dsh-client-web-react': + specifier: workspace:^ + version: link:../web-react + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + react: + specifier: ^18.2.0 + version: 18.3.1 + packages/client/ui-primitives: dependencies: '@shikijs/langs': @@ -3073,6 +3165,9 @@ importers: '@deepseek-ai/dsh-client-schema-form': specifier: workspace:^ version: link:../schema-form + '@deepseek-ai/dsh-client-ui-attachment': + specifier: workspace:^ + version: link:../ui-attachment '@deepseek-ai/dsh-client-ui-primitives': specifier: workspace:^ version: link:../ui-primitives @@ -3528,6 +3623,9 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:^ version: link:../../session/session-persistence-jsonl + '@deepseek-ai/dsh-settings': + specifier: workspace:^ + version: link:../../settings/settings '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../system-prompt @@ -7504,6 +7602,9 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session + '@deepseek-ai/dsh-settings': + specifier: workspace:^ + version: link:../../settings/settings '@deepseek-ai/dsh-web': specifier: workspace:^ version: link:../web diff --git a/scripts/verify-cordis-config.ts b/scripts/verify-cordis-config.ts index a70dae4d1c..3f760c9ae1 100644 --- a/scripts/verify-cordis-config.ts +++ b/scripts/verify-cordis-config.ts @@ -79,6 +79,7 @@ errors.push(...validateExampleResolution()) errors.push(...validateAppResolution()) errors.push(...validateSourcePlaneResolution()) errors.push(...validatePresetPlaneSeparation()) +errors.push(...validateClientHalvesDeclared()) if (errors.length > 0) { console.error('verify-cordis-config: invalid Loader metadata or plugin package resolution:') @@ -88,6 +89,35 @@ if (errors.length > 0) { console.log(`verify-cordis-config: ${files.length} config files passed.`) } +/** + * A browser plugin must declare the browser half it ships. + * + * The browser roster is discovered by scanning composed packages for a + * `dsh.client` block, and the node half of a surface plugin is an empty + * `apply`. A `packages/client` package that exports `./client` without that + * block therefore composes, activates, and contributes nothing — its bundle is + * never served and no error is raised anywhere. The mismatch is invisible in + * the composition file, so it is checked against the manifests instead. Only + * this group is checked: a Host package's `./client` export is the typed wire + * face its browser consumers import, not a plugin the roster serves. + * @returns one violation per client package whose `./client` export and + * `dsh.client` declaration disagree. + */ +function validateClientHalvesDeclared(): string[] { + return globSync('packages/client/*/package.json', { cwd: root }).flatMap((manifestPath) => { + const manifest = readManifest(manifestPath) as PackageManifest & { + exports?: Record + dsh?: { client?: unknown } + } + const shipsClient = manifest.exports !== undefined && Object.hasOwn(manifest.exports, './client') + const declaresClient = manifest.dsh?.client !== undefined + if (shipsClient === declaresClient) return [] + return [shipsClient + ? `${manifestPath}: exports "./client" but declares no dsh.client, so its browser half is never served` + : `${manifestPath}: declares dsh.client but exports no "./client" entry to serve`] + }) +} + /** * No shipped agent preset may repeat a row the host composition still runs. * diff --git a/scripts/verify-mermaid.ts b/scripts/verify-mermaid.ts index 79e80d802d..c38445be93 100644 --- a/scripts/verify-mermaid.ts +++ b/scripts/verify-mermaid.ts @@ -84,7 +84,9 @@ const mermaid = (await import('mermaid')).default // maxEdges: mermaid's default 500-edge render guard; the module graph grows // with every package edge and crossed it legitimately. Raise the guard here // (a secure config settable only via initialize) rather than trimming edges. -mermaid.initialize({ startOnLoad: false, maxEdges: 1000 }) +// The graph passed 1000 the same way it passed 500, so the headroom doubles +// again rather than being set to whatever the current count happens to be. +mermaid.initialize({ startOnLoad: false, maxEdges: 2000 }) for (const block of blocks) { try { await mermaid.parse(block.source, { suppressErrors: false }) diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index cef363c1df..251789f803 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -61,6 +61,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/modules': { kind: 'none', reason: 'Browser-side module-loading kernel machinery; registers nothing model-facing.' }, 'packages/client/test-runtime': { kind: 'none', reason: 'Browser-side test infrastructure (jsdom bench); registers nothing model-facing.' }, 'packages/client/ui-slots': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, + 'packages/client/ui-attachment': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, 'packages/client/ui-primitives': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, 'packages/client/web-react': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, 'packages/client/schema-form': { kind: 'none', reason: 'Browser-side form-rendering library; registers nothing model-facing.' }, @@ -79,6 +80,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-model': { kind: 'indirect', reason: 'Selection routes session.selectModel; the Host snapshots the selection at the next prompt-assembly boundary and owns the model-visible effect.' }, 'packages/client/ui-goal': { kind: 'indirect', reason: 'The strip verbs route goal.* mutations; the host GoalService owns the model-visible goal/change context message.' }, 'packages/client/ui-permission': { kind: 'indirect', reason: 'The picker submits the host /permission command; the knob events it appends own the model-visible effect through the sandbox/approval consumers.' }, + 'packages/client/ui-plugin-config': { kind: 'none', reason: 'Browser-side settings surface; registers no model surface.' }, 'packages/client/ui-plan': { kind: 'indirect', reason: 'The chip dispatches /plan off; dsh-plan-mode owns the model-visible policy, exit tool, and logged state.' }, 'packages/client/ui-question': { kind: 'indirect', reason: 'The package mounts dsh-tool-ask-user; that tool owns the model-visible schema and answer rendering.' }, 'packages/client/ui-trajectory': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 2984f6fafd..ba090b9252 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -161,6 +161,7 @@ "@deepseek-ai/dsh-host-apiproxy/*": ["./packages/host/apiproxy/src/*"], "@deepseek-ai/dsh-host-webserver": ["./packages/host/webserver/src"], "@deepseek-ai/dsh-client-ui-slots": ["./packages/client/ui-slots/src"], + "@deepseek-ai/dsh-client-ui-attachment": ["./packages/client/ui-attachment/src"], "@deepseek-ai/dsh-client-ui-primitives": ["./packages/client/ui-primitives/src"], "@deepseek-ai/dsh-client-schema-form": ["./packages/client/schema-form/src"], "@deepseek-ai/dsh-client-schema-form/invariant": ["./packages/client/schema-form/src/invariant.ts"], @@ -187,6 +188,7 @@ "@deepseek-ai/dsh-client-ui-permission": ["./packages/client/ui-permission/src"], "@deepseek-ai/dsh-client-ui-skill": ["./packages/client/ui-skill/src"], "@deepseek-ai/dsh-client-ui-subagent": ["./packages/client/ui-subagent/src"], + "@deepseek-ai/dsh-client-ui-plugin-config": ["./packages/client/ui-plugin-config/src"], "@deepseek-ai/dsh-client-ui-task": ["./packages/client/ui-task/src"], "@deepseek-ai/dsh-client-ui-plan": ["./packages/client/ui-plan/src"], "@deepseek-ai/dsh-client-ui-question": ["./packages/client/ui-question/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index 3ccdbc3f1d..a054cb8751 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -46,6 +46,7 @@ { "path": "./packages/compact/compact" }, { "path": "./packages/client/ui-slots" }, { "path": "./packages/client/schema-form" }, + { "path": "./packages/client/ui-attachment" }, { "path": "./packages/client/ui-primitives" }, { "path": "./packages/client/web-react" }, { "path": "./packages/client/modules" }, @@ -73,6 +74,7 @@ { "path": "./packages/client/ui-agent-preset" }, { "path": "./packages/client/ui-permission" }, { "path": "./packages/client/ui-plan" }, + { "path": "./packages/client/ui-plugin-config" }, { "path": "./packages/client/ui-question" }, { "path": "./packages/client/ui-trajectory" }, { "path": "./packages/client/ui-theme" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index be794ba04b..b5e43cb523 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -25,6 +25,7 @@ "apps/web/tests/trajectory-virtualization.e2e.ts", "apps/web/tests/lifecycle-chrome.e2e.ts", "apps/web/tests/details-session-lifecycle.e2e.ts", + "apps/web/tests/plugin-config.e2e.ts", "apps/web/tests/settings-chrome.e2e.ts", "apps/web/tests/models-settings.e2e.ts", "apps/web/tests/onboarding-deepseek-config.e2e.ts",