Merge branch 'master' into worktree/session-panel-stay-pinned-128657
This commit is contained in:
commit
1f54d627bb
240 files changed
+2476
-1453
No files matched your search
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: e42db40b879fdbf4
|
||||
zh: 6017da9c4da17835
|
||||
/agent-note-node-ptc-execution-modes-and-in-memory-state/decision:
|
||||
en: 411054071757d5fe
|
||||
zh: e683ef7d80f33fc6
|
||||
en: 13a72b9728d25394
|
||||
zh: 1f44510fe93836dc
|
||||
/agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered:
|
||||
en: 396157a9fc293198
|
||||
zh: a061f05b4423e26f
|
||||
|
||||
@@ -18,7 +18,7 @@ One npm package and one plugin entry keep existing installation and loading path
|
||||
|
||||
The Session records submitted programs, nested tool calls and returned output. It does not serialize the REPL heap or rerun earlier programs after restart, resume or fork: replaying automation could repeat external side effects. A missing variable is a normal program error, and the model-visible instructions require recreating variables and reacquiring resources. No environment identifier or new durable Session event is required because the provider exposes no unlogged model input.
|
||||
|
||||
Protocol or output-limit failure, owner disposal and process exit discard the environment. The [interruption decision](2026-10-29-retained-ptc-interruption.md) owns timeout and cancellation recovery with retained state. Ordinary exceptions retain earlier mutations. A retained function uses the active evaluation's host bindings; asynchronous work from an earlier evaluation cannot acquire a later evaluation's tool authority or output sink.
|
||||
Protocol failure, owner disposal and process exit discard the environment. [Output truncation](2026-11-13-ptc-output-truncation.md) owns bounded output without state disposal. The [interruption decision](2026-10-29-retained-ptc-interruption.md) owns timeout and cancellation recovery with retained state. Ordinary exceptions retain earlier mutations. A retained function uses the active evaluation's host bindings; asynchronous work from an earlier evaluation cannot acquire a later evaluation's tool authority or output sink.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ Status: implemented
|
||||
|
||||
Session 记录提交的程序、嵌套工具调用和返回输出。它不序列化 REPL 堆,也不在重启、恢复或派生后重新执行旧程序,因为重放自动化可能重复外部操作。缺失变量产生普通程序错误,模型指引要求重新创建变量并获取资源。提供方没有引入日志之外的模型输入,因此不需要环境标识或新的持久 Session 事件。
|
||||
|
||||
协议失败、输出超限、所有者销毁和进程退出都会丢弃环境。[中断决策](2026-10-29-retained-ptc-interruption.zh.md)负责保留状态的超时和取消恢复。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。
|
||||
协议失败、所有者销毁和进程退出都会丢弃环境。[输出截断](2026-11-13-ptc-output-truncation.zh.md)负责限制输出而不丢弃状态。[中断决策](2026-10-29-retained-ptc-interruption.zh.md)负责保留状态的超时和取消恢复。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-13-ptc-output-truncation.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-13-ptc-output-truncation.md
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation:
|
||||
en: 781fba10ab5fcd45
|
||||
zh: 88276a5a9cdf8c19
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation/problem:
|
||||
en: a6430b7910bebaa2
|
||||
zh: dff6c3553e22283e
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation/decision:
|
||||
en: b24a08b0037adab4
|
||||
zh: 92fb390a0e460ba5
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation/alternatives-considered:
|
||||
en: 717295afe374b2e5
|
||||
zh: cf4fd1365169f9e3
|
||||
/agent-note-ptc-output-truncation-without-execution-cancellation/consequences:
|
||||
en: 420e2556a878b48a
|
||||
zh: bff5f63189562d57
|
||||
@@ -0,0 +1,25 @@
|
||||
# Agent Note: PTC output truncation without execution cancellation
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-13-ptc-output-truncation.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Stopping a program because its logs exceed the output budget can interrupt a sequence of external actions. Earlier effects remain, but the caller cannot tell which later actions ran. Repeating the program to obtain less output can repeat those effects. A full log budget can also hide a subsequent exception by replacing its kind with an output-limit failure.
|
||||
|
||||
## Decision
|
||||
|
||||
Captured output has bounded retention. Exhaustion preserves an ordered prefix, discards subsequent output and sets `outputTruncated`; it does not cancel execution or discard retained variables. Existing deadlines, cancellation, heap limits and control-message limits still apply. Finalization prioritizes the required completion value or bounded failure diagnostic within the combined payload budget. Truncated diagnostics preserve their failure kind. Required completion values remain lossless and fail if they cannot fit.
|
||||
|
||||
This supersedes only captured-output termination and diagnostic reclassification in [typed tool returns](../feature/2026-07-20-ptc-typed-tool-returns.md), and overflow-driven state disposal in [retained PTC](2026-09-23-best-effort-persistent-ptc.md). Those records still own lossless values and retained-state lifetime; [explicit output](2026-11-09-explicit-ptc-output.md) still owns inspection and image projection.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Terminate on output exhaustion.** It limits output production earlier, but turns a presentation limit into interrupted external work without rollback.
|
||||
|
||||
**Return success with a truncated completion value.** It violates the caller's requirement for complete JSON data. Only captured output and diagnostic text may be shortened.
|
||||
|
||||
## Consequences
|
||||
|
||||
Successful truncated runs remain successful tool results. Callers inspect current state for missing information instead of replaying completed actions. Output suppression does not bound allocations in argument evaluation or native code; existing resource controls retain that responsibility. Tests cover subsequent actions, retained variables, initialization, ordered images, byte limits and later exceptions, deadlines and cancellation.
|
||||
@@ -0,0 +1,25 @@
|
||||
# Agent Note: PTC 输出截断不取消执行
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-13-ptc-output-truncation.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
因日志超出输出预算而停止程序,可能打断一系列外部动作。此前的效果仍然保留,但调用方无法判断后续哪些动作已经执行。为了减少输出而重跑程序,可能重复这些效果。日志预算耗尽还可能使后续异常被替换成输出超限失败,掩盖真实类型。
|
||||
|
||||
## 决策
|
||||
|
||||
捕获输出采用有界保留。预算耗尽时保留有序前缀,丢弃后续输出并设置 `outputTruncated`,但不取消执行或丢弃保留变量。原有截止时间、取消、堆限制和控制消息限制继续生效。最终结算在组合负载预算内优先保留必需完成值或有界失败诊断。截断诊断保留原来的失败类型。必需完成值保持无损,无法容纳时仍然失败。
|
||||
|
||||
本决策只取代[类型化工具返回值](../feature/2026-07-20-ptc-typed-tool-returns.zh.md)中的捕获输出超限终止和诊断重新分类,以及[保留状态 PTC](2026-09-23-best-effort-persistent-ptc.zh.md)中的超限清空状态规则。这些记录仍负责无损值和保留状态生命周期;[显式输出](2026-11-09-explicit-ptc-output.zh.md)仍负责检查展示与图片投影。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**输出耗尽时终止。** 能更早限制输出生产,但将展示限制变成没有回滚的外部工作中断。
|
||||
|
||||
**截断完成值后返回成功。** 违反调用方对完整 JSON 数据的要求。只有捕获输出和诊断文本可以缩短。
|
||||
|
||||
## 后果
|
||||
|
||||
成功但输出截断的执行仍是成功工具结果。调用方读取当前状态以获取遗漏信息,不重放已完成动作。输出抑制不限制参数求值或原生代码中的分配,这仍由现有资源控制负责。测试覆盖后续动作、保留变量、初始化、有序图片、字节上限以及后续异常、截止到期和取消。
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 8b10f08e67ca9323
|
||||
zh: e57adb520049f407
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/outer-result-and-output-ledger:
|
||||
en: e48ef4dbe1ac9a1e
|
||||
zh: b87b0c0a3f1c2a4e
|
||||
en: f6fb803d2dc061bb
|
||||
zh: 05432104d5876f99
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/decision/typed-handles-and-lifetime:
|
||||
en: b2b9318c2812e3a4
|
||||
zh: 73cf34bfd487e2f1
|
||||
@@ -33,8 +33,8 @@
|
||||
en: 069a1e170c7d1dfb
|
||||
zh: 14ce5a56e602595c
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/consequences:
|
||||
en: f5726b5e7a2fc73f
|
||||
zh: 0b9aa884db5d920f
|
||||
en: 16cb8d972867b62f
|
||||
zh: d253114975e96fe8
|
||||
/agent-note-typed-tool-returns-in-ptc-mode/known-limitations-and-deferred-work:
|
||||
en: 19828c2e5796df2d
|
||||
zh: 2ef63df81fca7a72
|
||||
@@ -59,9 +59,9 @@ Ordinary binding arguments and JSON resolutions are revalidated as lossless JSON
|
||||
|
||||
Runtime consumers that retain completions receive exact lossless JSON: `undefined` omits the completion and `null` is an explicit result. TypeScript `run_code` requests completion discard and returns captured logs plus optional sandbox facts as its canonical value; selected images enter its rendered content separately.
|
||||
|
||||
`NodePtcRuntime` replaces the former independent log and value caps with configurable `maxOutputBytes`, defaulting to `67_108_864` bytes. The worker charges captured logs by their exact JSON-string serialization and preflights the detached completion or program exception against the remaining combined budget before posting a terminal message. A giant thrown string or stack therefore crosses the worker port only as the fixed `output-limit` diagnostic. The host repeats the hostile-peer ledger for forged traffic and native pipe writes the worker cannot observe. Fixed `PtcRunResult` field names, braces, the bounded error-kind tag, and later presentation whitespace are deliberately outside this variable-payload ledger. Neither stage materializes an over-limit serialized completion. A result at or below the cap is exact. A completion that cannot survive lossless JSON snapshotting fails as `invalid-output`; a value, diagnostic, or combined outcome over the cap fails as `output-limit` rather than becoming inspected or truncated text.
|
||||
`NodePtcRuntime` uses the configurable `maxOutputBytes` combined payload budget, defaulting to `67_108_864` bytes. Required completion values remain lossless JSON: unsupported values fail with `invalid-output`, and values that cannot fit fail with `output-limit`. The [output-truncation decision](../architecture/2026-11-13-ptc-output-truncation.md) owns captured-output retention and diagnostic priority. Fixed `PtcRunResult` field names, braces, bounded metadata and later presentation whitespace remain outside this variable-payload ledger. The host validates untrusted process traffic and native pipe writes independently; neither side serializes oversized completions.
|
||||
|
||||
Logs stream eagerly so a terminated run can retain output already admitted. Native stdout and stderr writes that bypass the worker's patched stream slots use independent pipes, so terminal settlement continues bounded capture until worker termination completes before materializing the result. When the cap is crossed, the runtime returns an explicit bounded failure with the fitting captured prefix. That outer result then traverses the ordinary `run_code` rendering and spill policy, which may save the captured text and expose its configured head/tail preview. The spill layer cannot recover bytes the runtime rejected beyond the hard cap.
|
||||
Logs stream eagerly so a terminated run can retain output already admitted. Native stdout and stderr writes that bypass the worker's patched stream slots use independent pipes, so terminal settlement continues bounded capture until worker termination completes before materializing the result. When the cap is crossed, captured output is truncated to a fitting prefix and marked with `outputTruncated`, while execution continues. Finalization reserves the required completion or diagnostic budget before retaining output; only a required completion that cannot fit causes `output-limit`. That outer result then traverses the ordinary `run_code` rendering and spill policy, which may save the captured text and expose its configured head/tail preview. The spill layer cannot recover bytes the runtime rejected beyond the hard cap.
|
||||
|
||||
Compute time, wall time, worker heap, cancellation, and fresh-worker isolation remain independent limits. The outer ledger never charges intermediate bindings, so snapshotting, flat-wire encoding and decoding, structured-clone cost, and available process or worker memory are their practical bounds.
|
||||
|
||||
@@ -101,7 +101,7 @@ Keyless real-worker integration tests pin the two handle workflows that prose re
|
||||
|
||||
Code programs can compose tools through stable values instead of reverse-engineering Native prose. Native mode retains its existing text and UI presentation, while PTC mode receives output-schema types and exact runtime JSON. Tool authors must treat the canonical value as their programmatic API and put display-only formatting in the renderer.
|
||||
|
||||
The worker performs bounded-depth flat-wire transport and lossless validation but does not make intermediate values cheap or durable. Outer overflow is an explicit failed run, and error handling remains intentionally human-guided rather than a versioned code union.
|
||||
The worker performs bounded-depth flat-wire transport and lossless validation but does not make intermediate values cheap or durable. An oversized required completion is an explicit failed run, and error handling remains intentionally human-guided rather than a versioned code union.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
|
||||
@@ -59,9 +59,9 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
|
||||
|
||||
保留完成值的运行时消费方接收精确无损 JSON:`undefined` 省略完成值,`null` 是显式结果。TypeScript `run_code` 请求丢弃完成值,将捕获日志和可选沙箱信息作为规范值返回;所选图片单独进入渲染内容。
|
||||
|
||||
`NodePtcRuntime` 以可配置的 `maxOutputBytes` 取代彼此独立的日志与值上限,默认值为 `67_108_864` 字节。worker 会将已捕获日志序列化为 JSON 字符串后的精确字节数计入账本,并在发送终态消息前,根据组合账本的剩余额度预检分离后的完成值或程序异常。因此,即使抛出的字符串或堆栈极大,通过 worker 端口的也只会是固定的 `output-limit` 诊断。宿主侧会针对伪造流量以及 worker 无法观察的原生管道写入,重复执行这套面向不可信对端的账本校验。固定的 `PtcRunResult` 字段名、花括号、有界的错误类型标签及后续展示空白有意不计入这份可变负载账本。这两个阶段都不会实际生成超出上限的完成值序列化结果。结果不超过上限时会保持精确。完成值无法通过无损 JSON 快照时,以 `invalid-output` 失败;值、诊断或包含日志的组合结果超过上限时,以 `output-limit` 失败,而不会变成检查格式化后或截断的文本。
|
||||
`NodePtcRuntime` 使用可配置的 `maxOutputBytes` 组合负载预算,默认值为 `67_108_864` 字节。必需完成值保持无损 JSON:不支持的值以 `invalid-output` 失败,无法容纳的值以 `output-limit` 失败。[输出截断决策](../architecture/2026-11-13-ptc-output-truncation.zh.md)负责捕获输出保留和诊断优先级。固定的 `PtcRunResult` 字段名、花括号、有界元数据和后续展示空白仍不计入可变负载账本。宿主独立校验不可信进程通信和原生管道写入;两端都不会序列化过大的完成值。
|
||||
|
||||
日志会在产生时立即流出,因此运行被终止时仍可保留已经纳入额度的输出。绕过 worker 中已改写流写入入口的原生 stdout 和 stderr 写入会经由彼此独立的管道传输,因此运行时在终态结算期间仍会继续在上限内捕获输出,直至 worker 完全终止,然后才组装结果。超过上限后,运行时会返回一个显式的有界失败,并携带可容纳的已捕获前缀。该外层结果随后通过普通的 `run_code` 渲染与 spill 策略;策略可以保存已捕获的文本,并暴露其配置指定的头尾预览。spill 层无法恢复运行时在硬上限之外拒绝的字节。
|
||||
日志会在产生时立即流出,因此运行被终止时仍可保留已经纳入额度的输出。绕过 worker 中已改写流写入入口的原生 stdout 和 stderr 写入会经由彼此独立的管道传输,因此运行时在终态结算期间仍会继续在上限内捕获输出,直至 worker 完全终止,然后才组装结果。超过上限后,捕获输出会截断为可容纳的前缀并标记 `outputTruncated`,执行继续。最终结算先为必需完成值或诊断预留预算,再保留输出;只有无法容纳的必需完成值才会导致 `output-limit`。该外层结果随后通过普通的 `run_code` 渲染与 spill 策略;策略可以保存已捕获的文本,并暴露其配置指定的头尾预览。spill 层无法恢复运行时在硬上限之外拒绝的字节。
|
||||
|
||||
计算时间、墙钟时间、worker 堆内存、取消和每次运行使用全新 worker 的隔离仍是互相独立的限制。外层账本从不计入中间绑定值,因此生成快照、扁平协议格式的编码与解码、结构化克隆开销,以及进程或 worker 的可用内存构成了这些值的实际边界。
|
||||
|
||||
@@ -101,7 +101,7 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert
|
||||
|
||||
PTC mode 程序可以通过稳定值组合工具,无需逆向解析 Native 自然语言。Native mode 保留现有文本与 UI 展示,PTC mode 则获得输出 schema 类型和精确的运行时 JSON。工具作者必须把规范值视为程序化 API,并将仅用于展示的格式化放入渲染器。
|
||||
|
||||
worker 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。外层输出溢出会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。
|
||||
worker 会以嵌套深度有界的扁平协议格式传输数据并执行无损校验,但不会降低中间值的开销,也不会使其具备持久性。必需完成值超限会显式导致运行失败,错误处理则有意由人类引导,而不是依赖带版本的错误代码联合。
|
||||
|
||||
## 已知限制与暂缓事项
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ The [`weighted-approval` workflow](../workflows/weighted-approval.yml) publishes
|
||||
|
||||
The weighted approval workflow exposes two pull-request checks. The `weighted approval publisher` Actions job reports whether evaluation and status publication completed, while the `weighted approval` commit status carries the approval decision on the pull request head. Branch rules must require only the commit status with GitHub Actions as its expected source; a context-only requirement can accept a same-named status from another integration. The publisher marks the head pending before Python setup or lexer installation, so failed setup or an interrupted history fetch cannot leave a previous success in place. Setup and evaluation failures publish an error status. A completed evaluation returns `pending` below two approval points, while the pull request is a draft, or while a write-capable reviewer has an effective `CHANGES_REQUESTED` review; the blocker keeps the status pending even when counted approvals reach the threshold. It returns `success` only when the threshold is met, the pull request is ready, and no such blocker exists. If evaluation fails, the publisher writes an `error` status. The publisher also writes a `weighted approval decision` check run that reports the same decision as a conclusion — `action_required` while the policy is unmet, `success` when it holds, and `failure` on setup or evaluation failures — with the score or blocker in its title. Branch rules do not require that check run, so it never blocks a merge; it names the blocked state beside the status that gates the merge. The check run is published with a token minted from a dedicated approval App (`DSH_APPROVAL_APP_CLIENT_ID`, `DSH_APPROVAL_APP_PRIVATE_KEY`, `DSH_APPROVAL_APP_SLUG`, scope `checks: write`): GitHub attaches a check run created with the job token to the earliest Actions check suite on the head, and when that suite belongs to this `pull_request_target` workflow the merge box omits it, so the App identity makes the association stable. The App publishes only runs whose `app.slug` is the App; job-token runs from earlier evaluations stay untouched and can coexist on a head. When the token or slug is missing, the publisher falls back to the job token and updates job-token runs only, which keeps the label on the Checks page. The App token step runs with `continue-on-error`, so a missing App configuration fails only that step and leaves the job-token fallback; a failed check-run write is logged by the publisher and never changes the status.
|
||||
|
||||
Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@imccyu`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author’s own review and reviewers without write permission do not count.
|
||||
Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@CreatixChu`, `@imccyu`, `@LegGasai`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author’s own review and reviewers without write permission do not count.
|
||||
|
||||
The PR author contributes `min(100, mergedPRCount) × 11 / 1000` points: 0 merged PRs → 0 points, 50 → 0.55, and 100 or more → 1.1. The publisher counts only merged PRs in this repository using the author’s immutable account ID, excluding the current PR. It stops at 100 matches and rejects incomplete history responses. Counts refresh at the next subscribed evaluation event. Author credit is separate from reviewer approvals and cannot satisfy the two-point requirement alone; the author’s own review remains excluded. Human and bot authors, including Dependabot, use the same rule. Drafts, blocking reviews, and sufficient reviewer points skip history lookup; logs mark credit as not evaluated. Otherwise, logs show author credit and the capped count separately. Below the cap, counting may scan the repository’s entire merged history; a failed required lookup publishes an error.
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
"defaultPoints": 1,
|
||||
"reviewerPoints": {
|
||||
"07akioni": 2,
|
||||
"CreatixChu": 2,
|
||||
"imccyu": 2,
|
||||
"LegGasai": 2,
|
||||
"tianyicui": 2,
|
||||
"tianyicui-bot": 2,
|
||||
"turtle1999": 2,
|
||||
|
||||
@@ -45,7 +45,9 @@ test('loads the repository approval score policy', () => {
|
||||
assert.equal(policy.defaultPoints, 1)
|
||||
assert.deepEqual([...policy.reviewerPoints], [
|
||||
['07akioni', 2],
|
||||
['creatixchu', 2],
|
||||
['imccyu', 2],
|
||||
['leggasai', 2],
|
||||
['tianyicui', 2],
|
||||
['tianyicui-bot', 2],
|
||||
['turtle1999', 2],
|
||||
|
||||
@@ -85,14 +85,18 @@ describe('dsh run with Agent Teams enabled', () => {
|
||||
expect(files).toHaveLength(4)
|
||||
const logs = await Promise.all(files.map(file => readFile(join(sessions, file), 'utf8')))
|
||||
const parsed = logs.map(records)
|
||||
const workflowTask = [
|
||||
{ type: 'text', text: 'Agent lead sent a message: ' },
|
||||
{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' },
|
||||
]
|
||||
const workflowChild = parsed.find(log => log.some(record => record.type === 'user/message'
|
||||
&& JSON.stringify((record.data as { content: unknown }).content) === JSON.stringify([{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }])))
|
||||
&& JSON.stringify((record.data as { content: unknown }).content) === JSON.stringify(workflowTask)))
|
||||
expect(workflowChild).toBeDefined()
|
||||
const workflowDescriptor = workflowChild!.find(record => record.type === 'subagent/descriptor')?.data as Record<string, unknown>
|
||||
expect(workflowDescriptor).toMatchObject({ mode: 'continuable', provider: 'spawn' })
|
||||
expect(workflowChild!.filter(record => record.type === 'user/message'
|
||||
&& (record.data as { source: { kind: string } }).source.kind === 'user').map(record => record.data))
|
||||
.toEqual([expect.objectContaining({ content: [{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }] })])
|
||||
&& (record.data as { source: { kind: string } }).source.kind === 'agent-message').map(record => record.data))
|
||||
.toEqual([expect.objectContaining({ content: workflowTask })])
|
||||
const root = parsed.find((log) => {
|
||||
const header = log[0]
|
||||
return header?.type === 'session' && typeof header.parentSession !== 'string'
|
||||
@@ -111,7 +115,8 @@ describe('dsh run with Agent Teams enabled', () => {
|
||||
expect(eventTypes).not.toContain('team/message/queued')
|
||||
expect(eventTypes).not.toContain('team/message/delivered')
|
||||
const peerMessages = parsed.flatMap(log => log.filter(record => record.type === 'user/message'
|
||||
&& (record.data as { source: { kind: string } }).source.kind === 'agent-message'))
|
||||
&& (record.data as { source: { kind: string } }).source.kind === 'agent-message'
|
||||
&& (record.data as { source: { senderSessionId: string } }).source.senderSessionId !== root![0]?.id))
|
||||
expect(peerMessages).toHaveLength(2)
|
||||
const taskEvents = root!.filter(record => record.type === 'team/task')
|
||||
expect(taskEvents.filter((record) => {
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
{
|
||||
"name": "cua_run_code",
|
||||
"title": "Computer use program",
|
||||
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
|
||||
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
+4
-5
@@ -2,19 +2,18 @@
|
||||
{"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Delegated write probe","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash","agentReasoningEffort":"low"}}
|
||||
{"type":"sandbox/mode","data":{"mode":"read-only","source":"delegation"}}
|
||||
{"type":"approval/policy","data":{"policy":"never","source":"delegation"}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}}
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
|
||||
{"type":"session/title","data":{"title":"Use the write tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"child-write","name":"write","arguments":"{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"child-write","name":"write","args":["{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"child-write","name":"write","arguments":"{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":1,"callId":"child-write","name":"write","arguments":"{\"file_path\": \"inherited.txt\", \"content\": \"escaped\"}"}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"child-write"},"toolCallId":"child-write","content":[{"type":"text","text":"Error: [sandbox: file access denied under read-only mode]\n[sandbox: escalation available — retry this exact operation once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]"}],"isError":true,"id":"{{sessionId}}"},"error":{"name":"FsError","code":"FS_SANDBOX_DENIED"}},"sourceEventSeqs":[14],"surfaceOp":"append"}
|
||||
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"child-write"},"toolCallId":"child-write","content":[{"type":"text","text":"Error: [sandbox: file access denied under read-only mode]\n[sandbox: escalation available — retry this exact operation once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]"}],"isError":true,"id":"{{sessionId}}"},"error":{"name":"FsError","code":"FS_SANDBOX_DENIED"}},"sourceEventSeqs":[13],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":1}}
|
||||
{"type":"step/start","data":{"turn":1,"step":2}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["CHILD_DENIED [sandbox: file access denied under read-only mode]"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
|
||||
|
||||
+3
-4
@@ -2,16 +2,15 @@
|
||||
{"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Return child result","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash"}}
|
||||
{"type":"sandbox/mode","data":{"mode":"workspace-write","source":"delegation"}}
|
||||
{"type":"approval/policy","data":{"policy":"never","source":"delegation"}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}}
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it. Messages from other agents begin with \"Agent <name> sent a message:\". Other user messages come from the human user, who reads this conversation directly. You can still message other agents to coordinate, but answer the human user in your reply."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
|
||||
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
|
||||
{"type":"session/title","data":{"title":"Reply with exactly CHILD_RESULT and","messageSeqs":[8],"source":{"kind":"fallback"}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"CHILD_RESULT"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["CHILD_RESULT"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"CHILD_RESULT"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":1}}
|
||||
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
|
||||
@@ -18,7 +18,7 @@ function latestAssistantCalls(messages) {
|
||||
|
||||
function hasNewCoordinationInput(messages) {
|
||||
const toolIndex = messages.findLastIndex(message => message.role === 'tool')
|
||||
return messages.some((message, index) => index > toolIndex && message.role === 'user'
|
||||
return toolIndex >= 0 && messages.some((message, index) => index > toolIndex && message.role === 'user'
|
||||
&& ['agent-message', 'subagent-settled'].includes(message.source?.kind))
|
||||
}
|
||||
|
||||
@@ -191,13 +191,15 @@ function lead(messages) {
|
||||
class TeamFixtureAdapter extends LlmAdapter {
|
||||
async * stream(options) {
|
||||
const tools = options.tools.map(tool => tool.name)
|
||||
const initial = options.messages.findLast(message => message.role === 'user' && message.source.kind === 'user')
|
||||
const workflowChild = initial?.content[0]?.text === 'TEAM_WORKFLOW_CHILD'
|
||||
const initial = options.messages.find(message => message.role === 'user'
|
||||
&& ['user', 'agent-message'].includes(message.source.kind))
|
||||
const taskContent = initial?.source.kind === 'agent-message' ? initial.content.slice(1) : initial?.content
|
||||
const workflowChild = taskContent?.[0]?.text === 'TEAM_WORKFLOW_CHILD'
|
||||
const context = options.messages.findLast(message => message.source?.kind === 'runtime-context')
|
||||
const section = name => context?.source.sections?.find(candidate => candidate.name === name)?.text
|
||||
const role = section('subagent:identity')
|
||||
const parentId = role?.match(/You are a subagent delegated by agent "([^"]+)"/u)?.[1]
|
||||
const task = initial?.content.filter(block => block.type === 'text').map(block => block.text).join('\n')
|
||||
const task = taskContent?.filter(block => block.type === 'text').map(block => block.text).join('\n')
|
||||
if (!workflowChild && (!tools.includes('subagent') || !tools.includes('workflow') || !tools.includes('team_task_create'))) {
|
||||
throw new Error('Team profile is missing delegation, workflow, or task tools')
|
||||
}
|
||||
|
||||
@@ -1116,15 +1116,22 @@ describe('headless stream-json snapshots', () => {
|
||||
const parent = logs.find(log => typeof log.header.parentSession !== 'string')
|
||||
if (parent === undefined) throw new Error('Agent Teams snapshot did not persist its Lead')
|
||||
const rows = parseJsonl(parent.content)
|
||||
const workflowTask = [
|
||||
{ type: 'text', text: 'Agent lead sent a message: ' },
|
||||
{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' },
|
||||
]
|
||||
const workflowChild = logs.find(log => parseJsonl(log.content).some(row => row.type === 'user/message'
|
||||
&& JSON.stringify((row.data as JsonObject).content) === JSON.stringify([{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }])))
|
||||
&& JSON.stringify((row.data as JsonObject).content) === JSON.stringify(workflowTask)))
|
||||
if (workflowChild === undefined) throw new Error('Team profile did not persist its workflow child')
|
||||
const workflowRows = parseJsonl(workflowChild.content)
|
||||
expect(workflowRows.find(row => row.type === 'subagent/descriptor')?.data)
|
||||
.toMatchObject({ mode: 'continuable', provider: 'spawn' })
|
||||
expect(workflowRows.filter(row => row.type === 'user/message'
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'user').map(row => row.data))
|
||||
.toEqual([expect.objectContaining({ content: [{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }] })])
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'agent-message').map(row => row.data))
|
||||
.toEqual([expect.objectContaining({
|
||||
content: workflowTask,
|
||||
source: { kind: 'agent-message', form: 'relay', senderSessionId: parent.header.id },
|
||||
})])
|
||||
const teammates = rows.filter(row => row.type === 'subagent/catalog')
|
||||
.flatMap(row => typeof (row.data as JsonObject).label === 'string' && ((row.data as JsonObject).label as string).startsWith('Own deterministic ') ? [(row.data as JsonObject).label as string] : [])
|
||||
const tasks = rows.filter(row => row.type === 'team/task')
|
||||
@@ -1160,6 +1167,7 @@ describe('headless stream-json snapshots', () => {
|
||||
const source = (row.data as JsonObject).source
|
||||
return typeof source === 'object' && source !== null && !Array.isArray(source)
|
||||
&& (source as JsonObject).kind === 'agent-message'
|
||||
&& (source as JsonObject).senderSessionId !== parent.header.id
|
||||
})
|
||||
const openTurnStart = implementerRows.findLastIndex((row, index) => (
|
||||
index < steeredMessageIndex && row.type === 'turn/start'
|
||||
@@ -1176,11 +1184,11 @@ describe('headless stream-json snapshots', () => {
|
||||
const identities = logs.flatMap((log) => {
|
||||
if (log === parent || log === workflowChild) return []
|
||||
const initial = parseJsonl(log.content).find(row => row.type === 'user/message'
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'user')
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'agent-message')
|
||||
if (initial === undefined) throw new Error('Teammate Session has no initial task')
|
||||
const content = (initial.data as JsonObject).content as JsonObject[]
|
||||
// The task block is followed by the standard return guidance naming the Lead.
|
||||
expect(content).toHaveLength(2)
|
||||
expect(content).toHaveLength(3)
|
||||
expect(content[0]).toEqual({ type: 'text', text: 'Agent lead sent a message: ' })
|
||||
const context = parseJsonl(log.content).find(row => row.type === 'user/message'
|
||||
&& ((row.data as JsonObject).source as JsonObject).kind === 'runtime-context')
|
||||
const source = (context?.data as JsonObject)?.source as JsonObject
|
||||
|
||||
@@ -1141,7 +1141,7 @@ describe('a user preset declared from the shipped cordis rows', () => {
|
||||
expect(listed.isError).toBe(false)
|
||||
const providers = (JSON.parse(resultText(listed)) as { providers: Array<{ id: string; platform: string }> }).providers
|
||||
expect(providers.filter(provider => provider.platform === 'host').map(provider => provider.id))
|
||||
.toEqual(['Service', 'Event', 'Config', 'Tool'])
|
||||
.toEqual(['Service', 'Event', 'Config', 'Runtime', 'Tool'])
|
||||
|
||||
// The `Tool` provider is the one built over the host context: it
|
||||
// answers with the shared registry's view of the REQUESTING agent,
|
||||
|
||||
@@ -271,7 +271,20 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
|
||||
const opened = await context.newPage()
|
||||
tripwires.push(watchConsole(opened))
|
||||
await opened.addInitScript(() => {
|
||||
Object.defineProperty(globalThis, 'dshDesktop', { value: { protocolVersion: 1 } })
|
||||
// The update carrier stays idle until a scenario publishes a status for the account row.
|
||||
let update: { phase: string; version?: string } = { phase: 'idle' }
|
||||
const updateListeners = new Set<(state: typeof update) => void>()
|
||||
Object.defineProperty(globalThis, '__bonusPublishUpdate', {
|
||||
value: (state: typeof update) => { update = state; for (const listener of updateListeners) listener(state) },
|
||||
})
|
||||
Object.defineProperty(globalThis, 'dshDesktop', { value: { protocolVersion: 1, updates: {
|
||||
status: () => Promise.resolve(update),
|
||||
open: () => Promise.resolve(),
|
||||
subscribe: (listener: (state: typeof update) => void) => {
|
||||
updateListeners.add(listener)
|
||||
return () => { updateListeners.delete(listener) }
|
||||
},
|
||||
} } })
|
||||
// The embedded Platform view is a native child window owned by the Desktop shell.
|
||||
// The double answers immediately and records the calls, so the scenario observes
|
||||
// which page was opened and that returning destroyed the view.
|
||||
@@ -667,6 +680,30 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
|
||||
})
|
||||
expect(transition).toBe('0.25s ease-out')
|
||||
observations.push(`stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=${transition}`)
|
||||
// A Desktop update status shares the account row and leaves the card row at full width.
|
||||
const publishUpdate = (state: { phase: string; version?: string }) => stackPage.evaluate((value) => {
|
||||
(globalThis as typeof globalThis & { __bonusPublishUpdate: (next: typeof value) => void }).__bonusPublishUpdate(value)
|
||||
}, state)
|
||||
await publishUpdate({ phase: 'installing', version: '0.1.5' })
|
||||
const updateTag = stackPage.getByText('正在准备重启…', { exact: true })
|
||||
await updateTag.waitFor()
|
||||
const artifactDir = fileURLToPath(new URL('../../../.artifacts', import.meta.url))
|
||||
await mkdir(artifactDir, { recursive: true })
|
||||
await stackPage.screenshot({ path: join(artifactDir, 'bonus-notice-update-tag.png'), clip: { x: 0, y: 560, width: 420, height: 400 } })
|
||||
const taggedBox = await cards.first().boundingBox()
|
||||
const tagBox = await updateTag.boundingBox()
|
||||
const accountBox = await stackPage.getByRole('button', { name: '账号菜单', exact: true }).boundingBox()
|
||||
expect(taggedBox!.x).toBeCloseTo(10, 0)
|
||||
expect(taggedBox!.width).toBeCloseTo(260, 0)
|
||||
expect(taggedBox!.y + taggedBox!.height).toBeLessThanOrEqual(accountBox!.y)
|
||||
expect(tagBox!.y).toBeGreaterThanOrEqual(accountBox!.y)
|
||||
expect(tagBox!.y + tagBox!.height).toBeLessThanOrEqual(accountBox!.y + accountBox!.height)
|
||||
// The card floats over the session list: the list still reaches down to the card's bottom edge.
|
||||
const listBottom = await stackPage.locator('[class*="scrollRegion"]').first().evaluate(element => element.getBoundingClientRect().bottom)
|
||||
expect(listBottom).toBeGreaterThanOrEqual(taggedBox!.y + taggedBox!.height - 1)
|
||||
observations.push('stack.update-tag card=260 left-inset=10 card-above-account-row=true tag-in-account-row=true floats-over-list=true')
|
||||
await publishUpdate({ phase: 'idle' })
|
||||
await updateTag.waitFor({ state: 'detached' })
|
||||
for (const [delta, width, edge] of [[80, 280, 360], [-80, 260, 280]] as const) {
|
||||
const handle = await stackPage.locator('[data-side="sidebar"]').boundingBox()
|
||||
const x = handle!.x + handle!.width / 2
|
||||
@@ -700,8 +737,6 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
|
||||
expect(platform.acks.length).toBe(beforeCollapseAcks)
|
||||
expect(platform.dismissals.length).toBe(beforeCollapseDismissals)
|
||||
observations.push('stack.expanded cards=3 duplicate-acks=0 dismissed=0')
|
||||
const artifactDir = fileURLToPath(new URL('../../../.artifacts', import.meta.url))
|
||||
await mkdir(artifactDir, { recursive: true })
|
||||
await stackPage.screenshot({ path: join(artifactDir, 'bonus-notice-stack-light.png') })
|
||||
await stackPage.emulateMedia({ colorScheme: 'dark' })
|
||||
await expect.poll(() => stackPage.locator('body').getAttribute('data-ds-dark-theme')).not.toBeNull()
|
||||
@@ -736,6 +771,16 @@ describe.skipIf(MODE === 'record')('web e2e: bonus notice', () => {
|
||||
await expect.poll(() => platform.acks.length).toBe(ackStart + 2)
|
||||
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222'])
|
||||
observations.push('stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true')
|
||||
// In a short window the long card scrolls its copy instead of pushing the account row out of view.
|
||||
await stackPage.setViewportSize({ width: 1440, height: 390 })
|
||||
const shortAccount = await stackPage.getByRole('button', { name: '账号菜单', exact: true }).boundingBox()
|
||||
const shortCard = await second.boundingBox()
|
||||
const copyScrolls = await second.getByRole('status').evaluate(element => element.scrollHeight > element.clientHeight)
|
||||
expect(shortAccount!.y + shortAccount!.height).toBeLessThanOrEqual(390)
|
||||
expect(shortCard!.y + shortCard!.height).toBeLessThanOrEqual(shortAccount!.y)
|
||||
expect(copyScrolls).toBe(true)
|
||||
observations.push('stack.short-window account-row-visible=true card-above-account-row=true copy-scrolls=true')
|
||||
await stackPage.setViewportSize({ width: 1440, height: 960 })
|
||||
await second.getByRole('button', { name: '关闭', exact: true }).click()
|
||||
await expect.poll(() => platform.acks.length).toBe(ackStart + 3)
|
||||
expect(platform.acks.slice(ackStart).map(ack => ack.orderId)).toEqual(['a1111111-1111-4111-8111-111111111111', 'a2222222-2222-4222-8222-222222222222', 'a3333333-3333-4333-8333-333333333333'])
|
||||
|
||||
@@ -36,11 +36,13 @@ en.get locale=en_US query=
|
||||
web.notice=赠金已到账 / 已赠送您 4.00 元 DSH 体验赠金。 acks=1
|
||||
stack.hidden cards=3 acks=0
|
||||
stack.initial cards=3 acks=stack-first widths=260,252 inset=10 offset=-4 transition=0.25s ease-out
|
||||
stack.update-tag card=260 left-inset=10 card-above-account-row=true tag-in-account-row=true floats-over-list=true
|
||||
stack.resized sidebar=360 card=280 left-inset=10
|
||||
stack.resized sidebar=280 card=260 left-inset=10
|
||||
stack.rail cards=3 visible=false dismissed=0
|
||||
stack.expanded cards=3 duplicate-acks=0 dismissed=0
|
||||
stack.promoted cards=2 acks=stack-first,stack-second width=260 same-node=true
|
||||
stack.short-window account-row-visible=true card-above-account-row=true copy-scrolls=true
|
||||
stack.dismissed cards=0 acks=stack-first,stack-second,stack-third
|
||||
refresh.retained cards=3 acks=refresh-first same-node=true
|
||||
refresh.localized locale=en_US content-reads=3 list-reads=0 acks=1 same-node=true
|
||||
|
||||
@@ -12,10 +12,10 @@
|
||||
- button "调整「变更请求」的顺序"
|
||||
- list:
|
||||
- listitem:
|
||||
- img "变更请求状态:需要处理"
|
||||
- link "Add the pull request panel":
|
||||
- /url: https://github.com/octo/demo/pull/7
|
||||
- text: "#7 feat → main"
|
||||
- button "变更请求状态:需要处理 Add the pull request panel":
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: Add the pull request panel
|
||||
- text: "#7"
|
||||
- button "#7 的操作"
|
||||
- 'button "收起 #7" [expanded]'
|
||||
- button "检查 已加载 1 项检查,仍有更多"
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
- button "调整「变更请求」的顺序"
|
||||
- list:
|
||||
- listitem:
|
||||
- img "变更请求状态:需要处理"
|
||||
- link "Add the pull request panel":
|
||||
- /url: https://github.com/octo/demo/pull/7
|
||||
- text: "#7 feat → main"
|
||||
- button "变更请求状态:需要处理 Add the pull request panel":
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: Add the pull request panel
|
||||
- text: "#7"
|
||||
- button "#7 的操作"
|
||||
- 'button "收起 #7" [expanded]'
|
||||
- button "检查 已加载 1 项检查,仍有更多"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
- listitem:
|
||||
- img "变更请求状态:需要处理"
|
||||
- link "Add the pull request panel":
|
||||
- /url: https://github.com/octo/demo/pull/7
|
||||
- text: "#7 feat → main"
|
||||
- button "变更请求状态:需要处理 Add the pull request panel":
|
||||
- img "变更请求状态:需要处理"
|
||||
- text: Add the pull request panel
|
||||
- text: "#7"
|
||||
- button "#7 的操作"
|
||||
- 'button "收起 #7" [expanded]'
|
||||
- button "检查 已加载 1 项检查,仍有更多"
|
||||
|
||||
@@ -776,7 +776,7 @@ async function expectNumberedReference({ scaffold, page, project, tripwire }: Pa
|
||||
await page.getByRole('button', { name: TOGGLE_ATTENTION, exact: true }).waitFor({ timeout: 20_000 })
|
||||
await showSessionPanel(page)
|
||||
const change = page.locator(`[data-forge-change="${PULL}"]`)
|
||||
await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await change.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' }).waitFor({ timeout: 20_000 })
|
||||
await change.getByText('等待评审', { exact: true }).waitFor()
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'),
|
||||
await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE)
|
||||
@@ -884,7 +884,7 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
await page.getByRole('tooltip').filter({ hasText: `工作树(基于 release):${abbreviateHomePath(directory, homedir())}` }).waitFor()
|
||||
await page.mouse.move(0, 0)
|
||||
const change = panel.locator(`[data-forge-change="${PULL}"]`)
|
||||
const title = change.getByRole('link', { name: 'Add the pull request panel', exact: true })
|
||||
const title = change.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' })
|
||||
await title.waitFor({ timeout: 20_000 })
|
||||
// The only open change request starts expanded.
|
||||
await change.getByText('等待评审', { exact: true }).waitFor()
|
||||
@@ -954,6 +954,42 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('creates the requested worktree for the first message, not for the notice an access mode change queues before it', async () => {
|
||||
const { scaffold, page, project, tripwire } = await requestReleaseWorktree('web-e2e-forge-panel-access-mode')
|
||||
await page.locator('button[aria-label^="访问模式"]').first().click()
|
||||
await page.getByRole('menuitem', { name: '完全权限', exact: true }).click()
|
||||
const confirmation = page.getByRole('dialog', { name: '确认启用完全权限?' })
|
||||
await confirmation.getByRole('checkbox', { name: '我已了解风险,并愿意继续' }).check()
|
||||
await confirmation.getByRole('button', { name: '启用完全权限' }).click()
|
||||
await page.locator('button[aria-label="访问模式,当前:完全权限"]').waitFor()
|
||||
// The switch queues its approval notice for the next step, which opens no turn. A hold would run as maintenance of
|
||||
// the Agent until the worktree exists, and the Session would then work in it.
|
||||
const noticed = () => scaffold.ctx.agents.list()
|
||||
.find(candidate => candidate.inbox.nextStep.some(message => message.source.kind === 'user-approval'))
|
||||
await expect.poll(() => noticed() !== undefined).toBe(true)
|
||||
const agent = noticed()
|
||||
if (agent === undefined) throw new Error('The access mode change must queue its notice')
|
||||
await agent.runMaintenance(() => Promise.resolve())
|
||||
expect(scaffold.ctx.workingDirectory.get(agent.session)).toBe(project)
|
||||
|
||||
const { settled } = await sendPrompt(page, scaffold)
|
||||
const sessionId = await settled
|
||||
await page.getByText('LIGHTHOUSE', { exact: true }).waitFor()
|
||||
expect(sessionId).toBe(agent.session.id)
|
||||
|
||||
// The prompt opens the first turn, and its hold creates the worktree.
|
||||
const events = await readPersistedEvents(scaffold, sessionId)
|
||||
const queued = (target: 'next-step' | 'next-turn', kind: string): number => events.findIndex(event => event.type === 'agent/inbox/spliced'
|
||||
&& event.data.target === target && event.data.inserted.some(message => message.source.kind === kind))
|
||||
const created = events.findIndex(event => pluginRecordOf(event)?.type === 'plugin:worktree/created')
|
||||
expect(queued('next-step', 'user-approval')).toBeGreaterThan(-1)
|
||||
expect(queued('next-turn', 'user')).toBeGreaterThan(queued('next-step', 'user-approval'))
|
||||
expect(created).toBeGreaterThan(queued('next-turn', 'user'))
|
||||
expect(created).toBeLessThan(events.findIndex(event => event.type === 'turn/start'))
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
})
|
||||
|
||||
it.skipIf(MODE === 'record')('keeps the first message waiting when the worktree cannot be created, tries again, and sends it without the worktree', async () => {
|
||||
const { scaffold, page, project, tripwire } = await requestReleaseWorktree('web-e2e-forge-panel-failure')
|
||||
await git(project, 'branch', '--quiet', '-D', 'release')
|
||||
@@ -1004,7 +1040,7 @@ it.skipIf(MODE === 'record')('marks a draft change request ready for review and
|
||||
scaffold.ctx.forgeSession.track(session, DRAFT)
|
||||
await showSessionPanel(page)
|
||||
const change = page.locator(`[data-forge-change="${DRAFT}"]`)
|
||||
await change.getByRole('link', { name: 'Add the merge button', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await change.locator('[data-forge-opens]').filter({ hasText: 'Add the merge button' }).waitFor({ timeout: 20_000 })
|
||||
|
||||
// The only open change request starts expanded, so its Merge action shows once it is ready.
|
||||
await chooseCardAction(page, change, '#9', '标记为可评审')
|
||||
@@ -1137,7 +1173,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
|
||||
scaffold.ctx.forgeSession.track(session, PULL)
|
||||
await showSessionPanel(page)
|
||||
const change = page.locator(`[data-forge-change="${PULL}"]`)
|
||||
await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await change.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' }).waitFor({ timeout: 20_000 })
|
||||
await card.getByRole('button', { name: '本地变更 · 4 个文件,新增 4 行,删除 1 行', exact: true }).waitFor()
|
||||
// The open change request of the checked-out branch replaces the offer to create one.
|
||||
await card.getByRole('button', { name: '本地变更操作', exact: true }).click()
|
||||
@@ -1150,7 +1186,8 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
|
||||
await card.getByRole('button', { name: '本地变更 · 4 个文件,新增 4 行,删除 1 行', exact: true }).click()
|
||||
await local.getByText('暂存区与 HEAD 比较', { exact: true }).waitFor()
|
||||
await showSessionPanel(page)
|
||||
await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click()
|
||||
// A press on the card's line opens the changes, as its Changes row and its View changes item do.
|
||||
await change.locator('[data-forge-opens="changes"]').click()
|
||||
const view = page.locator('[data-forge-changes="change"]')
|
||||
const panelFile = view.locator('[data-forge-diff-file="src/panel.ts"]')
|
||||
const title = await view.getByText('Add the pull request panel', { exact: true }).boundingBox()
|
||||
@@ -1774,9 +1811,9 @@ it.skipIf(MODE === 'record')('aligns localized status rows by their glyphs in th
|
||||
width: document.documentElement.clientWidth,
|
||||
}
|
||||
})
|
||||
// The glyph starts 30px into the card, where the card's title starts.
|
||||
expect(geometry.iconInset).toBe(8)
|
||||
expect(geometry.rowInset).toBeGreaterThanOrEqual(6)
|
||||
expect(geometry.rowInset).toBeLessThanOrEqual(7)
|
||||
expect(geometry.rowInset).toBe(22)
|
||||
offsets.add(geometry.valueOffset)
|
||||
expect(geometry.gap).toBeGreaterThanOrEqual(8)
|
||||
expect(geometry.right).toBeLessThanOrEqual(geometry.width)
|
||||
@@ -2507,7 +2544,7 @@ it.skipIf(MODE === 'record')('summarizes checks, reviewers, and the merge state
|
||||
await showSessionPanel(page)
|
||||
const card = page.locator(`[data-forge-change="${PULL}"]`)
|
||||
// The card chooses its default expansion once its first status arrives, which names the title.
|
||||
await card.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
|
||||
await card.locator('[data-forge-opens]').filter({ hasText: 'Add the pull request panel' }).waitFor({ timeout: 20_000 })
|
||||
if (await card.getAttribute('data-expanded') === null) await card.getByRole('button', { name: '展开 #7', exact: true }).click()
|
||||
const checks = card.locator('[data-forge-checks]')
|
||||
await expect.poll(() => checks.textContent(), { timeout: 20_000 }).toBe('检查3 项失败 · 1 项进行中')
|
||||
|
||||
@@ -48,7 +48,7 @@ const LABEL = 'event-sourcing researcher'
|
||||
const CHILD_NAME = 'agent-1'
|
||||
const ONE_SHOT_LABEL = 'event-sourcing reviewer'
|
||||
const NESTED_LABEL = 'example editor'
|
||||
const CHILD_TITLE = 'Explain event sourcing in one'
|
||||
const CHILD_TITLE = 'Now give the same explanation'
|
||||
const PARENT_PROMPT = 'Ask a research subagent to explain event sourcing.'
|
||||
const INITIAL_PROMPT = 'Explain event sourcing in one sentence.'
|
||||
/** The grandchild's own first message; its arrival is what says its history finished loading. */
|
||||
@@ -693,7 +693,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
|
||||
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) })
|
||||
.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).click()
|
||||
const sidebarChat = page.locator('[data-sidebar-chat]')
|
||||
await sidebarChat.getByText(/^Explain event sourcing in one sentence\./).waitFor({ timeout: 15_000 })
|
||||
await sidebarChat.getByRole('button', { name: /^Task message received/ }).waitFor({ timeout: 15_000 })
|
||||
await compareOrRefreshGolden(
|
||||
SIDEBAR_CHAT_EXPECTED,
|
||||
await captureStableAria(page, '[data-sidebar-chat]', scaffold.workspaceCwd),
|
||||
@@ -715,7 +715,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-open'))
|
||||
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(LABEL, { exact: true }).click()
|
||||
await expect.poll(
|
||||
() => page.getByText(/^Explain event sourcing in one sentence\./).count(),
|
||||
() => page.getByRole('button', { name: /^Task message received/ }).count(),
|
||||
{ timeout: 15_000 },
|
||||
).toBe(1)
|
||||
if (scaffold.ctx.agents.get(childId) !== undefined) {
|
||||
@@ -773,7 +773,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
|
||||
await expect.poll(() => requested, { timeout: 15_000 }).toBe(true)
|
||||
expect(await page.getByText('This subagent is read-only for now', { exact: true }).count()).toBe(0)
|
||||
expect(await page.getByRole('navigation', { name: 'Session hierarchy' }).count()).toBe(0)
|
||||
expect(await page.getByText(/^Explain event sourcing in one sentence\./).count()).toBe(0)
|
||||
expect(await page.getByRole('button', { name: /^Task message received/ }).count()).toBe(0)
|
||||
releaseCatalog()
|
||||
await page.getByRole('button', { name: `Switch subagent: ${LABEL}` }).waitFor({ timeout: 15_000 })
|
||||
const input = page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' })
|
||||
|
||||
@@ -21,8 +21,8 @@ it('places the inherited-history divider between the parent turn and the child p
|
||||
const paths = await Promise.all(['session.v4.jsonl', 'session.1.v4.jsonl']
|
||||
.map(file => selectedSessionFixture(join(DIR, file))))
|
||||
const childPrompt = parseSessionLog(await readFile(paths[1]!, 'utf8')).findLast(event =>
|
||||
event.type === 'user/message' && event.data.source.kind === 'user')
|
||||
if (childPrompt?.type !== 'user/message') throw new Error('child fixture has no user prompt')
|
||||
event.type === 'user/message' && event.data.source.kind === 'agent-message')
|
||||
if (childPrompt?.type !== 'user/message') throw new Error('child fixture has no delegated task')
|
||||
const scaffold = await launchWebScaffold({
|
||||
replayFixture: paths[0]!, replayChildFixtures: [paths[1]!], compareReplaySession: false,
|
||||
})
|
||||
@@ -43,7 +43,7 @@ it('places the inherited-history divider between the parent turn and the child p
|
||||
|
||||
const activation = await scaffold.ctx.subagents.startActivation({
|
||||
provider: 'fork', label: LABEL, delivery: 'caller',
|
||||
signal: new AbortController().signal, parent, prompt: [...childPrompt.data.content],
|
||||
signal: new AbortController().signal, parent, prompt: childPrompt.data.content.slice(1),
|
||||
})
|
||||
try {
|
||||
await activation.result
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/** Forked Web agents inherit the standard preset and refuse every reminder tool. */
|
||||
/** Recorded Web subagent composition, tool restrictions, and human-message attribution. */
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { expect, it } from 'vitest'
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { SubagentPromptRequestId } from '@deepseek-ai/dsh-subagent'
|
||||
import { createUserMessage, type ContentBlock } from '@deepseek-ai/dsh-llm'
|
||||
import { parseSessionLog, prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import {
|
||||
@@ -27,7 +29,7 @@ const MODE = webSnapshotMode()
|
||||
it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a seeded Web fork', async () => {
|
||||
const paths = await Promise.all(['session.v4.jsonl', 'session.1.v4.jsonl']
|
||||
.map(file => selectedSessionFixture(join(DIR, file))))
|
||||
let expected = await Promise.all(paths.map(path => readFile(path, 'utf8')))
|
||||
const expected = await Promise.all(paths.map(path => readFile(path, 'utf8')))
|
||||
const scaffold = await launchWebScaffold({
|
||||
replayFixture: paths[0]!, replayChildFixtures: [paths[1]!], compareReplaySession: false,
|
||||
})
|
||||
@@ -42,13 +44,12 @@ it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a
|
||||
parent.followup(createUserMessage({ content: [{ type: 'text', text: prompt }], source: { kind: 'user' } }))
|
||||
await parent.whenIdle()
|
||||
|
||||
const childPrompt = parseSessionLog(expected[1]!).findLast(event => event.type === 'user/message'
|
||||
&& event.data.source.kind === 'user')
|
||||
if (childPrompt?.type !== 'user/message') throw new Error('child fixture has no user prompt')
|
||||
const childPrompt = fixtureChildInputs(expected[1]!)[0]
|
||||
if (childPrompt === undefined) throw new Error('child fixture has no delegated task')
|
||||
const activation = await scaffold.ctx.subagents.startActivation({
|
||||
provider: 'fork', label: 'Check child reminder refusal', delivery: 'caller',
|
||||
signal: new AbortController().signal,
|
||||
parent, prompt: [...childPrompt.data.content],
|
||||
parent, prompt: childPrompt,
|
||||
})
|
||||
try {
|
||||
await activation.result
|
||||
@@ -62,22 +63,6 @@ it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a
|
||||
expect(child.inheritedEventCount).toBeGreaterThan(0)
|
||||
expect(child.requestHeader()).toEqual(parent.session.requestHeader())
|
||||
|
||||
for (const session of sessions) {
|
||||
expect(await readPersistedEvents(scaffold, session.id)).toEqual(session.snapshotEvents())
|
||||
}
|
||||
const raw = sessions.map(session => normalizeWebSessionVolatiles(rawSessionLog(session), scaffold.workspaceCwd))
|
||||
const context = { sessionIds: sessions.map(session => String(session.id)), cwd: scaffold.workspaceCwd }
|
||||
const schemas = parseToolSchemasSnapshot(await readFile(join(PIN, 'tool-schemas.expected.json'), 'utf8'))
|
||||
const promptPin = await readFile(join(PIN, 'system-prompt.expected.md'), 'utf8')
|
||||
for (const log of raw) {
|
||||
const headers = normalizedToolSchemas(log, context)
|
||||
expect(headers.length).toBeGreaterThan(0)
|
||||
for (const tools of headers) expect(tools).toEqual(schemas.initial)
|
||||
for (const prompt of normalizedSystemPrompts(log, context)) {
|
||||
expect(formatSystemPromptSnapshot(prompt.split(REPO_ROOT).join('{{sourceRoot}}')
|
||||
.split(scaffold.baseUrl).join('{{webUrl}}'))).toBe(promptPin)
|
||||
}
|
||||
}
|
||||
const results = child.snapshotEvents().slice(child.inheritedEventCount)
|
||||
.filter(event => event.type === 'tool/result')
|
||||
expect(results.map(event => event.data.message.content)).toEqual(Array.from({ length: 4 }, () => [
|
||||
@@ -85,21 +70,115 @@ it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a
|
||||
]))
|
||||
expect((await scaffold.ctx.schedule.list({ active: true })).items).toEqual([])
|
||||
|
||||
if (MODE === 'refresh') {
|
||||
const replacements = refreshFixtureReplacements(raw.map((content, index) => ({
|
||||
id: sessions[index]!.id, createdAt: sessions[index]!.header.createdAt, content,
|
||||
})), expected)
|
||||
expected = redactSessionSnapshotIds(stabilizeFixtureMessageIds(raw.map((log, index) =>
|
||||
tokenizeSessionFixtureCwd(scrubSessionSnapshot(stabilizeRefreshLog(
|
||||
prepareSessionSnapshotFixtureForComparison(log), expected[index]!, replacements, context,
|
||||
))).split(scaffold.harnessHome).join('{{harnessHome}}')), expected))
|
||||
await Promise.all(expected.map((log, index) => writeFile(
|
||||
recordedSessionFixturePath(paths[index]!, sessions[index]!.header.version), log,
|
||||
)))
|
||||
}
|
||||
expect(normalizeSessionSnapshots(raw, context))
|
||||
.toEqual(normalizeSessionSnapshots(expected, fixtureContext(expected[0]!)))
|
||||
await assertSubagentSessions(scaffold, sessions, paths, expected)
|
||||
} finally {
|
||||
await scaffold.close()
|
||||
}
|
||||
})
|
||||
|
||||
const HUMAN_DIR = fileURLToPath(new URL('../../../snapshots/web/subagent-human-message', import.meta.url))
|
||||
|
||||
it.skipIf(MODE === 'record')('distinguishes the delegated task from a direct human message after a Web subagent cold resume', async () => {
|
||||
const paths = await Promise.all(['session.v4.jsonl', 'session.1.v4.jsonl']
|
||||
.map(file => selectedSessionFixture(join(HUMAN_DIR, file))))
|
||||
const expected = await Promise.all(paths.map(path => readFile(path, 'utf8')))
|
||||
const scaffold = await launchWebScaffold({
|
||||
replayFixture: paths[0]!, replayChildFixtures: [paths[1]!], compareReplaySession: false,
|
||||
})
|
||||
try {
|
||||
const { sessionId } = await scaffold.ctx.sessionController.create({ cwd: scaffold.workspaceCwd })
|
||||
const parent = scaffold.ctx.agents.get(sessionId)!
|
||||
parent.followup(createUserMessage({
|
||||
content: [{ type: 'text', text: fixtureUserPrompts(expected[0]!)[0]! }],
|
||||
source: { kind: 'user', rpcId: brandString<SubagentPromptRequestId>('root-question') },
|
||||
}))
|
||||
await parent.whenIdle()
|
||||
let child: Session | undefined
|
||||
scaffold.ctx.on('subagent/start', (info) => { child = scaffold.ctx.agents.get(info.id)!.session })
|
||||
const inputs = fixtureChildInputs(expected[1]!)
|
||||
const activation = await scaffold.ctx.subagents.startActivation({
|
||||
provider: 'fork', label: 'Identify direct human messages', delivery: 'caller',
|
||||
parent, prompt: inputs[0]!, signal: new AbortController().signal,
|
||||
})
|
||||
try {
|
||||
await activation.result
|
||||
} finally {
|
||||
await activation.dispose()
|
||||
}
|
||||
expect(scaffold.ctx.agents.get(activation.childId)).toBeUndefined()
|
||||
const settled = Promise.withResolvers<undefined>()
|
||||
scaffold.ctx.on('subagent/end', (info) => {
|
||||
if (info.id === activation.childId) settled.resolve(undefined)
|
||||
})
|
||||
const content = inputs[1]!.map((block) => {
|
||||
if (block.type !== 'text') throw new Error('human fixture input must be text')
|
||||
return block
|
||||
})
|
||||
const receipt = await scaffold.ctx.subagents.prompt({
|
||||
childSessionId: activation.childId,
|
||||
requestId: brandString<SubagentPromptRequestId>('human-question'), delivery: 'steer', content,
|
||||
}, new AbortController().signal)
|
||||
await settled.promise
|
||||
await parent.whenIdle()
|
||||
await scaffold.ctx.sessions.flush(parent.session)
|
||||
if (child === undefined) throw new Error('subagent start did not expose its Session')
|
||||
const received = child.deriveMessages().find(message => message.id === receipt.messageId)
|
||||
expect(received).toMatchObject({
|
||||
source: { kind: 'user', rpcId: 'human-question' },
|
||||
content,
|
||||
})
|
||||
await assertSubagentSessions(scaffold, [parent.session, child], paths, expected)
|
||||
} finally {
|
||||
await scaffold.close()
|
||||
}
|
||||
})
|
||||
|
||||
/** Compare durable parent/child logs and the shared Web request-header pins. */
|
||||
async function assertSubagentSessions(
|
||||
scaffold: Awaited<ReturnType<typeof launchWebScaffold>>,
|
||||
sessions: Session[],
|
||||
paths: string[],
|
||||
expected: string[],
|
||||
): Promise<void> {
|
||||
for (const session of sessions) {
|
||||
expect(await readPersistedEvents(scaffold, session.id)).toEqual(session.snapshotEvents())
|
||||
}
|
||||
const raw = sessions.map(session => normalizeWebSessionVolatiles(rawSessionLog(session), scaffold.workspaceCwd))
|
||||
const context = { sessionIds: sessions.map(session => String(session.id)), cwd: scaffold.workspaceCwd }
|
||||
const schemas = parseToolSchemasSnapshot(await readFile(join(PIN, 'tool-schemas.expected.json'), 'utf8'))
|
||||
const promptPin = await readFile(join(PIN, 'system-prompt.expected.md'), 'utf8')
|
||||
for (const log of raw) {
|
||||
const headers = normalizedToolSchemas(log, context)
|
||||
expect(headers.length).toBeGreaterThan(0)
|
||||
for (const tools of headers) expect(tools).toEqual(schemas.initial)
|
||||
for (const prompt of normalizedSystemPrompts(log, context)) {
|
||||
expect(formatSystemPromptSnapshot(prompt.split(REPO_ROOT).join('{{sourceRoot}}')
|
||||
.split(scaffold.baseUrl).join('{{webUrl}}'))).toBe(promptPin)
|
||||
}
|
||||
}
|
||||
if (MODE === 'refresh') {
|
||||
const replacements = refreshFixtureReplacements(raw.map((content, index) => ({
|
||||
id: sessions[index]!.id, createdAt: sessions[index]!.header.createdAt, content,
|
||||
})), expected)
|
||||
expected = redactSessionSnapshotIds(stabilizeFixtureMessageIds(raw.map((log, index) =>
|
||||
tokenizeSessionFixtureCwd(scrubSessionSnapshot(stabilizeRefreshLog(
|
||||
prepareSessionSnapshotFixtureForComparison(log), expected[index]!, replacements, context,
|
||||
))).split(scaffold.harnessHome).join('{{harnessHome}}')), expected))
|
||||
await Promise.all(expected.map((log, index) => writeFile(
|
||||
recordedSessionFixturePath(paths[index]!, sessions[index]!.header.version), log,
|
||||
)))
|
||||
}
|
||||
expect(normalizeSessionSnapshots(raw, context))
|
||||
.toEqual(normalizeSessionSnapshots(expected, fixtureContext(expected[0]!)))
|
||||
}
|
||||
|
||||
/** Read the child's admitted inputs, removing the parent prefix when recreating its initial task. */
|
||||
function fixtureChildInputs(log: string): ContentBlock[][] {
|
||||
const events = parseSessionLog(log)
|
||||
const start = events.findLastIndex(event => event.type === 'subagent/descriptor')
|
||||
return events.slice(start + 1).flatMap(event => event.type === 'agent/inbox/spliced'
|
||||
? event.data.inserted.map(message => message.source.kind === 'agent-message'
|
||||
? message.content.slice(1)
|
||||
: [...message.content])
|
||||
: [])
|
||||
}
|
||||
@@ -212,7 +212,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co
|
||||
await (await showSessionPanel(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).press('Enter')
|
||||
const input = page.locator('[data-composer-input]').first()
|
||||
await input.waitFor({ timeout: 15_000 })
|
||||
await page.getByText(/^Explain event sourcing in one sentence\./)
|
||||
await page.getByRole('button', { name: /^Task message received/ })
|
||||
.waitFor({ timeout: 15_000 })
|
||||
expect(await input.isDisabled()).toBe(false)
|
||||
const stop = page.getByRole('button', { name: 'Stop generating' })
|
||||
@@ -363,9 +363,18 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co
|
||||
&& event.data.source.kind === 'user'
|
||||
? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : [])
|
||||
: [])
|
||||
expect(userTexts[0]).toBe(INITIAL)
|
||||
expect(userTexts[1]).toMatch(/^Your final answer is delivered automatically if your parent is still online\./)
|
||||
expect(userTexts.slice(2)).toEqual([REARM, REARM_WAKE, EDITED_FOLLOWUP, WAKING])
|
||||
expect(userTexts).toEqual([REARM, REARM_WAKE, EDITED_FOLLOWUP, WAKING])
|
||||
const delegatedTask = events.find(event => event.type === 'user/message'
|
||||
&& event.data.source.kind === 'agent-message')
|
||||
const taskContent = delegatedTask?.type === 'user/message' ? delegatedTask.data.content : undefined
|
||||
expect(taskContent).toHaveLength(3)
|
||||
expect(taskContent?.slice(0, 2)).toEqual([
|
||||
{ type: 'text', text: 'Agent lead sent a message: ' },
|
||||
{ type: 'text', text: INITIAL },
|
||||
])
|
||||
const guidance = taskContent?.[2]
|
||||
expect(guidance?.type === 'text' && guidance.text)
|
||||
.toMatch(/^Your final answer is delivered automatically if your parent is still online\./)
|
||||
const imageMessage = events.find(event => event.type === 'user/message'
|
||||
&& event.data.content.some(block => block.type === 'image'))
|
||||
expect(imageMessage?.type === 'user/message' && imageMessage.data.content.map(block => block.type)).toEqual(['image'])
|
||||
|
||||
@@ -183,9 +183,18 @@ describe.skipIf(MODE === 'record')('web e2e: subagents/interruptByUser over the
|
||||
&& event.data.source.kind === 'user'
|
||||
? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : [])
|
||||
: [])
|
||||
expect(userTexts[0]).toBe(INITIAL)
|
||||
expect(userTexts[1]).toMatch(/^Your final answer is delivered automatically if your parent is still online\./)
|
||||
expect(userTexts.slice(2)).toEqual([FOLLOWUP, WAKING])
|
||||
expect(userTexts).toEqual([FOLLOWUP, WAKING])
|
||||
const delegatedTask = events.find(event => event.type === 'user/message'
|
||||
&& event.data.source.kind === 'agent-message')
|
||||
const taskContent = delegatedTask?.type === 'user/message' ? delegatedTask.data.content : undefined
|
||||
expect(taskContent).toHaveLength(3)
|
||||
expect(taskContent?.slice(0, 2)).toEqual([
|
||||
{ type: 'text', text: 'Agent lead sent a message: ' },
|
||||
{ type: 'text', text: INITIAL },
|
||||
])
|
||||
const guidance = taskContent?.[2]
|
||||
expect(guidance?.type === 'text' && guidance.text)
|
||||
.toMatch(/^Your final answer is delivered automatically if your parent is still online\./)
|
||||
const turnEndKinds = events
|
||||
.filter(event => event.type === 'turn/end')
|
||||
.map(event => (event).data.reason.kind)
|
||||
|
||||
@@ -173,7 +173,8 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () =
|
||||
await page.setViewportSize({ width: 1280, height: 800 })
|
||||
|
||||
await member.click()
|
||||
await page.getByText(CHILD_PROMPT, { exact: true }).waitFor({ timeout: 15_000 })
|
||||
await page.getByRole('button', { name: /^Task message received/ }).click()
|
||||
await page.getByText(`Agent lead sent a message: ${CHILD_PROMPT}`, { exact: true }).waitFor({ timeout: 15_000 })
|
||||
|
||||
const sessions = page.getByRole('tree', { name: 'Sessions' })
|
||||
await sessions.getByRole('treeitem', { name: /Use the workflow tool exactly/ }).click()
|
||||
@@ -221,7 +222,8 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () =
|
||||
|
||||
const catalog = (await showSessionPanel(page)).getByRole('tree', { name: 'Subagent sessions' })
|
||||
await catalog.getByRole('treeitem', { name: /snapshot-flow child 1/ }).press('Enter')
|
||||
await page.getByText(CHILD_PROMPT, { exact: true }).waitFor({ timeout: 15_000 })
|
||||
await page.getByRole('button', { name: /^Task message received/ }).click()
|
||||
await page.getByText(`Agent lead sent a message: ${CHILD_PROMPT}`, { exact: true }).waitFor({ timeout: 15_000 })
|
||||
expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(1)
|
||||
}, 60_000)
|
||||
|
||||
|
||||
@@ -2953,7 +2953,7 @@ export interface Config {
|
||||
timeoutMs?: number
|
||||
/** Maximum numeric elapsed budget accepted by resolve. */
|
||||
maxTimeoutMs?: number
|
||||
/** Combined serialized logs, completion and diagnostic byte cap. */
|
||||
/** Combined serialized output and completion or diagnostic cap; terminal data takes priority over captured output. */
|
||||
maxOutputBytes?: number
|
||||
/** V8 old-generation heap limit in MiB; native allocations are excluded. */
|
||||
maxOldGenerationSizeMb?: number
|
||||
|
||||
@@ -2955,7 +2955,7 @@ export interface Config {
|
||||
timeoutMs?: number
|
||||
/** Maximum numeric elapsed budget accepted by resolve. */
|
||||
maxTimeoutMs?: number
|
||||
/** Combined serialized logs, completion and diagnostic byte cap. */
|
||||
/** Combined serialized output and completion or diagnostic cap; terminal data takes priority over captured output. */
|
||||
maxOutputBytes?: number
|
||||
/** V8 old-generation heap limit in MiB; native allocations are excluded. */
|
||||
maxOldGenerationSizeMb?: number
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
en: a387577007373804
|
||||
zh: a330173368db598d
|
||||
/ptc-runtime/captured-output-and-the-failure-taxonomy:
|
||||
en: ef553620e77bd638
|
||||
zh: 40ff2f5ba3de5ed5
|
||||
en: 8d30aeb0fbd6001d
|
||||
zh: 5eb1cbc7f67bfae0
|
||||
/ptc-runtime/the-service:
|
||||
en: 67e0b628723fa962
|
||||
zh: 885994929216aa78
|
||||
@@ -101,6 +101,8 @@ interface PtcRunResult {
|
||||
* the outer result.
|
||||
*/
|
||||
output: PtcOutput[]
|
||||
/** Captured output or diagnostic text was truncated; execution still follows its normal completion, timeout and cancellation rules. */
|
||||
outputTruncated?: boolean
|
||||
/** Present iff the run failed; see {@link PtcRunFailure} for the taxonomy. */
|
||||
error?: PtcRunFailure
|
||||
}
|
||||
@@ -202,7 +204,7 @@ declare class PtcInspectableValue {
|
||||
|
||||
## Captured output and the failure taxonomy
|
||||
|
||||
`output` contains text and image entries in emission order: `{ type: 'text', text }` or `{ type: 'image', attachment }`. Text entries retain emitted newline characters; concatenate adjacent text without separators. Each source channel preserves emission order; interleaving across independent channels is backend-dependent. Host bindings return `PtcImage` descriptors containing the attachment reference and a readable execution-world `path`; the program receives an `Image` with that path and the stored pixel dimensions. The Node provider caps serialized text, image descriptors, and completion or diagnostic payloads together; overflow is an explicit failure.
|
||||
`output` contains text and image entries in emission order: `{ type: 'text', text }` or `{ type: 'image', attachment }`. Text entries retain emitted newline characters; concatenate adjacent text without separators. Each source channel preserves emission order; interleaving across independent channels is backend-dependent. Host bindings return `PtcImage` descriptors containing the attachment reference and a readable execution-world `path`; the program receives an `Image` with that path and the stored pixel dimensions. The Node provider caps serialized text, image descriptors, and completion or diagnostic payloads together; captured-output truncation is reported independently through `outputTruncated`, while required completion values remain lossless. See the [Node provider](../../packages/ptc-runtime/ptc-runtime-node/README.md) for budget priority and execution semantics.
|
||||
|
||||
```ts public-api
|
||||
/** A stored image readable from the program's execution environment. */
|
||||
@@ -239,7 +241,7 @@ Failure kinds are **orthogonal outcomes reported independently** (per [defensive
|
||||
* - `'abort'` — {@link PtcRunRequest.signal} fired.
|
||||
* - `'worker-exit'` — the execution substrate died without settling (e.g. OOM).
|
||||
* - `'invalid-output'` — the completion value was not lossless JSON.
|
||||
* - `'output-limit'` — the serialized outer logs/value/diagnostic exceeded the configured cap.
|
||||
* - `'output-limit'` — the required completion value exceeded the configured cap.
|
||||
* - `'protocol'` — the program sent invalid or over-budget control traffic.
|
||||
* - `'sandbox-unavailable'` — required confinement could not be established.
|
||||
*/
|
||||
|
||||
@@ -101,6 +101,8 @@ interface PtcRunResult {
|
||||
* the outer result.
|
||||
*/
|
||||
output: PtcOutput[]
|
||||
/** Captured output or diagnostic text was truncated; execution still follows its normal completion, timeout and cancellation rules. */
|
||||
outputTruncated?: boolean
|
||||
/** Present iff the run failed; see {@link PtcRunFailure} for the taxonomy. */
|
||||
error?: PtcRunFailure
|
||||
}
|
||||
@@ -202,7 +204,7 @@ declare class PtcInspectableValue {
|
||||
|
||||
## 捕获的输出与失败分类体系
|
||||
|
||||
`output` 按发出顺序保存文本和图片条目:文本使用 `{ type: 'text', text }`,图片使用 `{ type: 'image', attachment }`。文本条目保留实际输出的换行,相邻文本直接拼接,不额外插入分隔符。每个来源通道都保留发出顺序;独立通道之间的交错顺序由后端决定。宿主绑定返回 `PtcImage` 描述符,包含附件引用和可在执行环境读取的 `path`;程序收到带有该路径和存储像素尺寸的 `Image`。Node 提供方对序列化文本、图片描述符、完成值或诊断一起计量;超限会显式失败。
|
||||
`output` 按发出顺序保存文本和图片条目:文本使用 `{ type: 'text', text }`,图片使用 `{ type: 'image', attachment }`。文本条目保留实际输出的换行,相邻文本直接拼接,不额外插入分隔符。每个来源通道都保留发出顺序;独立通道之间的交错顺序由后端决定。宿主绑定返回 `PtcImage` 描述符,包含附件引用和可在执行环境读取的 `path`;程序收到带有该路径和存储像素尺寸的 `Image`。Node 提供方对序列化文本、图片描述符、完成值或诊断一起计量;捕获输出截断通过 `outputTruncated` 独立报告,要求返回的完成值保持无损。预算优先级与执行语义见 [Node 提供方](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md)。
|
||||
|
||||
```ts public-api
|
||||
/** A stored image readable from the program's execution environment. */
|
||||
@@ -239,7 +241,7 @@ type PtcOutput = { type: 'text'; text: string } | { type: 'image'; attachment: I
|
||||
* - `'abort'` — {@link PtcRunRequest.signal} fired.
|
||||
* - `'worker-exit'` — the execution substrate died without settling (e.g. OOM).
|
||||
* - `'invalid-output'` — the completion value was not lossless JSON.
|
||||
* - `'output-limit'` — the serialized outer logs/value/diagnostic exceeded the configured cap.
|
||||
* - `'output-limit'` — the required completion value exceeded the configured cap.
|
||||
* - `'protocol'` — the program sent invalid or over-budget control traffic.
|
||||
* - `'sandbox-unavailable'` — required confinement could not be established.
|
||||
*/
|
||||
|
||||
@@ -86,7 +86,7 @@ interface SubagentStartRequest {
|
||||
readonly agentPreset?: string
|
||||
/** Optional short display label persisted with a session-backed child. */
|
||||
readonly label?: string
|
||||
/** Content delivered as the child's user message. */
|
||||
/** Initial task; local continuable children record it as a message from the parent agent. */
|
||||
readonly prompt: ContentBlock[]
|
||||
/**
|
||||
* The spawning agent. Its effective directory supplies the default cwd;
|
||||
|
||||
@@ -86,7 +86,7 @@ interface SubagentStartRequest {
|
||||
readonly agentPreset?: string
|
||||
/** Optional short display label persisted with a session-backed child. */
|
||||
readonly label?: string
|
||||
/** Content delivered as the child's user message. */
|
||||
/** Initial task; local continuable children record it as a message from the parent agent. */
|
||||
readonly prompt: ContentBlock[]
|
||||
/**
|
||||
* The spawning agent. Its effective directory supplies the default cwd;
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: e0143916bb634762
|
||||
zh: e0143916bb634762
|
||||
/tool-schema-catalog/deepseek-ai-dsh-plugin-manager/plugin-manager:
|
||||
en: 2fbe2e5b88e81a54
|
||||
zh: a9de46c13bda53d8
|
||||
en: 8ad01461754a9c3b
|
||||
zh: 67eb5c02a821643a
|
||||
/tool-schema-catalog/deepseek-ai-dsh-plugin-market:
|
||||
en: 1ec7b4cbc3d98e28
|
||||
zh: 1ec7b4cbc3d98e28
|
||||
|
||||
@@ -60,7 +60,7 @@ This table connects model-visible tool names to the plugin package and service s
|
||||
|
||||
### `plugin_manager`
|
||||
|
||||
List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.
|
||||
List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. The application field of a change result is authoritative: applied means the change is in effect and needs no restart; any other value carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
|
||||
### `plugin_manager`
|
||||
|
||||
列出当前 profile 中的插件或组合包,启用或禁用它们,安装组合包或移除已安装的组合包。每项操作都要求 danger-full-access 权限或本次调用的批准。批准不改变会话权限模式。变更影响该 profile 的所有会话。先列出条目以获取准确标识。包安装可能运行已获批准的构建脚本。支持热更新的 profile 立即应用变更,包括已安装包的升级;未直接应用的变更结果带有 nextStep,说明下一步要做什么或告诉用户什么。不兼容的 DSH peer 依赖会阻止安装和激活。版本豁免可能导致崩溃和数据丢失:授权前必须警告用户,并获得用户对精确插件版本与运行时版本组合的明确许可。
|
||||
列出当前 profile 中的插件或组合包,启用或禁用它们,安装组合包或移除已安装的组合包。每项操作都要求 danger-full-access 权限或本次调用的批准。批准不改变会话权限模式。变更影响该 profile 的所有会话。先列出条目以获取准确标识。包安装可能运行已获批准的构建脚本。变更结果的 application 字段具有权威性:applied 表示变更已生效,无需重启;其他取值都带有 nextStep,说明下一步要做什么或告诉用户什么。不兼容的 DSH peer 依赖会阻止安装和激活。版本豁免可能导致崩溃和数据丢失:授权前必须警告用户,并获得用户对精确插件版本与运行时版本组合的明确许可。
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/ptc-output-limit/guide.md
|
||||
/:
|
||||
en: 0f89c66e70c37465
|
||||
zh: a80ca7a5c6b392bc
|
||||
/ptc-output-truncation:
|
||||
en: 7655f9eb80930413
|
||||
zh: 4664b640aa95291b
|
||||
/ptc-output-truncation/change:
|
||||
en: 55abb1d0227dc89a
|
||||
zh: 6a93f97e22ca90e0
|
||||
/ptc-output-truncation/migration:
|
||||
en: dfa6e80718350ca7
|
||||
zh: c06d1e686dff1938
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "PTC display-output overflow truncates output while execution continues."
|
||||
---
|
||||
|
||||
# PTC output truncation
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
The Node PTC runtime discards subsequent display output after `maxOutputBytes` is exhausted and continues execution under the original timeout and cancellation rules. Truncation alone no longer terminates the process or clears retained variables. This also applies to environment initialization.
|
||||
|
||||
`PtcRunResult.outputTruncated` marks truncated captured output or diagnostics independently of `error`. A later exception, timeout or cancellation keeps its actual failure kind. Required JSON completion values take priority over captured output and remain lossless; a completion that cannot fit still fails with `output-limit`.
|
||||
|
||||
`run_code` and tools created by `createRunCodeTool` return success when the program completes normally, with `outputTruncated: true` and a visible truncation notice. Failed runs retain their usual error codes and mention truncation. Historical Session records remain unchanged.
|
||||
|
||||
## Migration
|
||||
|
||||
1. Treat truncation as incomplete output, not evidence that execution stopped. Read current state for missing information; do not repeat completed actions merely to recover logs.
|
||||
2. Update runtime consumers to inspect `outputTruncated` separately from `error`. A successful required completion value remains complete even if captured output was truncated.
|
||||
3. Update custom Node bootstrap deployments together with the host: the private protocol revision is 5 and includes output suppression without cancellation. Bootstraps announcing revision 3 or 4 are rejected before program dispatch.
|
||||
4. Verify actions before and after output overflow both complete, retained variables survive, and later exceptions, timeouts and cancellation still report their original outcomes. To display a CUA screenshot, use `inspect(await window.getScreenshot())`.
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "PTC 展示输出超限后截断输出,程序继续执行。"
|
||||
---
|
||||
|
||||
# PTC 输出截断
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
Node PTC 运行时在耗尽 `maxOutputBytes` 后丢弃后续展示输出,执行仍遵循原有超时和取消规则。截断本身不再终止进程或清空保留变量,环境初始化也适用。
|
||||
|
||||
`PtcRunResult.outputTruncated` 标记捕获输出或诊断被截断,与 `error` 独立。后续异常、超时或取消保留实际失败类型。要求返回的 JSON 完成值优先于捕获输出,并保持无损;无法容纳的完成值仍以 `output-limit` 失败。
|
||||
|
||||
`run_code` 和通过 `createRunCodeTool` 创建的工具在程序正常结束时返回成功,携带 `outputTruncated: true` 和可见的截断提示。失败执行保留原有错误码,并说明输出截断。历史 Session 记录保持不变。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 将截断视为输出不完整,而非执行停止的证据。需要遗漏信息时读取当前状态;不要仅为恢复日志而重复已完成的动作。
|
||||
2. 更新运行时消费者,分别检查 `outputTruncated` 和 `error`。即使捕获输出被截断,成功返回的必需完成值仍然完整。
|
||||
3. 自定义 Node bootstrap 部署需与宿主一起更新:私有协议版本为 5,包含不取消执行的输出抑制操作。声明版本 3 或 4 的 bootstrap 会在程序分发前被拒绝。
|
||||
4. 验证超限前后的动作均会完成,保留变量仍可使用,且后续异常、超时和取消仍报告原来的结果。展示 CUA 截图时使用 `inspect(await window.getScreenshot())`。
|
||||
@@ -3,14 +3,14 @@
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md
|
||||
/:
|
||||
en: 31e27f1eb83f9740
|
||||
zh: 85c7c3637222f1d8
|
||||
/ptc-tool-result-inspection-and-bootstrap-protocol-4:
|
||||
en: 2509c4fe8d208eb8
|
||||
zh: 5f5dfd41fd29cd55
|
||||
/ptc-tool-result-inspection-and-bootstrap-protocol-4/change:
|
||||
en: a374fea86e00efb1
|
||||
zh: fa50515f25ef048e
|
||||
/ptc-tool-result-inspection-and-bootstrap-protocol-4/migration:
|
||||
en: bfb868b271b5113d
|
||||
zh: 597c95d985891d43
|
||||
en: 26e38cbd61901bf1
|
||||
zh: 9a172ed6093c0c44
|
||||
/ptc-tool-result-inspection-and-bootstrap-protocol-5:
|
||||
en: 5b9fde7497bdcff2
|
||||
zh: 54aed9165dffc06e
|
||||
/ptc-tool-result-inspection-and-bootstrap-protocol-5/change:
|
||||
en: 0dca4571f5c1cb2f
|
||||
zh: 9576d20ace4233b7
|
||||
/ptc-tool-result-inspection-and-bootstrap-protocol-5/migration:
|
||||
en: ec68709618b442e3
|
||||
zh: 8e579e9607f51b6c
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "Direct inspection of unchanged PTC object and array tool results uses tool-rendered text, and custom Node bootstraps require protocol 4."
|
||||
description: "Direct inspection of unchanged PTC object and array tool results uses tool-rendered text, and custom Node bootstraps require protocol 5."
|
||||
---
|
||||
|
||||
# PTC tool-result inspection and bootstrap protocol 4
|
||||
# PTC tool-result inspection and bootstrap protocol 5
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
@@ -15,7 +15,7 @@ Non-empty associated text occupies a separate output group. `inspect('result:',
|
||||
|
||||
Field selections, copies, modified results, and results nested inside another value still use generic formatting. Scalar results, Images, and mixed text/image outputs keep their behavior. This affects programs and checks that depend on the exact text produced by inspecting a complete tool result. Inspectable containers may retain Image fields: direct inspection shows the supplied text; inspect the image field separately to display it.
|
||||
|
||||
The Node bootstrap protocol changes from 3 to 4. `HostMethods.invoke` replies now use `{ value: flatWire, inspection?: string }`. Custom `launch.bootstrapPath` deployments must update their bootstrap; the bundled bootstrap updates with the host.
|
||||
The Node bootstrap protocol changes from 3 to 5. `HostMethods.invoke` replies now use `{ value: flatWire, inspection?: string }`. Custom `launch.bootstrapPath` deployments must update their bootstrap; the bundled bootstrap updates with the host.
|
||||
|
||||
## Migration
|
||||
|
||||
@@ -30,5 +30,5 @@ The Node bootstrap protocol changes from 3 to 4. `HostMethods.invoke` replies no
|
||||
|
||||
2. For an array result, use `inspect([...result])` to display its elements with generic formatting. Update any expected output that relied on the previous full-result object formatting.
|
||||
3. If you implement a third-party `PtcRuntime`, recognize `PtcInspectableValue` binding results from `@deepseek-ai/dsh-ptc-runtime`. Deliver `.value` as the program's object or array, and associate `.text` with that unchanged value for direct `inspect`. Do not expose the wrapper or add inspection metadata to program fields.
|
||||
4. If you configure `launch.bootstrapPath`, deploy the matching `@deepseek-ai/dsh-ptc-runtime-node` bootstrap and its dependencies in that execution environment. Use the package's built `lib/process.js`, or `lib/persistent-process.js` for a REPL default. A custom protocol implementation must handle the new reply envelope as well as announce protocol 4; changing the version alone is insufficient.
|
||||
4. If you configure `launch.bootstrapPath`, deploy the matching `@deepseek-ai/dsh-ptc-runtime-node` bootstrap and its dependencies in that execution environment. Use the package's built `lib/process.js`, or `lib/persistent-process.js` for a REPL default. A custom protocol implementation must handle the new reply envelope and [output suppression](../ptc-output-limit/guide.md), and announce protocol 5; changing the version alone is insufficient.
|
||||
5. Run the example above. Confirm that the first inspection shows the tool's rendered file text, while the other two show object and array data. For a custom provider, also confirm that field access and `JSON.stringify(result)` use the original data. For a custom bootstrap, confirm that a PTC program starts without a protocol-mismatch error.
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "直接展示未修改的 PTC 工具对象和数组结果时使用工具渲染文本,自定义 Node bootstrap 须升级到协议 4。"
|
||||
description: "直接展示未修改的 PTC 工具对象和数组结果时使用工具渲染文本,自定义 Node bootstrap 须升级到协议 5。"
|
||||
---
|
||||
|
||||
# PTC 工具结果展示与 bootstrap 协议 4
|
||||
# PTC 工具结果展示与 bootstrap 协议 5
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
@@ -15,7 +15,7 @@ PTC 工具保留声明的 JSON 返回值。无论是否附带展示元数据,
|
||||
|
||||
字段选择、拷贝、修改后的结果,以及嵌套在其他值中的结果,仍使用通用格式。标量结果、Image 和混合文本与图片的输出保持原有行为。依赖完整工具结果展示文本的程序和检查会受到影响。可展示的容器可以保留 Image 字段:直接展示容器时输出附带文本;单独展示图片字段时输出该图片。
|
||||
|
||||
Node bootstrap 协议从 3 升至 4。`HostMethods.invoke` 的回复现在使用 `{ value: flatWire, inspection?: string }`。自定义 `launch.bootstrapPath` 部署必须更新 bootstrap;内置 bootstrap 随宿主一同更新。
|
||||
Node bootstrap 协议从 3 升至 5。`HostMethods.invoke` 的回复现在使用 `{ value: flatWire, inspection?: string }`。自定义 `launch.bootstrapPath` 部署必须更新 bootstrap;内置 bootstrap 随宿主一同更新。
|
||||
|
||||
## 迁移
|
||||
|
||||
@@ -30,5 +30,5 @@ Node bootstrap 协议从 3 升至 4。`HostMethods.invoke` 的回复现在使用
|
||||
|
||||
2. 对数组结果,使用 `inspect([...result])` 以通用格式展示元素。更新依赖此前完整结果对象格式的预期输出。
|
||||
3. 如果实现了第三方 `PtcRuntime`,请识别绑定返回的 `@deepseek-ai/dsh-ptc-runtime` 包中的 `PtcInspectableValue`。将 `.value` 作为程序的对象或数组,并为该未修改的原值关联 `.text`,供直接 `inspect` 使用。不要暴露包装对象,也不要向程序字段添加展示元数据。
|
||||
4. 如果配置了 `launch.bootstrapPath`,请在执行环境中部署匹配版本的 `@deepseek-ai/dsh-ptc-runtime-node` bootstrap 及其依赖。使用包内构建产物 `lib/process.js`,或默认采用 REPL 的 `lib/persistent-process.js`。自定义协议实现必须处理新的回复信封并声明协议 4;只改版本号并不足够。
|
||||
4. 如果配置了 `launch.bootstrapPath`,请在执行环境中部署匹配版本的 `@deepseek-ai/dsh-ptc-runtime-node` bootstrap 及其依赖。使用包内构建产物 `lib/process.js`,或默认采用 REPL 的 `lib/persistent-process.js`。自定义协议实现必须处理新的回复信封和[输出抑制](../ptc-output-limit/guide.zh.md),并声明协议 5;只改版本号并不足够。
|
||||
5. 运行上面的示例。确认第一次展示工具渲染的文件文本,后两次分别展示对象和数组数据。对于自定义提供方,还须确认字段访问和 `JSON.stringify(result)` 使用原有数据。对于自定义 bootstrap,确认 PTC 程序启动时不再报告协议不匹配。
|
||||
@@ -0,0 +1,16 @@
|
||||
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/subagent-initial-task-source/guide.md
|
||||
/:
|
||||
en: 643defc5c1f7c556
|
||||
zh: d0eb87e9f9b8ab04
|
||||
/subagent-initial-tasks-are-agent-messages:
|
||||
en: d1488b39c6a3de61
|
||||
zh: 0fd2612274767091
|
||||
/subagent-initial-tasks-are-agent-messages/change:
|
||||
en: bace0953390241ba
|
||||
zh: 208b75e8f024d83f
|
||||
/subagent-initial-tasks-are-agent-messages/migration:
|
||||
en: 87f787e243c43531
|
||||
zh: fd05bf541be3ea63
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "In-process continuable subagents record their initial delegated task as an agent-message from the parent agent instead of a user message."
|
||||
---
|
||||
|
||||
# Subagent initial tasks are agent messages
|
||||
|
||||
English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
In-process continuable subagents started by `subagent-spawn-in-process` or `subagent-fork-in-process` record the initial delegated task as a message from the parent agent. Its `user/message` source changes from `{ "kind": "user" }` to `{ "kind": "agent-message", "form": "relay", "senderSessionId": "<parent Session id>" }`, and its content starts with a text block `Agent <parent name> sent a message: ` before the task blocks. Child Session logs, SDK Session event notifications, and Python SDK results show the new form. Sessions written earlier keep the old form.
|
||||
|
||||
Consumers that treat `user` sources as human input no longer apply to the task: `$skill` mentions in it do not load skills, Session references in it are not expanded, Markdown export and the turn outline omit it, and a child without human messages gets no fallback title. Direct human messages to a child keep the `user` source and their original content.
|
||||
|
||||
## Migration
|
||||
|
||||
1. Where code finds a child's task as its first `user`-source message, match an `agent-message` source whose `senderSessionId` equals the child Session's `parentSession`, and drop the first content block to read the task text. Keep accepting `user` for Sessions written before the upgrade.
|
||||
2. Where a delegated task relies on `$skill` to load a skill, name the skill in the task and let the child call the `skill` tool.
|
||||
3. Confirm by starting a continuable child and checking that its first non-context `user/message` has the `agent-message` source and the sender prefix.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
kind: upgrade-guide
|
||||
description: "进程内可续聊子 agent 的初始委派任务改为记录成来自父 agent 的 agent-message,不再是 user 消息。"
|
||||
---
|
||||
|
||||
# 子 agent 初始任务改为 agent 消息
|
||||
|
||||
[English](guide.md) | 中文
|
||||
|
||||
## 变更
|
||||
|
||||
由 `subagent-spawn-in-process` 或 `subagent-fork-in-process` 启动的进程内可续聊子 agent,把初始委派任务记录为来自父 agent 的消息。其 `user/message` 的 source 从 `{ "kind": "user" }` 变为 `{ "kind": "agent-message", "form": "relay", "senderSessionId": "<父级 Session id>" }`,正文在任务内容块之前多一个文本块 `Agent <parent name> sent a message: `。子 Session 日志、SDK Session 事件通知和 Python SDK 结果都使用新形式。升级前写入的 Session 保持旧形式。
|
||||
|
||||
把 `user` 来源当作真人输入的使用方不再作用于该任务:任务中的 `$skill` 不再加载 skill,任务中的 Session 引用不再展开,Markdown 导出与 turn 大纲不包含该任务,没有真人消息的子会话不再生成回退标题。真人直接发给子 agent 的消息保持 `user` 来源和原文。
|
||||
|
||||
## 迁移
|
||||
|
||||
1. 如果代码把子会话的第一条 `user` 来源消息当作任务,改为匹配 `senderSessionId` 等于子 Session `parentSession` 的 `agent-message` 来源,并去掉第一个内容块后读取任务文本。对升级前写入的 Session 仍接受 `user`。
|
||||
2. 如果委派任务依赖 `$skill` 加载 skill,改为在任务中写明 skill 名称,由子 agent 调用 `skill` 工具。
|
||||
3. 启动一个可续聊子 agent,确认其第一条非上下文 `user/message` 使用 `agent-message` 来源并带有发送方前缀。
|
||||
@@ -86,7 +86,7 @@ export const inject = ['tools', 'pluginManager', 'sandboxPolicy']
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.tools.register(defineTool({
|
||||
name: 'plugin_manager',
|
||||
description: 'List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.',
|
||||
description: 'List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. The application field of a change result is authoritative: applied means the change is in effect and needs no restart; any other value carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.',
|
||||
parameters: {
|
||||
action: { type: 'string', required: true, enum: ['list_plugins', 'list_bundles', 'set_plugin', 'set_bundle', 'install_bundle', 'remove_bundle', 'list_version_exemptions', 'set_version_exemption'], description: 'Management operation.' },
|
||||
target: { type: 'string', description: 'Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle.' },
|
||||
|
||||
@@ -9,14 +9,14 @@
|
||||
en: c8d24427c7fcd3aa
|
||||
zh: 5c0cf16f36ae6165
|
||||
/deepseek-ai-dsh-client-ui-account-notifications/summary:
|
||||
en: 46cf31a87b0b765c
|
||||
zh: 04f6b33570b046f7
|
||||
en: 81f1f0bcf51bad6b
|
||||
zh: 84a2a8bcc593f581
|
||||
/deepseek-ai-dsh-client-ui-account-notifications/table-of-contents:
|
||||
en: af856ba79fe31b8e
|
||||
zh: c9b0188689359236
|
||||
/deepseek-ai-dsh-client-ui-account-notifications/use-this-package:
|
||||
en: c466836df88d4ae1
|
||||
zh: 036e859139daa51d
|
||||
en: b138ea2fb39d73af
|
||||
zh: 71382a554aeae5ea
|
||||
/deepseek-ai-dsh-client-ui-account-notifications/model-experience:
|
||||
en: 5fed5504300020e6
|
||||
zh: efd8e7c32b699e7e
|
||||
@@ -27,5 +27,5 @@
|
||||
en: 0d59eea475321fd0
|
||||
zh: 1cf67a196e76b832
|
||||
/deepseek-ai-dsh-client-ui-account-notifications/known-limitations-and-deferred-work/dev-note:
|
||||
en: 64006edb418180b1
|
||||
zh: 12f7d7ab2cbccd43
|
||||
en: a7d8cbb5b6313e02
|
||||
zh: 83f0d8d6cd988d2e
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Show server-authored account notifications beside the account menu. Displayed cards survive later list omissions and refresh their content when the interface language changes.
|
||||
Show server-authored account notifications above the account menu. Displayed cards survive later list omissions and refresh their content when the interface language changes.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -20,13 +20,13 @@ Show server-authored account notifications beside the account menu. Displayed ca
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
The Web bundle includes this plugin with [account settings](../ui-settings-account/README.md). It contributes to `settings.launcher.notifications`; the account menu supplies visibility and the action that opens Account settings. The notification plugin owns cards, polling, localized content, and interaction reports.
|
||||
The Web bundle includes this plugin with [account settings](../ui-settings-account/README.md). It contributes to `settings.launcher.notifications`; account settings fills the settings shell's row above the account launcher with this slot and supplies visibility and the action that opens Account settings. The notification plugin owns cards, polling, localized content, and interaction reports.
|
||||
|
||||
Startup with a stored account, sign-in, and each Settings entry start a new polling cycle with an immediate request. `notificationPollIntervalMs` on the `ui-account-notifications` row supplies the initial delay, defaulting to 600,000 ms. A successful list response replaces it with `next_poll_after` seconds, including empty lists. The delay starts after the request settles; failures retain the latest delay, and restarting restores the configured initial value. Polling continues in the background.
|
||||
|
||||
Account settings owns the sole account stream and exposes its current state and lifecycle events through `accountUi` and `account-ui/change`. Login-progress updates retain cards and polling. Credential replacement, disconnection, access revocation, sign-out, and plugin disposal clear cards, stop polling, and discard late replies. Notification requests do not wait for profile or avatar data. Notification state is not stored in the browser.
|
||||
|
||||
Cards render inside the sidebar above the account launcher and below menus and dialogs without taking focus. Their width follows the expanded launcher up to 280px, leaving 10px on the left and at least 10px on the right. Collapsing the sidebar hides the cards; expanding it restores them without another display report. Closing a card promotes the next with a 250ms position and scale transition, disabled by reduced-motion preferences.
|
||||
Cards float over the sidebar list, anchored 4px above the account launcher row, below menus and dialogs, without taking focus or space from the list. Status indicators beside the launcher do not narrow them. Title and body text taller than 40% of the viewport scrolls inside the card, so a long notice does not cover the whole sidebar. Their width follows the expanded sidebar up to 280px, leaving 10px on the left and at least 10px on the right. Collapsing the sidebar hides the cards; expanding it restores them without another display report. Closing a card promotes the next with a 250ms position and scale transition, disabled by reduced-motion preferences.
|
||||
|
||||
Notifications wait for Desktop and model-credential onboarding to finish. Only the foreground card is interactive and reports `displayed`, once per mount after a painted frame while it intersects the viewport and the sidebar and document are visible. The Settings overlay does not exclude that frame. A displayed foreground card remains until close or expiry even when a later list omits it; waiting cards follow server order.
|
||||
|
||||
@@ -54,4 +54,4 @@ No model request prefix changes.
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
The package tests cover lifecycle ownership; the Web notification scenario checks the assembled account menu.
|
||||
The package tests cover lifecycle ownership; the Web notification scenario checks the assembled sidebar account rows.
|
||||
@@ -9,7 +9,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
在账号菜单旁展示服务端提供的账号通知。已展示卡片不会因后续列表省略而消失,并在界面语言切换时刷新内容。
|
||||
在账号菜单上方展示服务端提供的账号通知。已展示卡片不会因后续列表省略而消失,并在界面语言切换时刷新内容。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -20,13 +20,13 @@ kind: "package-reference"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用此包
|
||||
|
||||
Web 组合将本插件与[账号设置](../ui-settings-account/README.zh.md)一同加载。本插件向 `settings.launcher.notifications` 注册内容;账号菜单提供可见性和打开账号设置的操作。通知插件负责卡片、轮询、本地化内容和交互上报。
|
||||
Web 组合将本插件与[账号设置](../ui-settings-account/README.zh.md)一同加载。本插件向 `settings.launcher.notifications` 注册内容;账号设置在设置外壳位于账号入口上方的行中渲染该插槽,并提供可见性和打开账号设置的操作。通知插件负责卡片、轮询、本地化内容和交互上报。
|
||||
|
||||
带有已存账号的启动、登录及每次进入设置页都会启动新一轮轮询,并立即请求。`ui-account-notifications` 行中的 `notificationPollIntervalMs` 提供初始间隔,默认 600,000 ms。成功的列表响应通过 `next_poll_after` 秒替换间隔,空列表也相同。从请求结束时开始计时;失败沿用最近间隔,重启轮询恢复配置的初始值。轮询在后台继续。
|
||||
|
||||
账号设置拥有唯一的账号流,通过 `accountUi` 和 `account-ui/change` 提供当前状态及生命周期事件。登录进度更新沿用卡片和轮询。凭据替换、断连、权限撤销、退出登录和插件卸载会清空卡片、停止轮询并丢弃迟到响应。通知请求不等待资料或头像。通知状态不写入浏览器存储。
|
||||
|
||||
卡片在侧栏内部、账号入口上方渲染,位于菜单和对话框之下,不抢占焦点。宽度跟随展开的账号入口,最大为 280px,左侧留 10px、右侧至少留 10px。收起侧栏会隐藏卡片;展开后恢复卡片,不重复上报展示。关闭卡片后,下一张通过 250ms 的位置和缩放过渡补位;偏好减少动态效果时禁用过渡。
|
||||
卡片浮在侧栏列表之上,锚定在账号入口行上方 4px,位于菜单和对话框之下,不抢占焦点,也不占用列表空间。入口旁的状态指示器不会挤压卡片。标题和正文高度超过视口 40% 时在卡片内滚动,避免长通知遮住整个侧栏。宽度跟随展开的侧栏,最大为 280px,左侧留 10px、右侧至少留 10px。收起侧栏会隐藏卡片;展开后恢复卡片,不重复上报展示。关闭卡片后,下一张通过 250ms 的位置和缩放过渡补位;偏好减少动态效果时禁用过渡。
|
||||
|
||||
通知等待 Desktop 和模型凭据引导完成。只有前排卡片可交互并上报 `displayed`:卡片与视口相交、侧栏和文档可见并完成一帧绘制后,同一次挂载只上报一次。设置蒙层不排除该帧。已展示的前排卡片保留至关闭或过期,即使后续列表不再返回它;待展示卡片遵循服务端顺序。
|
||||
|
||||
@@ -54,4 +54,4 @@ Web 组合将本插件与[账号设置](../ui-settings-account/README.zh.md)一
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
包内测试覆盖生命周期所有权;Web 通知场景验证组合后的账号菜单。
|
||||
包内测试覆盖生命周期所有权;Web 通知场景验证组合后的侧栏账号行。
|
||||
@@ -1,10 +1,12 @@
|
||||
/* Each deeper card is centered 4px above the preceding card and narrows by the
|
||||
design's 252/260 ratio. The foreground alone determines the stack height. */
|
||||
.stack { position: relative; isolation: isolate; width: 100%; max-width: 280px; }
|
||||
.card { position: relative; box-sizing: border-box; width: 100%; padding: 20px; border: 0; border-radius: 16px; background: var(--dsw-specific-input-major); box-shadow: var(--dsw-elevation-panel); color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 22px; z-index: calc(0 - var(--notice-depth)); transform: translateY(calc(-4px * var(--notice-depth))) scaleX(var(--notice-scale)); transform-origin: center top; transition: transform 250ms ease-out; }
|
||||
.card { position: relative; box-sizing: border-box; width: 100%; padding: 20px; border: 0; border-radius: 16px; background: var(--dsw-specific-input-major); box-shadow: var(--dsw-elevation-panel); --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 22px; z-index: calc(0 - var(--notice-depth)); transform: translateY(calc(-4px * var(--notice-depth))) scaleX(var(--notice-scale)); transform-origin: center top; transition: transform 250ms ease-out; }
|
||||
.card[data-front="false"] { position: absolute; inset: 0; height: 100%; overflow: hidden; pointer-events: none; }
|
||||
@media (prefers-reduced-motion: reduce) { .card { transition: none; } }
|
||||
.copy { display: flex; flex-direction: column; gap: 2px; overflow-wrap: anywhere; }
|
||||
/* Long server copy scrolls inside the card so a tall notice does not cover the whole sidebar;
|
||||
the card rebinds the l2 scrollbar colors for its elevated surface (ui-theme styles/scrollbar.css). */
|
||||
.copy { display: flex; flex-direction: column; gap: 2px; max-height: 40vh; overflow-y: auto; overflow-wrap: anywhere; }
|
||||
.copy p { margin: 0; white-space: pre-wrap; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
|
||||
.action { max-width: 100%; height: auto; min-height: 28px; white-space: normal; overflow-wrap: anywhere; }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Notification extension rendered inside the sidebar account menu. */
|
||||
/** Notification extension rendered in the sidebar row above the account menu. */
|
||||
import { useEffect, useRef, type CSSProperties } from 'react'
|
||||
import { Button, IconCloseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
@@ -23,7 +23,7 @@ export interface AccountNotificationsInjected {
|
||||
export type AccountNotificationsProps = PropsRuntime<'settings.launcher.notifications'>
|
||||
& InjectFace<AccountNotificationsInjected> & PropsLocale<'account.notifications'>
|
||||
|
||||
/** @param props - account-menu availability and notification content. @returns the anchored notification stack. */
|
||||
/** @param props - account availability and notification content. @returns the notification stack. */
|
||||
export function AccountNotifications({ active, openAccount, useNotices, shown, ctaClicked, dismiss, t }: AccountNotificationsProps) {
|
||||
const notices = useNotices(value => value)
|
||||
return active && <AccountNoticeStack notices={notices} closeLabel={t('close')}
|
||||
|
||||
@@ -15,14 +15,14 @@
|
||||
en: c26f81e8adf0128b
|
||||
zh: e11ab371f51f66bc
|
||||
/deepseek-ai-dsh-client-ui-settings-account/use-this-package:
|
||||
en: 9e61a6adc39fddbc
|
||||
zh: fbcb4852ca4eded1
|
||||
en: 7a0e9f683d496167
|
||||
zh: 63a7278d96ecdd71
|
||||
/deepseek-ai-dsh-client-ui-settings-account/use-this-package/desktop-onboarding:
|
||||
en: 7ae4e68f9491b068
|
||||
zh: f7478269bf8d28b3
|
||||
en: b17e3d33f66af025
|
||||
zh: 780f813205d955d9
|
||||
/deepseek-ai-dsh-client-ui-settings-account/understand-the-implementation:
|
||||
en: a0da9e739f2aa682
|
||||
zh: 27aa6d13dba6f4b4
|
||||
en: 916a0c6e3d735da9
|
||||
zh: 0310dca3463e2201
|
||||
/deepseek-ai-dsh-client-ui-settings-account/further-exploration:
|
||||
en: f5ca95916ef486dc
|
||||
zh: 1e238d8299e0d838
|
||||
|
||||
@@ -52,7 +52,7 @@ The account card’s More account information link has no underline and opens th
|
||||
|
||||
Sign out first queries running account-token tasks and opens a confirmation dialog. The warning describes interruption when such tasks exist; otherwise it explains that data is retained and the account can be signed in again. Cancel, close, and Escape dismiss without signing out. Failed impact queries still open confirmation with an explicit unknown-task warning; failed sign-out keeps the dialog available for retry.
|
||||
|
||||
Account notification polling and presentation belong to [ui-account-notifications](../ui-account-notifications/README.md). The account menu positions the notification slot above its launcher inside the sidebar, keeps its DOM mounted while the rail hides it, and publishes account lifecycle and refresh events.
|
||||
Account notification polling and presentation belong to [ui-account-notifications](../ui-account-notifications/README.md). The plugin fills the settings shell's `settings.notice` row above the launcher row with the notification slot, and publishes account lifecycle and refresh events.
|
||||
|
||||
<a id="desktop-onboarding"></a>
|
||||
### Desktop onboarding
|
||||
@@ -61,12 +61,12 @@ The Desktop preload marker enables the introduction after account credentials ar
|
||||
|
||||
The welcome page requires Get started. The credit page always appears. A positive balance confirmed at first entry selects Continue as the primary action and Add credits as the secondary action. This choice stays fixed until the onboarding controller is recreated and is never persisted; late balance results cannot change the buttons. Only a confirmed absence of positive credit adds a confirmation before continuing without recharge; pending or failed queries do not block continuing. Purpose descriptions remain unchanged when selected. Returning from the native top-up view keeps the credit page and re-reads profile and balance in the background after any read already running, whether loading or payment succeeded. That read does not recompute the funded-mode choice, so a completed recharge leaves the buttons as first entered while continuing still evaluates the refreshed balance. Next confirms only a known zero balance; Skip uses the credit warning on the credit page and the setup warning on the question pages. Office-only use completes with compact presentation; development or both purposes also ask for process detail. Back preserves selections, and explicit skip from any supported step applies standard process, compact performance/usage, and disabled Coding Tools. This flow creates no workspace or demonstration task.
|
||||
|
||||
Access: the account stream, quota notice, settings launcher, account settings section, and models sign-in entry exist only while the current Peer may call `account/watch`; Desktop onboarding and the platform page are not gated. Losing that access discards the account reads that grant started, closes a pending authorization tab, and clears the account view, details, picture, and sign-in dialog state; a later grant shows the account section again once its first frame arrives. The owner always has access.
|
||||
Access: the account stream, quota notice, settings launcher, notification row, account settings section, and models sign-in entry exist only while the current Peer may call `account/watch`; Desktop onboarding and the platform page are not gated. Losing that access discards the account reads that grant started, closes a pending authorization tab, and clears the account view, details, picture, and sign-in dialog state; a later grant shows the account section again once its first frame arrives. The owner always has access.
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## Understand the implementation
|
||||
|
||||
The Account section appears first in Settings only while signed in; it is hidden before account state loads and after sign-out. The plugin owns one Host snapshot stream shared through framework hooks by settings.section and settings.launcher. The launcher opens Settings and offers Sign out only while an account credential is stored. Platform failures leave the menu available for retry. It maintains no independent credential state.
|
||||
The Account section appears first in Settings only while signed in; it is hidden before account state loads and after sign-out. The plugin owns one Host snapshot stream shared through framework hooks by settings.section, settings.launcher, and settings.notice. The launcher opens Settings and offers Sign out only while an account credential is stored. Platform failures leave the menu available for retry. It maintains no independent credential state.
|
||||
|
||||
The desktop controller writes progress to `ui-settings-account` through Host settings. Completion first applies `ui-chat.transcriptView` and `ui-chat.performanceUsage` together, then calls the shared Coding Tools preference to persist `ui-settings.enabled`, and finally saves the done marker; a rejected write keeps the flow available for retry. Successful completion reveals the workspace through a 180ms fade; choices and ordinary navigation preview immediately while writes run in order. A failed final queued write restores saved progress and allows retry. Completion waits for queued choices and retains the page until preferences persist; reduced motion skips the fade. Onboarding choices compact, standard, and detailed apply directly to the corresponding Chat work-detail modes. API-key entry and explicit skip select standard; onboarding does not select verbose. Complete Figma illustration layers ship as transparent, lossless 3× WebP [package assets](../AGENTS.md#dependency-declaration); welcome layers are merged with local sidebar blur; recharge uses a 70% opaque foreground window with local blur of the covered illustration, and headings use the bundled Montserrat brand font; English headings and descriptions use Light (300), except the DeepSeek Harness brand within headings uses Medium (500); card titles retain Regular (400) when selected. English footer navigation uses Light (300). Confirmed onboarding sets a 960px minimum window width and enlarges narrower windows; completion releases the minimum without restoring the previous size. Loading or already-completed onboarding does not resize the window. Empty footer navigation space passes pointer events through to the primary action. Cards exclude native window dragging and own the keyboard focus outline for their checkbox. The account package owns its onboarding overlay and control geometry. Each step and the confirmation dialog has a separate component; the flow coordinates navigation, transitions, and recharge. The overlay hides the workspace while initial account and progress state loads. Question headings and cards follow the Figma positions at 1440 × 920 and 960 × 600, independently of their action buttons. On macOS, the shell resets inherited window regions on each element, and a first-child drag band leaves an 8px native resize margin. The stage’s `data-window-drag-controls` scope excludes its interactive controls, later dialogs exclude their own boxes, and a native Platform page disables the underlying onboarding band. The upper workspace popup illustration has an opaque background in both languages and themes; the underlying sidebar omits its selected-row highlight. Welcome keeps its illustration at its original size, repositions and clips the artwork in narrow windows, and reveals the complete illustration on wide windows. The [historical onboarding decision](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md) owns persistence and presentation trade-offs.
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ Chat 通过 `shell.overlay` 中的宿主把已绑定 Session 的实时欠费交
|
||||
|
||||
退出登录先查询正在使用账号 token 的任务,再打开确认弹窗。有此类任务时提示执行将被打断,否则提示数据保留且可重新登录。取消、关闭和 Escape 均不退登。影响查询失败仍打开确认弹窗,并明确提示无法确认任务状态;退登失败保留弹窗以便重试。
|
||||
|
||||
账号通知的轮询与展示由 [ui-account-notifications](../ui-account-notifications/README.zh.md) 负责。账号菜单在侧栏内部将通知插槽定位于入口上方,收起为窄栏时隐藏但保留其 DOM,并发布账号生命周期和刷新事件。
|
||||
账号通知的轮询与展示由 [ui-account-notifications](../ui-account-notifications/README.zh.md) 负责。插件在设置外壳位于入口行上方的 `settings.notice` 行中渲染通知插槽,并发布账号生命周期和刷新事件。
|
||||
|
||||
<a id="desktop-onboarding"></a>
|
||||
### Desktop 引导
|
||||
@@ -61,12 +61,12 @@ Desktop preload 标记在账号凭证已存储后启用引导。进度属于本
|
||||
|
||||
欢迎页必须点击“开始设置”。额度页始终展示。首次进入时若已确认有正余额,则主操作为“继续”,次操作为“去充值”。该选择在引导控制器重建前保持固定且不持久化,后到的余额结果不会改变按钮。仅在确认不存在正余额时,继续而不充值才需确认;查询中或失败时不阻止继续。用途卡片选中后描述不变。从原生充值视图返回后保留额度页,并在等待任何已在进行的读取结束后于后台重读资料与余额,不受页面加载或支付结果影响。该读取不会重新计算该选择,因此充值成功后按钮仍保持首次进入时的状态,而继续前行仍按刷新后的余额判断。“下一步”仅在确认零余额时提示;额度页的“跳过”使用充值提示,答题页使用设置提示。仅选办公用途时以简洁展示完成;选择开发或两种用途时还会询问过程详情。上一步保留已有选择,任意可跳过步骤均采用标准工作过程、简洁性能与用量以及关闭代码工作工具的默认值。此流程不创建工作区或示例任务。
|
||||
|
||||
访问控制:账号状态流、额度提醒、设置启动器、账号设置分区与模型登录入口只在当前 Peer 可以调用 `account/watch` 时存在;桌面引导与平台页面不受此控制。失去该权限时,这一轮发出的账号读取作废,待授权的浏览器标签页关闭,账号视图、详情、头像与登录对话框状态清空;之后再次授权时,账号分区等新流的第一帧到达后才重新出现。owner 始终有权限。
|
||||
访问控制:账号状态流、额度提醒、设置启动器、通知行、账号设置分区与模型登录入口只在当前 Peer 可以调用 `account/watch` 时存在;桌面引导与平台页面不受此控制。失去该权限时,这一轮发出的账号读取作废,待授权的浏览器标签页关闭,账号视图、详情、头像与登录对话框状态清空;之后再次授权时,账号分区等新流的第一帧到达后才重新出现。owner 始终有权限。
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 理解实现
|
||||
|
||||
仅登录后在设置导航首位显示账号页;账号状态加载完成前以及退出登录后隐藏该页。 插件持有一条 Host 快照流,通过框架 hook 供 settings.section 和 settings.launcher 共享。入口菜单可打开设置,并仅在已存储账号凭证时提供退出登录。Platform 请求失败时保留菜单,以供重试。插件不维护独立凭证状态。
|
||||
仅登录后在设置导航首位显示账号页;账号状态加载完成前以及退出登录后隐藏该页。 插件持有一条 Host 快照流,通过框架 hook 供 settings.section、settings.launcher 和 settings.notice 共享。入口菜单可打开设置,并仅在已存储账号凭证时提供退出登录。Platform 请求失败时保留菜单,以供重试。插件不维护独立凭证状态。
|
||||
|
||||
桌面控制器通过 Host 设置将进度写入 `ui-settings-account`。完成时先一并应用 `ui-chat.transcriptView` 与 `ui-chat.performanceUsage`,再通过共享代码工作工具偏好保存 `ui-settings.enabled`,最后保存完成标记;写入被拒绝时保留引导以供重试。成功完成后通过 180ms 淡出显露工作区;选择和普通翻页立即预览,写入在后台按顺序执行。队列最后一次写入失败时恢复已保存进度,并允许重试。完成操作会等待选择队列及偏好保存成功,再关闭页面;减少动态效果偏好会跳过淡出。onboarding 选项 compact、standard、detailed 直接应用到对应的 Chat 工作过程模式。API Key 进入与显式跳过均采用 standard;onboarding 不选择 verbose。完整 Figma 示意图层以透明、无损编码的 3× WebP [包资源](../AGENTS.md#dependency-declaration)形式提供;欢迎页图层合并并烘焙侧栏局部模糊;充值页前景窗口不透明度为 70%,仅烘焙其覆盖插图区域的模糊,标题使用已打包的 Montserrat 品牌字体,英文标题和描述使用 Light(300),标题中的 DeepSeek Harness 使用 Medium(500);卡片标题选中前后均使用 Regular(400)。英文底部导航使用 Light(300)。确认进入引导后,窗口最小宽度设为 960px,较窄窗口自动放大;完成后解除宽度限制,但不恢复原尺寸。加载中或已完成引导的启动不改变窗口尺寸。底部导航空白区域透过鼠标事件,避免遮挡主操作。卡片区域不参与原生窗口拖动,复选框的键盘焦点仅在卡片外框展示。账号包负责引导覆盖层和控件尺寸样式。每个步骤和确认弹窗各有独立组件,流程组件协调导航、切换动画和充值。初始账号与进度加载期间,覆盖层隐藏工作区。答题标题和卡片独立于操作按钮,位置对齐 Figma 的 1440 × 920 和 960 × 600 断点。在 macOS 上,Shell 为每个元素重置继承的窗口区域,位于内容之前的拖拽层保留 8px 原生缩放边缘。内容层的 `data-window-drag-controls` 范围排除交互控件,后续弹窗排除自身矩形;原生平台页面打开时禁用底层引导拖拽层。上方工作区弹窗插画在两种语言和主题下均使用不透明背景,下层侧边栏不绘制选中行高亮。欢迎页保持示意图的原始尺寸,在窄窗口内调整插图位置并裁切,在宽窗口内展示完整插图。[历史引导决策](../../../.agents/notes/archived/feature/2026-09-16-desktop-onboarding.md)记录持久化与展示方面的取舍。
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
.root { position: relative; flex: 1; min-width: 0; }
|
||||
.root { flex: 1; min-width: 0; }
|
||||
.root[data-inset='true'] { margin-inline: 2px; }
|
||||
.notifications { position: absolute; inset-inline: 0; bottom: calc(100% + 4px); z-index: 1; }
|
||||
.anchor { width: 100%; }
|
||||
.trigger { user-select: none; display: flex; align-items: center; width: 100%; height: 44px; gap: 8px; padding: 6px calc(var(--dsh-sidebar-row-padding) - var(--dsh-sidebar-paint-inset)); border: 0; border-inline: var(--dsh-sidebar-paint-inset) solid transparent; box-sizing: border-box; border-radius: var(--dsw-radius-md); background: transparent; background-clip: padding-box; color: var(--dsw-alias-label-primary); font: inherit; font-size: 14px; cursor: pointer; }
|
||||
.trigger[data-signed-out='false']:not([data-collapsed='true']) { padding: 6px; border-inline: 0; background-clip: border-box; }
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/** Sidebar account launcher and locally authoritative sign-out action. */
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Toast, Menu, IconEllipsisOutlineMedium, IconPaperPlaneOutlineMedium, IconSettingsOutlineMedium, IconUserOutlineMedium,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { InjectFace, PropsLocale, PropsRuntime, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { AccountSectionInjected } from './AccountSection.tsx'
|
||||
import { SignOutDialog } from './SignOutDialog.tsx'
|
||||
import { SignInDialog } from './SignInDialog.tsx'
|
||||
@@ -13,7 +13,7 @@ import type {} from './account-ui.ts'
|
||||
import css from './AccountMenu.module.css'
|
||||
|
||||
/** Account launcher composed by the settings shell. */
|
||||
export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsRenderSlots<'settings.launcher.notifications'> & PropsLocale<'settings.account'> & InjectFace<AccountSectionInjected>
|
||||
export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsLocale<'settings.account'> & InjectFace<AccountSectionInjected>
|
||||
|
||||
/** The signed-in label stays empty while the profile loads.
|
||||
* @param props - sidebar geometry, settings navigation and account operations.
|
||||
@@ -21,7 +21,7 @@ export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsRenderSl
|
||||
*/
|
||||
export function AccountMenu({
|
||||
subscribeSessionExpired, subscribeModelSignInRequired, wide, settingsShortcut, openSettings, openOnboarding, settingsOpen,
|
||||
useAccount, useTheme, signOut, hasRunningAccountTasks, refreshAccount, renderSlot,
|
||||
useAccount, useTheme, signOut, hasRunningAccountTasks, refreshAccount,
|
||||
contactUs, showLogin, start, cancel, avatarFailed, t,
|
||||
}: AccountMenuProps) {
|
||||
// The launcher outlives the panel, so a false-to-true edge is one Settings entry:
|
||||
@@ -53,13 +53,9 @@ export function AccountMenu({
|
||||
}
|
||||
// The plugin's start publishes `loginFailed` before it rejects, so the dialog owns the report.
|
||||
const beginSignIn = (): void => { setOpen(false); void start().catch(() => undefined) }
|
||||
const openAccount = useCallback(() => { openSettings('account') }, [openSettings])
|
||||
return <div className={css.root} data-inset={signedIn && wide}>
|
||||
{signInNotice > 0 && <Toast key={signInNotice} text={t('modelSignInRequired')} onDone={() => { setSignInNotice(0) }} />}
|
||||
{expiryNotice && <Toast text={t('sessionExpired')} onDone={() => { setExpiryNotice(false) }} />}
|
||||
<div className={css.notifications} hidden={!wide}>{renderSlot('settings.launcher.notifications', {
|
||||
active: signedIn && !account.desktopOnboardingVisible && !account.onboarding, openAccount,
|
||||
})}</div>
|
||||
<Menu open={open} side="top" portal autoFocus className={css.anchor} listClassName={signedIn ? undefined : css.signedOutMenu}
|
||||
anchor={<button ref={trigger} type="button" className={css.trigger} data-collapsed={!wide} data-signed-out={!signedIn} aria-label={t('menu')}
|
||||
aria-haspopup="menu" aria-expanded={open} onClick={() => { setOpen(value => !value) }}>
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/* Matches the signed-in launcher inset so the card edges align with the account row. */
|
||||
.root { margin-inline: 2px; }
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Account notification row above the sidebar account launcher. */
|
||||
import type { InjectFace, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { AccountSectionInjected } from './AccountSection.tsx'
|
||||
import type {} from './account-ui.ts'
|
||||
import css from './AccountNotices.module.css'
|
||||
|
||||
/** Notice row composed by the settings shell. */
|
||||
export type AccountNoticesProps = PropsRuntime<'settings.notice'>
|
||||
& PropsRenderSlots<'settings.launcher.notifications'> & InjectFace<AccountSectionInjected>
|
||||
|
||||
/**
|
||||
* @param props - settings navigation and account state.
|
||||
* @returns the account notification extension, active only when signed in outside onboarding.
|
||||
*/
|
||||
export function AccountNotices({ openSettings, useAccount, renderSlot }: AccountNoticesProps) {
|
||||
const account = useAccount(state => state)
|
||||
const active = account.view?.status === 'credential-stored' && !account.desktopOnboardingVisible && !account.onboarding
|
||||
return <div className={css.root}>{renderSlot('settings.launcher.notifications', {
|
||||
active, openAccount: () => { openSettings('account') },
|
||||
})}</div>
|
||||
}
|
||||
@@ -20,9 +20,9 @@ export interface AccountUi {
|
||||
clientMetadata(locale: string): AccountClientMetadata
|
||||
}
|
||||
|
||||
/** Account-menu presentation facts supplied to its notification extension. */
|
||||
/** Account presentation facts supplied to its notification extension. */
|
||||
export interface AccountNotificationsOwnerProps {
|
||||
/** Whether the account menu can display notifications outside onboarding. */
|
||||
/** Whether a signed-in account can display notifications outside onboarding. */
|
||||
active: boolean
|
||||
/** Open the account section in the existing settings shell. */
|
||||
openAccount: () => void
|
||||
@@ -43,7 +43,7 @@ declare module '@deepseek-ai/cordis' {
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface SlotMap {
|
||||
/** Notifications anchored at the account menu; the contribution owns its markup and lifecycle. */
|
||||
/** Notifications in the row above the account launcher; the contribution owns its markup and lifecycle. */
|
||||
'settings.launcher.notifications': { kind: 'single'; scope: 'root'; owner: AccountNotificationsOwnerProps }
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { BrowserLogin } from './browser-login.ts'
|
||||
import { AccountOnboarding } from './AccountOnboarding.tsx'
|
||||
import { AccountPlatformHost, type AccountPlatformHostInjected } from './AccountPlatformHost.tsx'
|
||||
import { AccountMenu } from './AccountMenu.tsx'
|
||||
import { AccountNotices } from './AccountNotices.tsx'
|
||||
import { createPlatformPages, type PlatformPages } from './platform-pages.ts'
|
||||
import { AccountSection, type AccountSnapshot, type AccountSectionInjected } from './AccountSection.tsx'
|
||||
import { accountClientMetadata } from './client-metadata.ts'
|
||||
@@ -313,8 +314,11 @@ export function apply(ctx: Context): void {
|
||||
}
|
||||
ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.launcher', () => ctx.slots.register({
|
||||
name: 'settings.launcher', locale: 'settings.account', inject: () => operations,
|
||||
children: { 'settings.launcher.notifications': { kind: 'single', scope: 'root' } },
|
||||
}, AccountMenu)))
|
||||
ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.notice', () => ctx.slots.register({
|
||||
name: 'settings.notice', inject: () => operations,
|
||||
children: { 'settings.launcher.notifications': { kind: 'single', scope: 'root' } },
|
||||
}, AccountNotices)))
|
||||
ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.section', () => {
|
||||
let unregister: (() => void) | undefined
|
||||
const update = () => {
|
||||
|
||||
@@ -92,22 +92,22 @@ it('withdraws every account surface and the account stream on revocation, and re
|
||||
},
|
||||
}
|
||||
const surfaces = (): Record<string, number | undefined> => Object.fromEntries(
|
||||
['settings.launcher', 'shell.quota-notice', 'settings.models.sign-in', 'settings.section'].map(name => [name, registered.get(name)]),
|
||||
['settings.launcher', 'settings.notice', 'shell.quota-notice', 'settings.models.sign-in', 'settings.section'].map(name => [name, registered.get(name)]),
|
||||
)
|
||||
try {
|
||||
apply(ctx as never)
|
||||
expect(new Set(guards.map(guard => guard.action))).toEqual(new Set(['account/watch']))
|
||||
grant(guards)
|
||||
await streams[0]!.accepted
|
||||
expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 })
|
||||
expect(surfaces()).toEqual({ 'settings.launcher': 1, 'settings.notice': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 })
|
||||
|
||||
revoke(guards)
|
||||
expect(streams[0]!.signal.aborted).toBe(true)
|
||||
expect(surfaces()).toEqual({ 'settings.launcher': 0, 'shell.quota-notice': 0, 'settings.models.sign-in': 0, 'settings.section': 0 })
|
||||
expect(surfaces()).toEqual({ 'settings.launcher': 0, 'settings.notice': 0, 'shell.quota-notice': 0, 'settings.models.sign-in': 0, 'settings.section': 0 })
|
||||
|
||||
grant(guards)
|
||||
await streams[1]!.accepted
|
||||
expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 })
|
||||
expect(surfaces()).toEqual({ 'settings.launcher': 1, 'settings.notice': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 })
|
||||
} finally {
|
||||
revoke(guards)
|
||||
for (const dispose of lifetime.reverse()) dispose()
|
||||
|
||||
@@ -10,6 +10,7 @@ import { createPlatformPages, type PlatformPages } from '../src/client/platform-
|
||||
import { AccountPlatformHost } from '../src/client/AccountPlatformHost.tsx'
|
||||
import { AccountSection, type AccountSectionInjected, type AccountSnapshot } from '../src/client/AccountSection.tsx'
|
||||
import type { AccountMenuProps } from '../src/client/AccountMenu.tsx'
|
||||
import type { AccountNoticesProps } from '../src/client/AccountNotices.tsx'
|
||||
import type { AccountNotificationsOwnerProps } from '../src/client/account-ui.ts'
|
||||
import type {} from '../src/client/index.ts'
|
||||
import { en, zh, type AccountKey } from '../src/client/locales.ts'
|
||||
@@ -92,14 +93,12 @@ function SharedPlatformHost({ Globals, pages, platform, copy, refreshAccount }:
|
||||
* @param settingsOpen - whether the settings panel covers the sidebar.
|
||||
* @returns the sidebar launcher with its framework hooks wired to the test face.
|
||||
*/
|
||||
async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean,
|
||||
renderSlot: AccountMenuProps['renderSlot'] = () => null,
|
||||
openSettings: AccountMenuProps['openSettings'] = () => {}, wide = true) {
|
||||
async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean) {
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
return <AccountMenu renderSlot={renderSlot} {...({} as GlobalStandardProps)} {...operations}
|
||||
settingsOpen={settingsOpen} useAccount={selector => selector(snapshot())} wide={wide}
|
||||
return <AccountMenu {...({} as GlobalStandardProps)} {...operations}
|
||||
settingsOpen={settingsOpen} useAccount={selector => selector(snapshot())} wide
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())}
|
||||
openOnboarding={() => {}} openSettings={openSettings} t={key => en[key as AccountKey]} />
|
||||
openOnboarding={() => {}} openSettings={() => {}} t={key => en[key as AccountKey]} />
|
||||
}
|
||||
|
||||
it.each([en, zh])('renders account cards without inventing profile or balance data', async (copy) => {
|
||||
@@ -129,7 +128,7 @@ it.each([en, zh].flatMap(copy => ([false, true, 'unknown'] as const).map(running
|
||||
const operations = mount({ status: 'credential-stored', attempt: null }, copy)
|
||||
cleanup()
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
render(<AccountMenu renderSlot={() => null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} signOut={signOut}
|
||||
render(<AccountMenu {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} signOut={signOut}
|
||||
hasRunningAccountTasks={async () => { if (running === 'unknown') throw new Error('offline'); return running }}
|
||||
useAccount={selector => selector(operations.hooks.account.getSnapshot())}
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings}
|
||||
@@ -156,7 +155,7 @@ it.each([en, zh])('updates the Settings menu keycaps and accessible combination
|
||||
const operations = mount({ status: 'signed-out', attempt: null }, copy)
|
||||
cleanup()
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
const props: AccountMenuProps = { renderSlot: () => null,
|
||||
const props: AccountMenuProps = {
|
||||
...({} as GlobalStandardProps), ...operations, wide: true, settingsOpen: false,
|
||||
useAccount: selector => selector(operations.hooks.account.getSnapshot()),
|
||||
useTheme: selector => selector(operations.hooks.theme.getSnapshot()),
|
||||
@@ -185,7 +184,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco
|
||||
const openSettings = vi.fn()
|
||||
const operations = operationsOf({ status: 'signed-out', attempt: null })
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
render(<AccountMenu renderSlot={() => null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
render(<AccountMenu {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
useAccount={selector => selector(operations.hooks.account.getSnapshot())}
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings}
|
||||
t={key => key in copy ? copy[key as AccountKey] : key} />)
|
||||
@@ -205,7 +204,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco
|
||||
it.each([true, false])('keeps the account inset local through sign-in changes with wide=%s', async (wide) => {
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
let operations = operationsOf({ status: 'signed-out', attempt: null })
|
||||
const props: AccountMenuProps = { renderSlot: () => null,
|
||||
const props: AccountMenuProps = {
|
||||
...({} as GlobalStandardProps), ...operations, wide, settingsOpen: false,
|
||||
useAccount: selector => selector(operations.hooks.account.getSnapshot()),
|
||||
useTheme: selector => selector(operations.hooks.theme.getSnapshot()),
|
||||
@@ -237,7 +236,7 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async (
|
||||
snapshot = { ...snapshot, loginVisible: true, loginFailed: true }
|
||||
return Promise.reject(new Error('account start failed'))
|
||||
})
|
||||
const view = render(<AccountMenu renderSlot={() => null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
const view = render(<AccountMenu {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
start={start}
|
||||
useAccount={selector => selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())}
|
||||
wide openOnboarding={() => {}} openSettings={() => {}}
|
||||
@@ -246,7 +245,7 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async (
|
||||
await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: en.signIn })) })
|
||||
expect(start).toHaveBeenCalledOnce()
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
view.rerender(<AccountMenu renderSlot={() => null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
view.rerender(<AccountMenu {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
start={start}
|
||||
useAccount={selector => selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())}
|
||||
wide openOnboarding={() => {}} openSettings={() => {}}
|
||||
@@ -263,7 +262,7 @@ it('keeps the confirmation dialog open after a failed sign-out', async () => {
|
||||
cleanup()
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
const signOut = vi.fn((): Promise<void> => Promise.reject(new Error('account sign-out failed')))
|
||||
render(<AccountMenu renderSlot={() => null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
render(<AccountMenu {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
signOut={signOut}
|
||||
useAccount={selector => selector(operations.hooks.account.getSnapshot())}
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide
|
||||
@@ -426,7 +425,7 @@ it.each([
|
||||
})
|
||||
cleanup()
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
render(<AccountMenu renderSlot={() => null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
render(<AccountMenu {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
useAccount={selector => selector(operations.hooks.account.getSnapshot())}
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())}
|
||||
wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />)
|
||||
@@ -439,7 +438,7 @@ it('shows the same shared picture outcome in settings and the sidebar', async ()
|
||||
profile: { status: 'ready', value: { id: null, name: 'User', contact: null, avatarUrl: 'https://example.test/avatar.png' } },
|
||||
}, undefined, avatar)
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
render(<AccountMenu renderSlot={() => null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
render(<AccountMenu {...({} as GlobalStandardProps)} {...operations} settingsOpen={false}
|
||||
useAccount={selector => selector(operations.hooks.account.getSnapshot())}
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())}
|
||||
wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />)
|
||||
@@ -510,7 +509,7 @@ it.each([en, zh])('shows a localized toast when the account credential expires',
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
let expire: (() => void) | undefined
|
||||
const unsubscribe = vi.fn()
|
||||
const element = <AccountMenu renderSlot={() => null} {...({} as GlobalStandardProps)} {...operations}
|
||||
const element = <AccountMenu {...({} as GlobalStandardProps)} {...operations}
|
||||
settingsOpen={false} subscribeSessionExpired={(listener) => { expire = listener; return unsubscribe }}
|
||||
useAccount={selector => selector(operations.hooks.account.getSnapshot())}
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}}
|
||||
@@ -609,7 +608,7 @@ it('dismisses a collapsed menu and hands its login dialog to the API-key onboard
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
const openOnboarding = vi.fn()
|
||||
let snapshot = operations.hooks.account.getSnapshot()
|
||||
const props = { ...({} as GlobalStandardProps), ...operations, renderSlot: () => null, wide: false, settingsOpen: false,
|
||||
const props = { ...({} as GlobalStandardProps), ...operations, wide: false, settingsOpen: false,
|
||||
openSettings: vi.fn(), openOnboarding,
|
||||
useAccount: <T,>(select: (value: AccountSnapshot) => T) => select(snapshot),
|
||||
useTheme: <T,>(select: (value: ThemeSnapshot) => T) => select(operations.hooks.theme.getSnapshot()),
|
||||
@@ -698,7 +697,7 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after
|
||||
const unsubscribe = vi.fn(() => { listener = undefined })
|
||||
operations.subscribeModelSignInRequired = (next) => { listener = next; return unsubscribe }
|
||||
const { AccountMenu } = await import('../src/client/AccountMenu.tsx')
|
||||
const element = <AccountMenu renderSlot={() => null} {...({} as GlobalStandardProps)} {...operations}
|
||||
const element = <AccountMenu {...({} as GlobalStandardProps)} {...operations}
|
||||
settingsOpen={false}
|
||||
useAccount={selector => selector(operations.hooks.account.getSnapshot())}
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}}
|
||||
@@ -720,12 +719,13 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after
|
||||
})
|
||||
|
||||
it.each(['desktopOnboardingVisible', 'onboarding'] as const)('hides the notification slot until %s ends', async (field) => {
|
||||
const { AccountNotices } = await import('../src/client/AccountNotices.tsx')
|
||||
const operations = operationsOf({ status: 'credential-stored', attempt: null })
|
||||
let snapshot: AccountSnapshot = { ...operations.hooks.account.getSnapshot(), [field]: true }
|
||||
let active: boolean | undefined
|
||||
let openAccount: (() => void) | undefined
|
||||
const openSettings = vi.fn()
|
||||
const renderSlot: AccountMenuProps['renderSlot'] = (name, owner) => {
|
||||
const renderSlot: AccountNoticesProps['renderSlot'] = (name, owner) => {
|
||||
expect(name).toBe('settings.launcher.notifications')
|
||||
const value: object = owner
|
||||
const props = value as AccountNotificationsOwnerProps
|
||||
@@ -733,25 +733,29 @@ it.each(['desktopOnboardingVisible', 'onboarding'] as const)('hides the notifica
|
||||
openAccount = props.openAccount
|
||||
return null
|
||||
}
|
||||
const view = render(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings))
|
||||
const notices = () => <AccountNotices renderSlot={renderSlot} {...({} as GlobalStandardProps)} {...operations}
|
||||
useAccount={selector => selector(snapshot)}
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())} openSettings={openSettings} />
|
||||
const view = render(notices())
|
||||
expect(active).toBe(false)
|
||||
snapshot = { ...snapshot, [field]: false }
|
||||
view.rerender(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings))
|
||||
view.rerender(notices())
|
||||
expect(active).toBe(true)
|
||||
openAccount?.()
|
||||
expect(openSettings).toHaveBeenCalledExactlyOnceWith('account')
|
||||
})
|
||||
|
||||
it('keeps notification DOM inside the launcher while the collapsed rail hides it', async () => {
|
||||
const operations = operationsOf({ status: 'credential-stored', attempt: null })
|
||||
const snapshot = () => operations.hooks.account.getSnapshot()
|
||||
const renderSlot: AccountMenuProps['renderSlot'] = () => <div role="status">Notification</div>
|
||||
const view = render(await accountMenu(operations, snapshot, false, renderSlot))
|
||||
const notice = screen.getByRole('status')
|
||||
expect(view.container.contains(notice)).toBe(true)
|
||||
view.rerender(await accountMenu(operations, snapshot, false, renderSlot, undefined, false))
|
||||
expect(screen.queryByRole('status')).toBeNull()
|
||||
expect(notice.isConnected).toBe(true)
|
||||
view.rerender(await accountMenu(operations, snapshot, false, renderSlot))
|
||||
expect(screen.getByRole('status')).toBe(notice)
|
||||
it('keeps the notification slot inactive while signed out', async () => {
|
||||
const { AccountNotices } = await import('../src/client/AccountNotices.tsx')
|
||||
const operations = operationsOf({ status: 'signed-out', attempt: null })
|
||||
const owners: AccountNotificationsOwnerProps[] = []
|
||||
const renderSlot: AccountNoticesProps['renderSlot'] = (_name, owner) => {
|
||||
const value: object = owner
|
||||
owners.push(value as AccountNotificationsOwnerProps)
|
||||
return null
|
||||
}
|
||||
render(<AccountNotices renderSlot={renderSlot} {...({} as GlobalStandardProps)} {...operations}
|
||||
useAccount={selector => selector(operations.hooks.account.getSnapshot())}
|
||||
useTheme={selector => selector(operations.hooks.theme.getSnapshot())} openSettings={() => {}} />)
|
||||
expect(owners.at(-1)?.active).toBe(false)
|
||||
})
|
||||
@@ -27,8 +27,8 @@
|
||||
en: 7600861d064dbc99
|
||||
zh: a52ba446016e3a21
|
||||
/deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation:
|
||||
en: 4d25df8fe0e60b20
|
||||
zh: cecd02d3b6e47b24
|
||||
en: 2ba62c7be5b79052
|
||||
zh: 9220e867a0e88076
|
||||
/deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation/ledger-projections:
|
||||
en: fd99444278ab8530
|
||||
zh: 2efc5831c7e19be1
|
||||
|
||||
@@ -68,7 +68,7 @@ Desktop also contributes an **Update channel** row to General when the preload e
|
||||
<a id="understand-the-implementation"></a>
|
||||
## Understand the implementation
|
||||
|
||||
The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section.
|
||||
The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. The shell also declares settings.notice and renders it in a zero-height, full-width row above the launcher row; its content floats over the sidebar list, so status indicators beside the launcher do not narrow its content; the collapsed rail hides that row without unmounting it.
|
||||
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
@@ -68,7 +68,7 @@ Web 与桌面端的通用设置底部显示当前发布版本,使用构建注
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 理解实现
|
||||
|
||||
外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。
|
||||
外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。外壳还声明 settings.notice,并在入口行上方零高度的满宽行中渲染它,其内容浮在侧栏列表之上,因此入口旁的状态指示器不会挤压其内容;折叠轨道隐藏该行但不卸载它。
|
||||
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
@@ -8,6 +8,20 @@
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
/* The notice row takes no height: its content floats above the sidebar list at
|
||||
the row's full width, so status indicators in the trigger row do not narrow it. */
|
||||
.noticeRow {
|
||||
position: relative;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.notice {
|
||||
position: absolute;
|
||||
inset-inline: 0;
|
||||
bottom: 0;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.triggerRow.railRow {
|
||||
width: 36px;
|
||||
margin: 8px 0 10px;
|
||||
|
||||
@@ -221,14 +221,17 @@ export function SettingsRoot(props: SettingsRootComponentProps) {
|
||||
connectionIndicator = 'recovered'
|
||||
}
|
||||
|
||||
const openSettings = (sectionId?: string): void => {
|
||||
if (sectionId === undefined) actions.open()
|
||||
else actions.openSection(sectionId)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={css.noticeRow} hidden={!wide}><div className={css.notice}>{renderSlot('settings.notice', { openSettings })}</div></div>
|
||||
<div className={clsx(css.triggerRow, !wide && css.railRow)}>
|
||||
{renderSlot('settings.launcher', {
|
||||
wide, settingsOpen: open, openSettings: (sectionId) => {
|
||||
if (sectionId === undefined) actions.open()
|
||||
else actions.openSection(sectionId)
|
||||
},
|
||||
wide, settingsOpen: open, openSettings,
|
||||
...(shortcut?.keys.length ? { settingsShortcut: { keys: shortcut.keys, aria: shortcut.aria } } : {}),
|
||||
openOnboarding: (id) => { close(); setRequestedOnboarding(id) },
|
||||
}, { fallback: <Tooltip disabled={open} label={t('trigger')} shortcutKeys={shortcut?.keys}>
|
||||
|
||||
@@ -236,6 +236,7 @@ export function apply(ctx: ClientContext): void {
|
||||
store: shellStore,
|
||||
children: {
|
||||
'settings.launcher': { kind: 'single', scope: 'root' },
|
||||
'settings.notice': { kind: 'single', scope: 'root' },
|
||||
'settings.trigger': { kind: 'single', scope: 'root' },
|
||||
'settings.header': { kind: 'single', scope: 'root' },
|
||||
'settings.action': { kind: 'list', scope: 'root' },
|
||||
|
||||
@@ -67,6 +67,7 @@ export type SettingsRootComponentProps =
|
||||
PropsRuntime<'sidebar.settings'>
|
||||
& PropsRenderSlots<
|
||||
| 'settings.launcher'
|
||||
| 'settings.notice'
|
||||
| 'settings.trigger'
|
||||
| 'settings.header'
|
||||
| 'settings.action'
|
||||
|
||||
@@ -42,6 +42,7 @@ type Step = { id: string; order: number }
|
||||
/** Slot-content stand-ins: the shell renders whatever the seats contribute. */
|
||||
const SEAT_CONTENT: Record<string, string> = {
|
||||
'settings.trigger': 'Settings',
|
||||
'settings.notice': 'Account notice',
|
||||
'settings.header': 'Settings Title',
|
||||
'settings.action': 'Open configuration file',
|
||||
'settings.close': 'Close',
|
||||
@@ -165,6 +166,7 @@ function mount({
|
||||
desktopUpdate = next
|
||||
view.rerender(<SettingsRoot {...props} />)
|
||||
}
|
||||
const setWide = (next: boolean) => { view.rerender(<SettingsRoot {...props} wide={next} />) }
|
||||
const setShortcuts = (next: readonly ShortcutCatalogEntry[]) => {
|
||||
shortcuts = next
|
||||
view.rerender(<SettingsRoot {...props} />)
|
||||
@@ -178,7 +180,7 @@ function mount({
|
||||
}
|
||||
return {
|
||||
view, renderSlot, renderFactorySlot, bump, listeners, reconnect,
|
||||
setConnectionState, setDesktopUpdate, setShortcuts, setOnboardingActive,
|
||||
setConnectionState, setDesktopUpdate, setShortcuts, setOnboardingActive, setWide,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -558,3 +560,24 @@ it('passes current Settings key labels to the launcher and removes them when unb
|
||||
setShortcuts([{ ...row, keys: [], aria: undefined, binding: null, modified: true }])
|
||||
expect(launcher()).not.toHaveProperty('settingsShortcut')
|
||||
})
|
||||
|
||||
it('renders the notice row before the launcher row and opens the requested section', () => {
|
||||
const { renderSlot } = mount({ rows: [{ id: 'general', order: 0, label: 'General' }, { id: 'account', order: 1, label: 'Account' }] })
|
||||
const notice = screen.getByText('Account notice').parentElement!
|
||||
expect(notice.nextElementSibling?.contains(screen.getByRole('button', { name: 'Settings' }))).toBe(true)
|
||||
const owner = renderSlot.mock.calls.find(call => call[0] === 'settings.notice')!
|
||||
act(() => { (owner[1] as { openSettings: (sectionId?: string) => void }).openSettings('account') })
|
||||
expect(screen.getByTestId('section-account')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('hides the notice row in the collapsed rail and keeps the same node', () => {
|
||||
const { setWide } = mount()
|
||||
const notice = screen.getByText('Account notice').parentElement!
|
||||
expect(notice.hidden).toBe(false)
|
||||
setWide(false)
|
||||
expect(screen.getByText('Account notice').parentElement).toBe(notice)
|
||||
expect(notice.hidden).toBe(true)
|
||||
setWide(true)
|
||||
expect(screen.getByText('Account notice').parentElement).toBe(notice)
|
||||
expect(notice.hidden).toBe(false)
|
||||
})
|
||||
@@ -28,6 +28,7 @@ function injectedOf(c: TestClient): SettingsRootInjected {
|
||||
/** The slots this package declares, through the shell or the `settings.section.view` Factory. */
|
||||
const CHILD_SPECS = {
|
||||
'settings.launcher': { kind: 'single', scope: 'root' },
|
||||
'settings.notice': { kind: 'single', scope: 'root' },
|
||||
'settings.trigger': { kind: 'single', scope: 'root' },
|
||||
'settings.header': { kind: 'single', scope: 'root' },
|
||||
'settings.action': { kind: 'list', scope: 'root' },
|
||||
|
||||
@@ -30,8 +30,8 @@
|
||||
en: 9767f17ca0f02ae3
|
||||
zh: 8e475d6d3d670702
|
||||
/deepseek-ai-dsh-client-ui-settings/understand-the-implementation:
|
||||
en: 84b6449030ffabe7
|
||||
zh: 958382ead3ab0407
|
||||
en: 6741f576de0585c2
|
||||
zh: 5b621d137e52b63e
|
||||
/deepseek-ai-dsh-client-ui-settings/understand-the-implementation/the-describe-mirror:
|
||||
en: 0cd270ddcac46776
|
||||
zh: 4e03bf1d153b3f04
|
||||
|
||||
@@ -55,7 +55,7 @@ A committed write folds its answer into the shared mirror. Refused writes refres
|
||||
<a id="understand-the-implementation"></a>
|
||||
## Understand the implementation
|
||||
|
||||
The optional `settings.launcher` contribution receives sidebar geometry, whether the open Settings panel covers the sidebar, the settings navigation callbacks, and the effective Settings key labels and accessible combination. The shell omits shortcut presentation for an unbound command and retains its plain Settings trigger when no launcher is registered. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section.
|
||||
The optional `settings.launcher` contribution receives sidebar geometry, whether the open Settings panel covers the sidebar, the settings navigation callbacks, and the effective Settings key labels and accessible combination. The shell omits shortcut presentation for an unbound command and retains its plain Settings trigger when no launcher is registered. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section. The optional `settings.notice` contribution receives openSettings and renders in a zero-height, full-width row above the launcher row, floating over the sidebar list; the shell hides that row in the collapsed rail without unmounting it.
|
||||
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
@@ -55,7 +55,7 @@ kind: "package-reference"
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 理解实现
|
||||
|
||||
可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。
|
||||
可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。可选的 `settings.notice` 贡献接收 openSettings,渲染在入口行上方零高度的满宽行中,浮在侧栏列表之上;折叠轨道中外壳隐藏该行但不卸载它。
|
||||
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
@@ -30,6 +30,12 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface SlotMap {
|
||||
/** Optional sidebar account launcher; opens the shell-owned settings panel. */
|
||||
'settings.launcher': { kind: 'single'; scope: 'root'; owner: SettingsLauncherOwnerProps }
|
||||
/**
|
||||
* Optional content anchored above the launcher row at the launcher row's
|
||||
* full width. The row takes no height, so the content floats over the
|
||||
* sidebar list; the shell hides it in the rail without unmounting it.
|
||||
*/
|
||||
'settings.notice': { kind: 'single'; scope: 'root'; owner: SettingsNoticeOwnerProps }
|
||||
|
||||
/**
|
||||
* The sidebar-foot trigger row content: icon + label, supplied as slot
|
||||
@@ -167,6 +173,12 @@ export interface SettingsOnboardingOwnerProps {
|
||||
openSection: (id: string) => void
|
||||
}
|
||||
|
||||
/** Settings navigation for the row above the launcher row. */
|
||||
export interface SettingsNoticeOwnerProps {
|
||||
/** @param sectionId - section to open; absent uses the shell's default section. */
|
||||
openSettings: (sectionId?: string) => void
|
||||
}
|
||||
|
||||
/** Sidebar launcher geometry and settings navigation. */
|
||||
export interface SettingsLauncherOwnerProps {
|
||||
/** Whether the sidebar shows labels. */
|
||||
|
||||
@@ -14,7 +14,7 @@ import { SettingsDescribeMirror } from './settings-mirror.ts'
|
||||
|
||||
export type {
|
||||
SettingsLauncherOwnerProps, SettingsGeneralItemOwnerProps, SettingsHeaderOwnerProps, SettingsOnboardingOwnerProps,
|
||||
SettingsSectionIconOwnerProps, SettingsSectionOwnerProps, SettingsSectionViewProps, SettingsTriggerOwnerProps,
|
||||
SettingsNoticeOwnerProps, SettingsSectionIconOwnerProps, SettingsSectionOwnerProps, SettingsSectionViewProps, SettingsTriggerOwnerProps,
|
||||
} from './contract/slots.ts'
|
||||
export type { ConfigForms } from './config-form.ts'
|
||||
export type { ConfigForm, ConfigFormSnapshot } from './config-form-types.ts'
|
||||
|
||||
@@ -39,8 +39,8 @@ export function apply(ctx, config = {}) {
|
||||
if (!rejected || !signal.aborted) throw new Error('expected queue-clear rejection and activity cancellation')
|
||||
agent.inbox.remove(pending.id)
|
||||
for (const message of messages) {
|
||||
const ordinary = message.source.kind === 'user'
|
||||
agent.send(message, ordinary ? 'next-turn' : 'next-step', ordinary)
|
||||
const waking = message.source.kind === 'user' || message.source.kind === 'agent-message'
|
||||
agent.send(message, waking ? 'next-turn' : 'next-step', waking)
|
||||
}
|
||||
return next()
|
||||
})
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 78708b3779d999a9
|
||||
zh: ad6173f9f01630de
|
||||
/deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation/ptc-mode:
|
||||
en: 4da0f9293816b976
|
||||
zh: c5f77ea403d30ff5
|
||||
en: 630c852375ac0d30
|
||||
zh: 7b18b1aaae07d659
|
||||
/deepseek-ai-dsh-tool-executor-ptc/further-exploration:
|
||||
en: ee69078c38c655a9
|
||||
zh: fb0873407f23c8c5
|
||||
|
||||
@@ -72,7 +72,9 @@ New sub-calls use `<parent>:ptc:<n>` ids. Consumers treat these ids as opaque an
|
||||
|
||||
TypeScript bindings for `read_image` and CUA screenshot operations return an `Image` with a readable `path`, `width`, and `height`. Other tool values are substituted all or nothing: when `{ type: 'image', attachment }` entries reference every image of the finalized result and the program can read each one, those entries become `Image`s, as admitted MCP image blocks do, and the result's text and images reach the model only through `inspect`; otherwise the value stays raw and the complete result content reaches the model as additional context. Passing it to `inspect` places its durable attachment among the captured text in the `run_code` result. Images nested in arrays and objects are displayed with their containing value. On program failure, inspected output accompanies the original diagnostic; outer result replacements remain authoritative. If an output policy removes a screenshot or read_image image, the binding rejects with ToolCallError and includes the retained text notice. Additional contexts retain their producing tool’s attribution.
|
||||
|
||||
When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Other runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. A runtime rejection keeps a `PtcRuntimeError` code and otherwise becomes `CODE_RUN_FAILED` with the rejection as `cause`. A blank `description`, an invalid `timeoutMs`, or `timeoutMs` or `sandbox_permissions` on a runtime that does not support it fails as `ToolArgsError` with `INVALID_ARGS`; a call after executor disposal fails with `CODE_RUN_UNAVAILABLE`; and a missing runtime, `workingDirectory`, or `sandboxPolicy` fails as `ToolContextUnavailableError`. Cancellation can discard retained runtime state and does not undo completed tool effects.
|
||||
`run_code` and tools created by `createRunCodeTool` report `outputTruncated: true` when captured output or diagnostic text was truncated. With the Node runtime, display-output overflow discards subsequent output while execution continues under the original timeout and cancellation rules. A normally completed program remains a successful tool result, with a truncation notice directing the model to read current state without repeating completed actions. A later failure keeps its actual error kind and truncation notice. Retained images and settled subcall records remain available.
|
||||
|
||||
When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. A runtime rejection keeps a `PtcRuntimeError` code and otherwise becomes `CODE_RUN_FAILED` with the rejection as `cause`. A blank `description`, an invalid `timeoutMs`, or `timeoutMs` or `sandbox_permissions` on a runtime that does not support it fails as `ToolArgsError` with `INVALID_ARGS`; a call after executor disposal fails with `CODE_RUN_UNAVAILABLE`; and a missing runtime, `workingDirectory`, or `sandboxPolicy` fails as `ToolContextUnavailableError`. Cancellation can discard retained runtime state and does not undo completed tool effects.
|
||||
|
||||
`run_code` accepts `timeoutMs` when the mounted runtime supports an override; its schema reports the configured default and maximum, and the runtime's usage instructions. The Node default is 120,000 ms with a 600,000 ms cap, including nested tool and approval waits. A wider `sandbox_permissions` mode requires a non-empty `justification` and approval before the program starts. The schema asks the model to write that reason in the current user's language. The grant applies to that complete execution; standing Session policy and nested tools retain their own authority. Programs are never replayed automatically: inspect earlier effects before explicitly retrying a denied program. Retained PTC environments follow the standing file policy. PTC observes committed Session mode changes and immediately cancels affected calls in all Node modes. Later PTC calls wait for their nested-tool cleanup before resolving the latest policy. The runtime owns process invalidation and cleanup; permission setters remain synchronous. One-time escalations omit the state owner and complete in a temporary environment; standing variables remain available to ordinary calls.
|
||||
|
||||
|
||||
@@ -72,7 +72,9 @@ PTC 执行器公开保留的 `run_code` 传输,以及确定性的 TypeScript S
|
||||
|
||||
TypeScript 中的 `read_image` 与 CUA 截图操作返回 `Image`,其中包含可读取的 `path`、`width` 和 `height`。其他工具的返回值按全有或全无的方式替换:当 `{ type: 'image', attachment }` 条目引用了最终结果中的每张图片且程序能读取每张图片时,这些条目会变为 `Image`,与已接受的 MCP 图片块相同,结果的文本与图片仅通过 `inspect` 进入模型;否则返回值保持原样,完整的结果内容作为额外上下文进入模型。将其传给 `inspect` 后,持久附件会按顺序与文本一起进入 `run_code` 结果。数组和对象内嵌的图片会随所在值一起展示。程序失败时,已 inspect 的输出随原始诊断一起呈现;外层替换的结果保持生效。输出策略移除截图或 read_image 图片时,绑定以 ToolCallError 拒绝,并包含保留的文本提示。额外上下文保留生成工具的归属。
|
||||
|
||||
调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。其他运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。运行时拒绝保留 `PtcRuntimeError` 的 code,否则变为 `CODE_RUN_FAILED` 并以该拒绝为 `cause`。`description` 为空白、`timeoutMs` 无效,或运行时不支持却传入 `timeoutMs` 或 `sandbox_permissions` 时,以带 `INVALID_ARGS` 的 `ToolArgsError` 失败;执行器释放后的调用以 `CODE_RUN_UNAVAILABLE` 失败;缺少运行时、`workingDirectory` 或 `sandboxPolicy` 时以 `ToolContextUnavailableError` 失败。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。
|
||||
`run_code` 和通过 `createRunCodeTool` 创建的工具在捕获输出或诊断文本被截断时报告 `outputTruncated: true`。使用 Node 运行时时,展示输出超限会丢弃后续输出,执行仍受原有超时和取消规则约束。正常结束的程序仍是成功工具结果,并提示输出已截断,应读取当前状态而不重复已完成的动作。后续失败保留实际错误类型和截断提示。已保留的图片与已结算的子调用记录仍然可用。
|
||||
|
||||
调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。运行时拒绝保留 `PtcRuntimeError` 的 code,否则变为 `CODE_RUN_FAILED` 并以该拒绝为 `cause`。`description` 为空白、`timeoutMs` 无效,或运行时不支持却传入 `timeoutMs` 或 `sandbox_permissions` 时,以带 `INVALID_ARGS` 的 `ToolArgsError` 失败;执行器释放后的调用以 `CODE_RUN_UNAVAILABLE` 失败;缺少运行时、`workingDirectory` 或 `sandboxPolicy` 时以 `ToolContextUnavailableError` 失败。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。
|
||||
|
||||
当已挂载运行时支持覆盖时,`run_code` 接受 `timeoutMs`;其 schema 报告配置的默认值和上限以及运行时使用说明。Node 默认值为 120,000 ms,上限为 600,000 ms,包含嵌套工具和审批等待。更宽的 `sandbox_permissions` 模式要求非空 `justification`,并在程序启动前获得审批。schema 提示模型使用当前用户的语言撰写理由。授权仅用于该次完整执行;常驻 Session 策略与嵌套工具保留各自权限。程序不会自动重放:显式重试被拒程序前,应检查先前已发生的效果。 保留状态的 PTC 环境遵循会话文件策略。PTC 观察已提交的 Session 模式变化,并立即取消所有 Node 模式下受影响的调用。后续 PTC 调用等待这些调用的嵌套工具清理后,再解析最新策略。运行时负责进程失效和清理,权限设置保持同步。单次提权省略状态所有者,在临时环境中执行;普通调用仍可访问原环境的变量。
|
||||
|
||||
|
||||
@@ -161,7 +161,7 @@ function isCancellation(error: unknown, signal: AbortSignal): boolean {
|
||||
}
|
||||
|
||||
/** Canonical value returned by the outer PTC mode transport. */
|
||||
type RunCodeOutput = { logs: string[]; sandbox?: PtcRunSandbox }
|
||||
type RunCodeOutput = { logs: string[]; outputTruncated?: boolean; sandbox?: PtcRunSandbox }
|
||||
|
||||
/** Render captured text, selected images, and the applied file policy in emission order. */
|
||||
function renderRunOutput(
|
||||
@@ -183,6 +183,7 @@ function renderRunOutput(
|
||||
}
|
||||
appendText(remaining.join(''))
|
||||
const details: string[] = []
|
||||
if (value.outputTruncated) details.push('Program completed. Output was truncated; read current state for missing information without repeating completed actions.')
|
||||
if (value.sandbox?.enforcement === 'partial') details.push('File sandbox enforcement is partial on this host.')
|
||||
if (value.sandbox?.denied) details.push(`The ${value.sandbox.mode} file sandbox denied an operation.${guidance}`)
|
||||
appendText(details.filter(text => text.length > 0).join('\n'))
|
||||
@@ -278,6 +279,7 @@ export function createRunCodeTransport(
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
logs: { type: 'array', required: true, items: { type: 'string' } },
|
||||
outputTruncated: { type: 'boolean' },
|
||||
sandbox: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
@@ -703,7 +705,8 @@ export function createRunCodeTransport(
|
||||
? runController.signal.reason : undefined
|
||||
let failure: HarnessError
|
||||
if (result.error.kind === 'abort' && exec.signal.aborted && limitError === undefined) {
|
||||
const message = runtime.retainsState ? `tool call aborted: ${result.error.message}` : 'tool call aborted'
|
||||
const message = (runtime.retainsState ? `tool call aborted: ${result.error.message}` : 'tool call aborted')
|
||||
+ (result.outputTruncated ? '\nOutput was truncated.' : '')
|
||||
failure = new HarnessError(message, TOOL_ABORTED)
|
||||
failure.name = 'AbortError'
|
||||
} else {
|
||||
@@ -713,7 +716,8 @@ export function createRunCodeTransport(
|
||||
: `${logsText.endsWith('\n') ? '' : '\n'}File sandbox: ${result.sandbox.mode}${result.sandbox.enforcement === undefined ? '' : `; enforcement: ${result.sandbox.enforcement}`}${result.sandbox.denied ? '; operation denied' : ''}.`
|
||||
const failureText = limitError === undefined || limitError.message === result.error.message
|
||||
? result.error.message : `${limitError.message}\n${result.error.message}`
|
||||
failure = new CodeRunFailedError(`code run failed (${result.error.kind}): ${failureText}${logsText}${sandboxText}${result.sandbox?.denied ? escalationGuidance(runtime.sandboxMode) : ''}`)
|
||||
const truncation = result.outputTruncated ? '\nOutput was truncated.' : ''
|
||||
failure = new CodeRunFailedError(`code run failed (${result.error.kind}): ${failureText}${logsText}${sandboxText}${result.sandbox?.denied ? escalationGuidance(runtime.sandboxMode) : ''}${truncation}`)
|
||||
}
|
||||
if (hasImages) inspections.set(exec, {
|
||||
failure: {
|
||||
@@ -726,6 +730,7 @@ export function createRunCodeTransport(
|
||||
}
|
||||
const value: RunCodeOutput = {
|
||||
logs,
|
||||
...result.outputTruncated ? { outputTruncated: true } : {},
|
||||
...result.sandbox === undefined ? {} : { sandbox: result.sandbox },
|
||||
}
|
||||
if (hasImages) inspections.set(exec, { value, output: result.output })
|
||||
|
||||
@@ -43,6 +43,9 @@ try {
|
||||
}
|
||||
await assert.rejects(definition.execute({ code: 'probe', description: 'Check shared error identity' }, execution),
|
||||
error => error instanceof ptc.CodeRunFailedError && error.code === 'CODE_RUN_FAILED')
|
||||
runtime.run = async () => ({ output: [], outputTruncated: true })
|
||||
assert.deepEqual(await definition.execute({ code: 'probe', description: 'Check successful truncated output' }, execution),
|
||||
{ logs: [], outputTruncated: true })
|
||||
runtime.run = async (spec) => {
|
||||
assert.deepEqual(Object.keys(spec.bindings[0].functions), ['private_probe'])
|
||||
assert.equal(spec.discardCompletion, true)
|
||||
|
||||
@@ -1991,6 +1991,40 @@ describe('the run_code dispatch bridge', () => {
|
||||
expect(text).toBe(`Error: code run failed (timeout): execution timed out ${phase} (300ms); retained variables were cleared${logs.length > 0 ? '\nCaptured output:\ngot this far' : ''}`)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['output-limit', 'CODE_RUN_FAILED'],
|
||||
['invalid-output', 'CODE_RUN_FAILED'],
|
||||
['exception', 'CODE_RUN_FAILED'],
|
||||
['timeout', 'CODE_RUN_FAILED'],
|
||||
['worker-exit', 'CODE_RUN_FAILED'],
|
||||
['protocol', 'CODE_RUN_FAILED'],
|
||||
['sandbox-unavailable', 'CODE_RUN_FAILED'],
|
||||
['abort', 'CODE_RUN_FAILED'],
|
||||
] as const)('preserves completed subcalls when the runtime reports %s', async (kind, code) => {
|
||||
const { ctx, runtime } = await setup({ mode: 'ptc' })
|
||||
onTestFinished(async () => { await ctx.fiber.dispose() })
|
||||
const { agent, events } = fakeAgent()
|
||||
const calls = registerEcho(ctx)
|
||||
runtime.behavior = async (request) => {
|
||||
await request.bindings[0]!.functions.echo!({ value: 'action dispatched' })
|
||||
return { output: [{ type: 'text', text: 'before failure' }], outputTruncated: true, error: { kind, message: 'fixture failure' } }
|
||||
}
|
||||
|
||||
const result = await runCode(ctx, 'program', { agent })
|
||||
|
||||
expect(result.isError).toBe(true)
|
||||
expect(result.error).toMatchObject({ info: { name: 'CodeRunFailedError', code } })
|
||||
const first = result.content[0]
|
||||
if (first?.type !== 'text') throw new Error('Missing failure diagnostic')
|
||||
expect(first.text).toContain('Captured output:\nbefore failure')
|
||||
expect(events.filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(1)
|
||||
expect(events.find(event => event.type === 'tool/ptc-dispatch')?.data).toMatchObject({
|
||||
isError: false, content: [{ type: 'text', text: 'echo:action dispatched' }],
|
||||
})
|
||||
expect(calls).toEqual([{ value: 'action dispatched' }])
|
||||
expect(first.text).toBe(`Error: code run failed (${kind}): fixture failure\nCaptured output:\nbefore failure\nOutput was truncated.`)
|
||||
})
|
||||
|
||||
it('CodeRunFailedError is a HarnessError with the CODE_RUN_FAILED code', () => {
|
||||
const error = new CodeRunFailedError('boom')
|
||||
expect(error.code).toBe('CODE_RUN_FAILED')
|
||||
@@ -2433,18 +2467,18 @@ describe('the run_code dispatch bridge', () => {
|
||||
expect(calls).toEqual([])
|
||||
})
|
||||
|
||||
it.each(['preserved', 'cleared'])('reports retained variables were %s after caller cancellation', async (state) => {
|
||||
it.each(['preserved', 'cleared'])('reports retained variables were %s after caller cancellation with truncated output', async (state) => {
|
||||
const { ctx, runtime } = await setup({ mode: 'ptc' })
|
||||
vi.spyOn(runtime, 'retainsState', 'get').mockReturnValue(true)
|
||||
const controller = new AbortController()
|
||||
const message = `execution canceled; retained variables were ${state}`
|
||||
runtime.behavior = async () => {
|
||||
controller.abort({ kind: 'user' })
|
||||
return { output: [], error: { kind: 'abort', message } }
|
||||
return { output: [], outputTruncated: true, error: { kind: 'abort', message } }
|
||||
}
|
||||
const result = await runCode(ctx, 'program', { signal: controller.signal })
|
||||
expect(result.error).toEqual({
|
||||
message: `tool call aborted: ${message}`,
|
||||
message: `tool call aborted: ${message}\nOutput was truncated.`,
|
||||
info: { name: 'AbortError', code: TOOL_ABORTED },
|
||||
})
|
||||
})
|
||||
|
||||
@@ -196,6 +196,30 @@ describe('registered program tool factory', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it.each([false, true])('retains inspected images from private program tools, output overflow=%s', async (overflow) => {
|
||||
type Attachment = Extract<ContentBlock, { type: 'image' }>['attachment']
|
||||
const image: ContentBlock = { type: 'image', attachment: {
|
||||
attachmentId: brandString<Attachment['attachmentId']>('sha256:inspected'),
|
||||
mediaType: 'image/png', width: 1, height: 1, bytes: 1,
|
||||
} }
|
||||
const { runtime, execute } = await setup(privateTool(vi.fn(async () => 'private result')))
|
||||
runtime.behavior = async () => ({
|
||||
output: [{ type: 'text', text: 'before image' }, image],
|
||||
...overflow ? { outputTruncated: true } : {},
|
||||
})
|
||||
|
||||
const result = (await execute()).results[0]!.result
|
||||
|
||||
expect(result.isError).toBe(false)
|
||||
expect(result.content.slice(0, 2)).toEqual([{ type: 'text', text: 'before image' }, image])
|
||||
if (overflow) {
|
||||
expect(result.value).toMatchObject({ outputTruncated: true })
|
||||
expect(result.content[2]).toMatchObject({
|
||||
type: 'text', text: expect.stringContaining('Program completed. Output was truncated;') as string,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('cancels on owner disposal and awaits nested cleanup before releasing the factory', async () => {
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const aborted = Promise.withResolvers<undefined>()
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 2f8a621b991260a1
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
|
||||
en: f63d4a049eea1ede
|
||||
zh: e61269b6df6afcd4
|
||||
en: b077aea8c5f4cb0c
|
||||
zh: 6ca6d6ead647d870
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
|
||||
en: 43e18d718e1bda7b
|
||||
zh: c58f6b5bda5c0c45
|
||||
en: a88671f87adb5e84
|
||||
zh: a31d5f186c40683f
|
||||
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
|
||||
en: fa4d8c579ffc49ff
|
||||
zh: 5856ed7469e4585b
|
||||
|
||||
@@ -37,7 +37,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish
|
||||
- **Checkout row** — names the checked-out branch, or Not on a branch with the abbreviated commit on a detached HEAD, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip, shown after 500ms of hover, adds the path with the Host home shortened to `~`, and a branch name the row clips crawls into view while the pointer rests on the row. The row and its More button open the directory menu of the checkout root. For a removed worktree it shows a warning glyph and offers Restore. When Git cannot be read, the row says so, and its info button shows the failure after 500ms of hover, at once on keyboard focus, or on a press; outside a Git checkout there is no row.
|
||||
- **Connection row** — when the Session's panel stream ends, also before it delivered a first state, a status row at the end of the Environment section says the status stopped updating and that the Git and change request details may be out of date; Retry opens the stream again and the row goes away.
|
||||
- **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll.
|
||||
- **Change requests section** — shows while the Session has bound change requests or the repository's host needs sign-in. Its title carries their count. A status row above the cards asks to sign in to the host: with the sign-in command the provider names, such as `gh auth login --hostname github.com`, which crawls into view on hover, and Copy; when the provider names none, and when the sign-in check fails, with the host's reason behind an info button, as the checkout row shows its failure. The section shows with this row alone while the Session binds no change request. Each change request card shows a glyph for its state, its title on one line, which crawls into view on hover and opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the toggle's yellow dot does. The card's More menu offers Open in browser, Copy change request link, View changes for a change request a provider serves, Ready for review for an open draft, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended, on one line: while the line with failed checks does not fit, they take the shorter wording without their count, and a line that still does not fit ends in an ellipsis and crawls into view with the title. An expanded card shows the head and base branches, then one row per fact, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. The thread count and an issue's title show in a tooltip after 500ms of hover. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. A change request the host would merge now offers Merge below its rows, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When the Session binds exactly one change request, its card starts expanded whatever its state; with several, every card starts collapsed. A card the user expands or collapses keeps that choice across updates and while the panel is hidden, for as long as the Session stays open; a card the user never toggled follows the default.
|
||||
- **Change requests section** — shows while the Session has bound change requests or the repository's host needs sign-in. Its title carries their count. A status row above the cards asks to sign in to the host: with the sign-in command the provider names, such as `gh auth login --hostname github.com`, which crawls into view on hover, and Copy; when the provider names none, and when the sign-in check fails, with the host's reason behind an info button, as the checkout row shows its failure. The section shows with this row alone while the Session binds no change request. Each change request is a compact card, a filled block on the panel's row columns: one line with a glyph for its state, its title, its number, and a glyph for the outcome of its checks. A press on the line opens the change request's changes in the right sidebar; with Cmd or Ctrl held, with the middle button, and for a change request no provider serves or has read yet, it opens the host's page. The state glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the toggle's yellow dot does. The card's More menu, which shows on hover or focus as on the panel's other rows, offers View changes for a change request a provider serves, Open in browser, Copy change request link, Ready for review for an open draft, and Remove from this Session, whose toast offers Undo. While collapsed, the line reads its status in words to assistive technology, and the card's hover card shows the full title, the number with draft state and the head and base branches, and that status: the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended; a failed read or an unserved URL stands there instead. Cancelled checks have a separate count, which the status names when no listed check failed. The checks glyphs share one ring: a check for passed, a cross for failed, a half fill while they run, and a dash otherwise. An expanded card shows one row per fact below its line, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. The thread count and an issue's title show in a tooltip after 500ms of hover. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. A change request the host would merge now offers Merge below its rows, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. The list shows three cards; with more, the panel's fold control after them shows the rest and folds them again, and the Session keeps that choice while it stays open. When the Session binds exactly one change request, its card starts expanded whatever its state; with several, every card starts collapsed. A card the user expands or collapses keeps that choice across updates and while the panel is hidden, for as long as the Session stays open; a card the user never toggled follows the default.
|
||||
- **Local changes row** — whenever the `branch` scope changes files, independently of bound change requests, the row names the number of changed files with the added and deleted lines and opens the changes view. Its More menu offers View changes and, when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, Create change request, which sends the Session a user message in the UI language that asks the Agent to create a change request for these changes; a toast reports whether it was sent.
|
||||
- **Changes view** — The Changes row and View changes item of a change request card and the local changes row open a right-sidebar tab that lists the changed files, closing the Session panel while it floats over the conversation. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Its icon buttons and the header's Open in browser name their action after 500ms of hover or at once on keyboard focus. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one for 500ms shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A row of at most 20 lines expands with one click. A longer row expands 20 lines at a time, down from the hunk above it or up from the hunk below it, the row before the first hunk only up and the row after the last hunk only down, and shows how many lines it still hides; the first click on the unknown lines after the last hunk reads the file and shows their first 20. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. While the view reads changes it has not shown yet, it says Reading changes above file cards drawn as pulsing placeholders, one changed file in two columns when sides are split, and the files menu names no count; reduced motion keeps the placeholders still. The view reads again on Refresh and the page refresh shortcut, on each navigation, Line truncated
|
||||
|
||||
@@ -65,7 +65,7 @@ All files opens a searchable directory tree with the selected file scrolled to i
|
||||
|
||||
Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --quiet HEAD`, which names the checked-out branch when it is under `refs/heads/`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `worktreeBases` runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, takes each remote's default branch from its `refs/remotes/<remote>/HEAD`, leaves out other symbolic refs and the branches of unconfigured remotes, and keeps at most `maxBranches` local branches and `maxBranches` branches per remote whose names contain the query, with remotes in the code host order below; `requestWorktree` with a name checks it against Git's branch-name rules and runs `show-ref` in the checkout; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy.
|
||||
|
||||
A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. A request names its base by the full name of a local or remote-tracking branch, as earlier panels' short local names still resolve, and may name its branch. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, with `forgePanel/invalid-branch` for an empty base, with `forgePanel/invalid-name` for a branch name Git refuses, and with `forgePanel/branch-exists` for a branch name the checkout already uses; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the inbox of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. The hold makes one attempt on the requested branch name, or on a new generated one, asking the worktree service to fetch a remote-tracking base branch first; it publishes the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, fetch, failed step, reason, and whether the branch or directory existed stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, without the fetch when its `fetch` argument is false, refused with `forgePanel/not-waiting` while none waits or one runs; `requestWorktree` with another name changes the next attempt; and withdrawing the request lets the message go on in the current checkout. Each message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason.
|
||||
A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `working-directory/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. A request names its base by the full name of a local or remote-tracking branch, as earlier panels' short local names still resolve, and may name its branch. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, with `forgePanel/invalid-branch` for an empty base, with `forgePanel/invalid-name` for a branch name Git refuses, and with `forgePanel/branch-exists` for a branch name the checkout already uses; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the next-turn queue of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. A message queued for the next step, such as a notice another plugin injects, opens no turn and starts no hold. The hold makes one attempt on the requested branch name, or on a new generated one, asking the worktree service to fetch a remote-tracking base branch first; it publishes the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, fetch, failed step, reason, and whether the branch or directory existed stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, without the fetch when its `fetch` argument is false, refused with `forgePanel/not-waiting` while none waits or one runs; `requestWorktree` with another name changes the next attempt; and withdrawing the request lets the message go on in the current checkout. Each next-turn message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason.
|
||||
|
||||
|
||||
Restoration records `restoring` before mutation and `restored` only after success. Projection version 3 retains incomplete restoration across reloads. Directory existence alone cannot release a waiting message: the checkout root and shared Git directory must match the recorded worktree. Plugin unload cancels and joins all creation, restoration, and waiting tasks before releasing panel readers and the projection.
|
||||
|
||||
@@ -37,7 +37,7 @@ kind: "package-reference"
|
||||
- **检出行**——显示当前检出的分支(分离 HEAD 时为“不在分支上”与缩写提交),并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);悬停 500ms 后出现的提示给出路径,宿主主目录缩写为 `~`;分支名放不下时,指针停在这一行上会滚动显示全文。这一行及其“更多”按钮打开检出根目录的目录菜单。worktree 已被删除时显示警示图标并提供“恢复”。无法读取 Git 时,这一行说明这一点,行尾的信息按钮在悬停 500ms、键盘聚焦或按下时给出失败原因;不在 Git 检出中时不显示这一行。
|
||||
- **连接行**——Session 的面板流结束时(包括还没收到第一份状态就结束),环境分栏末尾的状态行说明状态已停止更新,Git 与变更请求信息可能已过时;「重试」重新打开流,这一行随即消失。
|
||||
- **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。
|
||||
- **变更请求分栏**——Session 有已绑定的变更请求,或仓库所在托管平台需要登录时显示。分栏标题旁显示数量。卡片上方的状态行请用户登录托管平台:显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`,悬停时滚动显示全文)和「复制」;提供方没有给出命令以及登录检查失败时,平台给出的原因收在信息按钮里,与检出行显示失败的方式相同。Session 没有绑定变更请求时,分栏只显示这一行。每张变更请求卡片显示状态图标、单行标题(悬停时滚动显示全文,点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单提供“在浏览器中打开”“复制变更请求链接”、由提供方服务的变更请求的“查看变更”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。这些内容只占一行:含失败检查的一行放不下时,失败检查改用不带数量的短文案;仍放不下的一行末尾显示省略号,并随标题一起滚动显示。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。
|
||||
- **变更请求分栏**——Session 有已绑定的变更请求,或仓库所在托管平台需要登录时显示。分栏标题旁显示数量。卡片上方的状态行请用户登录托管平台:显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`,悬停时滚动显示全文)和「复制」;提供方没有给出命令以及登录检查失败时,平台给出的原因收在信息按钮里,与检出行显示失败的方式相同。Session 没有绑定变更请求时,分栏只显示这一行。每个变更请求是一张紧凑卡片,即面板行列上的一块底色:一行内依次是状态图标、标题、编号和检查结果图标。点击这一行在右侧边栏打开该变更请求的变更;按住 Cmd 或 Ctrl 点击、用中键点击,以及没有提供方服务或尚未读取的变更请求,则打开托管平台上的页面。状态图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与面板开关的黄点一致。卡片的“更多”菜单与面板其他行一样在悬停或聚焦时出现,提供由提供方服务的变更请求的“查看变更”、“在浏览器中打开”“复制变更请求链接”、打开中草稿的“标记为可评审”,以及“从本会话移除”,移除后的 toast 提供“撤销”。收起时,这一行把状态以文字读给辅助技术,卡片的悬停卡片显示完整标题、编号(带草稿状态与源分支、目标分支)和这段状态:打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则是结束时间;读取失败或没有提供方服务的 URL 则显示相应说明。已取消的检查单独计数,列出的检查没有失败项时状态显示取消数量。检查结果图标共用同一个圆环:通过为勾,失败为叉,进行中为半填充,其余为短横。展开的卡片在这一行下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。讨论数和 issue 标题在悬停 500ms 后以提示显示。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。主机现在就会合并的变更请求在各行下方提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。列表显示三张卡片;更多时,卡片之后是面板的折叠控件,用来显示其余卡片或再次收起,Session 保持打开期间保留这一选择。Session 只绑定了一个变更请求时,无论其状态如何,它的卡片默认展开;绑定多个时,所有卡片默认收起。用户展开或收起某张卡片后,在 Session 保持打开期间,更新和隐藏面板都不会改变这一选择;用户没有动过的卡片仍按默认规则。
|
||||
- **本地变更行**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。这一行显示变更的文件数以及新增、删除行数,点击打开变更视图。它的“更多”菜单提供“查看变更”;识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,还提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。
|
||||
- **变更视图**——变更请求卡片上的“变更”一行与“查看变更”菜单项、以及本地变更行会打开一个右侧边栏标签页,列出所有变更的文件;会话面板浮在对话上方时随之关闭。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏的图标按钮和标题栏的“在浏览器中打开”悬停 500ms 后显示操作说明,键盘聚焦时立即显示。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停 500ms 后显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。不超过 20 行的折叠行点一次全部展开。更长的折叠行每次展开 20 行,可以从上方 hunk 向下展开,也可以从下方 hunk 向上展开;第一个 hunk 之前的折叠行只能向上展开,最后一个 hunk 之后的只能向下展开;折叠行上显示还隐藏的行数。最后一个 hunk 之后行数未知的折叠行,第一次点击时读取文件并显示前 20 行。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。视图读取尚未显示过的变更时,会在显示为脉动占位的文件卡片上方写出“正在读取变更…”,并排视图下其中一个已修改文件画成两栏,文件菜单不显示数量;开启“减少动态效果”时占位不动。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更Line truncated
|
||||
|
||||
@@ -65,7 +65,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后
|
||||
|
||||
检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --quiet HEAD`(指向 `refs/heads/` 下的分支时即为当前分支)、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`worktreeBases` 在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,从 `refs/remotes/<remote>/HEAD` 取每个远程的默认分支,略过其他符号引用与未配置远程的分支,并按下文的代码托管识别顺序排列远程,各保留最多 `maxBranches` 个名称包含查询文字的本地分支与每个远程的分支;带名称的 `requestWorktree` 按 Git 的分支名规则检查名称,并在检出中运行 `show-ref`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。
|
||||
|
||||
worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。请求用本地分支或远程跟踪分支的完整引用名指定基准(早期面板记录的本地短名称仍可解析),并可指定分支名。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;基准为空时以 `forgePanel/invalid-branch` 拒绝;Git 不接受分支名时以 `forgePanel/invalid-name` 拒绝;检出中已有同名分支时以 `forgePanel/branch-exists` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的收件箱时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。暂留用请求的分支名或新的自动名称进行一次尝试,基准是远程跟踪分支时请 worktree 服务先获取它;它在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、是否获取、失败步骤、原因以及分支或目录是否已存在以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,`fetch` 参数为 false 时不获取,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;用另一个名称调用 `requestWorktree` 会改变下一次尝试;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。
|
||||
worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。请求用本地分支或远程跟踪分支的完整引用名指定基准(早期面板记录的本地短名称仍可解析),并可指定分支名。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;基准为空时以 `forgePanel/invalid-branch` 拒绝;Git 不接受分支名时以 `forgePanel/invalid-name` 拒绝;检出中已有同名分支时以 `forgePanel/branch-exists` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的下一轮队列时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。排给下一步的消息(例如其他插件注入的通知)不开启一轮,也不启动暂留。暂留用请求的分支名或新的自动名称进行一次尝试,基准是远程跟踪分支时请 worktree 服务先获取它;它在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、是否获取、失败步骤、原因以及分支或目录是否已存在以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,`fetch` 参数为 false 时不获取,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;用另一个名称调用 `requestWorktree` 会改变下一次尝试;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入下一轮队列的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。
|
||||
|
||||
|
||||
恢复在修改前记录 `restoring`,仅在成功后记录 `restored`。投影版本 3 在重载后保留未完成的恢复。目录存在本身不能放行等待的消息:检出根目录与公共 Git 目录必须匹配记录的工作树。插件卸载会取消并等待所有创建、恢复与消息等待任务,然后释放面板读取器和投影。
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
/**
|
||||
* One change request as a card: its one-line title links to the host and
|
||||
* crawls into view while the pointer rests on the card's head, a one-line
|
||||
* summary shows while collapsed, taking the short wording of failed checks
|
||||
* while the full one does not fit and crawling with the title past that, and
|
||||
* while expanded one row per fact (checks, review, merge state, the changed
|
||||
* lines, which open its changes, and the linked issues) above the merge
|
||||
* action. Opening, copying, viewing changes, marking a draft ready, and
|
||||
* removing live in the card's actions menu.
|
||||
* One change request as a compact card of the Session panel: one line with
|
||||
* the state glyph, the title, the number, and the checks outcome, which opens
|
||||
* the changes view, and, while expanded, one row per fact (checks, review,
|
||||
* merge state, the changed lines, which open its changes too, and the linked
|
||||
* issues) above the merge action. Opening on the host, copying, viewing
|
||||
* changes, marking a draft ready, and removing live in the card's actions
|
||||
* menu, which shows on hover or focus as on the panel's other rows.
|
||||
*/
|
||||
|
||||
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type PointerEvent, type ReactNode, type RefObject } from 'react'
|
||||
import { useId, useState, type MouseEvent, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular,
|
||||
IconEllipsisOutlineRegular, IconFilesDiffOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, MarqueeText, Menu,
|
||||
MenuItemButton, StateDot, Tooltip, useHoverMarquee,
|
||||
type MenuEntry, type MenuItem,
|
||||
Button, HoverCard, IconCheckCircleOutlineRegular, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular,
|
||||
IconEllipsisOutlineRegular, IconFilesDiffOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, Menu,
|
||||
MenuItemButton, StateDot, Tooltip,
|
||||
type MenuEntry, type MenuItem, type StateDotState,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {
|
||||
ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, MergeMethod, MergeRequest,
|
||||
@@ -27,7 +27,7 @@ import { formatAgo } from './format.ts'
|
||||
import { ChangeRequestGlyph, CheckGlyph } from './glyphs.tsx'
|
||||
import type { ForgePanelKey, NS } from './locales.ts'
|
||||
import type { ForgeChangeRequestCardActionsProps } from './slots.ts'
|
||||
import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf } from './status.ts'
|
||||
import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf, type ChangeRequestTone } from './status.ts'
|
||||
import css from './Forge.module.css'
|
||||
|
||||
type Translate = PropsLocale<typeof NS>['t']
|
||||
@@ -55,6 +55,10 @@ export interface ChangeRequestActions extends OverviewActions {
|
||||
readonly viewChanges?: ((entry: ForgePanelChangeRequest) => void) | undefined
|
||||
/** Draw the icon buttons plugins add to the card's head through `forge.change-request.card.actions`. */
|
||||
readonly renderActions?: ((owner: ForgeChangeRequestCardActionsProps) => ReactNode) | undefined
|
||||
/**
|
||||
* Draw the content of the card's hover card, as the Session panel's rows do. A surface without it shows none.
|
||||
*/
|
||||
readonly renderDetails?: ((details: PanelDetailsProps) => ReactNode) | undefined
|
||||
}
|
||||
|
||||
/** Props of one change request card. */
|
||||
@@ -173,97 +177,50 @@ function finished(snapshot: ChangeRequestSnapshot, now: number, t: Translate): s
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapsed status after the number: checks and the most urgent flag, the merge or close time, or a read in progress.
|
||||
* With `short`, failed checks take the wording without their count.
|
||||
* The checks outcome after the number: a spinner before the first read, the combined outcome of an open change
|
||||
* request that has checks, and nothing for a finished one, whose glyph already says how it ended.
|
||||
*/
|
||||
function Summary({ snapshot, now, short, t }: {
|
||||
readonly snapshot: ChangeRequestSnapshot | null
|
||||
readonly now: number
|
||||
readonly short: boolean
|
||||
readonly t: Translate
|
||||
}): ReactNode {
|
||||
if (snapshot === null) return <StateDot state="ongoing" size={11} />
|
||||
if (snapshot.state !== 'open') {
|
||||
return <span className={css.finished} data-tone={snapshot.state}>{finished(snapshot, now, t)}</span>
|
||||
}
|
||||
function Mark({ snapshot }: { readonly snapshot: ChangeRequestSnapshot | null }): ReactNode {
|
||||
if (snapshot === null) return <StateDot state="ongoing" size={12} />
|
||||
if (snapshot.state !== 'open') return null
|
||||
const ci = ciSummary(snapshot)
|
||||
const flag = flagOf(snapshot)
|
||||
return (
|
||||
<>
|
||||
<span className={css.ci} data-tone={ci.kind === 'failed' ? 'error' : undefined}>
|
||||
{ci.kind !== 'none' && <CheckGlyph state={ci.kind === 'cancelled' ? 'cancelled' : ROLLUP[snapshot.checksRollup]} size={12} />}
|
||||
{ci.kind === 'failed'
|
||||
? ci.count > 0 && !short ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted')
|
||||
: ci.kind === 'cancelled' ? t('change.ci.cancelled', { count: ci.count }) : t(`change.ci.${ci.kind}`)}
|
||||
</span>
|
||||
{flag !== undefined && <span className={css.flag} data-flag={flag}>{t(`change.flag.${flag}`)}</span>}
|
||||
</>
|
||||
)
|
||||
if (ci.kind === 'none') return null
|
||||
return <CheckGlyph state={ci.kind === 'cancelled' ? 'cancelled' : ROLLUP[snapshot.checksRollup]} size={12} />
|
||||
}
|
||||
|
||||
/**
|
||||
* What the collapsed status line shows when its failed checks can take the shorter wording without their count: the full
|
||||
* wording and the flag, which decide the line's width. Null for any other status, and where the language's short wording
|
||||
* is no shorter.
|
||||
* The status in words: the checks and the most urgent flag of an open change request, or the merge or close time.
|
||||
* The card's line shows it as glyphs, so assistive technology and the hover card read it here.
|
||||
* @param snapshot - change request status.
|
||||
* @param now - current epoch milliseconds for the relative time.
|
||||
* @param t - copy.
|
||||
* @returns the line's full text after the number, or null.
|
||||
* @returns the status text.
|
||||
*/
|
||||
function shortenable(snapshot: ChangeRequestSnapshot | null, t: Translate): string | null {
|
||||
if (snapshot?.state !== 'open') return null
|
||||
function statusText(snapshot: ChangeRequestSnapshot, now: number, t: Translate): string {
|
||||
if (snapshot.state !== 'open') return finished(snapshot, now, t)
|
||||
const ci = ciSummary(snapshot)
|
||||
if (ci.kind !== 'failed' || ci.count === 0) return null
|
||||
const full = t('change.ci.failed', { count: ci.count })
|
||||
if (t('change.ci.failedUnlisted').length >= full.length) return null
|
||||
const checks = ci.kind === 'failed'
|
||||
? ci.count > 0 ? t('change.ci.failed', { count: ci.count }) : t('change.ci.failedUnlisted')
|
||||
: ci.kind === 'cancelled' ? t('change.ci.cancelled', { count: ci.count }) : t(`change.ci.${ci.kind}`)
|
||||
const flag = flagOf(snapshot)
|
||||
return flag === undefined ? full : `${full} ${t(`change.flag.${flag}`)}`
|
||||
return flag === undefined ? checks : `${checks} · ${t(`change.flag.${flag}`)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the collapsed status line shows the short wording of failed checks: only while the line with the full wording
|
||||
* does not fit. A change of the line's width, of the fonts, or of `full` shows the full wording again for one layout pass,
|
||||
* which measures it and switches before the frame is painted.
|
||||
* @param line - the clipping status line.
|
||||
* @param full - the line's full text after the number, from {@link shortenable}; null measures nothing.
|
||||
* @returns whether the line takes the short wording.
|
||||
*/
|
||||
function useShortWording(line: RefObject<HTMLElement | null>, full: string | null): boolean {
|
||||
const [measured, setMeasured] = useState<{ readonly full: string | null; readonly short: boolean }>({ full: null, short: false })
|
||||
const short = full !== null && measured.full === full && measured.short
|
||||
useLayoutEffect(() => {
|
||||
if (full === null || short) return
|
||||
const element = line.current
|
||||
/* v8 ignore next -- the status line is mounted whenever there is a full wording to measure */
|
||||
if (element === null) return
|
||||
if (element.scrollWidth > element.clientWidth) setMeasured({ full, short: true })
|
||||
})
|
||||
useEffect(() => {
|
||||
if (full === null) return
|
||||
const element = line.current
|
||||
/* v8 ignore next -- the status line is mounted whenever there is a full wording to measure */
|
||||
if (element === null) return
|
||||
// A new object renders again even when the line already shows the full wording, so the layout effect measures.
|
||||
const measure = (): void => { setMeasured({ full, short: false }) }
|
||||
const observer = new ResizeObserver(measure)
|
||||
observer.observe(element)
|
||||
const fonts = document.fonts
|
||||
fonts.addEventListener('loadingdone', measure)
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
fonts.removeEventListener('loadingdone', measure)
|
||||
}
|
||||
}, [line, full])
|
||||
return short
|
||||
/** The state dot of the hover card: red for what needs the user, and a spinner while the checks run. */
|
||||
function dotOf(tone: ChangeRequestTone, snapshot: ChangeRequestSnapshot): StateDotState {
|
||||
if (tone === 'blocked') return 'error'
|
||||
if (snapshot.state !== 'open') return snapshot.state === 'merged' ? 'done' : 'idle'
|
||||
return snapshot.checksRollup === 'pending' ? 'ongoing' : snapshot.checksRollup === 'success' ? 'done' : 'idle'
|
||||
}
|
||||
|
||||
/** Expanded identity after the number: draft state and the head and base branches. */
|
||||
function Target({ snapshot, t }: { readonly snapshot: ChangeRequestSnapshot; readonly t: Translate }): ReactNode {
|
||||
return (
|
||||
<>
|
||||
{snapshot.state === 'open' && snapshot.draft && <span>{t('change.state.draft')}</span>}
|
||||
<span className={css.ellipsis}>{`${snapshot.headBranch} → ${snapshot.baseBranch}`}</span>
|
||||
</>
|
||||
)
|
||||
/** The hover card's line under the title: the number, draft state, and the head and base branches. */
|
||||
function identity(number: number | null, snapshot: ChangeRequestSnapshot | null, t: Translate): string[] {
|
||||
const parts = [
|
||||
...number === null ? [] : [t('change.number', { number })],
|
||||
...snapshot?.state === 'open' && snapshot.draft ? [t('change.state.draft')] : [],
|
||||
...snapshot === null ? [] : [`${snapshot.headBranch} → ${snapshot.baseBranch}`],
|
||||
]
|
||||
return parts.length === 0 ? [] : [parts.join(' · ')]
|
||||
}
|
||||
|
||||
/** The merge button and its menu: a title row, one row per method with the chosen one checked, and the confirmation. */
|
||||
@@ -369,8 +326,8 @@ function Primary({ entry, snapshot, name, actions, t }: {
|
||||
}
|
||||
|
||||
/**
|
||||
* The card's actions menu: open on the host, copy the link, view the changes
|
||||
* of a served change request, mark an open draft ready, and remove the binding.
|
||||
* The card's actions menu: view the changes of a served change request, open
|
||||
* on the host, copy the link, mark an open draft ready, and remove the binding.
|
||||
*/
|
||||
function CardMenu({ entry, snapshot, name, url, actions, t }: {
|
||||
readonly entry: ForgePanelChangeRequest
|
||||
@@ -392,12 +349,12 @@ function CardMenu({ entry, snapshot, name, url, actions, t }: {
|
||||
: undefined
|
||||
// Each item carries the action it runs, so a selection never reaches another item's action.
|
||||
const choices: { readonly item: MenuItem; readonly run: () => void }[] = [
|
||||
{ item: { id: 'open', label: t('change.view'), icon: <IconRightUpOutlineRegular size={14} /> }, run: () => { actions.openLink(url) } },
|
||||
{ item: { id: 'copy', label: t('change.copy'), icon: <IconCopyOutlineRegular size={14} /> }, run: () => { actions.copyLink(url) } },
|
||||
...viewChanges !== undefined && snapshot !== null && entry.ref !== null ? [{
|
||||
item: { id: 'changes', label: t('change.viewChanges'), icon: <IconFilesDiffOutlineRegular size={14} /> },
|
||||
run: () => { viewChanges(entry) },
|
||||
}] : [],
|
||||
{ item: { id: 'open', label: t('change.view'), icon: <IconRightUpOutlineRegular size={14} /> }, run: () => { actions.openLink(url) } },
|
||||
{ item: { id: 'copy', label: t('change.copy'), icon: <IconCopyOutlineRegular size={14} /> }, run: () => { actions.copyLink(url) } },
|
||||
...ready === undefined ? [] : [{
|
||||
item: { id: 'ready', label: t('change.markReady'), icon: <IconCheckCircleOutlineRegular size={14} />, disabled: busy },
|
||||
run: ready,
|
||||
@@ -423,13 +380,12 @@ function CardMenu({ entry, snapshot, name, url, actions, t }: {
|
||||
anchor={(
|
||||
<button
|
||||
type="button"
|
||||
className={`${css.iconButton} ${css.moreButton}`}
|
||||
aria-label={t('change.actions', { name })}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => { setOpen(!open) }}
|
||||
>
|
||||
<IconEllipsisOutlineRegular size={14} />
|
||||
<IconEllipsisOutlineRegular size={16} />
|
||||
</button>
|
||||
)}
|
||||
items={items}
|
||||
@@ -480,7 +436,10 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: {
|
||||
}
|
||||
|
||||
/**
|
||||
* Render one change request.
|
||||
* Render one change request. A press on the card's line opens the changes view of a change request a provider serves
|
||||
* and has read; with the platform's modifier key or the middle button, and for any other change request, it opens
|
||||
* the host's page. The line shows its status as glyphs and, while collapsed, reads it in words to assistive
|
||||
* technology, which the expanded rows do otherwise; the hover card names the full title, the branches, and that status.
|
||||
* @param props - change request, expansion, current time, actions, and copy.
|
||||
* @returns the card.
|
||||
*/
|
||||
@@ -492,68 +451,60 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc
|
||||
const notice = entry.ref === null ? 'change.unserved' : failure === undefined ? undefined : FAILURE[failure.code]
|
||||
const tone = toneOf(snapshot)
|
||||
const name = number === null ? snapshot?.title ?? url : t('change.number', { number })
|
||||
const titleRef = useRef<HTMLSpanElement>(null)
|
||||
const lineRef = useRef<HTMLSpanElement>(null)
|
||||
const titleMarquee = useHoverMarquee(titleRef)
|
||||
const lineMarquee = useHoverMarquee(lineRef)
|
||||
// One hover on the head carries every text it clips: the title, and the collapsed number and status line.
|
||||
const marquee = useMemo(() => ({
|
||||
onPointerEnter: (event: PointerEvent): void => {
|
||||
titleMarquee.onPointerEnter(event)
|
||||
lineMarquee.onPointerEnter(event)
|
||||
},
|
||||
onPointerLeave: (): void => {
|
||||
titleMarquee.onPointerLeave()
|
||||
lineMarquee.onPointerLeave()
|
||||
},
|
||||
}), [titleMarquee, lineMarquee])
|
||||
const short = useShortWording(lineRef, expanded || notice !== undefined ? null : shortenable(snapshot, t))
|
||||
// A notice replaces the collapsed summary, so a failed read never shows its stale status beside it.
|
||||
const meta = expanded
|
||||
? snapshot === null ? null : <Target snapshot={snapshot} t={t} />
|
||||
: notice === undefined ? <Summary snapshot={snapshot} now={now} short={short} t={t} /> : null
|
||||
const parts = (
|
||||
<>
|
||||
{number !== null && <span>{t('change.number', { number })}</span>}
|
||||
{number !== null && meta !== null && <span className={css.dot} aria-hidden="true">·</span>}
|
||||
{meta}
|
||||
</>
|
||||
)
|
||||
return (
|
||||
<li className={css.change} data-forge-change={entry.url} data-expanded={expanded ? '' : undefined}>
|
||||
<div className={css.changeHead} {...marquee}>
|
||||
<ChangeRequestGlyph tone={tone} size={16} label={t('change.stateAria', { state: t(TONE_LABEL[tone]) })} />
|
||||
<div className={css.headText}>
|
||||
<a
|
||||
className={css.changeTitle}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
actions.openLink(url)
|
||||
}}
|
||||
>
|
||||
<MarqueeText ref={titleRef}>{snapshot?.title ?? url.replace(/^https?:\/\//i, '')}</MarqueeText>
|
||||
</a>
|
||||
{(number !== null || meta !== null) && (
|
||||
<div className={css.meta}>
|
||||
{expanded ? parts : <MarqueeText ref={lineRef} className={css.statusLine}>{parts}</MarqueeText>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
const title = snapshot?.title ?? url.replace(/^https?:\/\//i, '')
|
||||
// A notice replaces the status, so a failed read never reads its stale status beside it.
|
||||
const status: PanelDetailsProps['status'] = notice !== undefined
|
||||
? { state: 'warning', label: t(notice) }
|
||||
: snapshot === null ? undefined : { state: dotOf(tone, snapshot), label: statusText(snapshot, now, t) }
|
||||
const viewChanges = snapshot !== null && entry.ref !== null ? actions.viewChanges : undefined
|
||||
const open = (event: MouseEvent): void => {
|
||||
if (viewChanges === undefined || event.metaKey || event.ctrlKey) actions.openLink(url)
|
||||
else viewChanges(entry)
|
||||
}
|
||||
const head = (
|
||||
<div className={css.changeHead} data-session-panel-row="">
|
||||
<button
|
||||
type="button"
|
||||
data-row-part="body"
|
||||
data-forge-opens={viewChanges === undefined ? 'link' : 'changes'}
|
||||
onClick={open}
|
||||
onAuxClick={(event) => { if (event.button === 1) actions.openLink(url) }}
|
||||
>
|
||||
<span data-row-part="icon">
|
||||
<ChangeRequestGlyph tone={tone} size={16} label={t('change.stateAria', { state: t(TONE_LABEL[tone]) })} />
|
||||
</span>
|
||||
<span data-row-part="content">{title}</span>
|
||||
</button>
|
||||
<span data-row-part="trailing" className={css.status}>
|
||||
{number !== null && <span className={css.number}>{t('change.number', { number })}</span>}
|
||||
{notice === undefined && <Mark snapshot={snapshot} />}
|
||||
{!expanded && notice === undefined && status !== undefined && <span className={css.visuallyHidden}>{status.label}</span>}
|
||||
{actions.renderActions?.({ url: entry.url, ref: entry.ref, headSha: snapshot?.headSha ?? null, state: snapshot?.state ?? null })}
|
||||
</span>
|
||||
<span data-row-part="menu">
|
||||
<CardMenu entry={entry} snapshot={snapshot} name={name} url={url} actions={actions} t={t} />
|
||||
</span>
|
||||
<span data-row-part="trailing" className={css.end}>
|
||||
<button
|
||||
type="button"
|
||||
className={css.iconButton}
|
||||
className={css.expand}
|
||||
aria-expanded={expanded}
|
||||
aria-label={t(expanded ? 'change.collapse' : 'change.expand', { name })}
|
||||
onClick={onToggle}
|
||||
>
|
||||
<IconChevronDownOutlineRegular size={12} className={clsx(css.chevron, expanded && css.chevronOpen)} />
|
||||
<IconChevronDownOutlineRegular size={14} className={clsx(css.chevron, expanded && css.chevronOpen)} />
|
||||
</button>
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
const details = actions.renderDetails?.({
|
||||
title,
|
||||
lines: identity(number, snapshot, t),
|
||||
...status === undefined ? {} : { status },
|
||||
})
|
||||
return (
|
||||
<li className={css.change} data-forge-change={entry.url} data-expanded={expanded ? '' : undefined}>
|
||||
{details === undefined ? head : <HoverCard grouped anchor={head} content={details} />}
|
||||
{notice !== undefined && (
|
||||
<div className={css.notice}>
|
||||
<span>{t(notice)}</span>
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
}
|
||||
|
||||
.avatars > .avatar {
|
||||
box-shadow: 0 0 0 1.5px var(--dsw-alias-bg-layer-1);
|
||||
box-shadow: 0 0 0 1.5px var(--forge-card-surface, var(--dsw-alias-bg-layer-1));
|
||||
}
|
||||
|
||||
.moreCount {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/** Session panel section listing the Session's change requests, and its title control. */
|
||||
|
||||
import { useRef, type ReactNode } from 'react'
|
||||
import { useCallback, useRef, type ReactNode } from 'react'
|
||||
import {
|
||||
Button, IconWarningTriangleOutlineRegular, MarqueeText, useHoverMarquee,
|
||||
Button, HoverCardGroup, IconWarningTriangleOutlineRegular, MarqueeText, useHoverMarquee,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type {
|
||||
HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore,
|
||||
HostObservable, InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore,
|
||||
} from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ForgeReadiness, MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client'
|
||||
import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client'
|
||||
import type { ForgePanelChangeRequest, ForgePanelState } from '../types.ts'
|
||||
import { ChangeRequestCard, type ChangeRequestActions } from './ChangeRequestCard.tsx'
|
||||
import type { createChangeRequestsSectionStore } from './change-requests-store.ts'
|
||||
@@ -59,6 +59,7 @@ export interface ChangeRequestsSectionInjected {
|
||||
export type ChangeRequestsSectionProps =
|
||||
PropsRuntime<'conversation.session.panel.section'>
|
||||
& Pick<PropsRenderSlots<'forge.change-request.card.actions'>, 'renderSlot'>
|
||||
& PropsRenderFactories
|
||||
& InjectFace<ChangeRequestsSectionInjected>
|
||||
& PropsStore<ReturnType<typeof createChangeRequestsSectionStore>>
|
||||
& PropsLocale<typeof NS>
|
||||
@@ -77,6 +78,9 @@ export type ChangeRequestsActionsProps =
|
||||
|
||||
type Translate = ChangeRequestsSectionProps['t']
|
||||
|
||||
/** Cards the list shows before its fold control holds the rest back. */
|
||||
const FOLD_LIMIT = 3
|
||||
|
||||
/** Sign-in the repository's host still needs before its change requests show. */
|
||||
interface SignInNeed {
|
||||
readonly host: string
|
||||
@@ -144,20 +148,27 @@ function SignInRow({ need, copyText, t }: {
|
||||
* Render the Session's change request cards. The section shows while the
|
||||
* Session binds a change request or the repository's host needs sign-in, which
|
||||
* a status row above the cards says; a lost stream shows in the Environment
|
||||
* section instead. A card starts expanded when the Session binds
|
||||
* exactly one change request; a card the user expands or collapses keeps that
|
||||
* choice in the Session's store, across updates and while the panel is hidden.
|
||||
* Viewing changes closes the panel's overlay.
|
||||
* @param props - panel snapshot hooks, card actions, panel owner values, and copy.
|
||||
* section instead. The list shows three cards and then the panel's fold
|
||||
* control, which shows the rest; the choice is kept per Session. A card starts
|
||||
* expanded when the Session binds exactly one change request; a card the user
|
||||
* expands or collapses keeps that choice in the Session's store, across
|
||||
* updates and while the panel is hidden. Viewing changes closes the panel's
|
||||
* overlay.
|
||||
* @param props - panel snapshot hooks, card actions, panel owner values, the store, and copy.
|
||||
* @returns the cards, or null with neither bound change requests nor a sign-in to complete.
|
||||
*/
|
||||
export function ChangeRequestsSection({
|
||||
usePanel, useLocale, dismissOverlay, refresh, remove, markReady, merge, readChecks,
|
||||
rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, viewChanges, useStore, actions: store, renderSlot, t,
|
||||
rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, viewChanges, useStore, actions: store, renderSlot,
|
||||
renderFactorySlot, t,
|
||||
}: ChangeRequestsSectionProps): ReactNode {
|
||||
const snapshot = usePanel(current => current)
|
||||
const locale = useLocale(value => value)
|
||||
const chosen = useStore(current => current.expanded)
|
||||
const unfolded = useStore(current => current.unfolded)
|
||||
const renderDetails = useCallback(
|
||||
(details: PanelDetailsProps) => renderFactorySlot('conversation.session.panel.details', details), [renderFactorySlot],
|
||||
)
|
||||
const state = snapshot.state
|
||||
if (state === null) return null
|
||||
const signIn = signInNeedOf(state)
|
||||
@@ -170,30 +181,43 @@ export function ChangeRequestsSection({
|
||||
dismissOverlay()
|
||||
},
|
||||
renderActions: owner => renderSlot('forge.change-request.card.actions', owner),
|
||||
renderDetails,
|
||||
}
|
||||
const defaults = defaultExpanded(state.changeRequests)
|
||||
const expanded = (url: string): boolean => chosen[url] ?? defaults.has(url)
|
||||
const toggle = (url: string): void => { store.toggled(url, !expanded(url)) }
|
||||
const now = Date.now()
|
||||
const foldable = state.changeRequests.length > FOLD_LIMIT
|
||||
const shown = foldable && !unfolded ? state.changeRequests.slice(0, FOLD_LIMIT) : state.changeRequests
|
||||
const label = unfolded ? t('fold.less') : t('fold.more', { count: state.changeRequests.length - FOLD_LIMIT })
|
||||
return (
|
||||
<div className={css.cards} data-forge-panel="">
|
||||
{signIn !== null && <SignInRow need={signIn} copyText={copyText} t={t} />}
|
||||
{state.changeRequests.length > 0 && (
|
||||
<ul className={css.list}>
|
||||
{state.changeRequests.map(entry => (
|
||||
<ChangeRequestCard
|
||||
key={entry.url}
|
||||
entry={entry}
|
||||
expanded={expanded(entry.url)}
|
||||
onToggle={() => { toggle(entry.url) }}
|
||||
now={now}
|
||||
actions={actions}
|
||||
locale={locale}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{shown.length > 0 && (
|
||||
// Moving between cards swaps their hover cards without another dwell.
|
||||
<HoverCardGroup>
|
||||
<ul className={css.list}>
|
||||
{shown.map(entry => (
|
||||
<ChangeRequestCard
|
||||
key={entry.url}
|
||||
entry={entry}
|
||||
expanded={expanded(entry.url)}
|
||||
onToggle={() => { toggle(entry.url) }}
|
||||
now={now}
|
||||
actions={actions}
|
||||
locale={locale}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</HoverCardGroup>
|
||||
)}
|
||||
{foldable && renderFactorySlot('conversation.session.panel.fold', {
|
||||
expanded: unfolded,
|
||||
label,
|
||||
name: t('fold.name', { label }),
|
||||
onToggle: () => { store.unfoldedSet(!unfolded) },
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,134 +1,90 @@
|
||||
/* Change request cards in the Session panel section, at the panel's 13px row size. */
|
||||
.cards {
|
||||
--forge-fill: var(--dsw-alias-card-fill);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font-size: var(--dsh-content-font-size-secondary, 13px);
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.iconButton {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.iconButton:focus-visible {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.iconButton:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
}
|
||||
|
||||
/* A More button shares its surface: the glyph darkens without a fill, as on Session panel rows. */
|
||||
.iconButton.moreButton:focus-visible {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.iconButton.moreButton:hover {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
gap: 4px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
/* One change request: a filled block without a border, on the panel's row columns. The platform fill stands apart
|
||||
from the panel's surface in both themes; the card fill is nearly that surface's own color in the dark theme. */
|
||||
.change {
|
||||
min-width: 0;
|
||||
border: 0.5px solid var(--dsw-alias-border-l2);
|
||||
border-radius: var(--dsw-radius-md);
|
||||
background: var(--dsw-alias-bg-layer-1);
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
/* Named for what the block draws on itself, such as the ring that sets overlapping avatars apart. */
|
||||
--forge-card-surface: var(--dsw-alias-bg-module-platform);
|
||||
background: var(--forge-card-surface);
|
||||
}
|
||||
|
||||
/* Glyph, title link with the number line below it, then the actions menu
|
||||
and the expansion toggle. */
|
||||
.changeHead {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
padding: 12px 8px 10px 14px;
|
||||
/* The card's line is a panel row, 36px instead of 28px: the glyph in the icon column, the title, the number and the
|
||||
checks outcome, the actions menu the panel reveals on hover, and the expansion toggle in the end column. */
|
||||
.change .changeHead {
|
||||
min-height: 36px;
|
||||
}
|
||||
|
||||
.changeHead > .glyph {
|
||||
margin: 3px 10px 0 0;
|
||||
.change .changeHead > [data-row-part='body'] {
|
||||
height: 36px;
|
||||
}
|
||||
|
||||
/* The buttons center on the title's first line. */
|
||||
.changeHead > .iconButton {
|
||||
margin-top: -3px;
|
||||
/* The number and the checks outcome after the title. */
|
||||
.status {
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.headText {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
padding-top: 1px;
|
||||
.number {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.changeTitle {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font-weight: 500;
|
||||
line-height: 20px;
|
||||
text-decoration: none;
|
||||
/* The expansion toggle in the row's end column, 16px wide like the menu column: a 24px target around the chevron. */
|
||||
.change .changeHead > .end {
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
}
|
||||
|
||||
.expand {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
margin: -4px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--dsw-radius-xs);
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.expand:focus-visible {
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.changeTitle:hover {
|
||||
.expand:hover {
|
||||
color: var(--dsw-alias-label-primary);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.changeTitle:focus-visible,
|
||||
.rowButton:focus-visible {
|
||||
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* Number line below the title: the status while collapsed, the branches while expanded. */
|
||||
.meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
padding: 1px 0;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
/* Lifecycle glyph; drawn in the current color unless the state tints it. */
|
||||
.glyph {
|
||||
display: inline-flex;
|
||||
@@ -200,82 +156,27 @@
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
.ci {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.ci[data-tone='error'],
|
||||
.flag[data-flag='changesRequested'],
|
||||
.flag[data-flag='conflicting'] {
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
.flag {
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* Only the branch names and the collapsed status line shorten; the number, checks, and flags keep whole words on one line. */
|
||||
.meta > :not(.ellipsis):not(.statusLine) {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The collapsed number and status: one line as wide as the row, so a change of its wording never resizes it. It clips
|
||||
with an ellipsis and crawls with the title; its parts sit inline so the ellipsis cuts between characters. */
|
||||
.statusLine {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.statusLine .dot {
|
||||
margin: 0 6px;
|
||||
}
|
||||
|
||||
.statusLine .ci {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.statusLine .checkGlyph {
|
||||
margin-inline-end: 5px;
|
||||
vertical-align: -2px;
|
||||
}
|
||||
|
||||
.statusLine .flag {
|
||||
margin-inline-start: 6px;
|
||||
}
|
||||
|
||||
.finished {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.finished[data-tone='merged'] {
|
||||
color: var(--dsw-alias-state-done-primary);
|
||||
}
|
||||
|
||||
/* Read failure or unsupported host below the head, with its one action. */
|
||||
/* Read failure or unsupported host below the card's line, from where the title starts, with its one action. */
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 0 10px 10px 33px;
|
||||
padding: 0 8px 8px 30px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
/* Expanded facts, one sentence per row: an icon under the glyph, the value, an optional trailing part, and a chevron
|
||||
on a row that opens something. */
|
||||
/* Expanded facts inside the card's block, one sentence per row: an icon under the title's start, the value, an
|
||||
optional trailing part, and a chevron in the card's end column on a row that opens something. */
|
||||
.rows {
|
||||
/* Contains the visually hidden row labels, so they never extend a scroll area outside the panel. */
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: 24px minmax(0, 1fr) auto 12px;
|
||||
gap: 0 8px;
|
||||
padding: 4px 6px 6px;
|
||||
border-top: 0.5px solid var(--dsw-alias-border-l2);
|
||||
padding: 0 8px 4px 22px;
|
||||
}
|
||||
|
||||
.row {
|
||||
@@ -286,7 +187,7 @@
|
||||
column-gap: 8px;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-height: 32px;
|
||||
min-height: 28px;
|
||||
margin: 0;
|
||||
padding: 0 8px;
|
||||
border: 0;
|
||||
@@ -415,7 +316,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 2px 14px 12px;
|
||||
padding: 4px 8px 8px 26px;
|
||||
}
|
||||
|
||||
.primaryAction {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* The expansion the user chose for the change request cards of one Session. The
|
||||
* The expansion the user chose for the change request cards of one Session, and whether its list shows every card. The
|
||||
* registration declares it as an exclusive store, so each Session keeps its
|
||||
* choices while its scope is retained, across hiding and showing the panel.
|
||||
*/
|
||||
@@ -10,11 +10,14 @@ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-sto
|
||||
export interface ChangeRequestsSectionState {
|
||||
/** Whether the user expanded (true) or collapsed (false) a card, by change request URL; unchosen cards are absent. */
|
||||
expanded: Record<string, boolean>
|
||||
/** Whether the list shows the cards past its first three. */
|
||||
unfolded: boolean
|
||||
}
|
||||
|
||||
/** The change requests section store's write set. */
|
||||
type ChangeRequestsSectionActions = {
|
||||
toggled: (draft: ChangeRequestsSectionState, url: string, expanded: boolean) => void
|
||||
unfoldedSet: (draft: ChangeRequestsSectionState, unfolded: boolean) => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,7 +26,7 @@ type ChangeRequestsSectionActions = {
|
||||
*/
|
||||
export function createChangeRequestsSectionStore(): EngineStoreHandle<ChangeRequestsSectionState, ChangeRequestsSectionActions> {
|
||||
return defineStore({
|
||||
init: (): ChangeRequestsSectionState => ({ expanded: {} }),
|
||||
init: (): ChangeRequestsSectionState => ({ expanded: {}, unfolded: false }),
|
||||
actions: {
|
||||
/**
|
||||
* Record the user's choice for one card.
|
||||
@@ -34,6 +37,14 @@ export function createChangeRequestsSectionStore(): EngineStoreHandle<ChangeRequ
|
||||
toggled: (d, url: string, expanded: boolean) => {
|
||||
d.expanded[url] = expanded
|
||||
},
|
||||
/**
|
||||
* Show every card of the list, or fold it to its first three again.
|
||||
* @param d - draft state.
|
||||
* @param unfolded - whether the list now shows every card.
|
||||
*/
|
||||
unfoldedSet: (d, unfolded: boolean) => {
|
||||
d.unfolded = unfolded
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { IconCheckCircleFillRegular, IconCloseCircleFillRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { IconCheckCircleFillRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { CheckState, ChecksRollup } from '@deepseek-ai/dsh-experimental-forge/types'
|
||||
import type { ChangeRequestTone } from './status.ts'
|
||||
import css from './Forge.module.css'
|
||||
@@ -125,25 +125,24 @@ const CHECK_TONE: Record<CheckState, string | undefined> = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the decorative outcome of one check beside its text: a filled circle
|
||||
* for success or failure, a half-filled ring while it runs, and an empty ring
|
||||
* for neutral, skipped, and cancelled checks.
|
||||
* Draw the decorative outcome of one check beside its text, each inside the same ring: a check for success, a cross
|
||||
* for failure, a half fill while it runs, and a dash for neutral, skipped, and cancelled checks. The ring has the
|
||||
* radius and width of the success icon's, so mixed outcomes read as one set.
|
||||
* @param props.state - check outcome.
|
||||
* @param props.size - width and height in pixels, 16 by default.
|
||||
* @returns the glyph.
|
||||
*/
|
||||
export function CheckGlyph({ state, size = 16 }: { readonly state: CheckState; readonly size?: number | undefined }): ReactNode {
|
||||
const running = state === 'pending'
|
||||
return (
|
||||
<span className={clsx(css.checkGlyph, CHECK_TONE[state])} data-forge-check={state} aria-hidden="true">
|
||||
{state === 'success' && <IconCheckCircleFillRegular size={size} />}
|
||||
{state === 'failure' && <IconCloseCircleFillRegular size={size} />}
|
||||
{state !== 'success' && state !== 'failure' && (
|
||||
{state === 'success' ? <IconCheckCircleFillRegular size={size} /> : (
|
||||
<svg width={size} height={size} viewBox="0 0 16 16" fill="none">
|
||||
<circle cx="8" cy="8" r="6.25" stroke="currentColor" strokeWidth={1.5} />
|
||||
{running
|
||||
? <path d="M8 3.5A4.5 4.5 0 0 1 8 12.5Z" fill="currentColor" />
|
||||
: <path d="M5.5 8H10.5" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" />}
|
||||
<circle cx="8" cy="8" r="7.25" stroke="currentColor" strokeWidth={1.3} />
|
||||
{state === 'failure'
|
||||
? <path d="M5.9 5.9L10.1 10.1M10.1 5.9L5.9 10.1" stroke="currentColor" strokeWidth={1.5} strokeLinecap="square" />
|
||||
: state === 'pending'
|
||||
? <path d="M8 2.8A5.2 5.2 0 0 1 8 13.2Z" fill="currentColor" />
|
||||
: <path d="M5.5 8H10.5" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" />}
|
||||
</svg>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -97,6 +97,9 @@ export const zh = {
|
||||
'list.worktree': '在自己的工作树中',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '还有 {count} 个变更请求',
|
||||
'fold.more': '显示其余 {count} 个',
|
||||
'fold.less': '收起',
|
||||
'fold.name': '{label}(变更请求)',
|
||||
'change.expand': '展开 {name}',
|
||||
'change.collapse': '收起 {name}',
|
||||
'change.ci.none': '没有检查',
|
||||
@@ -585,6 +588,9 @@ export const en: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'In its own worktree',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '{count} more change requests',
|
||||
'fold.more': 'Show {count} more',
|
||||
'fold.less': 'Show less',
|
||||
'fold.name': '{label} (change requests)',
|
||||
'change.expand': 'Expand {name}',
|
||||
'change.collapse': 'Collapse {name}',
|
||||
'change.ci.none': 'No checks',
|
||||
@@ -1043,6 +1049,9 @@ export const ja: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': '専用のワークツリー内',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '他 {count} 件の変更リクエスト',
|
||||
'fold.more': '残り{count}件を表示',
|
||||
'fold.less': '折りたたむ',
|
||||
'fold.name': '{label}(変更リクエスト)',
|
||||
'tab.title': '変更リクエスト',
|
||||
'header.attention': 'このセッションの変更リクエストに対応が必要です',
|
||||
'checkout.worktree': 'ワークツリー',
|
||||
@@ -1528,6 +1537,9 @@ export const es: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'En su propio árbol de trabajo',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '{count} solicitudes de cambio más',
|
||||
'fold.more': 'Mostrar {count} más',
|
||||
'fold.less': 'Mostrar menos',
|
||||
'fold.name': '{label} (solicitudes de cambio)',
|
||||
'tab.title': 'Solicitudes de cambio',
|
||||
'header.attention': 'Las solicitudes de cambio de esta sesión requieren atención',
|
||||
'checkout.worktree': 'Árbol de trabajo',
|
||||
@@ -2013,6 +2025,9 @@ export const fr: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'Dans son propre arbre de travail',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '{count} demandes de changement supplémentaires',
|
||||
'fold.more': 'Afficher {count} de plus',
|
||||
'fold.less': 'Afficher moins',
|
||||
'fold.name': '{label} (demandes de modification)',
|
||||
'tab.title': 'Demandes de modification',
|
||||
'header.attention': 'Les demandes de modification de cette session nécessitent une intervention',
|
||||
'checkout.worktree': 'Arbre de travail',
|
||||
@@ -2498,6 +2513,9 @@ export const de: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'Im eigenen Arbeitsbaum',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': '{count} weitere Änderungsanfragen',
|
||||
'fold.more': '{count} weitere anzeigen',
|
||||
'fold.less': 'Weniger anzeigen',
|
||||
'fold.name': '{label} (Änderungsanfragen)',
|
||||
'tab.title': 'Änderungsanfragen',
|
||||
'header.attention': 'Änderungsanfragen dieser Sitzung erfordern Aufmerksamkeit',
|
||||
'checkout.worktree': 'Arbeitsbaum',
|
||||
@@ -2983,6 +3001,9 @@ export const ru: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'В собственном рабочем дереве',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': 'Ещё запросов на изменение: {count}',
|
||||
'fold.more': 'Показать ещё {count}',
|
||||
'fold.less': 'Свернуть',
|
||||
'fold.name': '{label} (запросы на изменение)',
|
||||
'tab.title': 'Запросы на изменение',
|
||||
'header.attention': 'Запросы на изменение этого сеанса требуют внимания',
|
||||
'checkout.worktree': 'Рабочее дерево',
|
||||
@@ -3468,6 +3489,9 @@ export const pt: Record<ForgePanelKey, string> = {
|
||||
'list.worktree': 'Na sua própria árvore de trabalho',
|
||||
'list.stateChecks': '{state} · {checks}',
|
||||
'list.more': 'Mais {count} solicitações de alteração',
|
||||
'fold.more': 'Mostrar mais {count}',
|
||||
'fold.less': 'Mostrar menos',
|
||||
'fold.name': '{label} (solicitações de alteração)',
|
||||
'tab.title': 'Solicitações de alteração',
|
||||
'header.attention': 'As solicitações de alteração desta sessão precisam de atenção',
|
||||
'checkout.worktree': 'Árvore de trabalho',
|
||||
|
||||
@@ -14,7 +14,7 @@ import type {
|
||||
import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session'
|
||||
import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types'
|
||||
import { appendPluginRecord } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent, UserMessage } from '@deepseek-ai/dsh-session'
|
||||
import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection'
|
||||
import type {} from '@deepseek-ai/dsh-session-projection-cache'
|
||||
import type {} from '@deepseek-ai/dsh-session-query'
|
||||
@@ -178,7 +178,7 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
this.creations = new WorktreeCreations(ctx, this.worktreeStates, this.config.worktreePrefix, (session) => {
|
||||
this.panels.get(session)?.updateWorktree()
|
||||
})
|
||||
const inbox = ctx.on('agent/inbox/inserted', ({ agent }) => { this.holdTurn(agent) })
|
||||
const inbox = ctx.on('agent/inbox/inserted', ({ agent, message }) => { this.holdTurn(agent, message) })
|
||||
const events = ctx.on('session/event', (session: Session, event: SessionEvent) => {
|
||||
this.panels.get(session)?.observe(event)
|
||||
})
|
||||
@@ -967,14 +967,17 @@ export class ForgePanelController extends TypertRemoteService {
|
||||
/* oxlint-enable typescript/require-await */
|
||||
|
||||
/**
|
||||
* Hold the turn of a message entering a Session's inbox while the
|
||||
* Hold the turn of a message entering a Session's next-turn queue while the
|
||||
* Session's requested worktree does not exist yet, or while the worktree
|
||||
* the Session works in is checked and, when gone, until it is restored or
|
||||
* left. The message is entering, so the delivery has not woken the Agent
|
||||
* yet and its wake waits for the hold.
|
||||
* yet and its wake waits for the hold. A message for the next step, such as
|
||||
* a notice another plugin queues, opens no turn and gets no hold.
|
||||
* @param agent - Agent whose inbox receives the message.
|
||||
* @param message - the entering message.
|
||||
*/
|
||||
private holdTurn(agent: Agent): void {
|
||||
private holdTurn(agent: Agent, message: UserMessage): void {
|
||||
if (!agent.inbox.nextTurn.some(queued => queued.id === message.id)) return
|
||||
const session = agent.session
|
||||
const state = this.worktreeState(session)
|
||||
if (state.request !== null && state.created === null && !state.locked) {
|
||||
|
||||
Loaded 100 of 240 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user