diff --git a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.i18n.yaml index d4ee6089be..179c89b322 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.i18n.yaml @@ -9,11 +9,11 @@ en: a22ddcfb339e503d zh: a1f4fadb46fce1e7 /agent-note-native-cua-objects-independent-of-evaluator-ownership/decision: - en: 176a9c2f6040f2a1 - zh: 2617ec13d25de998 + en: d08345b0b22b0884 + zh: 18a843df211bcabc /agent-note-native-cua-objects-independent-of-evaluator-ownership/alternatives-considered: - en: 3d0bc77e3c432cb9 - zh: 50a20eda1811f16c + en: f2bb7165b7c168a0 + zh: e6234e3464d971ee /agent-note-native-cua-objects-independent-of-evaluator-ownership/consequences: en: 528c644d5810e60b zh: 9649dfc3b1172a6d diff --git a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.md b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.md index 38b074818f..b4d450e2b0 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.md +++ b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.md @@ -14,7 +14,7 @@ The shared `cua` library owns application/window objects, consent, and logged di The experimental CUA package owns a native-app subset of the Codex-style object interface and selected MIT-licensed macOS behavior adapted from Cua Driver in a Swift helper. A source manifest records the adapted upstream files and local implementation. The helper is locally compiled; the package has no external Cua Driver runtime dependency. The existing [provider registration](2026-09-12-computer-use-provider-registration.md) prevents competing computer-use providers within one composition. -The facade accepts an operation dispatcher. Its tool adapter resolves the current tool binding for each operation, preserving normal authorization, logging and image admission. The execution host owns variable persistence and completion serialization. CUA defines no persistence directive, worker or run_code replacement. +The facade accepts an operation dispatcher. Its tool adapter resolves the current tool binding for each operation, preserving normal authorization, logging and image admission. The execution host owns variable persistence and completion serialization. The object API defines no persistence directive or evaluator; [CUA programs outside PTC](2026-11-09-cua-program-tool.md) supersedes the original exclusion of a dedicated program entry by composing the shared PTC factory and Node runtime. Native process ownership follows the [shared helper decision](2026-10-09-cua-shared-native-helper.md), with isolated Agent connections. App handles bind process identity and kernel start time; replacing the process or helper never revives old handles. The native helper retains per-app and per-window snapshots. The [object API](2026-11-05-cua-scoped-surfaces-and-input.md) keeps the latest successful observation per application handle. Coordinate actions select an owned window; the Host maps [screenshot coordinates](2026-10-13-cua-hover-routes-and-coordinates.md) to native window-local points. Providers declare keyboard scopes in `keyboard`. macOS supports keyboard input at the application's current focus. @@ -22,7 +22,7 @@ The operation schema owns shared data declarations. Host-only limits and launch Clipboard paste is distinct from Unicode key input: Return and Tab key events can trigger actions instead of inserting clipboard content. Pasteboard access runs on the AppKit main actor and retains promised data until a reader requests it. AX command completion alone does not establish that the application has fetched the data. Restoration checks ownership before replacing contents; the caller still verifies the application result. After successful command dispatch, `pasteReadTimeoutMs` bounds waiting for a data request, with a default of 1000 ms. Expiry returns `PASTE_NOT_CONSUMED`, closes the data provider against late delivery, and restores the clipboard only while still owned. The failure reports no read within that interval; it does not prove the application will never process its queued Paste command. A delayed command may read restored clipboard contents, so callers inspect the target and never retry automatically. Foreground-dependent consumption was observed in the installed ChatGPT/Codex application (`com.openai.codex`); other applications need their own validation. Guidance presents this as an example and applies recovery instructions to any `PASTE_NOT_CONSUMED` result. -CUA registers its own Harness tool and returns operation values directly. Screenshot capture requires a resolved image-capable model and the shared attachment service. The tool admits each screenshot once and renders its durable image reference; the window object and image sink retain the same `CuaScreenshot` containing encoded `bytes`, `mimeType`, `pixelWidth`, `pixelHeight` and `windowId` from the validated screenshot result. The bridge preserves this metadata without another upload or image emission. Callers use the reported format and dimensions when saving or declaring images. +CUA registers its own Harness tool and returns operation values directly. Screenshot capture requires a resolved image-capable model and the shared attachment service. The attachment pipeline stores the screenshot at the dimensions used for coordinate mapping; the native tool result describes its encoded format and pixels. The program facade returns observation results, including the stored Image for a screenshot. The [explicit PTC output decision](2026-11-09-explicit-ptc-output.md) owns image identity and caller-selected display. ## Alternatives considered @@ -32,7 +32,7 @@ A CUA-specific persistent evaluator duplicates execution lifecycle policy and pr Reusing the MCP result adapter would impose MCP envelopes and wire validation on native CUA operations. Direct Harness tool output and shared attachment admission provide the needed logging and images without a second protocol. -**Fixing the screenshot format** would require otherwise unnecessary re-encoding and discard the attachment pipeline’s pass-through optimization. A format convention alone still forces callers to guess, and cannot tell them when encoding policy changes. Returning the already computed format and dimensions preserves pass-through and makes each result describe its actual bytes. +**Fixing the screenshot format** would require otherwise unnecessary re-encoding and discard the attachment pipeline’s pass-through optimization. The native result describes its encoding; program Images expose the stored file and its pixel dimensions, so callers can use the file without a facade-specific byte representation. **Waiting until the full native-operation timeout** hides successful command dispatch behind a generic timeout. A separate configurable read budget reports the missing acknowledgement without treating slow applications as unsupported. Requiring every application to be foreground would claim a prerequisite that the available observations do not establish. diff --git a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.zh.md b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.zh.md index 7cd542b0f7..d37aa929b1 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-experimental-cua-object-api.zh.md @@ -14,7 +14,7 @@ Computer-use 程序需要一致的应用和窗口操作。将这些操作与 CUA 实验 CUA 包提供 Codex 风格的原生应用对象接口,并在 Swift 辅助进程中改写 Cua Driver 中选取的 MIT 许可 macOS 行为。源码清单记录改写的上游文件和本地实现。辅助进程在本地编译,本包不依赖外部 Cua Driver 运行时。已有的 [provider 注册机制](2026-09-12-computer-use-provider-registration.zh.md)防止同一组合中出现竞争 provider。 -对象接口接收操作分派器。工具适配模块每次操作都获取当前工具绑定,保留标准授权、日志和图片接入。执行宿主负责变量持久化和最终表达式值的序列化。CUA 不定义持久化指令、执行 worker 或 run_code 替代实现。 +对象接口接收操作分派器。工具适配模块每次操作都获取当前工具绑定,保留标准授权、日志和图片接入。执行宿主负责变量持久化和最终表达式值的序列化。对象 API 不定义持久化指令或求值器;[PTC 之外的 CUA 程序](2026-11-09-cua-program-tool.zh.md)通过组合共享 PTC 工厂和 Node 运行时,取代原先不提供专用程序入口的决定。 原生进程归属遵循[共享 helper 决策](2026-10-09-cua-shared-native-helper.zh.md),Agent 连接保持隔离。应用句柄绑定进程身份及内核启动时间,替换进程或辅助进程不会使旧句柄重新有效。原生 helper 按应用和可选窗口保存快照。[对象 API](2026-11-05-cua-scoped-surfaces-and-input.zh.md) 为每个应用句柄保留最近一次成功读取的快照。坐标操作选择属于该应用的窗口;Host 按[截图坐标规则](2026-10-13-cua-hover-routes-and-coordinates.zh.md)换算为原生窗口内 point。提供方通过 `keyboard` 声明可用范围。macOS 仅支持向应用当前焦点发送键盘输入。 @@ -22,7 +22,7 @@ Computer-use 程序需要一致的应用和窗口操作。将这些操作与 CUA 剪贴板粘贴与 Unicode 按键输入分别实现,因为 Return 和 Tab 按键可能触发动作,而不是插入剪贴板内容。剪贴板访问使用 AppKit 主线程,保留延迟提供的数据直到读取方请求。AX 命令完成本身不能证明应用已取得数据。恢复前检查剪贴板归属;调用方仍需验证应用中的结果。 命令成功分派后,`pasteReadTimeoutMs` 限制等待数据请求的时间,默认 1000 毫秒。到期返回 `PASTE_NOT_CONSUMED`,关闭数据提供方以阻止迟到的数据交付,并仅在仍持有剪贴板时恢复原内容。该失败只说明这段时间内没有读取,不证明应用以后不会处理已排队的 Paste 命令。迟到的命令可能读取恢复后的剪贴板内容,因此调用方必须检查目标,不能自动重试。已安装的 ChatGPT/Codex 应用(`com.openai.codex`)已观察到依赖前台才能读取的行为,其他应用需要分别验证。指引将其写为例子,并对任何 `PASTE_NOT_CONSUMED` 结果提供恢复步骤。 -CUA 注册自己的 Harness 工具,直接返回操作结果。截图要求解析到支持图片输入的模型,并提供共享附件服务。工具只接入一次截图,再渲染持久图片引用;窗口对象和图片输出回调保留同一个 `CuaScreenshot`,其中的编码 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 来自已校验的截图结果。桥接保留这些元数据,不再次上传或输出图片。调用方落盘或声明图片时使用返回的格式和尺寸。 +CUA 注册自己的 Harness 工具,直接返回操作结果。截图要求解析到支持图片输入的模型,并提供共享附件服务。附件流水线按坐标换算使用的尺寸保存截图,原生工具结果描述编码格式和像素。程序对象接口返回观察结果,截图操作返回已存储的 `Image`。[PTC 显式输出决策](2026-11-09-explicit-ptc-output.zh.md)负责图片身份及调用方选择展示的规则。 ## 考虑过的替代方案 @@ -32,7 +32,7 @@ CUA 专用持久执行器会重复实现执行生命周期规则,使 PTC 无 复用 MCP 结果适配器会给原生 CUA 操作引入 MCP 信封和协议校验。直接使用 Harness 工具输出与共享附件接入,即可取得所需的日志和图片能力,无需再经过一种协议。 -**固定截图格式**会要求原本不需要的重新编码,并失去附件处理的原样直通优化。仅约定格式仍要求调用方猜测,也无法告知编码策略的变化。返回已经算出的格式和尺寸,既保留直通优化,也让每个结果说明其实际字节。 +**固定截图格式**会要求原本不需要的重新编码,并失去附件处理的原样直通优化。原生结果描述编码格式;程序 Image 提供已存储文件及其像素尺寸,使调用方直接使用文件,无需对象接口专属的字节表示。 **等到原生操作的总超时**会用一条通用超时掩盖命令已经成功分派的事实。独立、可配置的读取等待上限能报告缺失的读取确认,而不将响应慢的应用认定为不支持粘贴。要求所有应用都必须位于前台,则超出了现有观察能支持的结论。 diff --git a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.i18n.yaml index 4a705f767e..40b3044fa1 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.i18n.yaml @@ -15,5 +15,5 @@ en: d6f40bf02df37ab7 zh: e5b85ce9d41e8754 /agent-note-ship-experimental-capabilities-as-optional-bundles/consequences: - en: 3064da835e892958 - zh: bfcf967b6acc6f85 + en: 49e2c3f9f641c38b + zh: 3aa772fb43c4bb6e diff --git a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.md b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.md index 2c5e6a73b5..d44030d607 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.md +++ b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.md @@ -34,4 +34,4 @@ Computer Use is a shipped optional bundle in the experimental group. Its bundle Official discovery does not imply experimental status or a different plugin lifecycle. Switching a bundle off keeps its installed files; failed activation retains the existing saved-selection behavior. Bundle rows are ordinary Host rows with their usual switches. Individual and combined composition tests cover the Host rows and every preset's tool catalog; live switching and recorded Sessions cover activation and model-visible behavior. -Computer Use keeps its permission service and native provider on the Host and registers tools in Agent scopes whose bound preset is `ptc`. Existing Agent events and `createScope()` maintain current, new and resumed Agents. Preset declarations remain unchanged. Only the explicit detail-page action changes the new-session default through the existing settings form; the activation switch does not configure PTC execution. +Computer Use keeps its permission service and native provider on the Host and registers tools in Agent scopes. The preset named by `agentPreset` receives raw `cua`; other composed presets receive the [CUA program tool](2026-11-09-cua-program-tool.md). Existing Agent events and `createScope()` maintain current, new and resumed Agents. Preset declarations remain unchanged. Only the explicit detail-page action changes the new-session default through the existing settings form; the activation switch does not configure PTC execution. diff --git a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.zh.md b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.zh.md index 31afdf2f3f..05573dd50a 100644 --- a/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-21-experimental-capabilities-as-optional-bundles.zh.md @@ -34,4 +34,4 @@ Computer Use 是 experimental 包组内随安装提供的可选组合包。组 官方发现不表示实验性状态,也不引入不同的插件生命周期。关闭 bundle 保留已安装文件;激活失败保留现有的已保存选择行为。Bundle 行是普通 Host 行,使用常规开关。独立与组合测试覆盖 Host 行及每个预设的工具目录;实时切换与已记录 Session 覆盖激活和模型可见行为。 -Computer Use 将权限服务和原生提供方保留在 Host,在已绑定 `ptc` preset 的 Agent 作用域中注册工具。现有 Agent 事件和 `createScope()` 维护当前、新建和恢复的 Agent,preset 声明保持不变。只有详情页的显式操作通过现有设置表单修改新会话默认模式,启用开关不配置 PTC 执行方式。 +Computer Use 将权限服务和原生提供方保留在 Host,并在 Agent 作用域中注册工具。`agentPreset` 指定的 preset 获得原始 `cua`;其他已组合的 preset 获得 [CUA 程序工具](2026-11-09-cua-program-tool.zh.md)。现有 Agent 事件和 `createScope()` 维护当前、新建和恢复的 Agent,preset 声明保持不变。只有详情页的显式操作通过现有设置表单修改新会话默认模式,启用开关不配置 PTC 执行方式。 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index 3e32b6eb92..81912accfe 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -9,8 +9,8 @@ en: f72db0b79aa02fb5 zh: b91c1f177dc93ab4 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision: - en: ec115e11f96ffe60 - zh: c1fe9eb2866196d0 + en: 41fd533d5be7642b + zh: c6fcbabec22bdbb7 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered: en: 32c970ae153e0f6c zh: 8431be0a10ffed15 diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md index cce266e52b..6d9aea0408 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -16,7 +16,7 @@ Provider startup capabilities are static. Platform, supported methods, applicati Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names. -Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getWindow` reads its initial tree silently; `getApp` does the same when the provider reports application-level accessibility. A later `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime. +Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getApp` and `getWindow` select objects without reading accessibility or replacing that snapshot; native window operations reject closed or foreign windows. An explicit `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md index 5135dc9be8..ceed375ff3 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -16,7 +16,7 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 -在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getWindow` 静默执行首次树读取;当 provider 报告应用级辅助功能时,`getApp` 也静默读取。之后的 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。 +在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getApp` 和 `getWindow` 只选择对象,不读取辅助功能或替换该快照;原生窗口操作会拒绝已关闭或属于其他应用的窗口。显式 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.i18n.yaml new file mode 100644 index 0000000000..0e2260eefc --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-09-cua-ax-traversal-defaults.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-09-cua-ax-traversal-defaults.md +/agent-note-ax-traversal-defaults-and-per-read-limits: + en: 71a088b589135b94 + zh: 40a0accb1f6d100b +/agent-note-ax-traversal-defaults-and-per-read-limits/problem: + en: 18405553f792f64c + zh: 1b6891403539c2f8 +/agent-note-ax-traversal-defaults-and-per-read-limits/decision: + en: 89cb2b1f33b0551c + zh: b57839093a735c2a +/agent-note-ax-traversal-defaults-and-per-read-limits/alternatives-considered: + en: c15d84e0bbb18b39 + zh: 4799291d7a66fa04 +/agent-note-ax-traversal-defaults-and-per-read-limits/consequences: + en: 687f4ba2af13e847 + zh: ae5777022619b71d diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.md b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.md new file mode 100644 index 0000000000..37a04b4aa7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.md @@ -0,0 +1,21 @@ +# Agent Note: AX traversal defaults and per-read limits + +Status: implemented + +English | [中文](2026-11-09-cua-ax-traversal-defaults.zh.md) + +## Problem + +A shallow read can omit a control in a deeply nested window. Increasing the profile settings to reach it also increases the work and possible output of subsequent reads. + +## Decision + +For an accessibility tree read, the Host takes each of `maxElements` and `maxDepth` from the request when present and from the provider configuration otherwise. A caller can raise or lower either value for one read. The native provider enforces its traversal ceilings. On macOS, Paste menu discovery always uses the configured values because the paste operation has no traversal options. + +## Alternatives considered + +**Cap each read at the configured values.** With a profile tuned for small reads, recovering a truncated branch would require changing the profile even when the provider can handle a larger request. Per-read overrides let the caller inspect that window and return to the usual limits on the next read. + +## Consequences + +Lowering a profile default reduces the budget for ordinary reads. An explicit larger request can take longer and produce more text. The native operation deadline and response size limit still apply. The [macOS configuration table](../../../../packages/experimental/cua-macos/README.md#use-this-package) lists the defaults. diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.zh.md b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.zh.md new file mode 100644 index 0000000000..536a6908eb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-ax-traversal-defaults.zh.md @@ -0,0 +1,21 @@ +# Agent Note: AX 树遍历的默认值和单次读取上限 + +Status: implemented + +[English](2026-11-09-cua-ax-traversal-defaults.md) | 中文 + +## 问题 + +读取深度较小时,控件可能位于窗口中被截断的分支里。为了找到这个控件而调高配置值,会让以后的读取也可能访问更多节点、返回更多文本。 + +## 决策 + +读取辅助功能树时,Host 分别处理 `maxElements` 和 `maxDepth`。调用方显式传入的值只对本次读取生效,可以高于或低于配置值。省略的参数使用平台配置。原生实现在遍历时执行自身的硬上限。macOS 的粘贴操作没有遍历参数,查找粘贴菜单时始终使用配置值。 + +## 考虑过的替代方案 + +**把配置值作为每次读取的硬上限。** 如果日常读取使用较小的配置值,即使平台支持读取更大的树,调用方也必须先修改配置才能看到被截断的分支。允许单次覆盖后,调用方可以单独扩大这次读取的范围,下次读取继续使用原有配置。 + +## 影响 + +调低配置值可以缩小常规读取的范围。显式请求更大的树可能耗时更长,也可能返回更多文本。原生调用仍受超时和响应大小限制。默认值见 [macOS 配置表](../../../../packages/experimental/cua-macos/README.zh.md#use-this-package)。 diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.i18n.yaml new file mode 100644 index 0000000000..e422ee1635 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-09-cua-program-tool.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-09-cua-program-tool.md +/agent-note-cua-programs-outside-the-ptc-preset: + en: a283f005c51274e7 + zh: 1f697efb2dbac3ba +/agent-note-cua-programs-outside-the-ptc-preset/problem: + en: 87ce83e36a6ab68e + zh: 8aa98dc7dae03c41 +/agent-note-cua-programs-outside-the-ptc-preset/decision: + en: 13e079e19b5f2d6d + zh: 2ce9b6aa981162d7 +/agent-note-cua-programs-outside-the-ptc-preset/alternatives-considered: + en: b5d8e00cbe4b53ae + zh: 4ef81611150a8d75 +/agent-note-cua-programs-outside-the-ptc-preset/consequences: + en: 22f25d54373ba06b + zh: ee335578caaf1ab3 diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md new file mode 100644 index 0000000000..91554ff6ac --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md @@ -0,0 +1,35 @@ +# Agent Note: CUA programs outside the PTC preset + +Status: implemented + +English | [中文](2026-11-09-cua-program-tool.zh.md) + +## Problem + +Computer Use needs reusable application and window objects in Standard and other presets without changing their ordinary tool calls or requiring users to change the profile's PTC runtime. Experimental CUA packages cannot appear in shipped preset definitions. Program dispatch must retain the same permission checks, cancellation, nested logs, and screenshots as PTC. + +## Decision + +CUA keeps `agentPreset: ptc` as the default selector for its raw `cua` tool. Every other composed preset receives `cua_run_code`; Agents without a composed preset receive neither tool. `agentPreset: false` retains global raw-tool registration. A base owner uses Agent scopes for registration and disposal, so enabling and disabling the provider affects existing and later Agents without editing presets. Raw registration depends only on base CUA services and preset selection. The private program producer publishes and withdraws its definition by identity; private dependency loss or startup failure leaves raw tools and prompts available. + +`cua_run_code` composes the shared [program-tool factory](../../../../packages/core/tool-executor-ptc/README.md) with one isolated Node `persistent-in-memory` runtime owned by the CUA provider. Agent `stateOwner` identities select separate retained processes. Its only binding is the private `tools.cua` definition; the model calls ordinary session tools directly. Nested CUA operations retain tool policy, guards, dispatch events, and image admission. Programs select text and screenshots through `inspect(...values)`, following the [explicit output decision](2026-11-09-explicit-ptc-output.md). The provider releases held keys when either program tool settles. Provider unload drains its own CUA programs before native teardown; releasing input held by other PTC programs does not wait for their unrelated work. State is in memory, separate from the profile's PTC state, and released with its Agent or provider. + +CUA registers a source program through `registerEnvironmentInitializer` before its isolated runtime admits a run. Each new environment evaluates it once after installing current bindings, including temporary escalated environments. The child awaits Host acceptance before starting model code. Initialization shares the first run's time and output budgets; failure discards the environment and prevents model execution without rolling back external effects. Separate evaluation preserves model source locations. An initializer-owning scope depends only on the runtime, so program-tool dependency reloads retain the registration. PTC keeps its explicit bridge initialization. + +This partially supersedes the exclusion of a CUA program entry in [native CUA objects](2026-09-17-experimental-cua-object-api.md). That note still owns the object API's independence from an evaluator and the split between shared objects and native operations. The shared Node provider owns evaluation; CUA supplies its restricted bindings and initialization. The [optional bundle decision](2026-09-21-experimental-capabilities-as-optional-bundles.md) still owns delivery and activation. + +## Alternatives considered + +**A CUA-specific evaluator** duplicates execution lifecycle policy. Reusing the PTC factory and runtime keeps cancellation, limits, sandboxing, and result handling with their existing owners. + +**The profile's shared runtime** couples CUA state to unrelated PTC and workflow settings. Its default per-call mode cannot retain objects. A separate CUA runtime preserves the profile's chosen execution mode. + +**Global registration of both tool forms** exposes a program runner inside PTC programs and exposes raw CUA calls to other presets. Selecting one form per Agent keeps each mode's intended tool list. Binding every session tool inside `cua_run_code` would duplicate ordinary direct calls and their declarations. + +**Prepending initialization to model code** shifts source locations. Running initialization as a separate tool call fails for temporary escalated environments because the next call starts another process. A separate program within the first runtime execution supports both retained and temporary environments. Passing initialization with every program couples environment setup to tool requests and repeats work in existing environments; registration keeps setup and cleanup with the runtime owner. + +## Consequences + +CUA adds no preset list or shipped preset dependency. Preset IDs select the tool form; custom PTC presets must match `agentPreset`. PTC and CUA share the public factory; CUA owns a runtime initializer registration and drains its program tools before unregistering it. Older custom Node bootstraps require the matching protocol revision, as described in the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.md). + +The private binding limits callable Harness tools, not Node APIs. File and process access still follow the selected sandbox policy. Retained variables do not reserve applications or survive process loss; callers recreate objects and observe state before continuing. Composition and recorded-session tests cover tool selection, automatic initialization, retained state, nested output, and removal; native fixtures remain responsible for platform input behavior. diff --git a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.zh.md b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.zh.md new file mode 100644 index 0000000000..9a0ddca6fa --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.zh.md @@ -0,0 +1,35 @@ +# Agent Note: PTC preset 之外的 CUA 程序 + +Status: implemented + +[English](2026-11-09-cua-program-tool.md) | 中文 + +## 问题 + +Computer Use 需要在标准及其他 preset 中复用应用和窗口对象,同时保留普通工具的调用方式,也不要求用户更改 profile 的 PTC 运行时。实验性 CUA 包不能出现在随产品提供的 preset 定义中。程序派发必须保留与 PTC 相同的权限检查、取消、嵌套日志和截图行为。 + +## 决策 + +CUA 保留 `agentPreset: ptc`,用默认选择器指定获得原始 `cua` 工具的 preset。其他已组合的 preset 获得 `cua_run_code`;未组合 preset 的 agent(智能体)不获得这两个工具。`agentPreset: false` 保留全局原始工具注册。基础注册的所有者通过 Agent 作用域管理注册和销毁,因此启停提供方会影响已有和后续 Agent,无需修改 preset。原始工具的注册只依赖基础 CUA 服务和 preset 选择。私有程序工具的提供方按定义对象的身份发布和撤回其定义;私有依赖缺失或启动失败时,原始工具和提示词仍然可用。 + +`cua_run_code` 将共享[程序工具工厂](../../../../packages/core/tool-executor-ptc/README.zh.md)与 CUA 提供方持有的单个隔离 Node `persistent-in-memory` 运行时组合。Agent 的 `stateOwner` 身份选择各自独立的保留进程。它只绑定私有 `tools.cua` 定义;模型直接调用其他普通会话工具。嵌套 CUA 操作保留工具策略、guard、派发事件和图像接纳。程序通过 `inspect(...values)` 选择文字和截图,遵循[显式输出决策](2026-11-09-explicit-ptc-output.zh.md)。任一程序工具结束时,提供方都会释放该程序仍按住的键。提供方卸载时,先等待自己持有的 CUA 程序结束再清理原生资源;释放其他 PTC 程序持有的输入时,不等待这些程序中的其他工作。状态保存在内存中,独立于 profile 的 PTC 状态,随所属 Agent 或提供方释放。 + +CUA 在隔离运行时首次接纳运行前,通过 `registerEnvironmentInitializer` 注册一段源码。每个新环境安装本次绑定后执行该程序一次,包括临时提权环境。子进程等待 Host 确认后才开始执行模型代码。初始化与首次运行共享时间和输出预算;失败会丢弃环境并阻止模型代码执行,但不回滚外部效果。独立求值保留模型源码位置。初始化程序所属的作用域只依赖运行时,因此程序工具的依赖重载时仍保留这项注册。PTC 保留显式 bridge 初始化。 + +这部分取代[原生 CUA 对象](2026-09-17-experimental-cua-object-api.zh.md)中不提供 CUA 程序入口的决定。原记录继续负责对象 API 独立于求值器,以及共享对象与原生操作之间的职责划分。共享 Node 提供方负责求值,CUA 提供受限的绑定和初始化。[可选组合包决策](2026-09-21-experimental-capabilities-as-optional-bundles.zh.md)继续负责分发和启用方式。 + +## 考虑过的替代方案 + +**CUA 专用求值器**会重复实现执行生命周期策略。复用 PTC 工厂和运行时,使取消、限制、沙箱和结果处理继续由现有实现负责。 + +**profile 的共享运行时**会使 CUA 状态依赖无关的 PTC 和工作流设置。其默认逐次调用模式无法保留对象。独立的 CUA 运行时保留 profile 选定的执行模式。 + +**全局注册两种工具形态**会在 PTC 程序中暴露另一个程序执行器,并向其他 preset 暴露原始 CUA 调用。按 Agent 选择一种形态,可以保留各模式预期的工具列表。在 `cua_run_code` 内绑定所有会话工具,会重复普通的直接调用及其声明。 + +**把初始化拼到模型代码前**会偏移源码位置。通过单独的工具调用执行初始化无法适用于临时提权环境,因为下次调用会启动另一个进程。首次运行时执行中的独立程序同时支持保留环境和临时环境。每次提交程序都传入初始化,会使环境准备依赖工具请求,并在已有环境中重复执行;注册使准备和清理继续由运行时所有者负责。 + +## 后果 + +CUA 不增加 preset 列表,也不向内置 preset 添加依赖。工具形态按 preset ID 选择;自定义 PTC preset 必须与 `agentPreset` 匹配。PTC 与 CUA 共享公开工厂;CUA 拥有运行时初始化程序的注册,注销前会等待自己的程序工具执行结束。旧版自定义 Node bootstrap 需要匹配协议版本,详见[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.zh.md)。 + +私有绑定限制可调用的 Harness 工具,不限制 Node API。文件与进程访问仍遵循所选沙箱策略。保留变量不会独占应用,也不能跨进程丢失保留;调用方应重建对象并观察状态后再继续。组合测试和已记录会话测试覆盖工具选择、自动初始化、状态保留、嵌套输出及移除;平台输入行为仍由原生 fixture(测试前置数据)负责验证。 diff --git a/.agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.i18n.yaml new file mode 100644 index 0000000000..45d3c7583b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-09-explicit-ptc-output.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-09-explicit-ptc-output.md +/agent-note-explicit-text-and-image-output-in-ptc: + en: b62f1fc259e6f4a7 + zh: 340942c222a38e2a +/agent-note-explicit-text-and-image-output-in-ptc/problem: + en: 51667474a3f9053d + zh: 70c6af69e943f4f5 +/agent-note-explicit-text-and-image-output-in-ptc/decision: + en: ec82c0ce9f6a371d + zh: 74596c0ab6a3cdd7 +/agent-note-explicit-text-and-image-output-in-ptc/alternatives-considered: + en: cfbca328947567f3 + zh: 3b2f619365d2250e +/agent-note-explicit-text-and-image-output-in-ptc/consequences: + en: 636609d91f12a960 + zh: b26397c72f972827 diff --git a/.agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.md b/.agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.md new file mode 100644 index 0000000000..c806842af4 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.md @@ -0,0 +1,43 @@ +# Agent Note: Explicit text and image output in PTC + +Status: implemented + +English | [中文](2026-11-09-explicit-ptc-output.zh.md) + +## Problem + +PTC lets a program acquire and filter intermediate tool results before choosing what the model sees. A final expression or return value can expose incidental data, while automatically attaching every acquired image defeats that selection. Separate screenshot bytes and image-output callbacks also make programs convert images before comparing or displaying them. + +## Decision + +TypeScript `run_code` programs select text, objects and images through top-level `inspect(...values)`. Arguments are rendered independently: strings appear directly, and other values use Node's object formatting without depth, array-length or string-length preview limits. Inspection displays undefined properties, Error objects and circular references; requiring lossless JSON for display would interrupt subsequent work after tools have already executed. Images can occur inside arrays or objects. The runtime Image's custom inspection hook collects images reached by Node's formatter; each formatting call owns its collector. One output sequence preserves the relationship between explanatory text and selected images. + +The tool executor requests `discardCompletion: true`, so completion values are discarded before JSON validation and serialization. This is a consumer choice: direct runtime and workflow consumers retain completion values when their protocols require them. The [PTC foundation](../feature/2026-06-15-ptc.md) owns dispatch and settlement. The [typed-return decision](../feature/2026-07-20-ptc-typed-tool-returns.md) continues to own ordinary JSON binding values, failures and output accounting; this note owns TypeScript output selection and image projection. + +The Node environment supplies `inspect` alongside the complete native console. Native console methods remain available to programs and imported libraries, and their stdout and stderr writes share the captured output sequence. Model instructions direct programs to select output through `inspect`. + +`read_image` and CUA screenshot bindings expose stored `Image` values. Readonly `attachmentId`, `path`, `width` and `height` identify the stored image and its readable execution-world file. The dimensions describe that file's pixels, including the image used for CUA coordinate mapping. The [CUA object API](2026-09-17-experimental-cua-object-api.md) returns screenshot Images and text observations directly to the program. The program passes selected values to `inspect` for display. + +The host carries the attachment reference with the program-readable path. The runtime transports image metadata and keeps the attachment reference behind a process-owned image ID. Inspection resolves that ID directly to the registered reference. Image identity is established by the runtime; matching object properties alone do not grant access to an image output. Retained program Images follow their owning process's lifetime. + +Nested tool dispatches retain their complete rendered content in the Session log. Successful outer `run_code` results interleave inspected images with text in emission order, where model history and UI rendering use the same durable attachment references. Successful outer-result replacement remains authoritative over the selected output. + +## Alternatives considered + +**Display the completion value alongside printed output.** The last expression or return then controls context admission as well as program control flow. Discarding it before validation lets a program finish with an arbitrary internal value while explicitly selecting a smaller visible result. + +**Automatically forward every acquired image.** Acquisition then implies model-context cost, even when the program needs several screenshots to select one. Explicit inspection gives text and images the same selection rule. + +**Keep a CUA byte-returning facade and image sink.** This maintains a separate screenshot representation and a second image-emission path. Returning the runtime's Image lets file reads and screenshots share inspection and preserves the stored attachment reference through display. + +**Discover images with a separate object traversal.** A separate traversal must duplicate Node's handling of collections, symbols and custom formatters and can emit images absent from the text representation. The Image hook ties collection to Node's formatting. + +**Bounded object previews.** Item and string preview limits can omit file contents that a program explicitly selected. Removing those limits keeps selected contents complete within the shared output budget. + +**Restrict console availability.** Missing bindings and incomplete replacements can break program code and imported libraries. The native console preserves Node methods while prompt guidance directs output selection through `inspect`. + +## Consequences + +Programs explicitly choose the output needed for the next model request, including image comparisons and selected nested results. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.md) owns caller migration. Acquiring an image still performs storage and processing work; selection controls its presentation to the model. + +The runtime owns process-local image identity and output ordering; the tool executor owns attachment projection and durable result content. Text and image-reference metadata share the outer output budget. Runtime teardown releases retained image identities, while stored attachments follow the attachment store's lifetime. diff --git a/.agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.zh.md b/.agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.zh.md new file mode 100644 index 0000000000..f3412ceb01 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-explicit-ptc-output.zh.md @@ -0,0 +1,43 @@ +# Agent Note: PTC 显式文本与图片输出 + +Status: implemented + +[English](2026-11-09-explicit-ptc-output.md) | 中文 + +## 问题 + +PTC 允许程序先获取和筛选中间工具结果,再选择模型看到的内容。末尾表达式或返回值可能暴露偶然产生的数据,而自动附加每张已获取的图片会使这种筛选失效。独立的截图字节和图片输出回调也要求程序先转换图片,再进行比较或展示。 + +## 决策 + +TypeScript `run_code` 程序通过顶层 `inspect(...values)` 选择文本、对象和图片。各参数独立渲染:字符串直接展示,其他值使用 Node 的对象格式,不限制预览深度、数组项数或字符串长度。inspect 展示 undefined 属性、Error 对象和循环引用;要求展示值必须是无损 JSON,会在工具已经执行后中断后续工作。图片也可以嵌入数组或对象。运行时 Image 的自定义 inspect 钩子收集 Node 格式化函数访问到的图片;每次格式化调用拥有自己的收集器。同一输出序列保留说明文字与所选图片的对应关系。 + +工具执行器请求 `discardCompletion: true`,在 JSON 校验和序列化前丢弃完成值。这是消费方的选择:直接运行时调用方和工作流消费方在其协议需要时保留完成值。[PTC 基础](../feature/2026-06-15-ptc.zh.md)负责分发与结算。[类型化返回值决策](../feature/2026-07-20-ptc-typed-tool-returns.zh.md)继续负责普通 JSON 绑定值、失败和输出计量;本记录负责 TypeScript 输出选择与图片投影。 + +Node 环境同时提供 `inspect` 和完整的原生 console。程序与导入的库均可使用原生 console 方法,其 stdout 和 stderr 写入共用捕获输出序列。模型指引要求程序通过 `inspect` 选择输出。 + +`read_image` 和 CUA 截图绑定提供已存储的 `Image` 值。只读的 `attachmentId`、`path`、`width` 和 `height` 标识已存储图片及其在执行环境中可读取的文件。尺寸描述该文件的像素,也对应 CUA 坐标换算所用的图片。[CUA 对象 API](2026-09-17-experimental-cua-object-api.zh.md)将截图的 `Image` 和观察文本直接返回给程序。程序将选中的值传给 `inspect` 展示。 + +宿主将附件引用与程序可读取的路径一起传递。运行时传输图片元数据,并用进程拥有的图片 ID 保存对应的附件引用。展示时,该 ID 直接解析为已登记的引用。图片身份由运行时建立,仅有相同对象属性不能取得图片输出权限。保留在程序中的 Image 跟随其所属进程的生命周期。 + +嵌套工具分发将完整渲染内容保留在 Session 日志中。成功的外层 `run_code` 结果按输出顺序穿插显式展示的图片和文本,模型历史和 UI 渲染使用相同的持久附件引用。成功外层结果的替换仍对所选输出具有最终决定权。 + +## 考虑过的替代方案 + +**同时展示完成值与打印输出。** 末尾表达式或返回值会同时控制上下文纳入和程序控制流。在校验前丢弃完成值,使程序可以用任意内部值结束,并显式选择更小的可见结果。 + +**自动转发每张已获取的图片。** 即使程序需要先获取多张截图才能选出一张,获取动作本身也会产生模型上下文成本。显式展示让文本和图片遵循同一选择规则。 + +**保留返回字节的 CUA 对象接口和图片输出回调。** 这会维护独立的截图表示和第二条图片输出路径。返回运行时 Image,使文件读取和截图共用展示方式,并在展示过程中保留已存储附件引用。 + +**单独遍历对象以发现图片。** 独立遍历必须重复实现 Node 对集合、Symbol 和自定义格式化的处理,还可能输出文本表示中未出现的图片。Image 钩子让收集跟随 Node 的格式化。 + +**限制对象预览。** 条目和字符串的预览上限可能省略程序已明确选中的文件内容。取消这些限制,在共享输出预算内完整保留选中的内容。 + +**限制 console 的可用性。** 缺失的绑定和不完整的替代实现可能使程序及导入的库出错。原生 console 保留 Node 方法,提示词指引程序通过 `inspect` 选择输出。 + +## 后果 + +程序显式选择下一次模型请求需要的输出,包括图片比较和嵌套结果中的所选内容。[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.zh.md)负责调用方迁移。获取图片仍会执行存储和处理工作,选择控制的是向模型展示的内容。 + +运行时负责进程内图片身份和输出排序;工具执行器负责附件投影和持久结果内容。文本和图片引用元数据共用外层输出预算。运行时拆卸释放保留的图片身份,已存储附件则遵循附件存储的生命周期。 diff --git a/.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.i18n.yaml new file mode 100644 index 0000000000..83255f1a86 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.i18n.yaml @@ -0,0 +1,73 @@ +# Bilingual-pair consistency record for 2026-11-09-retained-ptc-scoped-repl.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-09-retained-ptc-scoped-repl.md +/agent-note-scoped-repl-evaluator-for-retained-ptc: + en: ea465612c52ff8a6 + zh: 1c4021aecb7550c6 +/agent-note-scoped-repl-evaluator-for-retained-ptc/problem: + en: 9e115eb5c8b8d168 + zh: d47b2a783e154664 +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision: + en: 02e060e10da7bb75 + zh: d4b01038283943bd +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior: + en: 14dff09dd91c1533 + zh: d199bef553f9439c +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/syntax-and-results: + en: 4f0c54f87042943e + zh: 34b88dbb1d50a2c6 +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/across-calls: + en: d389222669ca94d7 + zh: cf19a71bce644ee4 +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/environment: + en: b1d35c4055c7f381 + zh: 404b3843b2348fec +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/errors: + en: 5b4209a69447bfac + zh: 3b1cb6297962b6c1 +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/exact-behavior/asynchronous-failures-and-lifecycle: + en: 70c47aba7a23fc4f + zh: 1d7d5f0809e748aa +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/comparison-with-node-repl-and-vm-script: + en: 013bfbf3d3944637 + zh: eba400efadf6229b +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/context-and-options: + en: 14fc1abb8e437555 + zh: 38a37fdb8ca7e17c +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/wrapper: + en: d886821f764b6804 + zh: a073534825d639a2 +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/kernel-scope-chain-acorn-scan-and-compilation: + en: 10d0459a356cd33d + zh: 07e7cd70119c4d4d +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/scope-chain-state-and-the-steps-of-a-call: + en: fbb63be77e727e07 + zh: 12f24e0d0672907c +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/failed-calls: + en: 64937f1d5acd7147 + zh: f262dff89139086f +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/asynchronous-failures-aligned-with-the-repl: + en: 7f867b69623f3652 + zh: 551a456448700171 +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/dynamic-import: + en: 2607ffb07f5c4b4b + zh: 5882d8c58d5a775b +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/redeclaration-notice-reserved: + en: c3eef0f99686acfe + zh: 9093c1e84abff335 +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/out-of-scope: + en: 725a4139f28961c3 + zh: b32da1bf86095e65 +/agent-note-scoped-repl-evaluator-for-retained-ptc/decision/integration: + en: b05235293c504467 + zh: 48f5f534812a12b3 +/agent-note-scoped-repl-evaluator-for-retained-ptc/alternatives-considered: + en: e548d12c174bb44e + zh: 9f67908a564d6f78 +/agent-note-scoped-repl-evaluator-for-retained-ptc/consequences: + en: d75ef0e16dcdcee2 + zh: 22ae67a41c1461ca +/agent-note-scoped-repl-evaluator-for-retained-ptc/testing: + en: 799de02ac67753f3 + zh: f3ad0647273fc458 diff --git a/.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.md b/.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.md new file mode 100644 index 0000000000..82e2d57423 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.md @@ -0,0 +1,524 @@ +# Agent Note: Scoped REPL evaluator for retained PTC + +Status: implemented + +English | [中文](2026-11-09-retained-ptc-scoped-repl.zh.md) + +## Problem + +`persistent-in-memory` runs every `run_code` call of one Agent in one global scope through node:repl ([best-effort persistent PTC](../../implemented/architecture/2026-09-23-best-effort-persistent-ptc.md)). When a later call declares a `const`, `let`, or `class` name again, V8 rejects the program before it runs with `SyntaxError: Identifier 'x' has already been declared`, and no statement executes. Model guidance can only ask for no redeclarations, and models rarely track every name across many calls. + +Rewriting declarations as `var` removes the error, but every call then shares one binding, so a later declaration changes the value that earlier functions, closures, and background tasks read: + +```js +// call 1 +var value = 1 +var read = () => value +// call 2 +var value = 2 // no error +// call 3 +read() // 2: call 2 changed the read written by call 1 +``` + +Five requirements must hold together: + +1. A later call may declare an earlier name again with any keyword without an error. +2. A redeclaration applies to that call and later calls; earlier functions, closures, and still-running code keep their original values. +3. Syntax matches the existing REPL: top-level `await` works, the final expression is the result, and top-level `return` is not supported. +4. Errors in asynchronous callbacks are handled as in the existing REPL: the process keeps running and variables are retained. +5. No scope analysis and no rewriting of declarations or references in model code; acorn only lists top-level declarations and finds the last statement. + +## Decision + +The scoped REPL evaluator is split into a kernel and an evaluator: + +| File | Contents | +|---|---| +| `packages/ptc-runtime/ptc-runtime-node/src/evaluators/scoped-repl.ts` | Kernel: the `ScopedReplScopes` scope chain, which owns binding state, copies and fallback values, redeclarations, and Script compilation; plus the acorn scan, top-level declarations and keywords, top-level `return` check, final expression, reserved-name check, syntax-error layout, and source generation | +| `packages/ptc-runtime/ptc-runtime-node/src/evaluators/scoped-repl-evaluator.ts` | Evaluator: exports `createScopedReplEvaluator(options)` implementing the existing `ProgramEvaluator` interface and connects the kernel to the existing modes: context and options, dynamic imports and the import handler, starting programs from a microtask and reading completions, the domain, and the injected `reportRedeclarations` | +| `packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl.spec.ts` | Kernel tests only; runs on its own and covers scanning, source generation, and scope layering across consecutive programs in a plain vm context | +| `packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl-evaluator.spec.ts` | Integration tests: completions, environment, modules and imports, errors, and asynchronous failures; every option tested on and off | + +The `scoped-repl` format connects the evaluator to the existing execution modes; see Integration. + +### Exact behavior + +#### Syntax and results + +- A program is a list of statements and supports top-level `await`. +- When the last non-empty top-level statement is an expression statement, its value is the result. A Promise value is not awaited: the Promise itself is the result, so the host reports `program completion must be lossless JSON`, as with the existing REPL. The `finalExpression` option controls this and defaults to on; when off, the final value is discarded, results come only from printing, and model guidance must change accordingly. `run_code` passes `discardCompletion: true` for TypeScript runtimes, so the host discards completion values and the model displays output with `inspect(...)`; callers that keep completions, such as workflow-ptc, still take the final expression's value as the result. +- When the last statement is a declaration, `if`, `for`, block, or another statement, there is no result. +- Top-level `return`, including inside top-level `if`, loops, and blocks, reports `SyntaxError: Illegal return statement`, and no statement of that call runs. Through `run_code`, the host's TypeScript erasure rejects it first with `Return statement is not allowed here`, as with the existing REPL. +- A static `import` or `export` reports acorn's `SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'`; acorn also rejects top-level `using` and `await using`, which remain available inside blocks and functions. +- A program that starts with `#!` reports `SyntaxError: Hashbang lines are not supported` and does not run: a hashbang is valid only at the very start of a Script, and the generated prefix precedes the program. +- Output is the printed text, such as `inspect(...)`, plus the final expression's value when the caller keeps completions. + +#### Across calls + +- Each call starts by copying every top-level name left by earlier calls into a same-named declaration; objects are shared by reference, so changes inside an object are visible on both sides. +- A call may declare an earlier name again with any keyword, including a `var`→`let`→`const`→`class`→`function` sequence. A name the call declares with `let`, `const`, `class`, or `function` is not copied, and the call's declaration wins; a name it declares again only with `var` is still copied, so that `var` starts from the earlier value. +- Assigning to an earlier name without declaring it changes this call's copy: later calls see the new value, and earlier functions keep the old one. This includes names declared with `const`, which are read-only only in the call that declares them. +- After a function is redefined, earlier callers still call the old function. +- Assignments that earlier code, such as timers and callbacks, makes to top-level variables after a call starts are not visible to later calls; keep shared mutable state in objects. +- Earlier functions cannot see names declared later; referencing them reports `ReferenceError`. +- When a call declares a name again with `let`, `const`, or `class`, every reference in that call resolves to the new declaration, including references written before it, and the old value is unreachable: reading the name before its declaration runs reports the native `ReferenceError: Cannot access 'x' before initialization`. Such code is a program error and is not handled. A `var` redeclaration starts from the earlier value until it assigns a new one, so `var count = count + 1` adds to the earlier value; a `function` name holds the new function from the start of the call. +- When a call fails partway: declarations completed before the throw are kept; an existing name redeclared but not yet initialized falls back to its earlier value in later calls; an uninitialized new name is dropped. +- A `var` declared inside a block, including `try`/`catch`/`finally`, `if`/`else`, loop bodies, `switch`, and labeled statements, hoists to the top level of the call and counts as the call's declaration like a top-level `var`: it carries to later calls and may reuse a name that an earlier call declared with any keyword. A `var` inside a nested function or class does not count. +- A `var` redeclaration that does not run, after a throw or in a branch that is not taken, keeps the earlier value, and so does `var x;` without an initializer. + +#### Environment + +These are the defaults; one option controls each of the first two items, see Context and options. + +- Strict mode: assigning an undeclared name reports `ReferenceError`; intentional globals use `globalThis.x`. With the option off, strict mode is not forced: a program that starts with `"use strict"` runs strict, and other programs run sloppy. +- No code generation from strings: the context's own `eval` and `new Function` report `EvalError`, and compiling WebAssembly from bytes reports `CompileError`. This is no isolation: main-realm functions copied into the context, such as `setTimeout.constructor`, still generate code in the main realm. +- Modules load only through dynamic `import()`, whose relative specifiers resolve from the working directory of the environment's first call and keep doing so after later calls change directory; there is no `require`, `module`, or built-in module global such as `fs` and `path`. Relative file access still follows the current directory. +- Top-level `this` is `undefined`, or `globalThis` when a program runs sloppy; top-level `arguments` is an empty arguments object with length 0. +- Top-level `var` and `function` declarations do not become `globalThis` properties. +- Node globals such as `setTimeout`, `Buffer`, `fetch`, `URL`, and `structuredClone` are available. + +#### Errors + +- Runtime error lines and columns are native positions in the model's code, and functions defined in an earlier call show that call's filename, for example `/.ptc-repl-1.js:2:9`. On the line of the final expression, columns after the insertion point shift right by 17, which is left as is. +- Syntax errors that acorn finds are reported with acorn's message and position, laid out like V8's: filename and line, source line, and caret. Two messages use V8's wording: top-level `return` reports `Illegal return statement`, and an error positioned at the end of the code reports `Unexpected end of input`. +- Errors that acorn accepts and V8 rejects during compilation report V8's native message; with the `strict` option on, strict-mode syntax violations such as `with` are reported this way. +- These are the evaluator's own reports. Through `run_code`, the host's TypeScript erasure parses the whole program first and reports most syntax errors itself, as with the existing REPL; only code that the erasure accepts and the scan rejects, such as reserved names, static `import`, or top-level `using`, shows the layout above. +- Runtime errors report the error name and stack, without an `Uncaught ` prefix and without evaluator frames. + +#### Asynchronous failures and lifecycle + +- Errors thrown by timers, callbacks, Promise continuations, and EventEmitters that a program starts, and unhandled rejections, do not end the process, and variables are retained. Exception: when a callback throws a frozen or non-extensible object, Node's domain fails to add its properties before notifying the listener, and the process ends, as with node:repl; rejecting with such an object is unaffected. +- If an evaluation is active, it fails with `Uncaught ` followed by the error text; otherwise the error is discarded. The error text is the error's `stack`, or `name: message` when the stack is not a string; a value that is not an error is formatted with `util.inspect` after removing the `domain` and `domainThrown` properties the domain added; a failure while formatting reports `program threw an unrenderable value`. An error belongs to the evaluation that created its callback, so a timer from an earlier call failing during a later call is not charged to the later call. +- Output printed after an evaluation ends is discarded; timeout, cancellation, and reset keep the existing host behavior ([retained PTC interruption](../../implemented/architecture/2026-10-29-retained-ptc-interruption.md)). + +### Comparison with node:repl and vm-script + +✓ means supported, ✗ means not supported, and "—" means not applicable: `vm-script` without persistence starts a new process for every call and has no cross-call state. "Persistent vm-script" is vm-script with `scriptPersistence: true` (#7992), and "both vm-script columns" means it and vm-script without persistence. The "ours" column is the default behavior, and its parenthesis names the columns it matches; the Environment table splits it into strict mode on, the default, and off. The Across calls table adds an implementation expected to support cross-call behavior, called the "expected implementation" in parentheses and notes. + +**Syntax and results** + +| Capability | node:repl (existing REPL evaluator) | Ours | vm-script (no persistence) | vm-script (persistent, #7992) | Notes | +|---|---|---|---|---|---| +| Top-level `return`, including inside `if` blocks | ✗ | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | All report `Illegal return statement` | +| Final expression as the result | ✓ | ✓ (default; matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours can turn it off with `finalExpression` | +| Awaiting a final Promise | ✗ | ✗ (matches node:repl) | ✓ | ✓ | Without awaiting, the host reports a non-JSON completion | +| A result when ending with `if`, `for`, or a block | ✓ | ✗ (matches node:repl, vm-script, and persistent vm-script when the code contains `await`) | ✓ | ✓ | node:repl and both vm-script columns have a result only without `await` | +| Top-level `await` | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | node:repl and both vm-script columns rewrite the whole program; ours rewrites only the final expression | +| Static `import` | ✗ | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | Ours reports acorn's message | +| Top-level `using` | ✗ | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | Available inside blocks and functions | +| A program that starts with `#!` | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours reports `Hashbang lines are not supported` | +| Two `function` declarations of one name, or a `var` and a `function` of one name, in one call | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | | +| Dynamic `import()` | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | | + +**Across calls** + +| Capability | node:repl | An implementation expected to support cross-call behavior | Ours | vm-script | Persistent vm-script | Notes | +|---|---|---|---|---|---|---| +| Variables retained across calls | ✓ | ✓ | ✓ (matches node:repl, the expected implementation, persistent vm-script) | ✗ | ✓ | node:repl and persistent vm-script share one scope; ours copies; the expected implementation copies as well | +| Redeclaration with any keyword | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | In node:repl and persistent vm-script, 21 of the 25 keyword pairs report `already declared`, and only `var` and `function` may replace each other; ours reserves a redeclaration notice that prints nothing; the expected implementation prints an extra warning when a `const` is declared again as `const` | +| Earlier functions unaffected by a later assignment without declaration | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | | +| Assigning to an earlier `const` without declaring it again | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | node:repl and persistent vm-script report `TypeError`; ours prints nothing; the expected implementation prints a warning first | +| A `var` redeclaration reads the earlier value of its name (`var n = n + 1`) | ✓ | ✗ | ✓ (matches node:repl, persistent vm-script) | — | ✓ | node:repl and persistent vm-script only when the earlier declaration is also `var`, and report `already declared` after `let`; ours also after `let` or `const`; the expected implementation yields `NaN` | +| Earlier callers keep calling the old function after a redefinition | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | | +| Later calls see values earlier code assigns afterwards | ✓ | ✗ | ✗ (matches the expected implementation) | — | ✓ | A timer-incremented variable read twice 30 ms apart: node:repl 23, 50; persistent vm-script 22, 44; ours 0, 0; the expected implementation 15, 15 | +| Earlier functions see names declared later | ✓ | ✗ | ✗ (matches the expected implementation) | — | ✓ | Ours reports `ReferenceError` | +| Changes inside an object visible on both sides | ✓ | ✓ | ✓ (matches node:repl, the expected implementation, persistent vm-script) | — | ✓ | | +| A name stays usable after its initializer throws | ✗ | ✓ | ✓ (matches the expected implementation) | — | ✗ | In node:repl and persistent vm-script a new name stays unusable, and declaring it again reports `already declared`; ours falls back to the earlier value for existing names and drops new names | +| Declarations completed before a throw are kept | ✓ | ✓ | ✓ (matches node:repl, the expected implementation, persistent vm-script) | — | ✓ | | +| A `var` redeclaration not reached before a throw keeps the old value | ✓ | ✓ | ✓ (matches node:repl, the expected implementation, persistent vm-script) | — | ✓ | Ours copies the earlier value into the call's `var`, which also keeps it through an untaken branch; the expected implementation inserts marker code to achieve this | +| A new `var` declared in a block is carried to later calls | ✓ | ✗ | ✓ (matches node:repl, persistent vm-script) | — | ✓ | Ours collects block-level `var` declarations | +| A block-level `var` with the same name as an earlier `let` is accepted | ✗ | ✗ | ✓ (matches none of node:repl, the expected implementation, persistent vm-script) | — | ✗ | node:repl and persistent vm-script report `already declared`; ours treats it as the call's new declaration; the expected implementation reports `already declared` as well | + +**Environment** + +| Capability | node:repl | Ours (strict, default) | Ours (non-strict) | vm-script | Persistent vm-script | Notes | +|---|---|---|---|---|---|---| +| Strict mode | ✗ | ✓ (matches none of node:repl, vm-script, persistent vm-script) | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | With the option off, a program's own leading `"use strict"` still applies | +| Assigning an undeclared name creates a global | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Without strict mode the global is shared by every call and earlier function and is not copied | +| Top-level `var` and `function` become `globalThis` properties | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | | +| Top-level `this` is `globalThis` | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours is `undefined` in strict mode | +| Top-level `arguments` | ✗ | ✓ (matches none of node:repl, vm-script, persistent vm-script) | ✓ (matches none of node:repl, vm-script, persistent vm-script) | ✗ | ✗ | Ours is an empty arguments object | +| `eval` and `new Function` | ✓ | ✗ (default; matches none of node:repl, vm-script, persistent vm-script) | ✗ (default; matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Can be turned on; limits only the context's own functions, while copied main-realm functions still generate code | +| WebAssembly compilation | ✓ | ✗ (default; matches none of node:repl, vm-script, persistent vm-script) | ✗ (default; matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Same option as `eval` | +| Node globals (`setTimeout`, `Buffer`, `fetch`, `URL`, `structuredClone`) | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | | +| `require`, `module`, and built-in module globals such as `fs` | ✓ | ✗ (matches vm-script, persistent vm-script) | ✗ (matches vm-script, persistent vm-script) | ✗ | ✗ | Only `import()` | +| Relative `import()` follows later directory changes | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours keeps the directory of the environment's first call | +| `_` and `_error` | ✓ | ✗ (matches vm-script, persistent vm-script) | ✗ (matches vm-script, persistent vm-script) | ✗ | ✗ | | +| Code starting with `{ a: 1 }` is an object literal | ✗ | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ (matches node:repl, vm-script, persistent vm-script) | ✗ | ✗ | node:repl treats it as an object; the existing REPL evaluator forces a block | + +**Errors** + +| Capability | node:repl | Ours | vm-script | Persistent vm-script | Notes | +|---|---|---|---|---|---| +| Accurate error positions (code without `await`) | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours excepts the final expression's line | +| Accurate first-line positions in code with `await` | ✗ | ✓ (matches none of node:repl, vm-script, persistent vm-script) | ✗ | ✗ | node:repl and both vm-script columns report column 22 as column 54 | +| Syntax errors show the source line and caret | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours lays out acorn's position; this is evaluator behavior, and through `run_code` the host's TypeScript erasure reports most syntax errors first, matching the node:repl column | +| Syntax error messages are V8's wording | ✓ | ✗ (matches none of node:repl, vm-script, persistent vm-script) | ✓ | ✓ | Ours uses acorn's message, and V8's wording for errors acorn accepts and V8 rejects | +| Incomplete code gets a clear message | ✗ | ✓ (matches vm-script, persistent vm-script) | ✓ | ✓ | node:repl reports an empty message; through `run_code` the host's erasure reports it first as well | +| Errors carry the error name and stack | ✓ | ✓ (matches node:repl, vm-script, persistent vm-script) | ✓ | ✓ | | +| `Uncaught ` prefix on synchronous and awaited failures | ✓ | ✗ (matches vm-script, persistent vm-script) | ✗ | ✗ | | +| `Uncaught ` prefix on asynchronous callback failures | ✓ | ✓ (matches node:repl) | — | — | Both vm-script columns end the process instead of reporting | + +**Asynchronous failures and lifecycle** + +| Capability | node:repl | Ours | vm-script | Persistent vm-script | Notes | +|---|---|---|---|---|---| +| A callback failure after an evaluation keeps the process and variables | ✓ | ✓ (matches node:repl) | — | ✗ | Persistent vm-script exits, the next call reports `worker-exit`, and every variable is lost; without persistence the process has already closed; a callback throwing a frozen object ends the process in node:repl and ours | +| A callback failure during an evaluation fails only that evaluation and keeps variables | ✓ | ✓ (matches node:repl) | ✗ | ✗ | Both vm-script columns exit with `worker-exit`, and persistent vm-script loses its variables | +| Output printed after an evaluation ends is discarded | ✓ | ✓ (matches node:repl, persistent vm-script) | — | ✓ | | +| Variables can survive a timeout or cancellation | ✓ | ✓ (matches node:repl, persistent vm-script) | — | ✓ | Requires the program to acknowledge the stop | +Sources: the node:repl, vm-script, and persistent vm-script columns come from running master's evaluators directly (Node v24.18.0). Persistent vm-script reuses one evaluator; its single-call rows equal vm-script's, and its cross-call rows and the two asynchronous rows were measured separately, the asynchronous ones through a real child process. `scoped-repl.spec.ts` tests the cross-call items of the "ours" column and `scoped-repl-evaluator.spec.ts` the rest. The two asynchronous rows of vm-script without persistence are inferred from the current implementation; node:repl, persistent vm-script, and ours share the host's timeout, cancellation, and reset behavior. The expected-implementation column was measured on that implementation with a fresh environment per case. + +### Context and options + +One evaluator owns one context. With the `codeGeneration` option off, the default, it is created as: + +```ts ignore-check +const runtimeContext = vm.createContext(Object.create(null), { codeGeneration: { strings: false, wasm: false } }) +``` + +- Node globals are copied by the same rule as `createScriptContext` in `vm-script`: every own property of the main `globalThis` that the new context lacks, with `global` pointing at the new context. The evaluator file contains its own copy of these lines and leaves [vm-script.ts](../../../../packages/ptc-runtime/ptc-runtime-node/src/evaluators/vm-script.ts) unchanged. +- The child still writes `tools`, binding error classes, `console`, and `process` to `evaluator.globals`, which is `runtimeContext`, before each evaluation. +- The sandbox object has no prototype, as in the vm-script and AsyncFunction evaluators, so global lookups do not reach the main realm's `Function` through a prototype chain, as `constructor.constructor("…")()` would. Main-realm values copied into the context, such as `setTimeout`, `console`, `process`, and tool namespaces, still have the main realm's `Function` as their `constructor`, and the main realm has no `codeGeneration` limits, so the option restricts only the context's own `eval`, `Function`, and WebAssembly and is no isolation; the process sandbox provides isolation. +- Only dynamic `import()` loads modules, with no option: each Script gets `importModuleDynamically`. There is no `require`, `module`, or built-in module global; host bindings under those names stay available unchanged. Static `import` is unsupported. +- The generated filename is `/.ptc-repl-.js`; no file exists at that path, and the name starts with a dot as a hidden file. The directory is the working directory when the evaluator is created, which is the directory of the environment's first call, and never changes. Node's default loader uses the filename as the `import()` referrer, so relative imports always resolve from that directory, and the directory cannot be left out. Following later directory changes would need an explicit operation, such as `js_switch_cwd`. +- Values from bindings and imports belong to the main realm, so cross-realm checks such as `instanceof Array` can be false, as with the REPL and `vm-script`. + +The three options are evaluator creation parameters, not Config fields: + +```ts ignore-check +interface ScopedReplEvaluatorOptions extends ProgramEvaluatorOptions { + /** Force strict mode for every program; when off, a program's own leading "use strict" decides. Defaults to true. */ + strict?: boolean + /** Allow eval, new Function and WebAssembly compilation inside the program context; defaults to false. */ + codeGeneration?: boolean + /** Use the last top-level expression statement as the completion value; defaults to true. */ + finalExpression?: boolean +} +``` + +| Option | On | Off | Notes | +|---|---|---|---| +| `strict` (default on) | The whole Script starts with `"use strict";`, so every call runs strict | Not forced: when a program starts with a `"use strict"` directive, the inner function body starts with `"use strict";`, so the copy declarations cannot void it; other programs run sloppy | acorn scans with script rules in both states, and V8 reports strict-mode syntax violations at compilation. When off, in calls that run sloppy, assigning an undeclared name creates a global that every call shares without copies, top-level `this` is `globalThis`, and a name declared with a strict-mode reserved word such as `package` makes later strict calls fail to compile; see Risks | +| `codeGeneration` (default off) | The context is created without the `codeGeneration` limits | The context is created as above | When on, a `var` declared inside `eval` is not in the scanned list and is not carried; when off, it still restricts only the context's own code generation and is no isolation | +| `finalExpression` (default on) | The final expression becomes `return { value: (…) }` | No rewrite; the final value is discarded and the result is empty | When off, output comes only from printing; model guidance and consumers of the completion value, such as workflow-ptc, must change; top-level `return` fails in both states | + +The integration uses the default of every option; the other values are intended uses kept by design, and each has tests. + +### Wrapper + +Each call compiles to its own `vm.Script`. For example, after earlier calls left `a` (`const`), `b` (`let`), and `v` (`var`), the model writes: + +```js +let c = a + b +c * 2 +``` + +The compiled source is: + +```js +"use strict";(function (__$binding_vals, __$binding_getters) { return async function () { let a = __$binding_vals[0]; let b = __$binding_vals[1]; var v = __$binding_vals[2]; __$binding_getters.push(() => a, () => b, () => v, () => c); +let c = a + b +return { value: (c * 2) } +} }) +``` + +| Part | Contents | Reason | +|---|---|---| +| `"use strict";` | With the `strict` option on, the whole Script is strict; when off, it is omitted, and a program that starts with `"use strict"` gets one at the start of the inner function body instead | On forces strict mode; off keeps the copy declarations from voiding the model's directive | +| Outer `function (__$binding_vals, __$binding_getters)` | Receives the copied values and an empty array and returns the inner function; the evaluator calls it synchronously | The internal values reach the program through a closure and stay out of its `arguments`; the outer function returns before the program runs, so its frame never appears in program stacks | +| Inner `async function ()` | The model's program is its body | Supports top-level `await`; top-level declarations are function locals, so calls never conflict; it is called without a receiver and without arguments, so `this` is `undefined` (`globalThis` when the program runs sloppy) and `arguments` is an empty arguments object | +| Copy declarations | Generated only for names that earlier calls left and this call does not declare or declares again only with `var`; values come from `__$binding_vals` by index | Index access is unaffected by names such as `__proto__` | +| `__$binding_getters.push(...)` | Before the model's code, pushes one read function per name, copied or declared, in the order the evaluator generated | The evaluator maps the i-th read function to the i-th name, so the prefix needs no name strings; a read function can be created early and read later, and it throws while its declaration is uninitialized | +| Final expression | Inserts `return ` before the statement, `{ value: (` before the expression, and `) }` after it | The same handling of the last statement as Node's `processTopLevelAwait`; the box keeps the async function from awaiting a returned Promise | +| Prefix on line 0 | Compiled with `lineOffset: -1` | Line N of the model's code reports as line N | +| Closing on its own line | `} })` | The model's last line can end with a `//` comment | + +A copy declaration exists when the call does not declare the name or declares it again only with `var`; when the call declares it with `let`, `const`, `class`, or `function`, there is no copy and the call's declaration wins. Copy keywords: + +| Case | Generated copy | +|---|---| +| Not declared by this call; earlier `let`, `const`, `function`, or `class` | `let` | +| Not declared by this call; earlier `var` | `var` | +| Declared again by this call only with `var` | `var` | + +A copy only carries the earlier value in, and writing it as `const` would only forbid later calls from assigning to it, so an earlier `const` is copied as `let` too: later calls can assign to it, changing only the copy, while it stays `const` in the call that declares it. The kernel does not check whether a call assigns the name, so it needs no syntax-tree walk and prints no warning. + +A call that declares a name again only with `var` gets a copy too: repeated `var` declarations in one function are one variable, so that `var` starts from the earlier value and a declaration that does not run never replaces it with `undefined`, as a global `var` behaves in node:repl. A `function` of the same name in the same call initializes at the start of the function and takes precedence over the `var`, so it gets no copy. + +Compilation and execution: + +```ts ignore-check +// Kernel: ScopedReplScopes.compile +const factory = new Script(source, { filename, lineOffset: -1, ...importOption }).runInContext(context) as ScopedReplFactory +const getters: (() => unknown)[] = [] +const program = factory(values, getters) +this.compiled = { bindings, getters, replaced } +return program + +// Evaluator: evaluate +const filename = resolve(baseDirectory, `.ptc-repl-${++submissions}.js`) // baseDirectory: process.cwd() at creation +const program = scopes.compile(code, { filename, context, finalExpression, ...importOption }) +const start = Reflect.apply.bind(undefined, program, undefined, []) as ScopedReplProgram +void programDomain.run(() => Promise.resolve().then(start)).then( + (completion) => { finish({ ok: true, value: completion?.value }) }, + (error: unknown) => { finish({ ok: false, error }) }, +) +``` + +- The kernel always compiles with `filename` and `lineOffset: -1`, and the evaluator always passes `importModuleDynamically`: `VmModuleImportLoader.forFile(filename)` with an import handler, otherwise `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`. +- A microtask calls the program directly, so synchronous throws carry no evaluator frames. The host receives the result with `.then` rather than `await`, which would append a host async frame. +- Measured: `this` is `undefined`, `arguments.length` is 0, and a synchronous throw's stack holds only the program's frame; the domain catches timer errors from programs started this way; a boxed Promise is returned without being awaited. +- Any occurrence of `__$binding_` in the code, including strings and comments, reports `SyntaxError: Names starting with '__$binding_' are reserved` at the first occurrence, and nothing runs. + +### Kernel: scope chain, acorn scan, and compilation + +The kernel depends only on acorn and `node:vm`, not on the child process or the evaluator, so its tests compile and run consecutive programs in a plain vm context to check scope layering on their own. Its interface: + +```ts ignore-check +class ScopedReplScopes { + constructor(options: { strict: boolean; onRedeclaration?: (redeclarations: readonly ScopedReplRedeclaration[]) => void }) + /** Scan and compile one program against the current bindings; throws SyntaxError and leaves the chain unchanged. */ + compile(code: string, options: { filename: string; context: Context; finalExpression: boolean; importModuleDynamically?: ScriptOptions['importModuleDynamically'] }): ScopedReplProgram +} +type ScopedReplProgram = () => Promise<{ value: unknown } | undefined> +interface ScopedReplRedeclaration { name: string; previous: ScopedReplBindingKind; current: ScopedReplBindingKind } +type ScopedReplBindingKind = 'var' | 'let' | 'const' | 'function' | 'class' +interface ScopedReplBinding { name: string; kind: ScopedReplBindingKind } +interface ScopedReplScan { + /** Top-level bindings declared by the program, in source order. */ + declarations: ReadonlyMap + /** Whether the program starts with a "use strict" directive. */ + useStrict: boolean + /** Last top-level statement when it is an expression statement. */ + finalExpression?: { statementStart: number; expressionStart: number; expressionEnd: number } +} +/** Parse once; throws a SyntaxError laid out like V8's for every error acorn reports. */ +function scanProgram(code: string, options: { filename: string }): ScopedReplScan +/** Build the Script source and every binding in the order of the read functions it pushes. */ +function buildProgramSource( + code: string, scan: ScopedReplScan, carried: readonly ScopedReplBinding[], options: { strict: boolean; finalExpression: boolean }, +): { source: string; bindings: ScopedReplBinding[] } +``` + +**Parsing**: regardless of the `strict` option, the kernel calls `parse(code, { ecmaVersion: 'latest', sourceType: 'script', allowAwaitOutsideFunction: true })`. These rules mostly match an async function body: top-level `await` is valid, top-level `return` is a syntax error, and two `function` declarations of one name, or a `var` and a `function` of one name, are valid. They differ in rejecting top-level `using`, `await using`, and static `import` and `export`. The scan does not decide strictness: with the option on, the Script's leading `"use strict";` does, and V8 reports strict-mode syntax violations at compilation. + +Before parsing, the kernel checks two things: a program that starts with `#!`, or any occurrence of `__$binding_`, reports an error, and the code is not parsed. + +**One parse yields four things**: + +1. The call's own top-level declarations, from top-level statements only: + + | Top-level statement | Collected names | Recorded keyword | + |---|---|---| + | `const`, `let`, and `var` declarations, including destructuring (objects, arrays, defaults, rest elements) | Every bound name | The original keyword | + | `function` declarations, including async and generator functions | The function name | `function`; a `var` of the same name in the same call is recorded as `function` too | + | `class` declarations | The class name | `class` | + | `var` in the head of `for (var …; …; …)` and `for (var … in/of …)` | Every bound name | `var` | + | `var` inside blocks, `try`/`catch`/`finally`, `if`/`else`, loop bodies, `switch`, labeled statements, and `with`, including `for` heads there; nested functions and classes are skipped | Every bound name | `var` | + +2. Whether a top-level `return` exists: acorn reports `'return' outside of function` with its position. +3. The last statement: skipping empty statements from the end, the first statement found, if it is an expression statement, records the statement's and expression's offsets. +4. Whether the leading directives include `"use strict"`: acorn marks directive statements with `directive`, and the kernel records `useStrict`. + +Out of scope: no search inside nested functions and classes; inside blocks only `var` is collected, while `let`, `const`, `class`, and `function` stay in their blocks; no reference analysis and no assignment search; no rewriting besides the three insertions around the final expression. + +**Syntax errors**: when acorn fails, the kernel throws a `SyntaxError` directly without a V8 compilation. Its `stack` follows V8's layout: + +```text +/work/.ptc-repl-3.js:1 +const x = ; + ^ + +SyntaxError: Unexpected token +``` + +- The message is acorn's text without its trailing `(line:column)`. +- Two messages use V8's wording: `'return' outside of function` reports `Illegal return statement`, and an error positioned at the end of the code reports `Unexpected end of input`. +- An occurrence of `__$binding_` reports an error with the same layout at its first position. + +### Scope chain state and the steps of a call + +`ScopedReplScopes` holds: + +- `bindings: Map`: the names available for copying and their read functions. `kind` is the keyword of the name's most recent declaration; a name that is only copied keeps its recorded keyword, so a `function` copied as `let` stays `function`. +- `replaced: ReadonlyMap`: the values that names redeclared by the most recently adopted program had when it was compiled. +- `compiled`: the binding order, read-function array, and `replaced` values of the most recently compiled program. + +Each `compile(code, options)`: + +1. Adopts `compiled`: when the read-function array holds at least one function per name, that program's prefix has run, so `bindings` maps the i-th name to the i-th read function and `replaced` takes its values. The child rejects overlapping evaluations (`overlapping PTC evaluation`), so the previous prefix always runs in a microtask before the next compilation; only two compilations in one synchronous run leave the first program unadopted. +2. Scans the program for its declarations and final expression; a syntax error is thrown and the state stays unchanged. +3. Calls every read function in `bindings` for its current value. When a read throws because its declaration never finished, the value from `replaced` is used; without either, the name is dropped. +4. Copies names the call does not declare or declares again only with `var`, and collects their values in `values`; for existing names the call declares, records the value in the new `replaced` and a redeclaration `{ name, previous, current }`. +5. Generates and compiles the source. With the `strict` option off and `useStrict` true, the inner function body starts with `"use strict";`. A V8 compile failure throws the native `SyntaxError` without the compiler frames after the error heading (the same handling as `vm-script`, in a separate copy) and leaves the state unchanged. +6. Calls `onRedeclaration(redeclarations)` when there are redeclarations. +7. Calls the outer function for the program, records `compiled`, and returns the program. + +Each evaluator `evaluate(code, finish)`: + +1. Increments the submission number, including for submissions with syntax errors; the filename is `/.ptc-repl-.js`. +2. Calls `scopes.compile`; a thrown error ends the evaluation. +3. Starts the program from a microtask inside the domain and calls `finish` when its Promise settles, taking `completion?.value` without further awaiting. + +Reads happen in kernel step 3, when a new program is compiled. Later assignments by earlier code change only that code's own variables. + +### Failed calls + +| Call | Code | Result | +|---|---|---| +| 1 | `const data = 1` | `data` is 1 | +| 2 | `const data = await tools.fetch()`, where `fetch` throws | Fails; call 2 declared `data` but never initialized it | +| 3 | `data` | 1: reading call 2's `data` in kernel step 3 throws, so the value recorded when call 2 was compiled is used | +| 4 | `let fresh = await tools.fetch()`, which throws | Fails; `fresh` is a new name | +| 5 | `typeof fresh` | `"undefined"`: there is no earlier value, so the name is dropped | + +- Declarations completed before a throw are kept. For example, after `let y = 5` runs and the call then throws, `y` is still 5 in later calls. +- A `var` redeclaration starts from the copied earlier value, so reading it never throws and needs no fallback: an unreached `var` keeps the earlier value. For example, when call 2 throws before `var v = 6`, or the tool call in `var config = await tools.loadConfig({})` fails, later calls still read the earlier value. A `function` name holds the new function from the start of the call. + +### Asynchronous failures: aligned with the REPL + +The REPL catches errors from the asynchronous work a program starts with Node's `domain`. The evaluator does the same: + +- On creation, the evaluator calls `domain.create()` for `programDomain` and starts every program inside `programDomain.run(...)`. Timers, callbacks, Promise continuations, and EventEmitters that the program creates belong to that domain. +- `programDomain.on('error', ...)` passes `Uncaught ` followed by the error text to `options.reportError`. The text is the error's `stack`, or `name: message` when the stack is not a string; errors are not formatted with `util.inspect` because the domain adds `domain` and `domainThrown`, which inspect would print. A value that is not an error is formatted with `util.inspect` after deleting those two properties, as node:repl does. +- Programs can make this formatting throw through a `stack` accessor, `toString`, or custom inspection. A throw from the listener would end the process, so the formatting runs in `try`/`catch` and a failure reports `program threw an unrenderable value`, the same fallback text as `prepareException` for synchronous failures. The `reportError` call stays outside the `try` because it is the child's own code, whose failures must surface. +- When a callback throws a frozen or non-extensible object, Node's domain fails to add its properties before calling the listener, and the process ends, as with node:repl. +- The child handles `reportError` unchanged: an active evaluation fails with the error; otherwise the error is discarded. Errors belong to the evaluation that created their callback (AsyncLocalStorage). +- No process-wide `uncaughtException` or `unhandledRejection` handler is registered, so errors in the child's own code still surface. +- When a program calls a tool, the asynchronous callbacks that the child creates for the call, such as RPC callbacks, also belong to the program's domain: an asynchronous error in the child's own code inside those callbacks is reported as the program's `Uncaught …` failure, and the child keeps running. The existing REPL evaluator behaves the same. + +Verified cases: + +- REPL: timer throws and unhandled Promise rejections are caught both after and during an evaluation; an EventEmitter `error` event is caught after an evaluation. +- A standalone domain: in the main realm it catches timer throws, rejections created in timers, failures of unawaited async functions, and EventEmitter `error` events; in a context with the default `codeGeneration` limits it catches timer throws and rejections created in timers; timer throws from programs started by a microtask are caught too. + +### Dynamic import + +- A program's `import()` goes through its Script's `importModuleDynamically`: `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER` without an import handler, and the existing `VmModuleImportLoader.forFile(filename)` with one, as in `vm-script`. +- Relative specifiers resolve from the directory where the evaluator was created, which is the working directory of the environment's first call; later directory changes do not move it. node:repl and `vm-script` follow each call's directory; after the Agent changes directory with `working_directory`, import with an absolute path to use the new directory. +- There is no `require`: node:repl's `require` resolves inconsistently (relative paths follow the current directory but are cached after their first resolution; packages resolve from the startup directory), so dynamic `import()` is the only way to load modules. + +### Redeclaration notice (reserved) + +The kernel calls `onRedeclaration` in step 6; the evaluator injects its `reportRedeclarations(redeclarations: readonly ScopedReplRedeclaration[])`, whose body stays empty with one `TODO` comment and prints nothing. A future notice writes to the program's `console` here, which makes it model-visible output. + +### Out of scope + +- Memory reclamation: not handled; every call copies every name. Earlier calls without surviving closures are collected; when a call leaves a surviving function, that function keeps every value copied into that call. +- Resolving `import()` from the working directory as it changes: an explicit operation such as `js_switch_cwd` can be added when needed. +- Reading the earlier value of a name in its own `let`, `const`, or `class` redeclaration, such as `let count = count + 1`: a program error. +- Problems from mixing strict and sloppy calls with the `strict` option off, listed under Risks: left to a future reset tool. +- The column shift on the final expression's line. + +### Integration + +The `scoped-repl` format connects the evaluator with only the changes the connection requires, without refactoring or reusing existing code, so rebases and merges with other ongoing PTC work stay simple. The program format is `scoped-repl` and the Config field is `replScoped`. + +| Location | Change | +|---|---| +| `PtcProgramFormat` in `ptc-runtime` | Includes `'scoped-repl'` | +| `config.ts` in `ptc-runtime-node` | The boolean field `replScoped`, accepted only with `persistent-in-memory` and rejected at load otherwise; when omitted, `resolveReplScoped` takes the value that `resolvePersistentExecution` writes for function bodies with `persistent-in-memory`, currently true, and false in other modes | +| `execution.ts` in `ptc-runtime-node` | In the `persistent-in-memory` branch with `replScoped`, format `scoped-repl`, `retainsState` true, REPL-statement TypeScript erasure, and new model guidance | +| `evaluators/index.ts` in `ptc-runtime-node` | The evaluator table maps `scoped-repl` to this evaluator with the default of all three options | +| `protocol.ts` in `ptc-runtime-node` | The protocol version is 3, so older bootstraps fail at readiness; the upgrade guide `docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/` also covers the new `PtcProgramFormat` member | +| `host.ts` in workflow-ptc | `scoped-repl` uses the same wrapper as `repl`, `await (async () => {…})()` | +| `configuration.ts` in `ptc-runtime-node` (used by CUA to merge settings) | `resolvePersistentExecution` returns `executionMode`, `scriptPersistence`, and `replScoped` to merge together: `script` keeps retained VM Scripts with `replScoped: false`, `scoped-repl` yields `replScoped: true`, and function bodies and REPL statements yield `persistent-in-memory` with the constant `SCOPED_REPL_BY_DEFAULT`, currently true, replacing a stale profile value. That constant also sets the omitted default in `config.ts`, so changing it changes one line; `config.ts` imports this function from `configuration.ts`, which is itself a published package entry, and `configuration.ts` imports only the `Config` type, so the build emits no shared chunk | +| Documentation, snapshots, and tests | Package README configuration, behavior, and known limitations; the config catalog; the snapshot scenario `ptc-scoped-repl`; a built-artifact e2e case with `replScoped: true` | + +tool-executor-ptc is unchanged: for every format other than `function-body` it uses its printing guidance. The model guidance states the exact behavior above, especially: output uses `inspect(...)`, in a sentence shared with the other modes; top-level `return` is unsupported; copies happen when a call starts and earlier code is unaffected; shared mutable state belongs in objects; an assignment without declaration changes only the copy, including for earlier `const` names; a `let`, `const`, or `class` redeclaration cannot read the earlier value of its name, so assign to the name or use a new one to compute from it; a `var` redeclaration starts from the earlier value; when a call fails, an unfinished `let`, `const`, `class`, or `var` redeclaration keeps the earlier value; a `var` inside a block is also a top-level name of the call, while other block declarations stay in their block; modules load only with `import()`, whose relative specifiers resolve from the directory of the environment's first call. Tests pin the model guidance verbatim. + +## Alternatives considered + +**Nesting each call in the previous call's scope with direct eval.** Calls can share live bindings, but earlier scopes are never reclaimed, positions require a source map or stack rewriting, and direct eval is unavailable in a context that forbids code generation from strings. + +**Rewriting declarations as `var` or global assignments.** Every call shares one binding, which violates requirement 2, and model code must be rewritten. + +**Compiling each call as an ES module.** Each module receives values through a synthetic module for the previous call and an appended `export`. Modules allow neither `return` nor a final value, and the prelude shifts every reported line; function parameters already pass values without modules. + +**Scope analysis with rewritten references.** Allows finer memory reclamation, but needs scope analysis and code rewriting, which violates requirement 5. + +**Printing only, without a final expression.** workflow-ptc and the `repl` format contract depend on completion values, and it departs from the existing REPL syntax. + +**Results from top-level `return`.** Conflicts with requirement 3, requires the function-body format, and changes the run_code guidance. + +**Awaiting a final Promise.** Matches `vm-script` but not the existing REPL; boxing as Node does keeps the REPL behavior. + +**Results for programs ending with `if`, `for`, or a block.** Only Script top-level code has V8 completion values, which a function body lacks; supporting them requires rewriting more statements. node:repl has no result there either when the code contains `await`. + +**Writing the wrapper as `async function (__$binding_vals, __$binding_getters)`.** `this` is also `undefined`, but the program's `arguments` exposes both internal values and has length 3. + +**An async arrow wrapper.** `this` is `globalThis` and `arguments` does not exist, as in the REPL; ours uses `undefined`, as a strict function call without a receiver does. + +**Returning read functions through a callback.** The prefix would need name strings and protection against repeated calls; pushing into an array that the evaluator maps by index is simpler. + +**Recompiling with V8 for syntax errors.** Yields V8's wording at the cost of another compilation; acorn already provides the position and message. + +**Module rules for strict programs.** Module rules are stricter than an async function body: two `function` declarations of one name, a `var` and a `function` of one name, and `await` as a variable name in a nested ordinary function are rejected, and HTML-like comments are handled differently from V8's Script compilation. They are unusable with strict mode off, because module code is always strict. + +**Scanning inside the same function wrapper as the runtime.** Matches the runtime grammar exactly and accepts top-level `using`, as Node's `processTopLevelAwait` does. It requires a statement walk to find top-level `return`, position mapping for the wrapper, and a guard against an extra `}` in the code closing the wrapper early; top-level `using` is not needed, so script rules are simpler. + +**Copying only assigned `const` names as `let`, with a warning.** This walks the new call's syntax tree and tracks shadowing, which is scope analysis and violates requirement 5. Ours copies every `const` as `let` without a notice. + +**Starting a `var` redeclaration from `undefined` without a copy.** `var count = count + 1` then yields `NaN`, but a `var` not reached before a throw or in a branch that is not taken replaces the earlier value with `undefined`; for example, a failed tool call in `var config = await tools.loadConfig({})` leaves later calls without the earlier `config`. With the copy, `var count = count + 1` adds to the earlier value, as in node:repl, which is accepted for now. + +**Falling back only when a call failed and the value reads `undefined`.** It needs no copy, but cannot tell an unreached declaration from one that ran and assigned `undefined`: a call that assigns `undefined` and then fails falls back by mistake, and an untaken branch or `var x;` without an initializer in a successful call is not covered. + +**Marking in the code whether each `var` ran.** It distinguishes the cases exactly but rewrites model code at declarations, earlier assignments, and loop heads, which violates requirement 5. + +**Skipping copies of strict-mode reserved words in strict calls.** It would keep names such as `package`, declared in a sloppy call, from breaking later strict calls; the problem comes from the model mixing both modes, so it is left to a future reset tool. + +**A process-wide handler for uncaught errors.** It would also swallow errors from the child's own code; the REPL's domain covers only the asynchronous work programs start. + +**Not collecting `var` declarations inside blocks.** A block-level `var` then collides with the copy declarations, so the whole program reports `already declared`, and the name is not carried to later calls; collecting it takes about 15 lines of statement traversal without reference analysis, so the scanner collects it. + +**Showing only `.ptc-repl-.js` in stacks, without the directory.** Without the directory, Node's default loader resolves relative `import()` specifiers from the current directory at import time, unlike calls with an import handler; a `//# sourceURL` comment that shows only the name makes V8 ignore `lineOffset`, so every line number grows by 1; handing imports to a callback would work, because both child launches pass `--experimental-vm-modules` and the callback can start `import()` from the first call's directory, but it requires scoped REPL imports to always go through a callback, which the default path does not do yet. The filename therefore keeps the directory of the first call for now. + +**Providing `require`, `module`, and built-in module globals, as node:repl does.** node:repl's `require` resolves inconsistently, and following directory changes needs a rule for when the base moves; only `import()` remains. + +## Consequences + +Gains: + +- Later calls may declare an earlier name again with any keyword, while earlier functions, closures, and still-running code keep their values. +- Syntax, results, errors, and asynchronous failure handling match the existing REPL, and asynchronous program failures do not end the process. +- There is no scope analysis, and model code is rewritten only at the three insertion points of the final expression. + +Costs: + +- Copying at call start differs from the REPL: assignments that earlier code, such as timers and callbacks, makes to top-level variables afterwards are invisible to later calls; the model guidance states this. +- An assignment without declaration affects only later calls and is invisible to earlier functions; in the REPL both sides change. +- Strict mode differs from the REPL: assigning an undeclared name creates a global in the REPL and throws here. +- For callers that keep completions, a final Promise without `await` makes the host report a non-JSON completion, as in the existing REPL; `run_code` discards completions and is unaffected. +- Programs ending with `if`, `for`, or a block have no result, while node:repl has one when the code contains no `await`. +- On the final expression's line, columns after the insertion point shift right by 17. +- Syntax error messages use acorn's text, which differs from V8's, for example `Unexpected token` instead of `Unexpected token ';'`. +- Scanning always uses script rules, so top-level `using` and `await using` are rejected; node:repl does not support them either. +- Top-level `arguments` is an empty arguments object, while it does not exist in node:repl. +- The context forbids code generation from strings by default: code relying on `eval` or `new Function` fails, including libraries loaded into this context through an import handler. The limit is no isolation, because copied main-realm functions such as `setTimeout.constructor` still generate code. +- There is no `require`: code that relies on it must use `await import()` instead. +- Relative `import()` keeps resolving from the directory of the environment's first call, also after the Agent changes directory. +- Node documents `domain` as deprecated; node:repl still builds on it, so a removal would change the REPL as well. +- An error in the child's own code inside a tool call's asynchronous callbacks is reported as the program's `Uncaught …` failure, and the child keeps running, as with the existing REPL. +- Programs that start with `#!` are rejected. +- Any occurrence of `__$binding_`, including in strings and comments, is rejected; internal names written with escapes such as `\u005f` are not checked. +- acorn must keep pace with V8's syntax, or newer syntax is rejected before it runs. +- A `var` redeclaration starts from the earlier value: `var count = count + 1` adds to it, as in node:repl, also when the earlier declaration was `let` or `const`, where node:repl reports `already declared`. +- A `let`, `const`, or `class` redeclaration cannot read the earlier value of its name and throws, as in `let count = count + 1`. This is a program error and is not handled. +- Every earlier `const` is copied as `let` into later calls, which can assign to it without any notice. +- With the `strict` option off, strict and sloppy calls can mix: a sloppy call that assigns an undeclared name creates a global shared by every call and earlier function, and a name declared in a sloppy call with a strict-mode reserved word (`package`, `public`, `private`, `protected`, `interface`, `implements`, `static`, `let`, `yield`, `eval`, `arguments`) makes later strict calls fail to compile. This is not handled and is left to a future reset tool. +- When a callback throws a frozen or non-extensible object, Node's domain handling fails and the process ends, losing retained variables, as with node:repl. +- Every call generates a copy declaration and a read function for every earlier name: the prototype measured about 10 ms per call with 1000 names. +- When a call leaves a surviving function, every value copied into that call stays in memory. + +## Testing + +- The kernel tests pass on their own and cover script-rule parsing and detection of a leading `"use strict"`, every statement in the declaration table, top-level `return` including inside blocks, locating and boxing the final expression, programs that start with `#!`, occurrences of `__$binding_`, the syntax-error layout with both message substitutions, and the generated source; with the `strict` option off, a leading `"use strict"` takes effect both with and without copies; running consecutive programs in a plain vm context, they cover every item under Across calls, including keyword combinations, failed calls, timers, function redefinition, and redeclaration notices. +- The evaluator tests use the evaluator and a real vm context and cover every item under Syntax and results, Environment, Errors, and Asynchronous failures and lifecycle, plus cross-call behavior through the evaluator, including that the global object's prototype chain does not reach the main realm's `Function` while copied main-realm functions such as `setTimeout.constructor` still generate code, and that host bindings named `module` or `require` stay untouched. +- Every option is tested on and off. +- Top-level `this` is `undefined`, `arguments.length` is 0, and a synchronous throw's stack holds only the program's frames. +- Asynchronous failures: each listed case is tested after and during an evaluation; the text passed to `reportError` starts with `Uncaught `; the process keeps running and variables are retained. A missing `stack`, a throwing `stack` accessor, and throwing custom inspection report `name: message` or the fixed text without ending the process; a thrown plain object is reported without `domainThrown`. +- Imports: both the default loader and an import handler; relative specifiers resolve from the directory at creation, also after the working directory changes. +- The built-artifact e2e covers `replScoped: true`. +- Tests that mount `persistent-in-memory` set `replScoped` explicitly, and retained-execution tests run both values; one test checks the default when it is omitted. +- New files have 100% coverage; existing evaluators and their tests are unchanged. diff --git a/.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.zh.md b/.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.zh.md new file mode 100644 index 0000000000..207617b1de --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.zh.md @@ -0,0 +1,524 @@ +# Agent Note: 保留状态 PTC 的 scoped REPL 求值器 + +Status: implemented + +[English](2026-11-09-retained-ptc-scoped-repl.md) | 中文 + +## 问题 + +`persistent-in-memory` 用 node:repl 在同一个全局作用域里执行同一个 Agent 的每次 `run_code`([尽力保留 PTC 状态](../../implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md))。模型在后面的调用里再次声明前面用过的 `const`、`let`、`class` 名字时,V8 在执行前就报 `SyntaxError: Identifier 'x' has already been declared`,整段代码一行都不执行。模型说明只能要求"不要重复声明",但模型在多轮调用里很难记住每个名字。 + +把声明改成 `var` 能消除报错,但所有调用共用同一个绑定,后面的声明会改掉前面的函数、闭包和后台任务读到的值: + +```js +// call 1 +var value = 1 +var read = () => value +// call 2 +var value = 2 // no error +// call 3 +read() // 2: call 2 changed the read written by call 1 +``` + +需要同时满足五条要求: + +1. 后面的调用可以用任意关键字再次声明前面的名字,不报错。 +2. 再次声明只对这次和之后的调用生效;前面的函数、闭包和仍在运行的代码继续使用它们原来的值。 +3. 写法与现有 REPL 一致:支持顶层 `await`,最后一个表达式的值是结果,不支持顶层 `return`。 +4. 异步回调里的错误与现有 REPL 一样处理:进程不退出,变量保留。 +5. 不做作用域分析,不改写模型代码里的声明和引用;acorn 只用来列出顶层声明、找到最后一条语句。 + +## 决策 + +scoped REPL 求值器分成内核和求值器两个文件: + +| 文件 | 内容 | +|---|---| +| `packages/ptc-runtime/ptc-runtime-node/src/evaluators/scoped-repl.ts` | 内核:作用域链 `ScopedReplScopes`,负责状态表、拷贝与退回旧值、重复声明、编译成 Script;以及 acorn 扫描、顶层声明与关键字、顶层 `return` 检查、最后一条表达式、保留名检查、语法错误格式化、拼源码 | +| `packages/ptc-runtime/ptc-runtime-node/src/evaluators/scoped-repl-evaluator.ts` | 求值器:导出 `createScopedReplEvaluator(options)`,实现现有的 `ProgramEvaluator` 接口,把内核接入现有模式:执行环境和开关、动态 import 与 import 处理器、由微任务启动程序并取完成值、domain、注入 `reportRedeclarations` | +| `packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl.spec.ts` | 只测内核,可以单独运行:扫描、拼源码,以及在普通 vm context 里连续执行多段程序的作用域分层 | +| `packages/ptc-runtime/ptc-runtime-node/tests/scoped-repl-evaluator.spec.ts` | 测接入层:完成值、执行环境、模块与 import、报错、异步错误;三个开关打开、关闭两种状态都测 | + +求值器以 `scoped-repl` 格式接入现有执行模式,见"接入"。 + +### 精确行为 + +#### 写法与结果 + +- 程序是一组语句,支持顶层 `await`。 +- 最后一条非空的顶层语句是表达式语句时,它的值就是结果。值是 Promise 时不等待,Promise 本身就是结果,宿主会报 `program completion must be lossless JSON`,和现有 REPL 一样。这一项由 `finalExpression` 开关控制,默认开;关闭后末尾表达式的值被丢弃,结果只能靠打印,模型说明要随之调整。`run_code` 对 TypeScript 运行时传 `discardCompletion: true`,宿主丢弃完成值,模型用 `inspect(...)` 输出;不丢弃完成值的调用方(例如 workflow-ptc)仍以末尾表达式的值为结果。 +- 最后一条是声明、`if`、`for`、块等其他语句时,没有结果。 +- 顶层 `return`,包括写在顶层 `if`、循环和块里的,报 `SyntaxError: Illegal return statement`,这次一行都不执行。经 `run_code` 执行时,宿主的 TypeScript 擦除会先拒绝它,报 `Return statement is not allowed here`,和现有 REPL 相同。 +- 静态 `import`、`export` 报 acorn 的 `SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'`;顶层 `using`、`await using` 同样被 acorn 拒绝,块里和函数里可以用。 +- 以 `#!` 开头的程序报 `SyntaxError: Hashbang lines are not supported`,这次不执行:`#!` 只能出现在 Script 的最开头,而生成的前缀排在程序前面。 +- 输出是 `inspect(...)` 等打印的内容;调用方不丢弃完成值时,再加上末尾表达式的值。 + +#### 跨次调用 + +- 每次调用开始时,把前面留下的每个顶层名字拷贝成本次的同名声明;对象按引用共享,修改对象内部两边都看得到。 +- 可以用任意关键字再次声明前面的名字,包括 `var`→`let`→`const`→`class`→`function` 依次换。本次用 `let`、`const`、`class`、`function` 声明的名字不再拷贝,以本次为准;只用 `var` 重新声明的名字照样拷贝,这次的 `var` 从旧值开始。 +- 不声明、直接给前面的名字赋值,改的是本次的拷贝:之后的调用看到新值,前面定义的函数仍看到旧值。前面用 `const` 声明的名字也一样,它只在声明它的那次调用里不能赋值。 +- 重定义函数后,前面定义的调用方仍然调用旧函数。 +- 本次开始以后,前面的代码(定时器、回调)再给顶层变量赋值,之后的调用看不到;需要共享的可变状态放进对象。 +- 前面定义的函数看不到后面才声明的名字,引用时报 `ReferenceError`。 +- 一次调用用 `let`、`const`、`class` 重新声明了某个名字,这次调用里的所有引用都指向新声明,包括写在声明之前的,拿不到旧值:在声明执行前读取报原生的 `ReferenceError: Cannot access 'x' before initialization`。这类写法是代码本身的问题,不做处理。用 `var` 重新声明时,这次的 `var` 从旧值开始,直到被赋上新值,例如 `var count = count + 1` 在旧值上加 1;`function` 从调用开始就是新函数。 +- 一次调用中途出错时:抛错前已经执行完的声明保留;重新声明了已有名字、但没来得及赋值的,之后的调用退回旧值;没来得及赋值的新名字直接丢掉。 +- 块里(包括 `try`/`catch`/`finally`、`if`/`else`、循环体、`switch`、标签语句)声明的 `var` 会提升到这次调用的顶层,和顶层 `var` 一样算这次的声明:带到之后的调用,也可以和前面任何关键字声明的名字同名。嵌套的函数和类里的 `var` 不算。 +- 没执行到的 `var` 再次声明,不论在抛错之后还是在没走到的分支里,都保留旧值;不带初始值的 `var x;` 也保留旧值。 + +#### 执行环境 + +下面是默认行为,前两项各由一个开关控制,见"执行环境与开关"。 + +- strict 模式:给未声明的名字赋值报 `ReferenceError`;有意的全局变量写 `globalThis.x`。开关关闭时不强制:程序以 `"use strict"` 开头,这次就按严格执行,否则按宽松执行。 +- 禁止从字符串生成代码:执行环境自己的 `eval`、`new Function` 报 `EvalError`,从字节编译 WebAssembly 报 `CompileError`。这不构成隔离:从主环境复制进来的函数(例如 `setTimeout.constructor`)仍能在主环境里生成代码。 +- 只能用动态 `import()` 加载模块,相对路径按这个环境第一次调用时的 working directory 解析,之后的调用换了目录也不变;不提供 `require`、`module` 和 `fs`、`path` 这类内置模块全局。读写文件的相对路径仍跟随当前目录。 +- 顶层 `this` 是 `undefined`,按宽松执行时是 `globalThis`;顶层 `arguments` 是一个空的 arguments 对象,长度为 0。 +- 顶层 `var` 和 `function` 不会成为 `globalThis` 的属性。 +- `setTimeout`、`Buffer`、`fetch`、`URL`、`structuredClone` 等 Node 全局对象可用。 + +#### 报错 + +- 运行时报错的行号、列号是模型代码里的原生位置,跨次调用定义的函数显示它自己那次的文件名,例如 `<目录>/.ptc-repl-1.js:2:9`。最后一条表达式所在的那一行,插入点之后的列号右移 17,这次不处理。 +- acorn 发现的语法错误直接报 acorn 的消息和位置,按 V8 的样式排版:文件名加行号、源码行、箭头。有两处消息改用 V8 的说法:顶层 `return` 报 `Illegal return statement`;报错位置在代码末尾时报 `Unexpected end of input`。 +- acorn 放行、V8 编译时才发现的错误,报 V8 原生的消息;strict 开关打开时,严格模式的语法违规(例如 `with`)也在这一步报出。 +- 以上是求值器自己的行为。经 `run_code` 执行时,宿主的 TypeScript 擦除先解析整段代码,多数语法错误由它报告,和现有 REPL 相同;只有擦除接受、扫描拒绝的代码(例如保留名、静态 `import`、顶层 `using`)才会看到上面的版式。 +- 运行时错误报错误名加堆栈,没有 `Uncaught ` 前缀,堆栈里没有求值器自己的帧。 + +#### 异步错误与生命周期 + +- 程序启动的定时器、回调、Promise 后续步骤和 EventEmitter 抛出的错误,以及未处理的 rejection,不让进程退出,变量保留。例外:回调里 `throw` 的是冻结或不可扩展的对象时,Node 的 domain 在通知监听器之前给它加属性失败,进程结束,和 node:repl 相同;以这样的对象 reject 不受影响。 +- 当时有执行在运行,就让那次执行以 `Uncaught ` 加错误文本失败;否则丢弃。错误文本取错误的 `stack`,`stack` 不是字符串时用"名字: 消息";不是 Error 的值,先去掉 domain 加上的 `domain`、`domainThrown` 再用 `util.inspect`;转换出错时报 `program threw an unrenderable value`。错误按创建回调时所属的执行归属,前一次留下的定时器在后一次运行时抛错,不会算到后一次头上。 +- 执行结束后才打印的输出被丢弃;超时、取消和重置沿用现有的宿主逻辑([保留状态的 PTC 中断](../../implemented/architecture/2026-10-29-retained-ptc-interruption.zh.md))。 + +### 与 node:repl、vm-script 的对比 + +✓ 表示支持,✗ 表示不支持,"—" 表示不适用:不开持久化的 `vm-script` 每次调用都是新进程,没有跨次状态。"持久化 vm-script"指设置 `scriptPersistence: true` 的 vm-script(#7992),"两种 vm-script"指它和不开持久化的 vm-script。"我们"一列是默认行为,括号里写和哪几列一致;执行环境一组把"我们"分成 strict 开启(默认)和关闭两列。跨次调用一组多列一项"预期支持跨次调用能力的一种实现",括号和备注里简称"预期实现"。 + +**写法与结果** + +| 能力 | node:repl(现有 REPL 求值器) | 我们 | vm-script(不开持久化) | vm-script(开持久化,#7992) | 备注 | +|---|---|---|---|---|---| +| 顶层 `return`,包括写在 `if` 块里的 | ✗ | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | 都报 `Illegal return statement` | +| 末尾表达式作为结果 | ✓ | ✓(默认;与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 可以用 `finalExpression` 开关关闭 | +| 末尾是 Promise 时等它完成 | ✗ | ✗(与 node:repl 一致) | ✓ | ✓ | 不等时宿主报"不是 JSON" | +| 以 `if`、`for`、块结尾时有结果 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 含 `await` 时一致) | ✓ | ✓ | node:repl 和两种 vm-script 只在代码不含 `await` 时有结果 | +| 顶层 `await` | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | node:repl 和两种 vm-script 靠改写整段代码;我们只改写最后一条表达式 | +| 静态 `import` | ✗ | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | 我们报 acorn 的消息 | +| 顶层 `using` | ✗ | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | 块里和函数里可以用 | +| 以 `#!` 开头的程序 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 我们报 `Hashbang lines are not supported` | +| 同一次里两个同名 `function`,或同名的 `var` 和 `function` | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | | +| 动态 `import()` | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | | + +**跨次调用** + +| 能力 | node:repl | 预期支持跨次调用能力的一种实现 | 我们 | vm-script | 持久化 vm-script | 备注 | +|---|---|---|---|---|---|---| +| 跨次保留变量 | ✓ | ✓ | ✓(与 node:repl、预期实现、持久化 vm-script 一致) | ✗ | ✓ | node:repl 和持久化 vm-script 共用一个作用域;我们靠拷贝;预期实现也靠拷贝 | +| 用任意关键字再次声明 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | node:repl 和持久化 vm-script 的 25 种关键字组合里 21 种报 `already declared`,只有 `var`、`function` 之间可以;我们预留重复声明提示,暂不输出;预期实现对 `const` 再次声明为 `const` 多输出一行警告 | +| 后面不声明直接赋值,前面定义的函数不受影响 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | | +| 不重新声明,直接给前面的 `const` 赋值 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | node:repl 和持久化 vm-script 报 `TypeError`;我们不提示;预期实现先打印警告 | +| 用 `var` 重新声明时读到同名旧值(`var n = n + 1`) | ✓ | ✗ | ✓(与 node:repl、持久化 vm-script 一致) | — | ✓ | node:repl 和持久化 vm-script 只在前面也是 `var` 时成立,前面是 `let` 时报 `already declared`;我们前面是 `let`、`const` 时也成立;预期实现得到 `NaN` | +| 重定义函数后,旧的调用方仍调旧函数 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | | +| 前面的代码之后改的值,后面的调用能看到 | ✓ | ✗ | ✗(与预期实现一致) | — | ✓ | 定时器自增的变量,间隔 30 ms 读两次:node:repl 23、50;持久化 vm-script 22、44;我们 0、0;预期实现 15、15 | +| 前面定义的函数能看到后面才声明的名字 | ✓ | ✗ | ✗(与预期实现一致) | — | ✓ | 我们报 `ReferenceError` | +| 修改对象内部,两边都看得到 | ✓ | ✓ | ✓(与 node:repl、预期实现、持久化 vm-script 一致) | — | ✓ | | +| 初始化抛错后,这个名字还能继续用 | ✗ | ✓ | ✓(与预期实现一致) | — | ✗ | node:repl 和持久化 vm-script 里新名字永久不可用,再次声明报 `already declared`;我们已有名字退回旧值,新名字丢掉 | +| 抛错前已经执行完的声明会保留 | ✓ | ✓ | ✓(与 node:repl、预期实现、持久化 vm-script 一致) | — | ✓ | | +| 抛错前没执行到的 `var` 再次声明,保留旧值 | ✓ | ✓ | ✓(与 node:repl、预期实现、持久化 vm-script 一致) | — | ✓ | 我们把旧值拷进这次的 `var`,没走到的分支里的 `var` 也保留旧值;预期实现靠插入标记代码做到 | +| 块里新声明的 `var` 带到下一次 | ✓ | ✗ | ✓(与 node:repl、持久化 vm-script 一致) | — | ✓ | 我们收集块里的 `var` | +| 块里的 `var` 和已有的 `let` 同名时不报错 | ✗ | ✗ | ✓(与 node:repl、预期实现、持久化 vm-script 都不一致) | — | ✗ | node:repl 和持久化 vm-script 报 `already declared`;我们把它算作这次的新声明;预期实现也报 `already declared` | + +**执行环境** + +| 能力 | node:repl | 我们(strict,默认) | 我们(非 strict) | vm-script | 持久化 vm-script | 备注 | +|---|---|---|---|---|---|---| +| strict 模式 | ✗ | ✓(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | strict 关闭时,程序自己开头的 `"use strict"` 仍然生效 | +| 给未声明的名字赋值会创建全局变量 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 非 strict 时创建的全局变量由所有调用和前面的函数共用,不走拷贝 | +| 顶层 `var`、`function` 挂到 `globalThis` | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | | +| 顶层 `this` 是 `globalThis` | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 我们 strict 时是 `undefined` | +| 顶层 `arguments` | ✗ | ✓(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗ | ✗ | 我们的是空的 arguments 对象 | +| `eval`、`new Function` | ✓ | ✗(默认;与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(默认;与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 可打开;只限执行环境自己的,复制进来的主环境函数仍能生成代码 | +| 编译 WebAssembly | ✓ | ✗(默认;与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(默认;与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 与 `eval` 同一个开关 | +| Node 全局对象(`setTimeout`、`Buffer`、`fetch`、`URL`、`structuredClone`) | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | | +| `require`、`module`、`fs` 等内置模块全局 | ✓ | ✗(与 vm-script、持久化 vm-script 一致) | ✗(与 vm-script、持久化 vm-script 一致) | ✗ | ✗ | 只能用 `import()` | +| 相对路径的 `import()` 跟随之后的目录变化 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 我们固定用这个环境第一次调用时的目录 | +| `_`、`_error` | ✓ | ✗(与 vm-script、持久化 vm-script 一致) | ✗(与 vm-script、持久化 vm-script 一致) | ✗ | ✗ | | +| 以 `{ a: 1 }` 开头的代码当对象字面量 | ✗ | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗(与 node:repl、vm-script、持久化 vm-script 一致) | ✗ | ✗ | node:repl 原本当对象,现有 REPL 求值器强制改成语句块 | + +**报错** + +| 能力 | node:repl | 我们 | vm-script | 持久化 vm-script | 备注 | +|---|---|---|---|---|---| +| 报错行列号准确(代码不含 `await`) | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 我们的例外是最后一条表达式所在行 | +| 报错行列号准确(代码含 `await` 时的第 1 行) | ✗ | ✓(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✗ | ✗ | node:repl 和两种 vm-script 把第 22 列报成第 54 列 | +| 语法错误带源码行和箭头 | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | 我们按 acorn 给出的位置自己排版;这是求值器层的行为,经 `run_code` 时多数语法错误先由宿主的 TypeScript 擦除报告,与 node:repl 列相同 | +| 语法错误消息是 V8 的原文 | ✓ | ✗(与 node:repl、vm-script、持久化 vm-script 都不一致) | ✓ | ✓ | 我们用 acorn 的消息,acorn 放行、V8 拒绝的错误用 V8 原文 | +| 代码不完整时有明确提示 | ✗ | ✓(与 vm-script、持久化 vm-script 一致) | ✓ | ✓ | node:repl 的报错消息为空;经 `run_code` 时同样先由宿主擦除报告 | +| 报错带错误名和堆栈 | ✓ | ✓(与 node:repl、vm-script、持久化 vm-script 一致) | ✓ | ✓ | | +| 同步错误和 `await` 失败带 `Uncaught ` 前缀 | ✓ | ✗(与 vm-script、持久化 vm-script 一致) | ✗ | ✗ | | +| 异步回调错误带 `Uncaught ` 前缀 | ✓ | ✓(与 node:repl 一致) | — | — | 两种 vm-script 的进程直接退出,没有这类报告 | + +**异步错误与生命周期** + +| 能力 | node:repl | 我们 | vm-script | 持久化 vm-script | 备注 | +|---|---|---|---|---|---| +| 执行结束后回调里出错,进程不崩、变量保留 | ✓ | ✓(与 node:repl 一致) | — | ✗ | 持久化 vm-script 的进程退出,下一次调用报 `worker-exit`,变量全部丢失;不开持久化时执行结束后进程已关闭;回调里 `throw` 冻结的对象时,node:repl 和我们的进程都会结束 | +| 执行中回调里出错,只让这次失败、变量保留 | ✓ | ✓(与 node:repl 一致) | ✗ | ✗ | 两种 vm-script 的进程都退出,报 `worker-exit`,持久化 vm-script 的变量丢失 | +| 执行结束后才打印的输出被丢弃 | ✓ | ✓(与 node:repl、持久化 vm-script 一致) | — | ✓ | | +| 超时或取消后变量可以保留 | ✓ | ✓(与 node:repl、持久化 vm-script 一致) | — | ✓ | 前提是程序确认已经停住 | +数据来源:node:repl、vm-script 和持久化 vm-script 三列直接调用 master 的求值器实测(Node v24.18.0)。持久化 vm-script 用同一个求值器连续执行;一次调用内的各行与 vm-script 相同,跨次调用各行和两行异步错误单独实测,异步错误经真实子进程。"我们"一列的跨次调用各项由 `scoped-repl.spec.ts` 测试,其余各项由 `scoped-repl-evaluator.spec.ts` 测试。不开持久化的 vm-script 两行异步错误按现有实现推断;node:repl、持久化 vm-script 和我们的超时、取消、重置沿用同一套宿主逻辑。预期实现一列在该实现上实测,每个用例新开一个环境。 + +### 执行环境与开关 + +一个求值器只有一个执行环境。`codeGeneration` 开关关闭(默认)时这样创建: + +```ts ignore-check +const runtimeContext = vm.createContext(Object.create(null), { codeGeneration: { strings: false, wasm: false } }) +``` + +- Node 全局对象按 `vm-script` 的 `createScriptContext` 同样的规则复制进来:主环境 `globalThis` 上、新环境没有的自有属性逐个复制,`global` 指向新环境自身。这几行在求值器文件里单独写一份,不改 [vm-script.ts](../../../../packages/ptc-runtime/ptc-runtime-node/src/evaluators/vm-script.ts)。 +- `tools`、绑定错误类、`console`、`process` 仍由子进程在每次执行前写到 `evaluator.globals`,也就是 `runtimeContext`。 +- 沙箱对象没有原型,和 vm-script、AsyncFunction 两个求值器一样,全局查找因此不会经原型链走到主环境的 `Function`,例如 `constructor.constructor("…")()`。但复制进来的主环境值(`setTimeout`、`console`、`process`、工具命名空间等)的 `constructor` 仍是主环境的 `Function`,主环境没有 `codeGeneration` 限制,所以这个开关只限制执行环境自己的 `eval`、`Function` 和 WebAssembly,不构成隔离;隔离靠进程级沙箱。 +- 只提供动态 `import()`,没有开关:每个 Script 都配 `importModuleDynamically`。不提供 `require`、`module` 和内置模块全局;宿主以这些名字注入的绑定原样可用。静态 `import` 不支持。 +- 生成的文件名是 `<目录>/.ptc-repl-<序号>.js`,这个路径上没有真实文件,文件名用点开头的隐藏名。目录是求值器创建时的 working directory,也就是这个环境第一次调用时的目录,之后不再改变;默认加载器把文件名当作 `import()` 的引用方,所以相对路径的 import 固定按这个目录解析,目录部分不能省。以后需要跟随目录变化时,另加显式操作(例如 `js_switch_cwd`)。 +- 绑定和 import 返回的值属于主环境,`instanceof Array` 这类跨环境判断可能为 false,和 REPL、`vm-script` 相同。 + +三个开关是求值器的创建参数,不是 Config 字段: + +```ts ignore-check +interface ScopedReplEvaluatorOptions extends ProgramEvaluatorOptions { + /** Force strict mode for every program; when off, a program's own leading "use strict" decides. Defaults to true. */ + strict?: boolean + /** Allow eval, new Function and WebAssembly compilation inside the program context; defaults to false. */ + codeGeneration?: boolean + /** Use the last top-level expression statement as the completion value; defaults to true. */ + finalExpression?: boolean +} +``` + +| 开关 | 打开时 | 关闭时 | 需要注意 | +|---|---|---|---| +| `strict`(默认开) | 整个 Script 以 `"use strict";` 开头,每次调用都按严格执行 | 不强制:程序以 `"use strict"` 指令开头时,在内层函数体最前面补一个 `"use strict";`,拷贝语句不会让它失效;否则按宽松执行 | 两种状态下 acorn 都按 script 规则扫描,严格模式的语法违规由 V8 编译时报出。关闭后,按宽松执行的调用里:给未声明的名字赋值会创建所有调用共用的全局变量,不走拷贝;顶层 `this` 是 `globalThis`;用严格模式保留字(如 `package`)声明的名字会让之后严格的调用编译失败,见"风险" | +| `codeGeneration`(默认关) | 创建执行环境时不加 `codeGeneration` 限制 | 按上面的代码创建 | 打开后,`eval` 里新声明的 `var` 不在扫描出的名单里,不会带到下一次;关闭时也只限制执行环境自己的代码生成,不构成隔离 | +| `finalExpression`(默认开) | 最后一条表达式改写成 `return { value: (…) }` | 不改写,末尾表达式的值被丢弃,结果为空 | 关闭后输出只能靠打印,模型说明和使用完成值的地方(例如 workflow-ptc)都要相应调整;顶层 `return` 在两种状态下都报错 | + +接入时三个开关都取默认值;非默认值是设计上预留的用法,各自都有测试。 + +### 包装 + +每次调用编译成一个独立的 `vm.Script`。例如前面留下了 `a`(`const`)、`b`(`let`)、`v`(`var`),这次模型写了: + +```js +let c = a + b +c * 2 +``` + +实际编译的源码是: + +```js +"use strict";(function (__$binding_vals, __$binding_getters) { return async function () { let a = __$binding_vals[0]; let b = __$binding_vals[1]; var v = __$binding_vals[2]; __$binding_getters.push(() => a, () => b, () => v, () => c); +let c = a + b +return { value: (c * 2) } +} }) +``` + +| 部分 | 内容 | 原因 | +|---|---|---| +| `"use strict";` | `strict` 开关打开时,整个 Script 是 strict 模式;关闭时省略,程序以 `"use strict"` 开头时改为在内层函数体最前面补一个 | 打开时强制严格;关闭时保证前缀里的拷贝语句不会让模型写的指令失效 | +| 外层 `function (__$binding_vals, __$binding_getters)` | 接收拷贝进来的值和一个空数组,返回内层函数;由求值器同步调用 | 内部值通过闭包交给程序,不出现在程序的 `arguments` 里;外层在程序运行前就已返回,它的帧不会出现在程序的堆栈里 | +| 内层 `async function ()` | 模型程序就是它的函数体 | 支持顶层 `await`;顶层声明是函数的局部变量,每次调用互不冲突;不带接收者、零参数调用,所以 `this` 是 `undefined`(按宽松执行时是 `globalThis`),`arguments` 是一个空的 arguments 对象 | +| 拷贝声明 | 只给"前面有、本次没声明或只用 `var` 重新声明"的名字生成,值按下标从 `__$binding_vals` 取 | 下标访问不受 `__proto__` 这类名字影响 | +| `__$binding_getters.push(...)` | 在模型代码之前,按求值器生成前缀时的名字顺序,给每个名字(拷贝来的和本次声明的)推入一个读取函数 | 求值器知道第 i 个读取函数对应第 i 个名字,前缀里不用写名字字符串;读取函数可以先建好、以后再读,声明还没初始化完时读取会抛错 | +| 最后一条表达式 | 语句前插入 `return `,表达式前插入 `{ value: (`,表达式后插入 `) }` | 和 Node 的 `processTopLevelAwait` 处理最后一条语句的方式相同;外包一层对象,返回的 Promise 不会被 async 函数自动等待 | +| 前缀单独占第 0 行 | 编译时 `lineOffset: -1` | 模型代码第 N 行就报告为第 N 行 | +| 收尾另起一行 | `} })` | 模型代码最后一行可能以 `//` 注释结尾 | + +拷贝语句在本次没有声明这个名字、或者只用 `var` 重新声明它时生成;本次用 `let`、`const`、`class`、`function`(包括 `const`)声明了它,就没有这行,以本次的声明为准。生成时的关键字: + +| 情况 | 前缀里生成 | +|---|---| +| 本次没有声明,前面是 `let`、`const`、`function`、`class` | `let` | +| 本次没有声明,前面是 `var` | `var` | +| 本次只用 `var` 重新声明 | `var` | + +拷贝语句只负责把旧值带进来,写成 `const` 唯一的效果是禁止之后的调用赋值,所以前面的 `const` 也拷成 `let`:之后的调用可以直接给它赋值,改的只是拷贝;声明它的那次调用里它仍是 `const`。不判断这次调用是否真的赋值,所以不需要遍历语法树,也不打印警告。 + +只用 `var` 重新声明时也生成拷贝:同一个函数里重复的 `var` 声明是同一个变量,所以这次的 `var` 从旧值开始,没执行到的声明不会把旧值换成 `undefined`,和 node:repl 里全局 `var` 的行为一致。同一次里同名的 `function` 在函数开头就初始化,优先于 `var`,这时不生成拷贝。 + +编译与运行: + +```ts ignore-check +// Kernel: ScopedReplScopes.compile +const factory = new Script(source, { filename, lineOffset: -1, ...importOption }).runInContext(context) as ScopedReplFactory +const getters: (() => unknown)[] = [] +const program = factory(values, getters) +this.compiled = { bindings, getters, replaced } +return program + +// Evaluator: evaluate +const filename = resolve(baseDirectory, `.ptc-repl-${++submissions}.js`) // baseDirectory: process.cwd() at creation +const program = scopes.compile(code, { filename, context, finalExpression, ...importOption }) +const start = Reflect.apply.bind(undefined, program, undefined, []) as ScopedReplProgram +void programDomain.run(() => Promise.resolve().then(start)).then( + (completion) => { finish({ ok: true, value: completion?.value }) }, + (error: unknown) => { finish({ ok: false, error }) }, +) +``` + +- 内核编译时固定给出 `filename` 和 `lineOffset: -1`;求值器总是传 `importModuleDynamically`:有 import 处理器时用 `VmModuleImportLoader.forFile(filename)`,没有时用 `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`。 +- 程序由微任务直接调用,同步抛错时堆栈里没有求值器的帧。宿主用 `.then` 接结果、不用 `await`,否则 V8 会在堆栈末尾补一帧宿主的 async 帧。 +- 已实测:`this` 是 `undefined`,`arguments.length` 是 0,同步抛错的堆栈只有程序自己的帧;domain 能接住这样启动的程序里定时器抛出的错误;外包对象里的 Promise 原样返回,不被等待。 +- 代码里任何位置出现 `__$binding_`(包括字符串和注释),都报 `SyntaxError: Names starting with '__$binding_' are reserved`,位置指向第一次出现的地方,这次不执行。 + +### 内核:作用域链、acorn 扫描与编译 + +内核文件只依赖 acorn 和 `node:vm`,不依赖子进程和求值器,可以在普通 vm context 里连续编译、执行多段程序,单独测试作用域分层。接口: + +```ts ignore-check +class ScopedReplScopes { + constructor(options: { strict: boolean; onRedeclaration?: (redeclarations: readonly ScopedReplRedeclaration[]) => void }) + /** Scan and compile one program against the current bindings; throws SyntaxError and leaves the chain unchanged. */ + compile(code: string, options: { filename: string; context: Context; finalExpression: boolean; importModuleDynamically?: ScriptOptions['importModuleDynamically'] }): ScopedReplProgram +} +type ScopedReplProgram = () => Promise<{ value: unknown } | undefined> +interface ScopedReplRedeclaration { name: string; previous: ScopedReplBindingKind; current: ScopedReplBindingKind } +type ScopedReplBindingKind = 'var' | 'let' | 'const' | 'function' | 'class' +interface ScopedReplBinding { name: string; kind: ScopedReplBindingKind } +interface ScopedReplScan { + /** Top-level bindings declared by the program, in source order. */ + declarations: ReadonlyMap + /** Whether the program starts with a "use strict" directive. */ + useStrict: boolean + /** Last top-level statement when it is an expression statement. */ + finalExpression?: { statementStart: number; expressionStart: number; expressionEnd: number } +} +/** Parse once; throws a SyntaxError laid out like V8's for every error acorn reports. */ +function scanProgram(code: string, options: { filename: string }): ScopedReplScan +/** Build the Script source and every binding in the order of the read functions it pushes. */ +function buildProgramSource( + code: string, scan: ScopedReplScan, carried: readonly ScopedReplBinding[], options: { strict: boolean; finalExpression: boolean }, +): { source: string; bindings: ScopedReplBinding[] } +``` + +**解析方式**:不论 `strict` 开关,都调用 `parse(code, { ecmaVersion: 'latest', sourceType: 'script', allowAwaitOutsideFunction: true })`。这和 async 函数体的规则基本一致:顶层 `await` 合法,顶层 `return` 是语法错误,同一次里两个同名 `function`、同名的 `var` 和 `function` 都合法。不同的是顶层 `using`、`await using` 和静态 `import`、`export` 会被拒绝。扫描时不判断严格与否:开关打开时由 Script 开头的 `"use strict";` 决定,严格模式的语法违规由 V8 编译时报出。 + +解析之前先查两件事:程序以 `#!` 开头,或者代码里任何位置出现 `__$binding_`,就报错,不再解析。 + +**一次解析得到四样东西**: + +1. 本次的顶层声明,只看顶层语句: + + | 顶层语句 | 收集的名字 | 记录的关键字 | + |---|---|---| + | `const`、`let`、`var` 声明,含解构(对象、数组、默认值、剩余元素) | 每个绑定名 | 原关键字 | + | `function` 声明,含 async 和 generator | 函数名 | `function`;同一次里同名的 `var` 也记为 `function` | + | `class` 声明 | 类名 | `class` | + | `for (var …; …; …)`、`for (var … in/of …)` 括号里的 `var` | 每个绑定名 | `var` | + | 块、`try`/`catch`/`finally`、`if`/`else`、循环体、`switch`、标签语句、`with` 里的 `var`,包括其中 `for` 括号里的 `var`;不进入函数和类 | 每个绑定名 | `var` | + +2. 有没有顶层 `return`:acorn 直接报 `'return' outside of function`,并给出位置。 +3. 最后一条语句:从后往前跳过空语句 `;`,找到的第一条如果是表达式语句,记下语句和表达式的起止位置。 +4. 开头的指令里有没有 `"use strict"`:acorn 在指令语句上标出 `directive`,有就记下 `useStrict`。 + +不做的事:不进入嵌套的函数和类;块里只找 `var`,`let`、`const`、`class`、`function` 留在块里;不分析引用,不找赋值;除了最后一条表达式的三处插入,不改写代码。 + +**语法错误**:acorn 报错时直接抛 `SyntaxError`,不再交给 V8 编译。`stack` 按 V8 的样式排版: + +```text +/work/.ptc-repl-3.js:1 +const x = ; + ^ + +SyntaxError: Unexpected token +``` + +- 消息取 acorn 的原文,去掉末尾的 `(行:列)`。 +- 两处改用 V8 的说法:`'return' outside of function` 报 `Illegal return statement`;报错位置在代码末尾时报 `Unexpected end of input`。 +- 代码里出现 `__$binding_` 时,按同样的样式报错,位置指向第一次出现的地方。 + +### 作用域链状态与每次调用的步骤 + +`ScopedReplScopes` 持有: + +- `bindings: Map`:当前可拷贝的名字和它们的读取函数。`kind` 是名字最近一次声明用的关键字;只是被拷贝的名字沿用之前记下的关键字,例如 `function` 拷贝成 `let` 后仍记为 `function`。 +- `replaced: ReadonlyMap`:最近采用的那次程序重新声明的名字,在它编译时的旧值。 +- `compiled`:最近一次编译的程序的绑定顺序、读取函数数组和它的 `replaced`。 + +每次 `compile(code, options)`: + +1. 采用 `compiled`:读取函数数组的长度不少于名字个数,说明那次的前缀已经执行过,`bindings` 换成"第 i 个名字对应第 i 个读取函数",`replaced` 换成它的值。子进程不允许两次执行重叠(`overlapping PTC evaluation`),上一次的前缀总在下一次编译之前的微任务里执行完;只有在一段同步代码里连续编译两次时,前一次才会因前缀还没执行而不被采用。 +2. 扫描,得到本次声明和最后一条表达式的位置;语法错误直接抛出,状态不再变化。 +3. 逐个调用 `bindings` 里的读取函数取当前值。读取抛错(声明没初始化完)就用 `replaced` 里的值;两边都没有,就丢掉这个名字。 +4. 本次没声明、或只用 `var` 重新声明的名字作为拷贝,值放进 `values`;本次声明了的已有名字,把值记进新的 `replaced`,同时记一条重复声明 `{ name, previous, current }`。 +5. 拼源码,然后编译。`strict` 关闭且 `useStrict` 为 true 时,内层函数体最前面加 `"use strict";`。V8 编译失败时抛出原生的 `SyntaxError`,裁掉错误标题之后的编译器内部帧(和 `vm-script` 做法相同,代码单独写一份),状态不再变化。 +6. 有重复声明时调用 `onRedeclaration(redeclarations)`。 +7. 调用外层函数拿到程序,记下 `compiled`,返回程序。 + +求值器每次 `evaluate(code, finish)`: + +1. 提交序号加 1(包括有语法错误的提交),文件名是 `<创建时的目录>/.ptc-repl-<序号>.js`。 +2. 调用 `scopes.compile`;抛错就用这个错误结束本次执行。 +3. 在 domain 里由微任务启动程序;Promise 完成后调用 `finish`,结果取 `completion?.value`,不再等待。 + +读取发生在内核第 3 步,也就是新一次编译的时刻。之后前面的代码再给顶层变量赋值,改的只是它自己那次的变量。 + +### 失败的调用 + +| 第几次 | 代码 | 结果 | +|---|---|---| +| 1 | `const data = 1` | `data` 是 1 | +| 2 | `const data = await tools.fetch()`,`fetch` 抛错 | 失败;第 2 次的 `data` 声明了,但没赋上值 | +| 3 | `data` | 1:内核第 3 步读第 2 次的 `data` 时抛错,改用第 2 次编译时记下的旧值 | +| 4 | `let fresh = await tools.fetch()`,抛错 | 失败;`fresh` 是新名字 | +| 5 | `typeof fresh` | `"undefined"`:没有旧值,名字被丢掉 | + +- 抛错之前已经执行完的声明保留。例如先执行了 `let y = 5` 再抛错,之后的调用里 `y` 仍是 5。 +- `var` 重新声明从拷贝进来的旧值开始,读取不会抛错,也不需要退回:没执行到的 `var` 保留旧值。例如第 2 次在 `var v = 6` 之前就抛错,或者 `var config = await tools.loadConfig({})` 的工具调用失败,之后的调用读到的仍是之前的值。`function` 在函数开头就是新函数。 + +### 异步错误:对齐 REPL + +REPL 用 Node 的 `domain` 接住程序启动的异步工作里抛出的错误。求值器照同样的做法: + +- 创建求值器时调用 `domain.create()` 得到 `programDomain`,每个程序都在 `programDomain.run(...)` 里启动。程序创建的定时器、回调、Promise 后续步骤和 EventEmitter 都归属这个 domain。 +- `programDomain.on('error', ...)` 把错误写成 `Uncaught ` 加错误文本,交给 `options.reportError`。错误文本取错误的 `stack`,`stack` 不是字符串时用"名字: 消息";不用 `util.inspect` 格式化 Error,是因为 domain 会往错误对象上加 `domain`、`domainThrown`,inspect 会把它们一起打印出来。不是 Error 的值,先删掉这两个属性再用 `util.inspect`,和 node:repl 一样。 +- 程序能让转换文字这一步抛错(`stack` 访问器、`toString`、自定义 inspect)。监听器里抛错会让 Node 结束进程,所以这一步包在 `try`/`catch` 里,出错时报 `program threw an unrenderable value`,和同步失败时 `prepareException` 的兜底文字相同。`reportError` 放在 `try` 外面,它是子进程自己的代码,出错应该照常暴露。 +- 回调里 `throw` 冻结或不可扩展的对象时,Node 的 domain 在调用监听器之前给它加属性就失败了,进程结束,和 node:repl 相同。 +- 子进程处理 `reportError` 的方式不变:当时有执行在运行,就让那次执行以这个错误失败;否则丢弃。错误按创建回调时所属的执行归属(AsyncLocalStorage)。 +- 不在整个进程上注册 `uncaughtException` 或 `unhandledRejection`,子进程自身代码的错误仍然暴露。 +- 程序调用工具时,子进程为这次调用创建的异步回调(例如 RPC 回调)也在程序的 domain 里:子进程自身代码在这些回调里的异步错误会被当成程序的 `Uncaught …` 报告,子进程继续运行、不退出。现有 REPL 求值器也是这样。 + +已验证的情况: + +- REPL:定时器里抛错、未处理的 Promise rejection,在执行结束后和执行中都被接住;EventEmitter 的 `error` 事件在执行结束后被接住。 +- 单独的 domain:在主环境里接住了定时器抛错、定时器里产生的 rejection、未被等待的 async 函数失败和 EventEmitter 的 `error` 事件;在带默认 `codeGeneration` 限制的执行环境里,接住了定时器抛错和定时器里产生的 rejection;由微任务启动的程序里,定时器抛错同样被接住。 + +### 动态 import + +- 程序里的 `import()` 经过每个 Script 的 `importModuleDynamically`:没有 import 处理器时用 `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER`,有处理器时用现有的 `VmModuleImportLoader.forFile(filename)`,和 `vm-script` 相同。 +- 相对路径按求值器创建时的目录解析,也就是这个环境第一次调用时的 working directory;之后的调用换了目录也不变。node:repl 和 `vm-script` 跟随每次调用的目录;Agent 用 `working_directory` 换目录后,需要按新目录 import 时用绝对路径。 +- 不提供 `require`:node:repl 的 `require` 解析规则不一致(相对路径跟随当前目录,但第一次解析后被缓存;包名固定按启动目录),只保留动态 `import()` 这一种加载方式。 + +### 重复声明提示(预留) + +内核在第 6 步调用 `onRedeclaration`;求值器把自己的 `reportRedeclarations(redeclarations: readonly ScopedReplRedeclaration[])` 注入进去,函数体先留空,只加一行 `TODO` 注释,不输出任何内容。以后要提示时,在这里写入程序的 `console`,内容会进入模型可见的输出。 + +### 范围外 + +- 内存回收:不处理,每次拷贝全部名字。没有闭包存活的旧调用会被回收;某次调用留下了存活的函数时,这个函数会留住这次开始时拷贝进来的所有值。 +- 跟随 working directory 变化解析 `import()`:以后需要时另加显式操作,例如 `js_switch_cwd`。 +- `let`、`const`、`class` 重新声明的初始化表达式里读同名旧值(例如 `let count = count + 1`):属于代码问题。 +- `strict` 关闭时严格和宽松调用混用造成的问题,见"风险":交给以后的重置工具。 +- 最后一条表达式所在行的列号偏移。 + +### 接入 + +以 `scoped-repl` 格式接入时只做必需的改动,不顺手重构或复用现有代码,方便和其他进行中的 PTC 改动 rebase、合并。程序格式名是 `scoped-repl`,配置字段名是 `replScoped`。 + +| 位置 | 改动 | +|---|---| +| `ptc-runtime` 的 `PtcProgramFormat` | 包含 `'scoped-repl'` | +| `ptc-runtime-node` 的 `config.ts` | 布尔字段 `replScoped`,只能和 `persistent-in-memory` 一起用,否则加载时报错;省略时由 `resolveReplScoped` 取 `resolvePersistentExecution` 对函数体写入的 `persistent-in-memory` 取值(目前为 true),其他模式下为 false | +| `ptc-runtime-node` 的 `execution.ts` | `persistent-in-memory` 分支里 `replScoped` 为 true 时:格式 `scoped-repl`,`retainsState` 为 true,TypeScript 按 REPL 语句擦除,配一段新的模型说明 | +| `ptc-runtime-node` 的 `evaluators/index.ts` | 求值器表含 `scoped-repl`,三个开关取默认值 | +| `ptc-runtime-node` 的 `protocol.ts` | 协议版本是 3,旧 bootstrap 在就绪阶段报错;升级指南 `docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/` 同时说明 `PtcProgramFormat` 新增的成员 | +| workflow-ptc 的 `host.ts` | `scoped-repl` 用和 `repl` 一样的包装 `await (async () => {…})()` | +| `ptc-runtime-node` 的 `configuration.ts`(CUA 用它合并配置) | `resolvePersistentExecution` 返回 `executionMode`、`scriptPersistence`、`replScoped` 三个字段,一起合并:`script` 保持持久化的 VM Script,`replScoped: false`;`scoped-repl` 为 `replScoped: true`;函数体和 REPL 语句为 `persistent-in-memory` 加常量 `SCOPED_REPL_BY_DEFAULT`(目前为 true),覆盖 profile 里残留的值。这个常量同时决定 `config.ts` 里省略时的默认值,改它只改一行;`config.ts` 从 `configuration.ts` 导入这个函数,而 `configuration.ts` 本身也是包的发布入口;`configuration.ts` 只导入 `Config` 类型,所以打包不会生成共用的 chunk | +| 文档、快照和测试 | 包 README 的配置项、行为说明和"已知限制"、config catalog、快照场景 `ptc-scoped-repl`;构建产物的 e2e 含 `replScoped: true` 用例 | + +tool-executor-ptc 没有改动:格式不是 `function-body` 时,它自动使用"打印输出"那套说明。模型说明写明上面的精确行为,尤其是:输出用 `inspect(...)`,这句和其他模式共用;不支持顶层 `return`;每次调用开始时拷贝、旧代码不受影响;需要共享的可变状态放进对象;不声明直接赋值只改拷贝,前面的 `const` 也可以这样赋值;`let`、`const`、`class` 重新声明的初始化表达式读不到同名旧值,要在旧值上计算就直接赋值或换个名字;`var` 重新声明从旧值开始;调用中途失败时,没执行完的 `let`、`const`、`class`、`var` 重新声明保留旧值;块里的 `var` 也算这次调用的顶层名字,其他块里的声明只属于它的块;只能用 `import()`,相对路径按这个环境第一次调用的目录解析。测试整段逐字比对模型说明。 + +## 考虑过的替代方案 + +**用直接 eval 把每次调用嵌进上一次的作用域。** 前后调用能共享活的绑定,但旧作用域永远无法回收,行列号要靠 source map 或改写堆栈才能对上;在禁止从字符串生成代码的执行环境里,直接 eval 也不可用。 + +**把声明改写成 `var` 或全局赋值。** 所有调用共用同一个绑定,违反要求 2,而且要改写模型代码。 + +**每次调用编译成一个 ES 模块。** 靠合成一个代表上一次调用的模块和追加的 `export` 传值。模块里既不能 `return`,也没有末尾表达式的值,前置代码还会让报错行号整体偏移;函数参数已经能传值,不需要模块。 + +**作用域分析加改写引用。** 能做更精细的内存回收,但需要作用域分析并改写代码,违反要求 5。 + +**只用打印输出、不支持末尾表达式。** workflow-ptc 和 `repl` 格式的约定都依赖完成值,也偏离现有 REPL 的写法。 + +**用顶层 `return` 给出结果。** 与要求 3 冲突,需要换成函数体格式,run_code 的说明也会随之变化。 + +**末尾的 Promise 等它完成。** 和 `vm-script` 一致,但和现有 REPL 不一致;按 Node 的写法外包一层对象,保持 REPL 的行为。 + +**以 `if`、`for`、块结尾时也给出结果。** 只有在 Script 顶层执行时才有 V8 的完成值,函数体里拿不到;要支持就得改写更多语句。node:repl 在代码含 `await` 时同样没有结果。 + +**包装直接写成 `async function (__$binding_vals, __$binding_getters)`。** `this` 同样是 `undefined`,但程序的 `arguments` 里能看到这两个内部值,长度是 3。 + +**包装用 async 箭头函数。** `this` 是 `globalThis`、没有 `arguments`,和 REPL 一致;我们选择 strict 模式下不带接收者调用函数时的 `undefined`。 + +**用回调交出读取函数。** 前缀里要写名字字符串,还要防止程序重复调用;推入数组、由求值器按下标对应名字更简单。 + +**语法错误交给 V8 再编译一次。** 能拿到 V8 原文的消息,但要多编译一次;acorn 已经给出位置和消息,直接报。 + +**strict 开启时按 module 规则扫描。** module 规则比 async 函数体严:同一次里两个同名 `function`、同名的 `var` 和 `function`、嵌套的普通函数里把 `await` 当变量名都会被拒绝,HTML 注释的处理也和 V8 编译 Script 时不一致。strict 关闭时也用不了,因为 module 规则一律是 strict 的。 + +**套上和运行时一样的函数外壳再扫描。** 和运行时的语法完全一致,顶层 `using` 也能用,Node 的 `processTopLevelAwait` 就是这样做的。但要自己遍历语句查找顶层 `return`,换算外壳带来的位置偏移,还要防止代码里多出的 `}` 提前关闭外壳;我们不需要顶层 `using`,script 规则更简单。 + +**只把被赋值的 `const` 拷成 `let`,并打印警告。** 要遍历新调用的语法树并判断遮蔽,属于作用域分析,违反要求 5。我们一律拷成 `let`,不提示。 + +**`var` 重新声明不拷贝旧值,从 `undefined` 开始。** `var count = count + 1` 得到 `NaN`;但抛错前没执行到、或在没走到的分支里的 `var` 会把旧值换成 `undefined`,例如工具调用失败的 `var config = await tools.loadConfig({})` 让之后的调用拿不到原来的 `config`。拷贝旧值后,`var count = count + 1` 在旧值上加 1,和 node:repl 一致,暂时接受。 + +**只在调用失败、且读到 `undefined` 时退回旧值。** 不用拷贝,但分不出"没执行到"和"执行了、值就是 `undefined`":赋上 `undefined` 之后同一次又失败时,会误退回旧值;成功调用里没走到的分支和不带初始值的 `var x;` 也覆盖不到。 + +**在代码里插标记,记录 `var` 是否执行到。** 能准确区分,但要在声明处、声明前的赋值和循环头改写模型代码,违反要求 5。 + +**严格的调用里跳过严格模式保留字的拷贝。** 能避免宽松调用里声明的 `package` 这类名字让之后严格的调用编译失败;但这是模型混用两种模式造成的,不处理,交给以后的重置工具。 + +**在整个进程上监听未捕获的错误。** 会把子进程自身代码的错误一起吞掉;REPL 用 domain,只接程序启动的异步工作。 + +**不收集块里的 `var`。** 块里的 `var` 会和拷贝语句撞名,整段程序报 `already declared`,这个名字也带不到之后的调用;收集它只需约 15 行语句遍历,不分析引用,所以采用收集。 + +**堆栈里只显示 `.ptc-repl-<序号>.js`,不带目录。** 文件名去掉目录后,默认加载器按导入那一刻的 cwd 解析相对 `import()`,和有 import 处理器时不一致;用 `//# sourceURL` 只显示短名时,V8 不再应用 `lineOffset`,每个行号多 1;把 import 交给回调函数可以解决:子进程两种启动方式都带 `--experimental-vm-modules`,回调可以在第一次调用的目录下发起 `import()`;但这要求 scoped-repl 总是走回调形式的 import,默认路径现在没有走,所以文件名暂时保留第一次调用的目录。 + +**提供 `require`、`module` 和内置模块全局(node:repl 做法)。** node:repl 的 `require` 解析规则不一致,跟随目录又要定义何时换基准;只保留 `import()`。 + +## 影响 + +得到的: + +- 后面的调用可以用任意关键字再次声明前面的名字,前面的函数、闭包和仍在运行的代码继续使用原来的值。 +- 写法、结果、报错和异步错误处理与现有 REPL 一致,程序的异步错误不让进程退出。 +- 不做作用域分析;除了最后一条表达式的三处插入,不改写模型代码。 + +付出的: + +- "开始时拷贝"和 REPL 不同:前面的代码(定时器、回调)之后再给顶层变量赋值,后面的调用看不到;模型说明写明了这一点。 +- 不声明直接赋值只影响之后的调用,前面定义的函数看不到;REPL 里两边会一起变。 +- strict 模式和 REPL 不同:REPL 里给未声明的名字赋值会创建全局变量,这里会报错。 +- 调用方不丢弃完成值时,末尾是没写 `await` 的 Promise,宿主报"不是 JSON",和现有 REPL 一样;`run_code` 丢弃完成值,不受影响。 +- 以 `if`、`for`、块结尾的程序没有结果,node:repl 在代码不含 `await` 时有。 +- 最后一条表达式所在行,插入点之后的列号右移 17。 +- 语法错误消息是 acorn 的文字,和 V8 原文不同,例如 `Unexpected token` 而不是 `Unexpected token ';'`。 +- 扫描统一按 script 规则:顶层 `using`、`await using` 会被拒绝,node:repl 也不支持。 +- 顶层 `arguments` 是一个空的 arguments 对象,node:repl 里它不存在。 +- 执行环境默认禁止从字符串生成代码:依赖 `eval` 或 `new Function` 的代码会失败,包括经 import 处理器加载到这个执行环境的库。这个限制不构成隔离,复制进来的主环境函数(例如 `setTimeout.constructor`)仍能生成代码。 +- 不提供 `require`:依赖 `require` 的代码要改用 `await import()`。 +- 相对路径的 `import()` 固定按这个环境第一次调用时的目录解析,Agent 换目录后仍按旧目录。 +- Node 文档把 `domain` 标为已弃用;node:repl 仍建立在它上面,如果 Node 移除它,REPL 也会一起变。 +- 子进程自身代码在工具调用的异步回调里出错时,会被当成程序的 `Uncaught …` 报告,子进程继续运行,和现有 REPL 相同。 +- 以 `#!` 开头的程序被拒绝。 +- 代码里任何位置出现 `__$binding_`(包括字符串、注释)都会被拒绝;用 `\u005f` 这类转义写出的内部名不在检查范围内。 +- acorn 必须跟上 V8 支持的语法,否则较新的语法会被拒绝执行。 +- `var` 重新声明从旧值开始:`var count = count + 1` 在旧值上加 1,和 node:repl 一致;即使前面是 `let`、`const` 也是这样,node:repl 在这种情况下报 `already declared`。 +- `let`、`const`、`class` 重新声明的初始化表达式读不到同名旧值,会报错,例如 `let count = count + 1`。属于代码问题,不处理。 +- 前面的 `const` 在之后的调用里一律拷成 `let`,可以被赋值,而且没有提示。 +- `strict` 关闭时,严格和宽松的调用可以混用:宽松调用里给未声明的名字赋值,会创建所有调用和旧函数共用的全局变量;宽松调用里用严格模式保留字(`package`、`public`、`private`、`protected`、`interface`、`implements`、`static`、`let`、`yield`、`eval`、`arguments`)声明的名字,会让之后严格的调用编译失败。不处理,交给以后的重置工具。 +- 回调里 `throw` 冻结或不可扩展的对象时,Node 的 domain 处理本身出错,进程结束,保留的变量丢失,和 node:repl 相同。 +- 每次调用都要为前面所有名字生成拷贝声明和读取函数:原型实测 1000 个名字时约 10 ms/次。 +- 某次调用留下存活的函数时,这次拷贝进来的所有值都会一直留在内存里。 + +## 测试 + +- 内核测试单独运行即可通过,覆盖:script 规则解析和开头 `"use strict"` 的检测、声明表里的每种语句、顶层 `return`(包括块里的)、最后一条表达式的定位与插入、以 `#!` 开头的程序、代码里出现 `__$binding_`、语法错误的排版和两处消息替换、拼出的源码;`strict` 关闭时,程序开头的 `"use strict"` 在有拷贝和没有拷贝时都生效;并在普通 vm context 里连续执行多段程序,覆盖"跨次调用"里的每一条,包括各种关键字组合、失败的调用、定时器、函数重定义和重复声明通知。 +- 求值器测试直接使用求值器和真实的 vm 执行环境,覆盖"写法与结果""执行环境""报错""异步错误与生命周期"里的每一条,以及经求值器的跨次调用;包括经全局对象的原型链拿不到主环境的 `Function`、复制进来的主环境函数(例如 `setTimeout.constructor`)仍能生成代码,以及宿主以 `module`、`require` 为名的绑定原样保留。 +- 三个开关各自在打开和关闭时都有测试。 +- 顶层 `this` 是 `undefined`、`arguments.length` 是 0,同步抛错的堆栈只有程序自己的帧。 +- 异步错误:上面列出的每种情况在执行结束后和执行中各测一次,交给 `reportError` 的文本以 `Uncaught ` 开头;进程不退出,变量保留。`stack` 为空、读取 `stack` 抛错、自定义 inspect 抛错时,分别报"名字: 消息"和固定文本,进程不退出;抛出普通对象时报错里没有 `domainThrown`。 +- import:默认加载器和 import 处理器两条路径,相对路径按创建时的目录解析,之后换了目录也不变。 +- 构建产物的 e2e 覆盖 `replScoped: true`。 +- 挂载 `persistent-in-memory` 的测试都显式写 `replScoped`,保留执行的测试两种取值都跑;只有一个测试检查省略时的默认值。 +- 新文件覆盖率 100%;现有求值器及其测试不变。 diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml index 43557a7492..4004147bbf 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml @@ -9,8 +9,8 @@ en: 4b312be894531bee zh: d655648ea5843ef5 /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision: - en: a1732e2b1b46cb39 - zh: ddfc2bdcffa099a5 + en: 109e418dd92ead24 + zh: e2564f0f98cc4641 /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/per-program-execution-controls: en: da694641e1d009de zh: 9d7492d39039af66 @@ -18,23 +18,23 @@ en: 4cd76a34f4712e1a zh: 303ef72a18644d7c /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-run-code-tool-and-the-dispatch-bridge: - en: c3d079330748cd24 - zh: 4e2cc41d00227780 + en: 69e4683ac3150bdf + zh: d8eaa12eaba6d67e /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/observability-tool-ptc-dispatch: - en: 5423da23d4e8d1d9 - zh: f1198d4f224f3fe6 + en: 951fb03a27841eea + zh: 38928d1ca859eced /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-ptc-runtime-seam: en: 4c423f4e9cef6055 zh: 5c23a3637eb420c0 /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/the-node-process-runtime: - en: 0b846ed33977e383 - zh: e45158758d657f9a + en: b2a8d7d654d1832b + zh: 5852a2a3660e5a2e /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/trust-posture: en: d62b41a6a5c58e5f zh: ef72c5a9b32b370e /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/decision/what-the-model-sees: - en: 81c12f19f7a967c1 - zh: 29734ca964acdec2 + en: 109d4c326bfcf572 + zh: 9f6be5afc281054d /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/consequences: en: 761eb6c1aeb7af18 zh: 5434456a3d0a1b65 diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.md b/.agents/notes/implemented/feature/2026-06-15-ptc.md index 8e12a2db3e..10ba6572f2 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.md @@ -22,7 +22,7 @@ Three decisions, each elaborated in its own section below: 2. **Code execution is a capability seam** — `packages/ptc-runtime/` contains the Service Definition package `@deepseek-ai/dsh-ptc-runtime`, which owns `ctx.ptcRuntime` ([capability seams](../architecture/2026-06-13-capability-seams.md); Consumer = `dsh-tools`, with core-consumes-a-seam precedent in `agent-loop` → `dsh-llm`). The runtime knows nothing about tools: it is handed a program and named async bindings, runs the program, and reports `{ value, logs, error? }`. Language and substrate are backend properties, so a future Python or container backend is another Service Provider package, not a redesign. 3. **The shipped implementation is `@deepseek-ai/dsh-ptc-runtime-node`**: each program runs in a fresh managed Node process under the calling Session's resolved sandbox policy. Direct Node APIs remain available within that policy; named host bindings cross a separately validated control channel. -This note owns PTC presentation, composition and settlement. The [typed tool-return decision](2026-07-20-ptc-typed-tool-returns.md) owns generated outputs, canonical binding values, `ToolCallError` and lossless outer output. The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-ptc-runtime.md) supersedes the worker execution, trust posture and budget realization while preserving this note's consumer rules. +This note owns PTC presentation, composition and settlement. The [typed tool-return decision](2026-07-20-ptc-typed-tool-returns.md) owns generated outputs, ordinary canonical binding values, `ToolCallError` and lossless runtime output. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript completion suppression and text/image selection. The [sandboxed Node decision](../architecture/2026-09-11-sandboxed-node-ptc-runtime.md) supersedes the worker execution, trust posture and budget realization while preserving this note's consumer rules. ### Per-program execution controls @@ -48,9 +48,9 @@ The [Node execution decision](../architecture/2026-09-11-sandboxed-node-ptc-runt Under `'ptc'` the registry owns `run_code` as a reserved presentation transport with two required parameters, `{ code: string; description: string }` (the description labels the call in UIs, the bash precedent). It is represented by a normal `ToolDefinition` for dispatch but stays outside the filterable capability layers, so restrictions cannot accidentally remove PTC mode's only entry point. Calls traverse the complete tool pipeline — `tools/pre-execute` → monotonic guards → `tools/execute` around dispatch → `tools/post-execute` → optional definition-owned `finalizeContent` → immutable `tools/result` notification — exactly like native calls; a permission plugin can inspect the program text before it runs, and final-result observers see the normalized outer outcome. Its `execute(args, exec)`: -1. **Build bindings.** One run-scoped signal follows outer cancellation and is aborted whenever the run settles. Each visible tool binding snapshots lossless-JSON arguments, enters the native-contract dispatch pool (the [live-parallel reference](../../../../packages/core/tools/README.md) owns the scheduling design), executes with a deterministic call id and the outer token as `parent`, defers returned contexts through the outer execution, and logs the `tool/ptc-dispatch-start`/`tool/ptc-dispatch` pair, the settle side carrying the full rendered result content. Success returns the tool's final canonical JSON value; failure becomes the program-visible `ToolCallError`. Every sub-call retains its own immutable execution identity and traverses the full tool pipeline. +1. **Build bindings.** One run-scoped signal follows outer cancellation and is aborted whenever the run settles. Each visible tool binding snapshots lossless-JSON arguments, enters the native-contract dispatch pool (the [live-parallel reference](../../../../packages/core/tools/README.md) owns the scheduling design), executes with a deterministic call id and the outer token as `parent`, defers returned contexts through the outer execution, and logs the `tool/ptc-dispatch-start`/`tool/ptc-dispatch` pair, the settle side carrying the full rendered result content. Success returns the consumer-facing value, including program Images for the selected TypeScript bindings; failure becomes the program-visible `ToolCallError`. Every sub-call retains its own immutable execution identity and traverses the full tool pipeline. 2. **Runs resolved inputs:** `ctx.ptcRuntime.run(ctx.ptcRuntime.resolve(request))`. The request carries the program, bindings, run-scoped signal, calling Session cwd and applicable resolved file policy. The run-scoped signal connects outer settlement to execution cancellation. -3. **Settle after quiescence.** When the runtime settles, the bridge aborts outstanding work and drains the dispatch queue before returning. Success returns captured logs and the completion value as canonical output; the registry renders that value into durable `tool/result.content`, which the result card reads directly. A runtime failure becomes `CodeRunFailedError`; backend rejection uses the registry's normal error boundary. Both produce structured error results, and no sub-call can append after `run_code` settles. +3. **Settle after quiescence.** When the runtime settles, the bridge aborts outstanding work and drains the dispatch queue before returning. TypeScript success returns captured logs as canonical output and projects inspected images into durable `tool/result.content`; other language consumers also render their completion value. The result card reads that content directly. A runtime failure becomes `CodeRunFailedError`; backend rejection uses the registry's normal error boundary. Both produce structured error results, and no sub-call can append after `run_code` settles. **Sub-call contexts are deferred through the parent.** Injecting inside `run_code` would break parent call/result adjacency, so `ToolRunContext.deferContext()` collects every sub-result `additionalContexts` entry in dispatch order. The registry carries that array even when the program later throws, and the loop appends each entry only after the outer result and every sibling result in the step. An outer post-execute block discards tool-deferred entries and exposes only contexts explicitly attached by the blocking decision. @@ -58,13 +58,13 @@ Under `'ptc'` the registry owns `run_code` as a reserved presentation transport **Tool-call allowance.** Counting attempts before validation and queuing bounds loops that repeatedly fail or enqueue work. The allowance scales with the resolved timeout and permits bursts; it does not enforce a rolling window. Exhaustion uses the run-scoped abort path so a program cannot catch a binding failure and keep running. Active calls are canceled, queued calls are abandoned, and settlement waits for cleanup. Completed effects remain; a new run receives a fresh allowance. The [executor README](../../../../packages/core/tool-executor-ptc/README.md#use-this-package) owns configuration and failure reporting. -**Presentation.** `run_code`'s render intent is decided here per the [render-intent Agent Note](../architecture/2026-07-02-tool-render-intent-union.md): `presentCall` creates a `generic` card with `kind: 'execute'`, the program text as its title, and the same program text as `rawInput`; `run_code` intentionally declares no `presentResult`, so the TUI and host/client runtime (Web) complete that card through their generic raw-content fallback using the final durable `tool/result.content`, including captured logs plus the returned value, failure, or post-policy spill preview. This is not a `terminal` card: that card's semantics are "a shell command in a working directory", which a program is not. See the [result-card completeness note](../../archived/bug-fix/2026-07-20-code-mode-result-card-completeness.md). +**Presentation.** `run_code` uses a `generic` card with `kind: 'execute'`, the model-authored description as its title and the submitted program as `rawInput`. UI adapters read durable `tool/result.content` for captured text, selected images, failure or the post-policy spill preview. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns selection of that content. ### Observability: `tool/ptc-dispatch` Each sub-dispatch appends a log-only `tool/ptc-dispatch-start` event at pool entry and a `tool/ptc-dispatch` settle event containing parent and child call ids, tool identity, normalized arguments, and the complete rendered `content`/`isError` outcome. It remains outside model history but available to persistence and UIs. Appends occur inside the open `run_code` turn. Direct executions without an agent still run but cannot log the event. -New sub-calls use `:ptc:` ids, numbered by tool-call attempt. Invalid arguments consume a number without a dispatch event, so logged ids may have gaps. All call ids are opaque to consumers: migration preserves every historical id byte-for-byte, including `:code:` substrings, so dispatch pairs, spill references, and other correlations remain intact. The bridge attributes forwarded image context to `{ kind: 'plugin', plugin: 'tools-ptc' }`. +New sub-calls use `:ptc:` ids, numbered by tool-call attempt. Invalid arguments consume a number without a dispatch event, so logged ids may have gaps. All call ids are opaque to consumers: migration preserves every historical id byte-for-byte, including `:code:` substrings, so dispatch pairs, spill references, and other correlations remain intact. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript image presentation; other language consumers attribute forwarded image contexts to `{ kind: 'ptc-mode' }`. The [V2-to-V3 PTC specification](../../../../packages/session/session-format-v2-to-v3/README.md#ptc-vocabulary) owns exact historical tag and attribution conversion; [native V3 admission](../../../../packages/session/session-format-v2-to-v3/README.md#native-v3-admission) owns predecessor-tag refusal. These are not runtime aliases: an opaque extension must not acquire PTC lifecycle meaning merely through a version change. @@ -78,7 +78,7 @@ Program outcomes resolve as result fields; caller misuse may reject. Lossless bi ### The Node process runtime -The Node provider strips erasable TypeScript, resolves its executable/bootstrap in the configured filesystem/subprocess world, and launches through the shared sandbox and managed process owners. Each child has an empty model environment and fresh program globals. Typed rejection constructors and the capturing console remain program-visible. +The Node provider strips erasable TypeScript, resolves its executable/bootstrap in the configured filesystem/subprocess world, and launches through the shared sandbox and managed process owners. Each child has an empty model environment and fresh program globals. Typed rejection constructors and `inspect` are program-visible; optional console support shares the inspection function. Binding traffic uses a dedicated control channel separate from stdout/stderr. The host validates frames, call identities and allowed bindings before dispatch. Output, pending calls and channel buffers have configured limits; completion, deadline, cancellation and protocol failure terminate and await the managed range. The provider README and sandboxed Node decision own exact bounds and platform limits. @@ -88,7 +88,7 @@ The selected OS backend constrains direct Node effects under the same policy use ### What the model sees -The SDK instructs the model to write an async body in the loaded runtime's language (an erasable-TypeScript body by default; a Python `async` body under a Python runtime — see the [language-dispatch note](../../archived/feature/2026-07-31-ptc-language-dispatch.md)), call tools through `await tools.name(args)`, catch rejected tool calls when needed, and return or log only the output that should re-enter context. Both flavors state the same contract in their own primitive: independent read-only calls MAY overlap under `Promise.all` (TypeScript) or `asyncio.gather` (Python), mutating calls run alone in submission order, and dependent work sequences with `await`. The declaration prefix can be as large as native schemas, but remains stable for provider caching. +The SDK declares the loaded runtime's source format and visible tool bindings, instructs the model to call tools through `await tools.name(args)` and catch rejected tool calls when needed, and presents language-specific output instructions. TypeScript selects output through `inspect`; the Python flavor retains return and print output. Independent read-only calls may overlap under `Promise.all` or `asyncio.gather`, mutating calls run alone in submission order, and dependent work sequences with `await`. The declaration prefix can be as large as native schemas, but remains stable for provider caching. The transport's own `description` and both SDK instruction flavors open by naming `code` and `description` as the call's two required arguments. Prose that describes the call as passing a program leaves the second argument discoverable only through the parameter schema, and a model that emits `{code}` alone loses the whole written program to an `INVALID_ARGS` rejection. diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md index 813a795888..d3befc7ddf 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md @@ -22,7 +22,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 2. **代码执行是一个能力 seam**——`packages/ptc-runtime/` 包含 Service Definition 包 `@deepseek-ai/dsh-ptc-runtime`,拥有 `ctx.ptcRuntime`([能力 seam](../architecture/2026-06-13-capability-seams.zh.md);消费方 = `dsh-tools`,core 消费 seam 的先例见 `agent-loop` → `dsh-llm`)。运行时对工具一无所知:它接收一段程序和命名的异步绑定,执行程序,报告 `{ value, logs, error? }`。语言和基底是后端属性,因此未来的 Python 或容器后端只是另一个 Service Provider 包,而非重新设计。 3. **交付的实现是 `@deepseek-ai/dsh-ptc-runtime-node`**:每个程序在全新的受管 Node 进程中,按调用 Session 的已解析沙箱策略运行。直接 Node API 在该策略内仍可使用;具名 Host 绑定通过单独验证的控制通道调用。 -本说明负责 PTC 呈现、组合与结算。[类型化工具返回决策](2026-07-20-ptc-typed-tool-returns.zh.md)负责生成输出、规范绑定值、`ToolCallError` 与无损外层输出。[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md)取代 worker 执行、信任姿态与预算实现,同时保留本说明的消费方规则。 +本说明负责 PTC 呈现、组合与结算。[类型化工具返回决策](2026-07-20-ptc-typed-tool-returns.zh.md)负责生成输出、普通规范绑定值、`ToolCallError` 与无损运行时输出。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript 完成值抑制及文本/图片选择。[沙箱 Node 决策](../architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md)取代 worker 执行、信任姿态与预算实现,同时保留本说明的消费方规则。 ### 每段程序的执行控制 @@ -48,9 +48,9 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 在 `'ptc'` 下,注册表拥有 `run_code` 作为保留的呈现传输通道,带两个必需参数 `{ code: string; description: string }`(description 为 UI 标注该调用,沿用 bash 的先例)。它由一个正常的 `ToolDefinition` 表示以供分发,但位于可过滤的能力层之外,因此限制规则不会意外移除 PTC mode 的唯一入口。调用遍历完整的工具流水线——`tools/pre-execute` → 单调性守卫 → `tools/execute` 包裹分发 → `tools/post-execute` → 由定义拥有的可选 `finalizeContent` → 不可变的 `tools/result` 通知——与原生调用完全一致;权限插件可以在程序运行前检查程序文本,最终结果观察者看到的是规范化的外层结果。其 `execute(args, exec)`: -1. **构建绑定。** 一个 run 级别的 signal 跟随外层取消,并在 run 结算时被 abort。每个可见工具绑定都会对无损 JSON 参数创建快照,进入原生约定的分发池(调度设计由[实时并行 参考](../../../../packages/core/tools/README.zh.md) 负责),以确定性的 call id 和外层 token 作为 `parent` 执行,通过外层 execution 延后返回的上下文,并记录 `tool/ptc-dispatch-start`/`tool/ptc-dispatch` 事件对,其中结算侧携带完整渲染后的结果内容。成功时返回工具最终的规范 JSON 值;失败则变为程序可见的 `ToolCallError`。每个子调用保留自己不可变的执行标识,并遍历完整的工具流水线。 +1. **构建绑定。** 一个 run 级别的 signal 跟随外层取消,并在 run 结算时被 abort。每个可见工具绑定都会对无损 JSON 参数创建快照,进入原生约定的分发池(调度设计由[实时并行 参考](../../../../packages/core/tools/README.zh.md) 负责),以确定性的 call id 和外层 token 作为 `parent` 执行,通过外层 execution 延后返回的上下文,并记录 `tool/ptc-dispatch-start`/`tool/ptc-dispatch` 事件对,其中结算侧携带完整渲染后的结果内容。成功时返回面向消费方的值,包括指定 TypeScript 绑定的程序 Image;失败则变为程序可见的 `ToolCallError`。每个子调用保留自己不可变的执行标识,并遍历完整的工具流水线。 2. **运行已解析输入:** `ctx.ptcRuntime.run(ctx.ptcRuntime.resolve(request))`。请求携带程序、绑定、运行级信号、调用 Session 的 cwd 与适用的已解析文件策略。运行级信号将外层结算与执行取消关联。 -3. **完全停稳后结算。** 运行时结算后,桥 abort 未完成的工作并排空分发队列后再返回。成功时返回捕获的日志和完成值,将其作为规范输出;注册表再把该值渲染为持久化的 `tool/result.content`,供结果卡片直接读取。运行时失败变为 `CodeRunFailedError`;后端拒绝使用注册表的正常错误边界。两者都产生结构化的错误结果,且 `run_code` 结算后不允许子调用追加。 +3. **完全停稳后结算。** 运行时结算后,桥接层 abort 未完成的工作并排空分发队列后再返回。TypeScript 成功结果将捕获日志作为规范输出,并将显式展示的图片投影到持久化的 `tool/result.content`;其他语言消费方还会渲染完成值。结果卡片直接读取该内容。运行时失败变为 `CodeRunFailedError`;后端拒绝使用注册表的正常错误边界。两者都产生结构化的错误结果,且 `run_code` 结算后不允许子调用追加。 **子调用上下文通过父调用延后。** 在 `run_code` 内部注入会破坏父调用/结果的相邻性,因此 `ToolRunContext.deferContext()` 按分发顺序收集每个子结果的 `additionalContexts` 条目。即使程序后来抛出异常,注册表仍携带该数组;循环只在外层结果与步骤中所有兄弟结果之后追加每个条目。外层 post-execute 阻止会丢弃工具延后的条目,只暴露阻止 decision 显式附加的上下文。 @@ -58,13 +58,13 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 **工具调用额度。** 在验证和排队之前对尝试计数,可以限制重复失败或持续入队的循环。额度随最终超时时间缩放,允许集中调用,不实施滑动窗口限制。额度耗尽时使用运行级取消路径,使程序无法捕获绑定错误后继续运行。活动调用被取消,排队调用被放弃,结算会等待清理完成。已完成的操作仍然生效;新运行获得完整额度。[执行器 README](../../../../packages/core/tool-executor-ptc/README.zh.md#use-this-package) 负责配置与失败报告。 -**呈现。** `run_code` 的 render intent 按[呈现意图 Agent Note](../architecture/2026-07-02-tool-render-intent-union.zh.md)在此决定:`presentCall` 创建一个 `generic` 卡片,`kind: 'execute'`,以程序文本作为标题,并将同一程序文本作为 `rawInput`;`run_code` 有意不声明 `presentResult`,因此 TUI 和宿主/客户端运行时(Web)会通过通用原始内容回退机制,使用最终持久化的 `tool/result.content` 补全该卡片,其中包括捕获的日志,以及返回值、失败信息或 post-policy spill 预览。这不是 `terminal` 卡片:该卡片的语义是「工作目录中的 shell 命令」,程序不是。参见[结果卡片完整性说明](../../archived/bug-fix/2026-07-20-code-mode-result-card-completeness.md)。 +**呈现。** `run_code` 使用 `kind: 'execute'` 的 `generic` 卡片,标题为模型填写的描述,`rawInput` 为提交的程序。UI 适配器读取持久化的 `tool/result.content`,展示捕获文本、所选图片、失败或 post-policy spill 预览。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责这些内容的选择。 ### 可观测性:`tool/ptc-dispatch` 每次子分发在进入分发池时追加一个仅日志的 `tool/ptc-dispatch-start` 事件,并以一个 `tool/ptc-dispatch` 结算事件收尾,后者包含父子 call id、工具标识、规范化参数以及完整渲染后的 `content`/`isError` 结果。它不进入模型历史,但可供持久化和 UI 使用。追加发生在开放的 `run_code` 轮次内。没有 agent 的直接执行仍然运行,但无法记录该事件。 -新子调用使用 `:ptc:` 标识,按工具调用尝试编号。无效参数会占用编号而不产生分发事件,因此日志中的编号可能有空缺。消费者将所有 call id 视为不透明值:迁移逐字节保留每个历史标识,包括 `:code:` 子串,因此分发事件对、spill 引用及其他关联保持完整。桥接层将转发图片上下文的来源标记为 `{ kind: 'plugin', plugin: 'tools-ptc' }`。 +新子调用使用 `:ptc:` id,按工具调用尝试编号。无效参数在没有分发事件时仍消耗编号,因此日志中的 id 可能有空缺。所有调用 id 对消费方均不透明:迁移逐字节保留每个历史 id,包括 `:code:` 子串,使分发事件对、spill 引用和其他关联保持完整。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript 图片呈现;其他语言消费方将转发的图片上下文归属为 `{ kind: 'ptc-mode' }`。 [V2 到 V3 PTC 规范](../../../../packages/session/session-format-v2-to-v3/README.zh.md#ptc-vocabulary)负责精确的历史标签与归属转换;[原生 V3 准入](../../../../packages/session/session-format-v2-to-v3/README.zh.md#native-v3-admission)负责前代标签拒绝。这些不是运行时别名:不透明扩展不能仅因版本变化就获得 PTC 生命周期含义。 @@ -78,7 +78,7 @@ Cloudflare 的 [Code Mode](https://blog.cloudflare.com/code-mode/) 提出了一 ### Node 进程运行时 -Node 提供方擦除可擦除 TypeScript,在配置的文件系统/子进程世界中解析可执行文件与 bootstrap,并通过共享沙箱与受管进程所有者启动。每个子进程都有空模型环境和全新程序全局对象。类型化拒绝构造器与捕获 console 仍对程序可见。 +Node 提供方擦除可擦除 TypeScript,在配置的文件系统/子进程世界中解析可执行文件与 bootstrap,并通过共享沙箱与受管进程所有者启动。每个子进程都有空模型环境和全新程序全局对象。类型化拒绝构造器与 `inspect` 对程序可见;可选 console 支持复用展示函数。 绑定通信使用与 stdout/stderr 分开的专用控制通道。Host 在分派前验证帧、调用身份与允许的绑定。输出、待处理调用与通道缓冲有配置上限;完成、截止、取消和协议失败会终止并等待受管范围。提供方 README 与沙箱 Node 决策负责确切上限和平台限制。 @@ -88,7 +88,7 @@ Node 提供方擦除可擦除 TypeScript,在配置的文件系统/子进程 ### 模型看到的内容 -SDK 指示模型编写一个所加载运行时语言的异步函数体(默认可擦除 TypeScript;Python 运行时下为 Python `async` 函数体——见[语言分发 note](../../archived/feature/2026-07-31-ptc-language-dispatch.md)),通过 `await tools.name(args)` 调用工具,在需要时捕获被拒绝的工具调用,并仅 return 或 log 应重新进入上下文的输出。两种 flavor 用各自的原语陈述同一约定:相互独立的只读调用可以(MAY)在 `Promise.all`(TypeScript)或 `asyncio.gather`(Python)下重叠,有副作用的调用按提交顺序单独运行,有依赖的工作用 `await` 排序。声明前缀可能与原生 schema 一样大,但对提供方缓存保持稳定。 +SDK 声明所加载运行时的源码格式和可见工具绑定,指示模型通过 `await tools.name(args)` 调用工具、在需要时捕获被拒绝的工具调用,并提供各语言的输出说明。TypeScript 通过 `inspect` 选择输出;Python flavor 保留 return 和 print 输出。相互独立的只读调用可通过 `Promise.all` 或 `asyncio.gather` 重叠,有副作用的调用按提交顺序单独运行,有依赖的工作用 `await` 排序。声明前缀可能与原生 schema 一样大,但对提供方缓存保持稳定。 传输自身的 `description` 与两种 flavor 的 SDK 说明都以点名 `code` 和 `description` 这两个必填参数开头。把该调用描述成「传入一个程序」的散文会让第二个参数只能从参数 schema 中发现,而只发出 `{code}` 的模型会因 `INVALID_ARGS` 被拒,连同已写好的整个程序一起丢失。 diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml index 5f8169b4c4..ef54355720 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.i18n.yaml @@ -9,32 +9,32 @@ en: e2403bc358c4e14b zh: dd37923097a3b24c /agent-note-typed-tool-returns-in-ptc-mode/decision: - en: 2218fac13ef57c77 - zh: d4a18daa9debc77c + en: 6dd62ee16c69536c + zh: aec9fa1c74be28e5 /agent-note-typed-tool-returns-in-ptc-mode/decision/generated-sdk: en: 30583e9ac6715952 zh: 3a85c9482abf574c /agent-note-typed-tool-returns-in-ptc-mode/decision/binding-values-and-failures: - en: ecb95cafa2dc1297 - zh: ccdf300ca936ca12 + en: 8b10f08e67ca9323 + zh: e57adb520049f407 /agent-note-typed-tool-returns-in-ptc-mode/decision/outer-result-and-output-ledger: - en: d907d0a8205157e1 - zh: 1ed99168266a7ca4 + en: d57456d76fed9c6d + zh: 453775faad48588c /agent-note-typed-tool-returns-in-ptc-mode/decision/typed-handles-and-lifetime: en: b2b9318c2812e3a4 zh: 73cf34bfd487e2f1 /agent-note-typed-tool-returns-in-ptc-mode/decision/persistence-metadata-and-spill: - en: c388619f862a92ba - zh: d557eae40c7b6b7a + en: 2c3ad4ec376ed2d5 + zh: 49e8206a4c17b1b3 /agent-note-typed-tool-returns-in-ptc-mode/testing: - en: 728513c779f031f8 - zh: f6d869f18add7242 + en: 81a4355914c918cf + zh: 36aa414cd382ff9c /agent-note-typed-tool-returns-in-ptc-mode/alternatives-considered: - en: dedd87b9b35d8fab - zh: 78db4c7e8c4e5f61 + en: 069a1e170c7d1dfb + zh: 14ce5a56e602595c /agent-note-typed-tool-returns-in-ptc-mode/consequences: en: f5726b5e7a2fc73f zh: 0b9aa884db5d920f /agent-note-typed-tool-returns-in-ptc-mode/known-limitations-and-deferred-work: - en: a42af629ad6872cc - zh: 41e5c0bb3de0ae4d + en: 19828c2e5796df2d + zh: 2ef63df81fca7a72 diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md index 032322407d..08a94ce5b7 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.md @@ -14,7 +14,7 @@ The [canonical tool-output contract](../../../../packages/core/tools/README.md) ## Decision -PTC mode is a typed projection of the visible tool registry. Each successful binding resolves to the final canonical `JsonValue` after post-execute policy, while a failed binding rejects with a real `ToolCallError`. Intermediate values remain inside the run and cross the worker boundary whole. The outer `run_code` logs, completion value, or failure diagnostic enter the configurable output ledger and model-facing spill pipeline; a successfully settled sub-call whose final Native content contains an image additionally defers that complete ordered content through the parent result as logged, source-attributed context. +PTC mode is a typed projection of the visible tool registry. Ordinary successful bindings resolve to the final canonical `JsonValue` after post-execute policy, while failed bindings reject with a real `ToolCallError`. Intermediate values remain inside the run and cross the process boundary whole. The [explicit output decision](../architecture/2026-11-09-explicit-ptc-output.md) owns TypeScript Image bindings, completion suppression and selection of visible text and images. Other language consumers retain completion rendering and deferred image-bearing content. This note owns the return and failure contract layered on the original [PTC mode foundation](2026-06-15-ptc.md). The unified schema vocabulary is owned by the [JSON-value schema DSL reference](../../../../packages/core/tools/README.md), and Native rendering and policy projection remain owned by the canonical-output note. @@ -49,15 +49,15 @@ declare const tools: { ### Binding values and failures -Before dispatch the bridge snapshots binding arguments as lossless JSON and snapshots the detached value again for an independent durable summary event. Host-side detachment, immutable execution, and output-schema projection all use iterative traversals rather than nested structured clone or recursive freezing. `undefined`, non-finite numbers, `-0`, sparse arrays, cycles, functions, and exotic objects reject that call before the tool runs. Successful dispatch returns `ToolExecutionResult.value`; Native `content`, metadata, and internal error information do not cross to the program. Image-bearing final content is not a second binding value: the bridge ferries it after the outer result so the next model request can see the durable image, while post-execute block/content replacement remains authoritative and text-only results are not duplicated. +Before dispatch the bridge snapshots binding arguments as lossless JSON and snapshots the detached value again for an independent durable summary event. Host-side detachment, immutable execution, and output-schema projection all use iterative traversals rather than nested structured clone or recursive freezing. `undefined`, non-finite numbers, `-0`, sparse arrays, cycles, functions, and exotic objects reject that call before the tool runs. Ordinary successful dispatch returns `ToolExecutionResult.value`; the selected TypeScript image bindings use the final image attachment to construct a program Image. Post-execute blocking and result projection remain authoritative. Native content envelopes, metadata and internal error information stay outside ordinary binding values. PTC mode declares its rejection capability on the runtime request as `{ name: "ToolCallError", memberNameProperty: "toolName" }`. The runtime Service Definition treats those names as data: the worker materializes and injects the actual constructor used for `tools` binding failures, so `error instanceof ToolCallError` works without making a generic runtime know about tools. The worker constructs failures and defines their public fields through module-captured error and property-definition intrinsics plus null-prototype descriptors, so model mutations cannot replace the promised rejection with a worker failure. The error has the standard `Error` message plus the exact `toolName`; it deliberately omits `ToolFailure.info`, error codes, and Native content. This is an exception contract for control flow, not a failure union for programmatic classification. -Binding arguments and resolutions are revalidated as lossless JSON on both sides of the hostile worker protocol and have no byte cap. Before crossing through structured clone, each detached value is encoded as a flat pre-order token stream whose transport nesting is bounded; the receiver rebuilds it iteratively. Valid application nesting therefore has neither a JavaScript call-stack depth cap nor a platform-specific nested structured-clone limit. At module initialization the worker captures its own realm's `Array.prototype` and `Object.prototype` identities, the native function-source intrinsic used only to recognize foreign-realm plain-container prototypes, and every structural and metering intrinsic used by the JSON boundary. Property writes use null-prototype descriptors, while private array and set operations invoke captured methods without consulting mutable global or prototype slots. Model code can therefore replace helpers such as `Object.keys`, `Array.isArray`, collection methods, string methods, or `Buffer.byteLength`, rewrite intrinsic-prototype constructor slots, or add descriptor-shaped fields to `Object.prototype` without changing validation, wire transport, or byte accounting. The foreign-realm native function-source check still rejects user-authored constructors that imitate `Object` or `Array`. The dependency-light runtime Service Definition names its structural equivalent `PtcJsonValue` so it need not depend on the session-owned canonical type; the generated SDK and tool API use `JsonValue`. Intermediate values are not prompt-truncated, context-spilled, or persisted. This preserves full acquired search, workflow, task, filesystem, and MCP values for programmatic filtering while leaving provider and executor acquisition limits truthful. +Ordinary binding arguments and JSON resolutions are revalidated as lossless JSON on both sides of the hostile worker protocol and have no byte cap. Before crossing through structured clone, each detached value is encoded as a flat pre-order token stream whose transport nesting is bounded; the receiver rebuilds it iteratively. Valid application nesting therefore has neither a JavaScript call-stack depth cap nor a platform-specific nested structured-clone limit. At module initialization the worker captures its own realm's `Array.prototype` and `Object.prototype` identities, the native function-source intrinsic used only to recognize foreign-realm plain-container prototypes, and every structural and metering intrinsic used by the JSON boundary. Property writes use null-prototype descriptors, while private array and set operations invoke captured methods without consulting mutable global or prototype slots. Model code can therefore replace helpers such as `Object.keys`, `Array.isArray`, collection methods, string methods, or `Buffer.byteLength`, rewrite intrinsic-prototype constructor slots, or add descriptor-shaped fields to `Object.prototype` without changing validation, wire transport, or byte accounting. The foreign-realm native function-source check still rejects user-authored constructors that imitate `Object` or `Array`. The dependency-light runtime Service Definition names its structural equivalent `PtcJsonValue` so it need not depend on the session-owned canonical type; the generated SDK and tool API use `JsonValue`. Intermediate values are not prompt-truncated, context-spilled, or persisted. This preserves full acquired search, workflow, task, filesystem, and MCP values for programmatic filtering while leaving provider and executor acquisition limits truthful. ### Outer result and output ledger -The runtime accepts an exact lossless JSON completion of any root. Returning `undefined` omits the completion; returning `null` is an explicit result. `run_code` exposes the canonical outer value `{ logs: string[], result?: JsonValue }`. Its Native renderer emits logs first, renders a string result raw, and renders every other JSON root with an iterative pretty printer. Total indentation is capped at ten characters and deeper subtrees remain compact, preserving the established shallow text while keeping traversal stack-safe and formatted size linear in the canonical JSON size. +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. Other language consumers also expose `result?: JsonValue`. Their renderer emits logs first, renders a string result raw, and renders every other JSON root with an iterative pretty printer. Total indentation is capped at ten characters and deeper subtrees remain compact, keeping traversal stack-safe and formatted size linear in the canonical JSON size. `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. @@ -73,13 +73,13 @@ Temporary Cordis Plugins follow the same rule: `cordis_mount` returns `{ id, plu ### Persistence, metadata, and spill -Nested dispatch logs the sub-call's full rendered `content`/`isError` on `tool/ptc-dispatch` but does not persist canonical values. `tool/result` continues to persist only rendered content, error, and optional metadata. A successful final content sequence containing an image is also wrapped in a source-attributed user message and deferred through the outer result; the normal session event makes that model-visible input reconstructable. The [PTC mode note](2026-06-15-ptc.md) owns durable event names and historical identity preservation; replay cannot recreate intermediate canonical program values. +Nested dispatch logs the sub-call's full rendered `content`/`isError` on `tool/ptc-dispatch` but does not persist canonical values. TypeScript programs select images for the outer `tool/result.content` through explicit inspection. Other language consumers defer successful image-bearing content as source-attributed user messages after the outer result. The normal Session events make these model-visible inputs reconstructable. The [PTC mode note](2026-06-15-ptc.md) owns durable event names and historical identity preservation; replay cannot recreate intermediate canonical program values. The opaque `exec.parent` token marks nested calls. Presentation metadata and generic or tool-owned spill projections skip those calls; their canonical values never enter context. The Client can derive [nested terminal cards](../../../../packages/client/ui-tool/README.md) from raw dispatch events without metadata. The outer `run_code` call produces the model-facing result and may spill its final post-policy presentation; `run_code` intentionally declares neither a result presenter nor presentation metadata, so UI adapters complete the card through their generic raw-content fallback using durable `tool/result.content`. ## Testing -Compile-time and snapshot tests pin exact `ToolArgsMap`, `ToolOutputMap`, `ToolName`, schema-to-TypeScript coverage, exotic names, and assembled PTC mode image forwarding. Registry and real-worker tests cover scalar, array, object, and null values; raw string rendering; absent `undefined`; consumer-declared real rejection classes, including `ToolCallError`; invalid arguments and completions, including intrinsic-looking forged prototypes; model-mutated JSON-boundary globals, prototype methods, constructor slots, and inherited descriptor fields; typed binding failures after those mutations; large uncapped intermediate bindings; nested spill suppression; generic image-bearing context deferral plus post-execute replacement/block precedence; exact and over-limit 64 MiB accounting; combined logs/value/diagnostic accounting; giant thrown stacks; bounded failure spill; hostile forged traffic; and built-package execution. +Compile-time and snapshot tests pin exact `ToolArgsMap`, `ToolOutputMap`, `ToolName`, schema-to-TypeScript coverage, exotic names, and assembled PTC mode image projection. Registry and real-worker tests cover scalar, array, object, and null values; raw string rendering; absent `undefined`; consumer-declared real rejection classes, including `ToolCallError`; invalid arguments and completions, including intrinsic-looking forged prototypes; model-mutated JSON-boundary globals, prototype methods, constructor slots, and inherited descriptor fields; typed binding failures after those mutations; large uncapped intermediate bindings; nested spill suppression; consumer-specific image projection plus post-execute replacement/block precedence; exact and over-limit 64 MiB accounting; combined logs/value/diagnostic accounting; giant thrown stacks; bounded failure spill; hostile forged traffic; and built-package execution. Keyless real-worker integration tests pin the two handle workflows that prose results could not safely support. A background bash call returns its job id, the outer run settles, and a later run polls that id to completion; separate cases prove pre-abort creates no task, post-publication call abort preserves the task, foreground execution stays signal-coupled, and `job_kill` owns cancellation. A Cordis program reads an active or pending mount's id and `waitingFor` fields directly, unmounts by that id, and confirms removal without parsing rendered text. @@ -93,9 +93,9 @@ Keyless real-worker integration tests pin the two handle workflows that prose re **Silently inspect or truncate an oversized completion.** Rejected because changing a JSON value into a string is lossy and type-incorrect. The explicit `output-limit` failure lets the model choose a smaller result, while the retained logs and diagnostic can still use normal outer spill. -**Require each rich leaf tool to inspect `exec.parent` and defer itself.** Rejected because it couples leaf tools to PTC mode internals, duplicates policy handling, and misses future rich tools. The dispatch bridge owns generic forwarding from the already settled final result. +**Require each rich leaf tool to inspect `exec.parent` and defer itself.** Rejected because it couples leaf tools to PTC mode internals and duplicates policy handling. The dispatch bridge owns consumer-specific image projection from the already settled final result. -**Expose Native rich content as part of every binding's canonical value.** Rejected because a canonical value is lossless JSON and tool-specific; attachment blocks are a model projection with durable lifecycle semantics. Keeping the value and projection separate preserves typed programs without dropping images from later model context. +**Expose Native rich content as part of every binding's canonical value.** Rejected because a canonical value is lossless JSON and tool-specific; attachment blocks are a model projection with durable lifecycle semantics. Consumer-owned program Image bindings preserve typed tool values while leaving image selection to the program. ## Consequences @@ -111,6 +111,6 @@ The worker performs bounded-depth flat-wire transport and lossless validation bu - Intermediate values have no byte cap and can exhaust process or worker memory through retention, flat-wire copies, or structured-clone cost. - The 64 MiB hard cap applies only to the outer variable payloads, excluding fixed result-envelope syntax and presentation whitespace; spill cannot recover bytes rejected beyond that cap. - Provider or executor acquisition limits may already have discarded source data before a canonical value reaches PTC mode. -- Unsupported MCP output schemas fall back to `JsonValue`; admitted MCP images use the generic deferred projection, while audio and embedded-resource payloads remain diagnostic-only. +- Unsupported MCP output schemas fall back to `JsonValue`; image projection follows the consumer-specific rules above, while audio and embedded-resource payloads remain diagnostic-only. - Nested calls have no separate model-facing result; Client child cards do not add model context. - Code failures expose `ToolCallError` message and tool name only, without a programmatic error-code union. diff --git a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md index 6d8bf2d771..08e3a427b8 100644 --- a/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md +++ b/.agents/notes/implemented/feature/2026-07-20-ptc-typed-tool-returns.zh.md @@ -14,7 +14,7 @@ PTC mode 过去会把每个嵌套工具的结果从 `ContentBlock[]` 重新投 ## 决策 -PTC mode 是可见工具注册表的类型化投影。每个成功的绑定调用都会解析为 post-execute 策略处理后的最终规范 `JsonValue`,失败的绑定调用则会以真正的 `ToolCallError` 拒绝 Promise。中间值只存在于本次运行中,并完整跨越 worker 边界。外层 `run_code` 的日志、完成值或失败诊断会进入可配置的输出账本以及面向模型的输出落盘流水线;如果成功结算的子调用最终 Native 内容包含图片,其完整有序内容还会经父结果延后为写入日志且带来源归属的上下文。 +PTC mode 是可见工具注册表的类型化投影。普通成功绑定调用解析为 post-execute 策略处理后的最终规范 `JsonValue`,失败的绑定调用则以真正的 `ToolCallError` 拒绝 Promise。中间值保留在运行中,并完整跨越进程边界。[显式输出决策](../architecture/2026-11-09-explicit-ptc-output.zh.md)负责 TypeScript Image 绑定、完成值抑制及可见文本和图片的选择。其他语言消费方保留完成值渲染和含图片内容的延后转发。 本文档定义叠加在原始 [PTC mode 基础](2026-06-15-ptc.zh.md)之上的返回值与失败约定。统一 schema 词汇由 [JSON 值 schema DSL reference](../../../../packages/core/tools/README.zh.md)负责定义;Native 渲染与策略投影仍由规范输出 Agent Note 负责定义。 @@ -49,15 +49,15 @@ declare const tools: { ### 绑定值与失败 -分发前,桥接层会把绑定参数快照为无损 JSON,再对分离后的值生成一次快照,供独立的持久摘要事件使用。宿主侧的值分离、执行数据的不可变处理与输出 schema 投影均采用迭代遍历,而不使用嵌套结构化克隆或递归冻结。`undefined`、非有限数、`-0`、稀疏数组、循环引用、函数和非普通对象都会使该调用在工具运行前被拒绝。成功分发会返回 `ToolExecutionResult.value`;Native `content`、元数据和内部错误信息不会传入程序。含图片的最终内容不是第二份绑定值:桥接层会在外层结果之后转运它,使下一次模型请求可以看到持久图片;post-execute 阻止/内容替换仍具有权威性,纯文本结果不会重复。 +分发前,桥接层会把绑定参数快照为无损 JSON,再对分离后的值生成一次快照,供独立的持久摘要事件使用。宿主侧的值分离、执行数据的不可变处理与输出 schema 投影均采用迭代遍历,而不使用嵌套结构化克隆或递归冻结。`undefined`、非有限数、`-0`、稀疏数组、循环引用、函数和非普通对象都会使该调用在工具运行前被拒绝。普通成功分发返回 `ToolExecutionResult.value`;指定的 TypeScript 图片绑定使用最终图片附件构造程序 Image。Post-execute 阻止和结果投影仍具有最终决定权。普通绑定值不包含 Native 内容信封、元数据和内部错误信息。 PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNameProperty: "toolName" }` 声明其以异常拒绝 Promise 的能力。运行时 Service Definition 只把这些名称视为数据:worker 会动态生成并注入真正用于 `tools` 绑定失败的构造函数,因此无需让通用运行时了解工具,`error instanceof ToolCallError` 也能成立。worker 使用模块初始化时捕获的 Error 构造函数与属性定义内建方法,配合原型为 null 的属性描述符,构造失败对象并定义其公开字段,因此模型代码的修改不会把约定承诺的 reject 变成 worker 失败。该错误包含标准的 `Error` 消息和确切的 `toolName`,并有意省略 `ToolFailure.info`、错误代码与 Native 内容。这是一项用于控制流的异常约定,而不是供程序分类的失败联合。 -绑定参数与绑定返回值会在不可信 worker 协议的两端重新校验为无损 JSON,且不设字节上限。每个分离后的值在通过结构化克隆跨越边界前,都会编码为扁平的前序 token 流,其传输结构的嵌套深度有界;接收方再以迭代方式重建该值。因此,有效应用数据的嵌套深度既不受 JavaScript 调用栈深度上限限制,也不受特定平台对嵌套结构化克隆施加的上限限制。模块初始化时,worker 会捕获自身 JavaScript 运行域中 `Array.prototype` 和 `Object.prototype` 的引用、仅用于识别其他运行域普通容器原型、可获取原生函数源码的内建函数,以及 JSON 边界用于结构处理和计量的全部内建方法。属性写入使用原型为 null 的属性描述符;内部的数组与集合操作直接调用捕获的方法,不会访问可变的全局或原型槽位。因此,即使模型代码替换 `Object.keys`、`Array.isArray`、集合方法、字符串方法或 `Buffer.byteLength` 等辅助方法,重写内建原型的构造函数槽位,或向 `Object.prototype` 添加形如属性描述符的字段,也不会改变校验、协议传输或字节计量。面向其他运行域的原生函数源码检查仍会拒绝由用户编写、冒充 `Object` 或 `Array` 的构造函数。为保持依赖轻量,运行时 Service Definition 将结构等价类型命名为 `PtcJsonValue`,从而无需依赖会话侧拥有的规范类型;生成的 SDK 和工具 API 则使用 `JsonValue`。这些值不会经过提示词截断、上下文 spill 或持久化。因此,程序可以完整筛选已经采集的搜索、工作流、任务、文件系统与 MCP 值,同时提供方和执行器的采集上限仍会实际生效。 +普通绑定参数与 JSON 返回值会在不可信 worker 协议的两端重新校验为无损 JSON,且不设字节上限。每个分离后的值在通过结构化克隆跨越边界前,都会编码为扁平的前序 token 流,其传输结构的嵌套深度有界;接收方再以迭代方式重建该值。因此,有效应用数据的嵌套深度既不受 JavaScript 调用栈深度上限限制,也不受特定平台对嵌套结构化克隆施加的上限限制。模块初始化时,worker 会捕获自身 JavaScript 运行域中 `Array.prototype` 和 `Object.prototype` 的引用、仅用于识别其他运行域普通容器原型、可获取原生函数源码的内建函数,以及 JSON 边界用于结构处理和计量的全部内建方法。属性写入使用原型为 null 的属性描述符;内部的数组与集合操作直接调用捕获的方法,不会访问可变的全局或原型槽位。因此,即使模型代码替换 `Object.keys`、`Array.isArray`、集合方法、字符串方法或 `Buffer.byteLength` 等辅助方法,重写内建原型的构造函数槽位,或向 `Object.prototype` 添加形如属性描述符的字段,也不会改变校验、协议传输或字节计量。面向其他运行域的原生函数源码检查仍会拒绝由用户编写、冒充 `Object` 或 `Array` 的构造函数。为保持依赖轻量,运行时 Service Definition 将结构等价类型命名为 `PtcJsonValue`,从而无需依赖会话侧拥有的规范类型;生成的 SDK 和工具 API 则使用 `JsonValue`。这些值不会经过提示词截断、上下文 spill 或持久化。因此,程序可以完整筛选已经采集的搜索、工作流、任务、文件系统与 MCP 值,同时提供方和执行器的采集上限仍会实际生效。 ### 外层结果与输出账本 -运行时接受以任意 JSON 类型为根的精确无损完成值。返回 `undefined` 表示省略完成值;返回 `null` 则是显式结果。`run_code` 暴露规范外层值 `{ logs: string[], result?: JsonValue }`。其 Native 渲染器先输出日志;字符串结果保持原文,其他所有 JSON 根值则使用迭代式美化渲染器。总缩进长度上限为 10 个字符,更深的子树保持紧凑格式,既保留既有的浅层文本,又确保遍历不受调用栈深度限制,且格式化输出大小与规范 JSON 大小呈线性关系。 +保留完成值的运行时消费方接收精确无损 JSON:`undefined` 省略完成值,`null` 是显式结果。TypeScript `run_code` 请求丢弃完成值,将捕获日志和可选沙箱信息作为规范值返回;所选图片单独进入渲染内容。其他语言消费方还提供 `result?: JsonValue`。其渲染器先输出日志,字符串结果保持原文,其他 JSON 根值使用迭代式美化渲染器。总缩进长度上限为十个字符,更深子树保持紧凑格式,使遍历不受调用栈深度限制,且格式化大小与规范 JSON 大小呈线性关系。 `NodePtcRuntime` 以可配置的 `maxOutputBytes` 取代彼此独立的日志与值上限,默认值为 `67_108_864` 字节。worker 会将已捕获日志序列化为 JSON 字符串后的精确字节数计入账本,并在发送终态消息前,根据组合账本的剩余额度预检分离后的完成值或程序异常。因此,即使抛出的字符串或堆栈极大,通过 worker 端口的也只会是固定的 `output-limit` 诊断。宿主侧会针对伪造流量以及 worker 无法观察的原生管道写入,重复执行这套面向不可信对端的账本校验。固定的 `PtcRunResult` 字段名、花括号、有界的错误类型标签及后续展示空白有意不计入这份可变负载账本。这两个阶段都不会实际生成超出上限的完成值序列化结果。结果不超过上限时会保持精确。完成值无法通过无损 JSON 快照时,以 `invalid-output` 失败;值、诊断或包含日志的组合结果超过上限时,以 `output-limit` 失败,而不会变成检查格式化后或截断的文本。 @@ -73,13 +73,13 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert ### 持久化、元数据与 spill -嵌套分发在 `tool/ptc-dispatch` 上记录子调用完整渲染后的 `content`/`isError`,但不会持久化规范值。`tool/result` 继续只持久化渲染后的内容、错误和可选元数据。包含图片的成功最终内容序列还会包装成带来源归属的用户消息,并经外层结果延后;普通会话事件使该模型可见输入可以重建。[PTC mode note](2026-06-15-ptc.zh.md) 负责持久事件名称与历史标识保留规则;回放无法重建程序的规范中间值。 +嵌套分发在 `tool/ptc-dispatch` 上记录子调用完整渲染后的 `content`/`isError`,但不会持久化规范值。TypeScript 程序通过显式展示为外层 `tool/result.content` 选择图片。其他语言消费方将成功的含图片内容作为带来源归属的用户消息,延后到外层结果之后。普通 Session 事件使这些模型可见输入可以重建。[PTC mode note](2026-06-15-ptc.zh.md)负责持久事件名称与历史标识保留规则;回放无法重建程序的规范中间值。 不透明的 `exec.parent` token 用于标识嵌套调用。展示元数据以及通用或工具自有的 spill 投影都会跳过这些调用;它们的规范值永远不会进入上下文。Client 可以从原始分发事件派生[嵌套 terminal 卡片](../../../../packages/client/ui-tool/README.zh.md),无需元数据。外层 `run_code` 调用产生面向模型的结果,并且可能对 post-policy 处理后的最终展示执行 spill;`run_code` 有意既不声明结果展示器,也不声明展示元数据,因此 UI 适配器会通过通用的原始内容回退机制,使用持久化的 `tool/result.content` 补全该卡片。 ## 测试 -编译期测试与快照测试锁定了精确的 `ToolArgsMap`、`ToolOutputMap`、`ToolName`、schema 到 TypeScript 的覆盖范围、特殊名称,以及组装后的 PTC mode 图片转发。注册表与真实 worker 测试覆盖标量、数组、对象和 null 值;字符串原文渲染;缺席的 `undefined`;消费方声明、实际用于拒绝 Promise 的异常类,包括 `ToolCallError`;无效参数与完成值,包括伪装为内建原型的伪造原型;模型代码修改过的 JSON 边界全局对象、原型方法、构造函数槽位,以及继承而来的属性描述符字段;上述修改后的类型化绑定失败;不设上限的大型中间绑定值;嵌套输出落盘抑制;通用含图片上下文延后以及 post-execute 替换/阻止优先级;64 MiB 上限内外的精确计量;日志、值与诊断的组合计量;抛出的超大堆栈;有界失败的输出落盘;不可信对端伪造的流量;以及构建后包的执行。 +编译期测试与快照测试锁定了精确的 `ToolArgsMap`、`ToolOutputMap`、`ToolName`、schema 到 TypeScript 的覆盖范围、特殊名称,以及组装后的 PTC mode 图片投影。注册表与真实 worker 测试覆盖标量、数组、对象和 null 值;字符串原文渲染;缺席的 `undefined`;消费方声明、实际用于拒绝 Promise 的异常类,包括 `ToolCallError`;无效参数与完成值,包括伪装为内建原型的伪造原型;模型代码修改过的 JSON 边界全局对象、原型方法、构造函数槽位,以及继承而来的属性描述符字段;上述修改后的类型化绑定失败;不设上限的大型中间绑定值;嵌套输出落盘抑制;按消费方规则投影图片以及 post-execute 替换/阻止优先级;64 MiB 上限内外的精确计量;日志、值与诊断的组合计量;抛出的超大堆栈;有界失败的输出落盘;不可信对端伪造的流量;以及构建后包的执行。 无密钥的真实 worker 集成测试锁定了自然语言结果无法安全支持的两种句柄工作流。后台 bash 调用返回 job id,外层运行结束,之后的运行再根据该 id 轮询直至任务完成;其他用例分别证明,预先中止不会创建任务、发布后的调用取消会保留任务、前台执行仍与信号耦合,并且由 `job_kill` 负责取消。Cordis 程序会直接读取 active 或 pending 挂载的 id 和 `waitingFor` 字段,按该 id 卸载,并在不解析渲染文本的情况下确认挂载已移除。 @@ -93,9 +93,9 @@ PTC mode 通过运行时请求中的 `{ name: "ToolCallError", memberNamePropert **静默检查格式化或截断过大的完成值:**不予采纳。把 JSON 值改成字符串既有损又违反类型。显式的 `output-limit` 失败让模型可以选择返回更小的结果,而保留的日志和诊断仍可使用普通的外层 spill 机制。 -**要求每个丰富叶子工具检查 `exec.parent` 并自行延后。** 不予采用,因为这会把叶子工具与 PTC mode 内部机制耦合、重复策略处理,并遗漏未来丰富工具。分发桥接层负责从已经结算的最终结果通用转发。 +**要求每个丰富叶子工具检查 `exec.parent` 并自行延后。** 不予采用,因为这会把叶子工具与 PTC mode 内部机制耦合,并重复策略处理。分发桥接层负责按消费方规则,从已经结算的最终结果投影图片。 -**把 Native 丰富内容暴露为每个绑定规范值的一部分。** 不予采用,因为规范值是无损 JSON 且由工具定义;附件块是具有持久生命周期语义的模型投影。保持值与投影分离,既能保留类型化程序,也不会从后续模型上下文中丢弃图片。 +**把 Native 丰富内容暴露为每个绑定规范值的一部分。** 不予采用,因为规范值是无损 JSON 且由工具定义;附件块是具有持久生命周期语义的模型投影。消费方拥有的程序 Image 绑定保留类型化工具值,并将图片选择交给程序。 ## 后果 @@ -111,6 +111,6 @@ worker 会以嵌套深度有界的扁平协议格式传输数据并执行无损 - 中间值没有字节上限,可能因值的保留、扁平协议格式副本或结构化克隆开销而耗尽进程或 worker 内存。 - 64 MiB 硬上限只适用于外层可变负载,不计固定的结果封装语法与展示空白;spill 无法恢复超出该上限后被拒绝的字节。 - 提供方或执行器的采集上限可能在规范值到达 PTC mode 前就已丢弃部分源数据。 -- 不支持的 MCP 输出 schema 会回退为 `JsonValue`;已准入的 MCP 图片使用通用延后投影,而音频和嵌入资源载荷仍只提供诊断。 +- 不支持的 MCP 输出 schema 回退为 `JsonValue`;图片投影遵循上述消费方规则,音频和嵌入资源负载仍仅用于诊断。 - 嵌套调用没有独立的面向模型的结果;Client 子调用卡片不会增加模型上下文。 - PTC mode 失败只暴露 `ToolCallError` 的消息与工具名,不提供程序可用的错误代码联合。 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml index f779b7be73..83daa37ac0 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml @@ -9,8 +9,8 @@ en: 344bcc7e9825bbc8 zh: c1d0f4b54f5b3786 /agent-note-change-request-panel-and-worktree-sessions/decision: - en: 66bde24e7c601eb6 - zh: 5091591f3dc1ac85 + en: 4695a1e4f8aa7a25 + zh: e17be0e36ea3eaa3 /agent-note-change-request-panel-and-worktree-sessions/deferred: en: 32ef8af85f4d2f66 zh: b82b67f94346399e diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md index 2b852ad824..32b6fb4edc 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md @@ -28,7 +28,7 @@ The panel does not move a Session between existing worktrees. Removing a change The panel also shows the changes behind a Session's work in a changes view, a resource tab type of this package. The Remote parses every diff on the Host into files and hunks, so the browser draws them without a patch parser, and bounds each read with `maxDiffBytes` and `maxUntrackedFiles`. Local changes come from `git diff` using the Session's permissions and execution world, in a scope the user picks: the branch against its fork point by default, or the uncommitted, unstaged, or staged changes; untracked files are read through the Session's filesystem and shown as new files. A change request's changes come from its code host at the head of the binding's latest status, through two provider reads the forge seam gained, `diff` and `fileText`. The Host keeps the patch it read last for each change request, keyed by the head commit and base branch and bounded by `maxCachedDiffBytes`, so reopening, refreshing, and navigating at the same head download nothing again; a host or provider that refuses an answer over its size limit reports the forge failure `too-large`, and the view then offers the change request's web page instead of a retry. Unchanged lines between hunks expand from the file's new side, which is the working tree, the index, or the head commit, and only while that text still matches the hunks. Each inspection also sizes the branch's changes for a local changes card, shown while no open change request carries the checked-out branch; its Create change request sends the Session a user message, so the Agent creates the change request with its own tools and the binding follows from `gh pr create` as for any other. -Review comments capture the file, side, range, complete hunk, and reviewed head when the user selects code. Agent references enter the existing composer quote mechanism, so the user controls batching and the sent message records exactly what the model receives. GitHub writes belong to the optional forge provider operation: preflight checks the current head, the write addresses that commit, and an ambiguous outcome blocks another write until the user reconciles it. Review drafts and inline records belong to a browser tab occurrence, not to the Session log or a GitHub pending review. Switching Sessions retains that occurrence; closing it discards the local state and rejects late write completions. Published GitHub comments remain external records. +Review comments capture the file, side, range, complete hunk, and reviewed head when the user selects code. Agent references enter the existing composer quote mechanism, so the user controls batching and the sent message records exactly what the model receives. GitHub writes belong to the optional forge provider operation: preflight checks the current head, the write addresses that commit, and an ambiguous outcome blocks another write until the user reconciles it. Inline records of Agent references and published comments, and the review summary, belong to a browser tab occurrence, not to the Session log; a pull request comment kept for a later review goes to the code host's pending review, as [the pending review decision](2026-11-05-forge-pending-review-drafts.md) records. Switching Sessions retains that occurrence; closing it discards the local state and rejects late write completions. Published GitHub comments remain external records. ## Deferred diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md index 660bd81d38..6e8438080c 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md @@ -28,7 +28,7 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都 面板还通过变更视图展示 Session 工作背后的变更;变更视图是本包的一个资源标签页类型。Remote 在宿主上把每个 diff 解析成文件与 hunk,因此浏览器无需补丁解析器即可绘制,每次读取都受 `maxDiffBytes` 与 `maxUntrackedFiles` 约束。本地变更来自使用 Session 权限与执行环境的 `git diff`,范围由用户选择:默认是分支相对于分叉点的变更,也可以是未提交、未暂存或已暂存的变更;未跟踪文件经 Session 的文件系统读取,显示为新文件。变更请求的变更来自代码托管平台,取自绑定最新状态中的 head,经 forge seam 新增的两个提供方读取操作 `diff` 与 `fileText` 获得。Host 为每个变更请求保留最近读到的补丁,按 head 提交与目标分支区分,总量受 `maxCachedDiffBytes` 约束,因此在同一 head 下重新打开、刷新与导航都不会再次下载;托管平台或提供方因结果超过其大小上限而拒绝时报告 forge 失败 `too-large`,视图随之提供变更请求的网页而不是重试。hunk 之间未变更的行从文件的新版本展开,即工作树、暂存区或 head 提交,并且只在该文本仍与 hunk 吻合时展开。每次检查还会为变更卡片统计分支的变更规模;没有打开中的变更请求以当前检出分支为源分支时才显示该卡片。卡片上的“创建变更请求”向 Session 发送一条用户消息,由 Agent 用自己的工具创建变更请求,绑定像其他变更请求一样来自 `gh pr create`。 -评审评论在用户选择代码时固定文件、侧、行范围、完整 hunk 与所评审的 head。Agent 引用进入既有输入框引用机制,由用户决定批量发送,发送后的消息记录模型实际收到的内容。GitHub 写入属于 forge 提供方的可选操作:预检核对当前 head,写入明确指向该提交;结果不明时阻止再次写入,直到用户核对。评审草稿与行内记录归浏览器页签实例所有,不进入 Session 日志,也不创建 GitHub 待提交评审。切换 Session 保留该实例;关闭时丢弃本地状态并拒绝迟到的写入结果。已发布的 GitHub 评论仍保留在外部平台。 +评审评论在用户选择代码时固定文件、侧、行范围、完整 hunk 与所评审的 head。Agent 引用进入既有输入框引用机制,由用户决定批量发送,发送后的消息记录模型实际收到的内容。GitHub 写入属于 forge 提供方的可选操作:预检核对当前 head,写入明确指向该提交;结果不明时阻止再次写入,直到用户核对。Agent 引用与已发布评论的行内记录以及评审总结归浏览器页签实例所有,不进入 Session 日志;留待之后一起提交的 PR 评论写入代码托管平台的待提交评审,见[待提交评审决策](2026-11-05-forge-pending-review-drafts.zh.md)。切换 Session 保留该实例;关闭时丢弃本地状态并拒绝迟到的写入结果。已发布的 GitHub 评论仍保留在外部平台。 ## Deferred diff --git a/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.i18n.yaml b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.i18n.yaml new file mode 100644 index 0000000000..eb6f1712fb --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-05-forge-pending-review-drafts.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/feature/2026-11-05-forge-pending-review-drafts.md +/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review: + en: 25b4da2d12f15b82 + zh: 6d9fec68e8bb0baa +/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/problem: + en: 2674866671bd0d4b + zh: e60d41a24d20d7bf +/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/decision: + en: 3df55965423b6d33 + zh: 2e8f0fbb4f7a311f +/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/alternatives-considered: + en: ef67e05cb9442f05 + zh: d4433ddd090a9cec +/agent-note-pull-request-comment-drafts-in-the-code-host-s-pending-review/consequences: + en: 198f6cf5a2bc2230 + zh: 92eb0a349356f100 diff --git a/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.md b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.md new file mode 100644 index 0000000000..d0c4cf0d89 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.md @@ -0,0 +1,31 @@ +# Agent Note: Pull request comment drafts in the code host's pending review + +Status: implemented + +English | [中文](2026-11-05-forge-pending-review-drafts.zh.md) + +## Problem + +The [forge panel](2026-10-09-forge-panel.md) kept a pull request's comment drafts in a browser tab occurrence, published them as one review, and recorded what it published. Once the changes view shows the code host's review threads and lets the user reply to them, browser drafts leave four gaps. A reply cannot join a later review, because the drafts and the threads live in different places. A review the user started on the GitHub page, or in another browser, does not appear, and GitHub refuses a review submitted while the user has one. Drafts are lost with the tab and invisible on another device. And GitHub keeps one pending review per user and pull request, so two stores of one review would disagree. + +## Decision + +A pull request comment that the user keeps for a later review goes to the user's pending review on the code host through the provider's optional `writeReview`. The first such comment or reply starts the pending review at the head the user saw; later ones join it. The changes view reads the pending review with the threads, shows its comments as threads tagged Pending, and Submit review submits or discards that review with the summary and decision. Replies, resolving and unresolving, and editing and deleting the user's own comments use the same write, which re-checks the head and is never retried. + +The browser keeps what the code host does not hold: the review summary and decision until submission, the records of Agent references and published comments, and the outgoing direct write whose outcome needs confirmation. Comments on local changes never had a host destination; they go to the main input as before. Comment drafts an earlier panel kept in the browser stay readable: they show beside their code as browser drafts, can move into the pending review, and keep Submit review disabled while a pending review exists; without one, Submit review publishes them as one review as before. + +GitHub measurements on a private test repository decided three rules. While the user has a pending review, GitHub refuses a directly created review and a single comment (HTTP 422, "can only have one pending review per pull request"), so the view offers neither; a reply sent without the review's id still joins the review, so the view offers no reply at once and the provider refuses one. GitHub refuses Approve and Request changes on the user's own pull request, so the dialog offers only Comment there. + +## Alternatives considered + +**Keeping drafts in the browser tab.** It needs no host write until submission, but replies cannot join the same review, a review started elsewhere blocks submission without explanation, and the drafts do not follow the user to another device. + +**Keeping both stores.** Mirroring browser drafts into the pending review or the reverse gives one review two owners whose contents can diverge, and every edit would need reconciliation of two writes. + +**Recording drafts in the Session log.** The log records what reaches the model; review drafts are host state the model never sees, and other Sessions on the same pull request would not see them. + +**Retrying a write after an unknown outcome.** A lost response does not show whether GitHub applied the mutation. A submission of the pending review is kept as the write to reconcile, as a direct submission is, and blocks another submission until the user checks GitHub; a reply, resolution, or comment change reads the threads again and asks the user to check them before trying again. + +## Consequences + +A comment kept for later is visible on the GitHub page to its author before submission, and is lost only when the user discards the review. Each comment, reply, or thread change costs one GraphQL query for the head check and one mutation. Resolving a thread does not change the pull request's update time, so every write from the panel drops the panel's kept threads; another view of the same pull request shows the change at its next status or after `reviewRefreshMs`. A provider without `writeReview` reports no write permissions, so its threads stay read-only and its pull request comments are published at once or added to the input. Comment drafts from an earlier panel remain until the user moves, publishes, or deletes them, or closes their tab. diff --git a/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.zh.md b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.zh.md new file mode 100644 index 0000000000..0dc9c99e2a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-forge-pending-review-drafts.zh.md @@ -0,0 +1,31 @@ +# Agent Note: PR 评论草稿保存在代码托管平台的待提交评审中 + +Status: implemented + +[English](2026-11-05-forge-pending-review-drafts.md) | 中文 + +## Problem + +[forge 面板](2026-10-09-forge-panel.zh.md)原先把 PR 的评论草稿保存在浏览器页签实例中,作为一次评审发布,并记录已发布的内容。变更视图显示代码托管平台的评审讨论并允许用户回复之后,浏览器草稿留下四个缺口。回复无法加入之后的评审,因为草稿与讨论保存在不同的地方。用户在 GitHub 页面或另一个浏览器中开始的评审不会显示,而用户已有待提交评审时,GitHub 会拒绝直接提交的评审。草稿随页签丢失,在其他设备上也看不到。GitHub 每个用户在每个 PR 上只保留一个待提交评审,两处保存同一个评审会出现不一致。 + +## Decision + +用户留待之后一起提交的 PR 评论,通过提供方的可选能力 `writeReview` 写入代码托管平台上该用户的待提交评审。第一条这样的评论或回复在用户看到的 head 上开始待提交评审,之后的评论或回复加入其中。变更视图随讨论一起读取待提交评审,把其中的评论显示为带“待提交”标签的讨论;“提交评审”带着总结和评审决定提交或丢弃这个评审。回复、解决与取消解决、编辑与删除用户自己的评论也使用同一写操作;写操作会重新检查 head,且从不重试。 + +浏览器只保存代码托管平台不保存的内容:提交前的评审总结与评审决定、Agent 引用与已发布评论的记录,以及结果有待确认的直接写入。本地变更上的评论本来就没有托管平台上的去处,仍像以前一样进入主输入框。早期面板保存在浏览器中的评论草稿仍可读取:它们作为浏览器草稿显示在对应代码旁,可以加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”像以前一样把它们作为一次评审发布。 + +在一个私有测试仓库上对 GitHub 的实测确定了三条规则。用户已有待提交评审时,GitHub 拒绝直接创建的评审和单条评论(HTTP 422,“每个 PR 只能有一个待提交评审”),因此视图两者都不提供;不带评审 id 发送的回复仍会加入该评审,因此视图不提供立即回复,提供方也拒绝这种回复。GitHub 拒绝用户批准或请求更改自己的 PR,因此在这种 PR 上,弹窗只提供“评论”。 + +## Alternatives considered + +**把草稿保存在浏览器页签中。** 提交之前不需要写入托管平台,但回复无法加入同一个评审,在别处开始的评审会无说明地阻止提交,草稿也无法随用户换到另一台设备。 + +**两处同时保存。** 把浏览器草稿同步到待提交评审,或反过来同步,会让一个评审有两个所有者,内容可能分歧,每次编辑都要核对两次写入。 + +**把草稿记录在 Session 日志中。** 日志记录的是到达模型的内容;评审草稿是模型永远看不到的托管平台状态,同一 PR 上的其他 Session 也看不到它们。 + +**结果不明时自动重试写操作。** 响应丢失并不能说明 GitHub 是否执行了 mutation。提交待提交评审时,与直接提交一样,这次提交会作为待核对的写入保留下来,在用户到 GitHub 核对之前阻止再次提交;回复、解决讨论或修改评论时,视图重新读取讨论,并请用户核对后再重试。 + +## Consequences + +留待之后提交的评论,在提交前其作者就能在 GitHub 页面上看到,只有用户丢弃评审时才会丢失。每条评论、回复或讨论状态的修改,都消耗一次用于检查 head 的 GraphQL 查询和一个 mutation。解决讨论不会改变 PR 的更新时间,因此面板发出的每个写操作都会丢弃面板保留的讨论;同一 PR 的其他视图在收到下一次状态时,或在 `reviewRefreshMs` 之后显示这一变化。未实现 `writeReview` 的提供方不报告任何写入权限,因此它的讨论保持只读,它的 PR 评论只能立即发布或添加到输入框。早期面板留下的评论草稿会一直保留,直到用户把它们加入评审、发布、删除,或关闭所在页签。 diff --git a/.github/workflows/cua-helper-package-windows.yml b/.github/workflows/cua-helper-package-windows.yml new file mode 100644 index 0000000000..0da925fa44 --- /dev/null +++ b/.github/workflows/cua-helper-package-windows.yml @@ -0,0 +1,107 @@ +name: Package CUA helper · Windows · x64 + +on: + workflow_dispatch: + workflow_call: + outputs: + artifact-id: + description: '包含 win-x64 helper ZIP 的产物编号' + value: ${{ jobs.package.outputs.artifact-id }} + run-id: + description: '产物所属的构建运行编号' + value: ${{ jobs.package.outputs.run-id }} + build-key: + description: '提交 SHA、.NET SDK 版本和 win-x64 RID 的 SHA-256 摘要' + value: ${{ jobs.package.outputs.build-key }} + +permissions: + contents: read + +jobs: + package: + runs-on: windows-latest + timeout-minutes: 30 + defaults: + run: + shell: pwsh + outputs: + artifact-id: ${{ steps.upload.outputs.artifact-id }} + run-id: ${{ github.run_id }} + build-key: ${{ steps.metadata.outputs.build-key }} + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-dotnet@v5.4.0 + with: + dotnet-version: '10.0.x' + - name: Restore locked Windows helper and run protocol checks + run: | + dotnet restore packages/experimental/cua-windows/native/cua-windows.slnx --locked-mode + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + dotnet run --project packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj --configuration Release --no-restore + - name: Publish Windows CUA helper + run: >- + dotnet publish packages/experimental/cua-windows/native/entry/CuaWindows.csproj + --configuration Release + --runtime win-x64 + --self-contained true + --no-restore + --output dist/cua-helper-win-x64 + # Standalone helper zip contract: flat root with cua-helper.json, + # dsh-cua-windows.exe, and its runtime files. Installed providers place + # the same payload under native/bin/win-x64. + - name: Add helper metadata + id: metadata + env: + GITHUB_SHA: ${{ github.sha }} + run: | + $ErrorActionPreference = 'Stop' + $directory = 'dist/cua-helper-win-x64' + $exe = Join-Path $directory 'dsh-cua-windows.exe' + if (-not (Test-Path $exe -PathType Leaf)) { throw "helper executable is missing: $exe" } + $version = (Get-Content package.json -Raw | ConvertFrom-Json).version + $commit = $env:GITHUB_SHA + $sdk = (& dotnet --version).Trim() + $keyBytes = [Text.Encoding]::UTF8.GetBytes("$commit`n$sdk`nwin-x64") + $buildKey = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($keyBytes)).ToLowerInvariant() + $files = [ordered]@{} + Get-ChildItem $directory -Recurse -File | Sort-Object FullName | ForEach-Object { + $relative = [IO.Path]::GetRelativePath($directory, $_.FullName) -replace '\\', '/' + $files[$relative] = (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant() + } + # sha256 is the executable alias of files[dsh-cua-windows.exe]. + # signing is an enum: unsigned or authenticode. + $metadata = [ordered]@{ + schemaVersion = 1 + platform = 'windows' + buildKey = $buildKey + version = $version + commit = $commit + architecture = 'x64' + executable = 'dsh-cua-windows.exe' + sha256 = $files['dsh-cua-windows.exe'] + signing = 'unsigned' + files = $files + } + $json = $metadata | ConvertTo-Json -Depth 5 + Set-Content -Path (Join-Path $directory 'cua-helper.json') -Value "$json`n" -NoNewline -Encoding utf8NoBOM + Add-Content -Path $env:GITHUB_OUTPUT -Value "build-key=$buildKey`n" -NoNewline -Encoding utf8 + - name: Archive publish output + run: | + $zipPath = 'dist/cua-helper-win-x64.zip' + Compress-Archive -Path dist/cua-helper-win-x64/* -DestinationPath $zipPath + $zip = [IO.Compression.ZipFile]::OpenRead((Resolve-Path $zipPath).Path) + try { + foreach ($name in 'dsh-cua-windows.exe', 'cua-helper.json') { + if (-not $zip.GetEntry($name)) { throw "Missing root entry in helper ZIP: $name" } + } + } finally { $zip.Dispose() } + - uses: actions/upload-artifact@v7.0.1 + id: upload + with: + name: cua-helper-${{ github.run_id }}-${{ github.run_attempt }}-${{ steps.metadata.outputs.build-key }} + path: dist/cua-helper-win-x64.zip + if-no-files-found: error + compression-level: 0 + retention-days: 14 diff --git a/apps/cli/package.json b/apps/cli/package.json index 4be57e7f46..0407a54d48 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh", "description": "dsh CLI: profile launch, plugin management, and configuration inspection", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/apps/cli/src/profile-boot.ts b/apps/cli/src/profile-boot.ts index da14308bd6..2b1977deed 100644 --- a/apps/cli/src/profile-boot.ts +++ b/apps/cli/src/profile-boot.ts @@ -261,6 +261,17 @@ export interface RunProfileOptions { packageManager?: ProfileContext['packageManager'] } +/** + * Render a profile name as an RFC 9110 `User-Agent` product version: bytes outside `tchar`, and `%`, are percent-encoded, + * so spaces, `/`, and non-ASCII names stay readable and reversible. + * @param name - the booted profile name. + * @returns the encoded name. + */ +export function userAgentProfile(name: string): string { + // encodeURIComponent leaves only `(` and `)` outside tchar. + return encodeURIComponent(name).replace(/[()]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`) +} + /** * Boot one profile invocation end to end and leave process lifetime to the * mounted plugins (or to a one-shot runner the composition mounts). @@ -269,6 +280,8 @@ export interface RunProfileOptions { * @throws after disposing startup resources; cleanup failures retain the original error. */ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Context; shutdown: ProcessShutdown }> { + // Model providers see which profile sent a request. + process.env.DSH_USER_AGENT_SUFFIX = `dsh-profile/${userAgentProfile(options.profile)}` // Before the first plugin mounts and before anything can issue a request: Node's fetch ignores the // proxy environment on its own, so every profile would otherwise connect directly. Resolving from // the launcher's snapshot — not `process.env` — is what lets a proxy declared in a `.env` layer diff --git a/apps/cli/tests/optional-bundle-transitions.e2e.ts b/apps/cli/tests/optional-bundle-transitions.e2e.ts index c63adb0823..749a2a4b1a 100644 --- a/apps/cli/tests/optional-bundle-transitions.e2e.ts +++ b/apps/cli/tests/optional-bundle-transitions.e2e.ts @@ -189,7 +189,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option expect(names(minimal.agent)).toContain('session_search') await turn(coded.agent, 'Read this session lineage through run_code.', [ toolCallResponse('ptc-search', 'run_code', { - code: 'console.log(await tools.session_trace({}));', + code: 'inspect(await tools.session_trace({}));', description: 'Read the current session lineage', }), textResponse('PTC_SEARCH_DONE'), ]) @@ -340,7 +340,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option if (coded === undefined) throw new Error('the PTC Agent was not created') await turn(coded, 'Read this session lineage and load the badge through one program.', [ toolCallResponse('combined-program', 'run_code', { - code: 'console.log(await tools.session_trace({})); console.log(await tools.skill({ name: "dsh-badge" }));', + code: 'inspect(await tools.session_trace({})); inspect(await tools.skill({ name: "dsh-badge" }));', description: 'Use optional session search and badge together', }), textResponse('COMBINED_DONE'), ]) diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts index 0eb7a187b0..a1b2b82a59 100644 --- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts @@ -38,7 +38,7 @@ import * as CordisInspectProviders from '@deepseek-ai/dsh-tool-cordis/host' */ const PERSONA = 'You are a coding agent. You work by writing TypeScript programs for run_code: ' - + 'batch related tool work into one program and print or return ONLY the findings that matter.' + + 'batch related tool work into one program and inspect ONLY the findings that matter.' const WORKSPACE_PROBE = 'dragonfruit-8675309' let ctx: Context | undefined @@ -106,14 +106,17 @@ function runCode( }) } -/** Read the optional completion from a successful canonical `run_code` value. */ +/** Read a JSON value explicitly inspected by the program. */ function completion(result: ToolExecutionResult): unknown { if (result.isError) { throw new Error(result.content.filter(block => block.type === 'text').map(block => block.text).join('\n')) } const value = result.value if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('invalid run_code result') - return value.result + if (!Array.isArray(value.logs)) throw new Error('run_code result has no captured output') + const text = value.logs.at(-1) + if (typeof text !== 'string') throw new Error('run_code did not inspect a JSON value') + return JSON.parse(text) } async function mountRuntime(harness: Context): Promise { @@ -184,7 +187,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => { exposesInfo: 'info' in error, }; } - return { length: large.length, failure }; + inspect(JSON.stringify({ length: large.length, failure })); `)) expect(value).toEqual({ @@ -211,12 +214,12 @@ describe('PTC mode typed values: keyless real-process contracts', () => { description: 'Run completion marker in background', run_in_background: true, }); - return started.jobId; + inspect(JSON.stringify(started.jobId)); `)) expect(jobId).toMatch(/^bash-[0-9a-f]{16}$/) const polled = completion(await runCode(ctx, ` - return await tools.job_output({ job_id: ${JSON.stringify(jobId)}, wait: true, timeout_ms: 5000 }); + inspect(JSON.stringify(await tools.job_output({ job_id: ${JSON.stringify(jobId)}, wait: true, timeout_ms: 5000 }))); `)) if (typeof polled !== 'object' || polled === null || Array.isArray(polled)) throw new Error('invalid job_output completion') const taskOutput = polled as Record @@ -231,7 +234,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => { const pre = new AbortController() pre.abort('pre-aborted') const preResult = await runCode(ctx, ` - return await tools.bash({ command: 'sleep 10', description: 'Must never start', run_in_background: true }); + inspect(JSON.stringify(await tools.bash({ command: 'sleep 10', description: 'Must never start', run_in_background: true }))); `, pre.signal) expect(preResult.isError).toBe(true) expect(ctx.jobs.list()).toEqual([]) @@ -246,7 +249,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => { const afterPublication = new AbortController() const running = runCode(ctx, ` const started = await tools.bash({ command: 'sleep 10', description: 'Wait for explicit task kill', run_in_background: true }); - console.log(started.jobId); + inspect(started.jobId); await new Promise(() => {}); `, afterPublication.signal) await Promise.race([ @@ -265,11 +268,11 @@ describe('PTC mode typed values: keyless real-process contracts', () => { expect(ctx.jobs.list()[0]).toMatchObject({ id: job!.id, status: 'running' }) const killed = completion(await runCode(ctx, ` - return await tools.job_kill({ job_id: ${JSON.stringify(job!.id)}, reason: 'test owns cancellation' }); + inspect(JSON.stringify(await tools.job_kill({ job_id: ${JSON.stringify(job!.id)}, reason: 'test owns cancellation' }))); `)) expect(killed).toMatchObject({ outcome: 'cancellation-requested', job: { id: job!.id } }) const settled = completion(await runCode(ctx, ` - return await tools.job_output({ job_id: ${JSON.stringify(job!.id)}, wait: true, timeout_ms: 5000 }); + inspect(JSON.stringify(await tools.job_output({ job_id: ${JSON.stringify(job!.id)}, wait: true, timeout_ms: 5000 }))); `)) expect(settled).toMatchObject({ job: { id: job!.id, status: 'killed' } }) }) @@ -280,7 +283,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => { const controller = new AbortController() const startedAt = Date.now() const pending = runCode(ctx, ` - return await tools.bash({ command: 'sleep 10', description: 'Run cancellable foreground command' }); + inspect(JSON.stringify(await tools.bash({ command: 'sleep 10', description: 'Run cancellable foreground command' }))); `, controller.signal) setTimeout(() => { controller.abort('stop-foreground') }, 200) const result = await pending @@ -306,7 +309,7 @@ describe('PTC mode typed values: keyless real-process contracts', () => { const inspected = await tools.cordis_inspect_query({ platform: provider.platform, provider: provider.id, method: provider.methods[0].name, }); - return { provider: provider.id, names: inspected.data.tools.map(tool => tool.name) }; + inspect(JSON.stringify({ provider: provider.id, names: inspected.data.tools.map(tool => tool.name) })); `, testToolSignal, agent)) expect(value).toEqual({ provider: 'Tool', names: ['cordis_inspect_list', 'cordis_inspect_query'] }) @@ -335,7 +338,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('PTC mode: real model writes a pr type: 'text', text: 'Using one run_code program: run `echo alpha-7` with the bash tool, run `echo beta-9` with the bash tool, ' + 'then write both outputs joined by a plus sign into combined.txt (bash heredoc or redirect), ' - + 'and return only the joined string.', + + 'and inspect the joined string. Reply with that string only.', }], source: { kind: 'user' } })) await waitForIdle(ctx, agent) const events: readonly SessionEvent[] = agent.session.snapshotEvents() diff --git a/apps/cli/tests/profiles/sdk/plugin-manager.expected.e2e.ts b/apps/cli/tests/profiles/sdk/plugin-manager.expected.e2e.ts index e27881ded0..0144ebabeb 100644 --- a/apps/cli/tests/profiles/sdk/plugin-manager.expected.e2e.ts +++ b/apps/cli/tests/profiles/sdk/plugin-manager.expected.e2e.ts @@ -46,7 +46,7 @@ it.for(['standard', 'ptc'] as const)('keeps %s plugin changes pending until the } catch (error) { fixtureError = error } const call = mode === 'ptc' ? { type: 'tool_use', id: `manage-${requests.length}`, name: 'run_code', input: { - code: `return await tools.plugin_manager(${JSON.stringify(args)});`, description: 'Disable web tools after restart', + code: `inspect(await tools.plugin_manager(${JSON.stringify(args)}));`, description: 'Disable web tools after restart', } } : { type: 'tool_use', id: `manage-${requests.length}`, name: 'plugin_manager', input: args } response.writeHead(200, { 'content-type': 'text/event-stream' }) diff --git a/apps/cli/tests/resolved-profile-boot.spec.ts b/apps/cli/tests/resolved-profile-boot.spec.ts index 6e7bc52060..b8415fb974 100644 --- a/apps/cli/tests/resolved-profile-boot.spec.ts +++ b/apps/cli/tests/resolved-profile-boot.spec.ts @@ -10,8 +10,8 @@ import { PluginPackages, type Profile, } from '@deepseek-ai/dsh-app-boot' import { installProxyFromEnvironment } from '@deepseek-ai/dsh-http-proxy' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { runProfile } from '../src/profile-boot.ts' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { runProfile, userAgentProfile } from '../src/profile-boot.ts' vi.mock('@deepseek-ai/dsh-app-boot', async (importOriginal) => { const actual = await importOriginal() @@ -25,6 +25,8 @@ vi.mock('@deepseek-ai/dsh-app-boot', async (importOriginal) => { vi.mock('@deepseek-ai/dsh-http-proxy', () => ({ installProxyFromEnvironment: vi.fn() })) const homes: string[] = [] +// runProfile writes the suffix into process.env; stubbing first lets afterEach restore it. +beforeEach(() => { vi.stubEnv('DSH_USER_AGENT_SUFFIX', undefined) }) afterEach(() => { vi.restoreAllMocks() vi.unstubAllEnvs() @@ -173,3 +175,40 @@ describe('runProfile with an application-owned profile', () => { } }) }) + +describe('profile User-Agent suffix', () => { + it.each([ + ['web', 'web'], + ['sdk-minimal', 'sdk-minimal'], + ['my web/v2', 'my%20web%2Fv2'], + ['工作', '%E5%B7%A5%E4%BD%9C'], + ['a(b)%', 'a%28b%29%25'], + ])('encodes %j as %j', (name, encoded) => { + expect(userAgentProfile(name)).toBe(encoded) + }) + + it('names the profile before any plugin loads', async () => { + const home = mkdtempSync(join(tmpdir(), 'dsh-profile-user-agent-')) + homes.push(home) + mkdirSync(join(home, 'runtime')) + writeFileSync(join(home, 'runtime/package.json'), '{"name":"test-runtime","version":"1.0.0"}') + writeFileSync(join(home, 'package.json'), '{"name":"test-bundle","version":"1.0.0"}') + vi.stubEnv('DSH_HOME', home) + vi.spyOn(process, 'on').mockReturnValue(process) + vi.mocked(installProxyFromEnvironment).mockResolvedValue(async () => {}) + const failure = new Error('stop after observing the environment') + let seen: string | undefined + vi.mocked(boot).mockImplementation(() => { + seen = process.env.DSH_USER_AGENT_SUFFIX + return Promise.reject(failure) + }) + const profile: Profile = { skippedBundles: [], + name: 'my web', dir: home, patchPath: join(home, 'cordis.patch.yml'), patches: [], layers: [], + } + await expect(runProfile({ + environment: createLaunchEnvironmentSnapshot([]), profile: 'my web', patchFiles: [], args: [], + resolvedProfile: { profile, installAnchor: join(home, 'runtime/package.json') }, + })).rejects.toBe(failure) + expect(seen).toBe('dsh-profile/my%20web') + }) +}) diff --git a/apps/desktop-host/package.json b/apps/desktop-host/package.json index c9f86adbf5..20f70a7aa4 100644 --- a/apps/desktop-host/package.json +++ b/apps/desktop-host/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop-host", "description": "Private Node-mode host process for the Electron desktop application", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c3cf87bfa4..f13ba3178c 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop", "description": "Electron desktop shell for a bundled dsh runtime and external plugins", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "private": true, "license": "MIT", "author": { diff --git a/apps/desktop/tests/cua-optional-package.spec.ts b/apps/desktop/tests/cua-optional-package.spec.ts index a6b42cdcfd..3df4a7d70d 100644 --- a/apps/desktop/tests/cua-optional-package.spec.ts +++ b/apps/desktop/tests/cua-optional-package.spec.ts @@ -10,11 +10,12 @@ import { pnpmCommand } from '../../../scripts/release/process.ts' const repository = resolve(import.meta.dirname, '../../..') const providerName = '@deepseek-ai/dsh-experimental-cua-macos' +const windowsProvider = '@deepseek-ai/dsh-cua-windows' const bundleName = '@deepseek-ai/dsh-cua-bundle' const readManifest = async (path: string): Promise> => JSON.parse(await readFile(join(repository, path, 'package.json'), 'utf8')) as Record -it('fetches the macOS optional tarball only for Darwin, with an empty cache for every target', async () => { +it('fetches the platform-declared CUA provider tarballs with an empty cache for every target', async () => { const root = await mkdtemp(join(tmpdir(), 'cua-cold-install-')) onTestFinished(() => rm(root, { recursive: true, force: true })) const userconfig = join(root, 'npmrc') @@ -37,17 +38,22 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for const cli = await readManifest('apps/cli') const bundle = await readManifest('packages/experimental/cua-bundle') const native = await readManifest('packages/experimental/cua-macos') + const windows = await readManifest('packages/experimental/cua-windows') expect(cli.dependencies).toHaveProperty(bundleName) expect(bundle.dependencies).not.toHaveProperty(providerName) - expect(bundle.optionalDependencies).toEqual({ [providerName]: 'workspace:*' }) + expect(bundle.dependencies).not.toHaveProperty(windowsProvider) + expect(bundle.optionalDependencies).toEqual({ [providerName]: 'workspace:*', [windowsProvider]: 'workspace:*' }) + expect(windows.os).toEqual(['win32', 'linux']) expect(native.os).toEqual(['darwin']) const version = '1.0.0' const bundleDependencies = Object.fromEntries(Object.keys(bundle.dependencies as Record).map(name => [name, version])) const manifests = [ { name: cli.name, version, dependencies: { [bundleName]: version } }, - { name: bundleName, version, dependencies: bundleDependencies, optionalDependencies: { [providerName]: version } }, + { name: bundleName, version, dependencies: bundleDependencies, + optionalDependencies: { [providerName]: version, [windowsProvider]: version } }, ...Object.keys(bundleDependencies).map(name => ({ name, version })), { name: providerName, version, os: native.os, files: native.files }, + { name: windowsProvider, version, os: windows.os, files: windows.files }, ] const generation = 'a'.repeat(64) const nativePayload = `native/bin/darwin-arm64/${generation}/DSH Computer Use.app/Contents/MacOS/dsh-cua-native` @@ -121,5 +127,7 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for expect(requests).toContain('/@deepseek-ai/dsh-cua.tgz') expect(requests.includes(`/${providerName}.tgz`), `${target}: ${JSON.stringify(requests)}\n${output}`) .toBe(target === 'darwin' || unrestricted) + expect(requests.includes(`/${windowsProvider}.tgz`), `${target}: ${JSON.stringify(requests)}\n${output}`) + .toBe(target !== 'darwin') } }, 120_000) diff --git a/apps/plugin-market-generator/package.json b/apps/plugin-market-generator/package.json index 5ea6d10246..c2b3aa4e62 100644 --- a/apps/plugin-market-generator/package.json +++ b/apps/plugin-market-generator/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-plugin-market-generator", "description": "Reference generator of plugin market index files from a list of npm packages and Git repositories", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "private": true, "type": "module", "scripts": { diff --git a/apps/web/package.json b/apps/web/package.json index 5ac5400998..52185ec9ca 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-web-frontend", "description": "Web application entry: vite build over the @deepseek-ai/dsh-client-web shell library; dist/ served by apps/cli's dsh web", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/apps/web/tests/bundle-platform.e2e.ts b/apps/web/tests/bundle-platform.e2e.ts index 2f3c673a3c..0784bd132c 100644 --- a/apps/web/tests/bundle-platform.e2e.ts +++ b/apps/web/tests/bundle-platform.e2e.ts @@ -21,7 +21,7 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct await writeFile(join(root, 'package.json'), JSON.stringify({ name, version: '1.0.0', dsh: { bundle: { patch: './cordis.patch.yml', platforms: [process.platform === 'darwin' ? 'win32' : 'darwin'], } } })) - await writeFile(join(root, 'cordis.patch.yml'), '- id: ptc-runtime\n config:\n executionMode: persistent-in-memory\n') + await writeFile(join(root, 'cordis.patch.yml'), '- id: ptc-runtime\n config:\n executionMode: persistent-in-memory\n replScoped: false\n') const scaffold = owned.scaffold = await launchWebScaffold({ profile: { packages: [{ dir: root }] } }) const browser = owned.browser = await chromium.launch() const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) @@ -44,8 +44,9 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct const names = [name] await page.locator('[data-plugin-panel]').getByRole('button', { name: '更多', exact: true }).click() const cua = page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]') - expect(await cua.count()).toBe(process.platform === 'darwin' ? 1 : 0) - if (process.platform !== 'darwin') { + const cuaSupported = process.platform === 'darwin' || process.platform === 'win32' + expect(await cua.count()).toBe(cuaSupported ? 1 : 0) + if (!cuaSupported) { expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle')) .toMatchObject({ listedByDefault: false, enabled: false, error: { code: 'unsupported-platform' } }) names.push('@deepseek-ai/dsh-cua-bundle') diff --git a/apps/web/tests/chat-long-interactions.e2e.ts b/apps/web/tests/chat-long-interactions.e2e.ts index 25cbcf590d..54bb83c305 100644 --- a/apps/web/tests/chat-long-interactions.e2e.ts +++ b/apps/web/tests/chat-long-interactions.e2e.ts @@ -19,7 +19,7 @@ import { webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { conversationContextKey, expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts' +import { conversationContextKey, expandOwningTurnProcess, loadEarlierChatPage, newEnglishPage, saveFailureShot } from './support.ts' const MODE = webSnapshotMode() const SESSION_ID = 'chat-long-interactions-e2e' @@ -219,10 +219,9 @@ describe('web e2e: long Chat interaction contract', () => { )) expect(await markPitch()).toBe(10) - const loadEarlier = page.getByRole('button', { name: 'Load earlier', exact: true }) const loadedRows = page.locator('[data-chat-flow-key]') const loadedBefore = await loadedRows.count() - await loadEarlier.click() + await loadEarlierChatPage(page) await expect.poll(() => loadedRows.count(), { timeout: 15_000 }).toBeGreaterThan(loadedBefore) await railScroller.hover() await page.mouse.wheel(0, -FIXTURE_TURNS * 10) diff --git a/apps/web/tests/cua-optin.e2e.ts b/apps/web/tests/cua-optin.e2e.ts index 77ec920da5..b1b2c6c27f 100644 --- a/apps/web/tests/cua-optin.e2e.ts +++ b/apps/web/tests/cua-optin.e2e.ts @@ -1,4 +1,4 @@ -/** CUA follows PTC Agent scopes and changes the default only from its detail page. */ +/** CUA selects each Agent's tool form and changes the default only from its detail page. */ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -13,7 +13,7 @@ import { expect, it, vi } from 'vitest' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode, type WebScaffold } from './scaffold.ts' import { connectFreshWorkspaceZh, ZH_BROWSER_LOCALE } from './support.ts' -// The shipped bundle admits only macOS Hosts; unsupported Hosts are exercised in bundle-platform.e2e.ts. +// This fixture exercises the macOS provider’s permission setup. it.skipIf(process.platform !== 'darwin').each([ { selectedDefault: undefined, codingTools: false, script: false }, { selectedDefault: undefined, codingTools: true, script: false }, @@ -110,8 +110,8 @@ it.skipIf(process.platform !== 'darwin').each([ expect(profileManifest().dependencies).toEqual(dependencies) expect(await card.getByText('实验性', { exact: true }).count()).toBe(1) expect(await card.textContent()).not.toContain('将 PTC 模式改为可持久化') - expect(await card.textContent()).toContain('请切换到 PTC 模式') - expect(await card.textContent()).toContain('Windows 支持正在开发中') + expect(await card.textContent()).not.toContain('请切换到 PTC 模式') + expect(await card.textContent()).toContain('通过 npm 安装 DSH 的 Windows 用户需要单独配置 helper') expect(await card.textContent()).not.toContain('Swift') const description = await card.getByRole('button', { name: '查看 Computer Use', exact: true }).evaluate((button) => { const element = document.getElementById(button.getAttribute('aria-describedby')!)! @@ -126,11 +126,14 @@ it.skipIf(process.platform !== 'darwin').each([ expect(scaffold.ctx.agents.get(ptcAgent.id) === ptcAgent).toBe(true) expect(scaffold.ctx.agentPresets.composedPreset(originalAgent.ctx)).toBe(initialDefault) expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua')).toBe(false) + expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua_run_code')).toBe(true) + expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua_run_code')).toBe(false) expect(scaffold.ctx.tools.schemas(ptcAgent).some(tool => tool.name === 'cua')).toBe(true) expect((await scaffold.ctx.systemPrompt.assemble({ scope: ptcAgent })).tools.map(tool => tool.name)).toEqual(['run_code']) for (const preset of ['ptc', 'standard', 'ptc', initialDefault]) { await scaffold.ctx.agentPresets.select(originalAgent, preset) expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua')).toBe(preset === 'ptc') + expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua_run_code')).toBe(preset !== 'ptc') } const child = await scaffold.ctx.agents.create({ sessionId: SessionId('cua-child'), @@ -163,6 +166,7 @@ it.skipIf(process.platform !== 'darwin').each([ })).agent expect(scaffold.ctx.agentPresets.composedPreset(freshDefault.ctx)).toBe(initialDefault) expect(scaffold.ctx.tools.schemas(freshDefault).some(tool => tool.name === 'cua')).toBe(false) + expect(scaffold.ctx.tools.schemas(freshDefault).some(tool => tool.name === 'cua_run_code')).toBe(true) const fresh = (await scaffold.ctx.agents.create({ sessionId: SessionId('cua-new-ptc'), setup: async (ctx) => { await scaffold.ctx.agentPresets.mount(ctx, 'ptc') }, @@ -170,17 +174,40 @@ it.skipIf(process.platform !== 'darwin').each([ expect(scaffold.ctx.agentPresets.composedPreset(fresh.ctx)).toBe('ptc') expect(scaffold.ctx.tools.schemas(fresh).some(tool => tool.name === 'cua')).toBe(true) await card.getByRole('button', { name: '查看 Computer Use', exact: true }).click() + await plugins.locator('[data-detail-document]').getByText('helperPath', { exact: true }).waitFor() toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用 Computer Use', exact: true }) const persistent = page.getByRole('group', { name: 'PTC 执行方式', exact: true }) + if (!codingTools) { + const panel = page.locator('[data-cua-settings]') + await expect.poll(() => panel.getAttribute('aria-busy')).toBe('false') + expect(await panel.textContent()).toContain('标准、创造和 PTC 模式均可使用 Computer Use') + expect(await persistent.textContent()).toContain('其他模式始终单独保留 Computer Use 状态') + for (const width of [1680, 390]) { + await page.setViewportSize({ width, height: 1000 }) + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await expect.poll(() => page.evaluate(() => document.body.hasAttribute('data-ds-dark-theme'))).toBe(colorScheme === 'dark') + await expect.poll(() => panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + if (webSnapshotMode() === 'refresh') { + const directory = fileURLToPath(new URL('../../../.playwright-mcp/cua-run-code-ui', import.meta.url)) + await mkdir(directory, { recursive: true }) + await panel.screenshot({ path: join(directory, `details-zh-${width}-${colorScheme}.png`), animations: 'disabled' }) + } + } + } + await page.emulateMedia({ colorScheme: null }) + await page.setViewportSize({ width: 1680, height: 1000 }) + } const beforePersistent = scaffold.ctx.ptcRuntime await persistent.getByRole('button', { name: '设为持久化', exact: true }).click() await persistent.getByRole('button', { name: '已设为持久化', exact: true }).waitFor() - expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'repl') + expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'scoped-repl') expect(scaffold.ctx.ptcRuntime.retainsState).toBe(true) expect(scaffold.ctx.ptcRuntime === beforePersistent).toBe(false) saved = await readFile(settingsPath, 'utf8') expect(saved).toContain(`executionMode: ${script ? 'vm-script' : 'persistent-in-memory'}`) expect(saved).toContain(`scriptPersistence: ${script}`) + expect(saved).toContain(`replScoped: ${!script}`) const runtime = scaffold.ctx.ptcRuntime const persistentRuntimeFiber = runtimeFiber() const owner = {} @@ -192,6 +219,9 @@ it.skipIf(process.platform !== 'darwin').each([ expect(runtimeFiber() === persistentRuntimeFiber).toBe(true) expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) expect(scaffold.ctx.agents.get(ptcAgent.id) === ptcAgent).toBe(true) + for (const agent of [originalAgent, freshDefault, ptcAgent, fresh]) { + expect(scaffold.ctx.tools.schemas(agent).some(tool => tool.name === 'cua_run_code')).toBe(false) + } for (const agent of [ptcAgent, fresh]) { expect(scaffold.ctx.tools.schemas(agent).some(tool => tool.name === 'cua')).toBe(false) expect((await scaffold.ctx.systemPrompt.assemble({ scope: agent })).tools.map(tool => tool.name)).toEqual(['run_code']) diff --git a/apps/web/tests/cua-run-code.e2e.ts b/apps/web/tests/cua-run-code.e2e.ts new file mode 100644 index 0000000000..272f418272 --- /dev/null +++ b/apps/web/tests/cua-run-code.e2e.ts @@ -0,0 +1,118 @@ +/** Standard-mode CUA programs retain code cards, nested calls, images, and source inspection. */ +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser } from 'playwright' +import { expect, it, onTestFailed, onTestFinished } from 'vitest' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-tools' +import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, + launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' + +const fixture = fileURLToPath(new URL('../../../snapshots/session/cua-run-code/session.v4.jsonl', import.meta.url)) +const snapshotDirectory = fileURLToPath(new URL('../../../snapshots/web/cua-run-code', import.meta.url)) +const mode = webSnapshotMode() + +it.skipIf(mode === 'record')('shows standard CUA programs and their recorded source through the Web composition', async () => { + const directory = await mkdtemp(join(tmpdir(), 'cua-run-code-web-')) + const resources: { scaffold?: WebScaffold; browser?: Browser } = {} + onTestFinished(async () => { + try { await resources.browser?.close() } finally { + try { await resources.scaffold?.close() } finally { await rm(directory, { recursive: true, force: true }) } + } + }) + const patch = join(directory, 'cua-fixture.yml') + await writeFile(patch, JSON.stringify([{ id: 'agent-default-model', config: { + provider: 'deepseek-official', model: 'deepseek-v4-flash-vision-exp', + } }, { insert: [ + { id: 'computer-use', name: '@deepseek-ai/dsh-computer-use' }, + { id: 'cua-run-code-fixture', name: fileURLToPath(new URL('../../../snapshots/session/cua-run-code/provider.mjs', import.meta.url)), + config: { allowedApps: [{ id: 'a'.repeat(64), name: 'Fixture', executablePath: '/fixture/app' }] } }, + ] }])) + const scaffold = resources.scaffold = await launchWebScaffold({ + replayFixture: fixture, compareReplaySession: false, extraOverlayPath: patch, + }) + const events: SessionEvent[] = [] + scaffold.ctx.on('session/event', (_session, event) => { events.push(event) }) + const browser = resources.browser = await chromium.launch() + const page = await newEnglishPage(browser), tripwire = watchConsole(page) + onTestFailed(() => saveFailureShot(page, 'web-e2e-cua-run-code')) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const agent = scaffold.ctx.agents.list()[0]! + expect(scaffold.ctx.agentPresets.composedPreset(agent.ctx)).toBe('standard') + expect(scaffold.ctx.tools.schemas(agent).map(tool => tool.name)).toContain('cua_run_code') + expect(scaffold.ctx.tools.schemas(agent).map(tool => tool.name)).not.toContain('cua') + const prompts = fixtureUserPrompts(await readFile(await selectedSessionFixture(fixture), 'utf8')) + expect(prompts).toHaveLength(1) + const prompt = prompts.at(0) + if (prompt === undefined) throw new Error('The CUA recording must contain a user prompt') + const settled = scaffold.whenTurnSettled() + const input = page.locator('[data-composer-input]').first() + await input.fill(prompt) + await input.press('Enter') + await settled + const results = events.filter(event => event.type === 'tool/result') + expect(results).toHaveLength(2) + expect(results.every(event => !event.data.message.isError)).toBe(true) + expect(events.filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(8) + const calls = page.locator('[data-tool="cua_run_code"]') + const description = 'Select and capture the fixture window' + const turnControl = page.locator('[data-turn-process="1"]') + await turnControl.waitFor({ state: 'visible' }) + await expect.poll(() => turnControl.getAttribute('aria-expanded')).toBe('false') + await turnControl.click() + await expect.poll(() => turnControl.getAttribute('aria-expanded')).toBe('true') + const group = calls.first().locator('xpath=ancestor::*[@data-chat-group-key][1]') + const groupControl = group.locator('[data-process-activity]').first() + await groupControl.waitFor({ state: 'visible' }) + if (await groupControl.getAttribute('aria-expanded') === 'false') await groupControl.click() + await expect.poll(() => groupControl.getAttribute('aria-expanded')).toBe('true') + await expect.poll(() => calls.count()).toBe(2) + await calls.first().getByRole('button', { name: `Code ${description}`, exact: true }).click() + const source = calls.first().locator('pre.shiki') + await source.waitFor() + expect(await source.textContent()).toContain('var app = await cua.getApp("test.fixture")') + expect(await page.locator('[data-subcalls] [data-tool="cua"]').count()).toBe(8) + expect(events.filter(event => event.type === 'tool/ptc-dispatch' && event.data.content.some(block => block.type === 'image'))).toHaveLength(1) + expect(events.filter(event => event.type === 'tool/result' + && event.data.message.content.some(block => block.type === 'image'))).toHaveLength(1) + expect(await calls.first().textContent()).toContain('(1x1px, 90 bytes)') + expect(await calls.first().textContent()).not.toContain('"type": "image"') + await compareOrRefreshGolden(join(snapshotDirectory, 'ui.expected.md'), + await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), mode) + if (mode === 'refresh') { + const evidence = fileURLToPath(new URL('../../../.playwright-mcp/cua-run-code-ui', import.meta.url)) + await mkdir(evidence, { recursive: true }) + await page.screenshot({ path: join(evidence, 'standard-code-cards.png'), animations: 'disabled' }) + const viewport = page.viewportSize() + await page.setViewportSize({ width: 800, height: 900 }) + await page.screenshot({ path: join(evidence, 'standard-code-cards-narrow.png'), animations: 'disabled' }) + if (viewport !== null) await page.setViewportSize(viewport) + } + await page.getByRole('tab', { name: 'Trajectory', exact: true }).click() + const row = page.getByRole('row', { name: new RegExp(`cua_run_code ${description}`) }) + await row.click() + await page.getByRole('tab', { name: 'Code', exact: true }).click() + expect(await page.getByRole('tabpanel').textContent()).toContain('var app = await cua.getApp("test.fixture")') + await page.getByRole('button', { name: 'Wrap lines', exact: true }).click() + await compareOrRefreshGolden(join(snapshotDirectory, 'code.expected.md'), + await captureStableAria(page, '[role="tabpanel"]', scaffold.workspaceCwd), mode) + if (mode === 'refresh') { + await page.screenshot({ path: fileURLToPath(new URL('../../../.playwright-mcp/cua-run-code-ui/source-inspector.png', import.meta.url)), animations: 'disabled' }) + } + const screenshot = page.locator('tr[data-kind="subtool"]').filter({ hasText: '"method":"screenshot"' }) + await screenshot.click() + await page.getByRole('tab', { name: 'Result', exact: true }).click() + const image = page.getByRole('tabpanel').locator('img').first() + await image.waitFor({ state: 'visible' }) + await expect.poll(() => image.evaluate((element: HTMLImageElement) => element.naturalWidth)).toBe(1) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + await assertFixtureInventory(snapshotDirectory, ['ui.expected.md', 'code.expected.md']) +}) diff --git a/apps/web/tests/expected/cua-permissions/default-mode.expected.md b/apps/web/tests/expected/cua-permissions/default-mode.expected.md index 36996c4d69..fba38356f3 100644 --- a/apps/web/tests/expected/cua-permissions/default-mode.expected.md +++ b/apps/web/tests/expected/cua-permissions/default-mode.expected.md @@ -1,4 +1,4 @@ - group "新会话默认模式": - strong: 新会话默认模式 - - paragraph: Computer Use 仅在 PTC 模式中可用。 + - paragraph: 标准、创造和 PTC 模式均可使用 Computer Use。在此选择 PTC,可将其设为新会话的默认模式 - button "设为 PTC" diff --git a/apps/web/tests/expected/cua-permissions/missing.expected.md b/apps/web/tests/expected/cua-permissions/missing.expected.md index 26ea6c5bd4..ab790a24de 100644 --- a/apps/web/tests/expected/cua-permissions/missing.expected.md +++ b/apps/web/tests/expected/cua-permissions/missing.expected.md @@ -2,11 +2,11 @@ - heading "Authorize computer use" [level=3] - group "Default mode for new sessions": - strong: Default mode for new sessions - - paragraph: Computer use is available only in PTC mode. + - paragraph: Computer use is available in Standard, Creator, and PTC modes. Choose PTC here to make it the default for new sessions. - button "Set to PTC" - group "PTC execution mode": - strong: PTC execution mode - - paragraph: Keep variables and application objects across tool calls. Switching restarts the PTC runtime. + - paragraph: Keep variables and application objects across PTC tool calls. Switching restarts the PTC runtime. Other modes always keep their computer use state separately. - button "Use persistent mode" - group "Accessibility": - strong: Accessibility diff --git a/apps/web/tests/expected/forge-panel/discard-review.expected.md b/apps/web/tests/expected/forge-panel/discard-review.expected.md new file mode 100644 index 0000000000..a31563daba --- /dev/null +++ b/apps/web/tests/expected/forge-panel/discard-review.expected.md @@ -0,0 +1,19 @@ +- dialog "提交评审": + - heading "提交评审" [level=2] + - button "关闭" + - text: 待提交评论(1) + - group "丢弃评审": + - text: 丢弃待提交的评审及其中的 1 条评论?此操作无法撤销 + - button "取消" + - button "丢弃评审" + - textbox "评审总结…" + - status + - radio "评论" [checked] + - text: 评论 + - radio "批准" + - text: 批准 + - radio "请求更改" + - text: 请求更改 + - button "丢弃评审" [disabled] + - button "取消" + - button "提交评审" [disabled] diff --git a/apps/web/tests/expected/forge-panel/local-and-pr.expected.md b/apps/web/tests/expected/forge-panel/local-and-pr.expected.md index e19aec25eb..a3d5433481 100644 --- a/apps/web/tests/expected/forge-panel/local-and-pr.expected.md +++ b/apps/web/tests/expected/forge-panel/local-and-pr.expected.md @@ -16,5 +16,6 @@ - 'button "从本会话移除 #7"' - 'button "收起 #7" [expanded]' - button "检查 已加载 1 项检查,仍有更多" - - text: 评审 等待评审 · 1 条未解决讨论 合并 无冲突 - - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 + - button "评审 等待评审" + - text: 合并 无冲突 + - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论 diff --git a/apps/web/tests/expected/forge-panel/panel.expected.md b/apps/web/tests/expected/forge-panel/panel.expected.md index f71db0bd64..d6573ae3a6 100644 --- a/apps/web/tests/expected/forge-panel/panel.expected.md +++ b/apps/web/tests/expected/forge-panel/panel.expected.md @@ -13,5 +13,6 @@ - 'button "从本会话移除 #7"' - 'button "收起 #7" [expanded]' - button "检查 已加载 1 项检查,仍有更多" - - text: 评审 等待评审 · 1 条未解决讨论 合并 无冲突 - - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 + - button "评审 等待评审" + - text: 合并 无冲突 + - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论 diff --git a/apps/web/tests/expected/forge-panel/reference.expected.md b/apps/web/tests/expected/forge-panel/reference.expected.md index 4a34c8f7c9..2db6846496 100644 --- a/apps/web/tests/expected/forge-panel/reference.expected.md +++ b/apps/web/tests/expected/forge-panel/reference.expected.md @@ -8,5 +8,6 @@ - 'button "从本会话移除 #7"' - 'button "收起 #7" [expanded]' - button "检查 已加载 1 项检查,仍有更多" - - text: 评审 等待评审 · 1 条未解决讨论 合并 无冲突 - - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 + - button "评审 等待评审" + - text: 合并 无冲突 + - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论 diff --git a/apps/web/tests/expected/forge-panel/review-record.expected.md b/apps/web/tests/expected/forge-panel/review-record.expected.md index 3e678d6071..aef059b24e 100644 --- a/apps/web/tests/expected/forge-panel/review-record.expected.md +++ b/apps/web/tests/expected/forge-panel/review-record.expected.md @@ -1,4 +1,8 @@ -- region "评论 R2–4": - - text: 你的评论 R2–4 已发布到 GitHub 请核对边界条件 +- region "R2–4": + - text: R2–4 · 在 aaaaaaa 上 lin 1 个月前 + - button "lin 的评论操作" + - paragraph: 请核对边界条件 + - button "回复…" - button "添加到输入框" - - button "在 GitHub 查看" + - button "在 GitHub 中查看" + - button "解决讨论" diff --git a/apps/web/tests/expected/forge-panel/review-summary-required.expected.md b/apps/web/tests/expected/forge-panel/review-summary-required.expected.md index 3e384b28e1..2a56eddd38 100644 --- a/apps/web/tests/expected/forge-panel/review-summary-required.expected.md +++ b/apps/web/tests/expected/forge-panel/review-summary-required.expected.md @@ -10,5 +10,6 @@ - text: 批准 - radio "请求更改" [checked] - text: 请求更改 + - button "丢弃评审" - button "取消" - button "提交评审" [disabled] diff --git a/apps/web/tests/expected/forge-panel/review-thread-reply.expected.md b/apps/web/tests/expected/forge-panel/review-thread-reply.expected.md new file mode 100644 index 0000000000..0a6b4b489c --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-thread-reply.expected.md @@ -0,0 +1,16 @@ +- region "R2": + - text: R2 · 在 aaaaaaa 上 lin 2 小时前 + - button "lin 的评论操作" + - paragraph: + - text: Why + - strong: two + - text: "?" + - text: octo 2 小时前 作者 + - paragraph: It reads better. + - textbox "回复…": 已改为字符串 + - button "取消" + - button "回复" + - button "回复选项" + - button "添加到输入框" + - button "在 GitHub 中查看" + - button "解决讨论" diff --git a/apps/web/tests/expected/forge-panel/review-threads.expected.md b/apps/web/tests/expected/forge-panel/review-threads.expected.md index f44d04fb59..ff5dc738a5 100644 --- a/apps/web/tests/expected/forge-panel/review-threads.expected.md +++ b/apps/web/tests/expected/forge-panel/review-threads.expected.md @@ -14,14 +14,17 @@ - text: export const n2 = 'two' - region "R2": - text: R2 · 在 aaaaaaa 上 lin 2 小时前 + - button "lin 的评论操作" - paragraph: - text: Why - strong: two - text: "?" - text: octo 2 小时前 作者 - paragraph: It reads better. + - button "回复…" - button "添加到输入框" - button "在 GitHub 中查看" + - button "解决讨论" - button "选择第 L3 行": "3" - text: export const n3 = 3 - button "选择第 R3 行": "3" @@ -53,9 +56,12 @@ - text: export const n15 = 'fifteen' - region "L15": - text: L15 · 在 aaaaaaa 上 lin 2 小时前 + - button "lin 的评论操作" - paragraph: The old fifteen was a number. + - button "回复…" - button "添加到输入框" - button "在 GitHub 中查看" + - button "解决讨论" - text: 已解决的讨论 · lin - button "展开" - button "选择第 L16 行": "16" @@ -77,6 +83,9 @@ - text: 原在 R9 · 在 fffffff 上 已过期 - button "查看当时的文件" - text: "@@ -1,5 +1,5 @@ export const n1 = 1 -export const n2 = 2 +export const n2 = 'two' lin 2 小时前" + - button "lin 的评论操作" - paragraph: This line moved. + - button "回复…" - button "添加到输入框" - button "在 GitHub 中查看" + - button "解决讨论" diff --git a/apps/web/tests/expected/forge-panel/submit-review.expected.md b/apps/web/tests/expected/forge-panel/submit-review.expected.md index 0687f7ba99..8affefb880 100644 --- a/apps/web/tests/expected/forge-panel/submit-review.expected.md +++ b/apps/web/tests/expected/forge-panel/submit-review.expected.md @@ -10,5 +10,6 @@ - text: 批准 - radio "请求更改" [checked] - text: 请求更改 + - button "丢弃评审" - button "取消" - button "提交评审" diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 7fdb3e9223..389d5a5d8c 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -1,5 +1,6 @@ /** Worktree Sessions and the change request panel through the real optional bundle, a Git checkout, and a scripted GitHub CLI. */ import { execFile } from 'node:child_process' +import { existsSync } from 'node:fs' import { access, chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { homedir, tmpdir } from 'node:os' import { basename, join } from 'node:path' @@ -10,7 +11,7 @@ import { pluginRecordOf, type SessionEvent } from '@deepseek-ai/dsh-session' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { initialShortcutConfig, type DesktopShortcutInput, type ShortcutRevision } from '@deepseek-ai/dsh-client-shortcuts/protocol' import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path' -import { chromium, type Browser, type Page } from 'playwright' +import { chromium, type Browser, type Locator, type Page } from 'playwright' import { expect, it, onTestFailed, onTestFinished } from 'vitest' import { captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, readPersistedEvents, watchConsole, @@ -50,7 +51,17 @@ const run = promisify(execFile) * and the matching diagnostic as GitHub's HTTP 406 refusal. The raw contents API * serves `contents.json`, keyed by `path@commit`, and the commit listing of pull * request 7 serves `commits.json`, oldest first. The review thread read serves - * `threads.json` as its one page of threads, or no threads without it. Every invocation is appended to `calls.jsonl`. + * `threads.json` as its one page of threads, with the viewer `lin`, who may write + * to the repository and did not open either pull request, or no threads without it. `overview.json` replaces fields + * of pull request 7, such as its checks and reviewers, and the viewer's + * permission. Viewed marks start from `viewed.json`, keyed by path; reading + * them fails while `viewed.unreadable` exists. Mutations, which arrive as + * JSON on stdin, change what later reads report through `state.json`: replies, + * which join the pending review whenever one exists, resolution, comment edits and + * deletions, the pending review of `lin` with its new threads, which a + * submission publishes, viewed marks, which fail while `viewed.refused` exists, + * review requests, and branch updates. Each mutation is appended to + * `mutations.jsonl`, each REST rerun to `reruns.jsonl`, and every invocation to `calls.jsonl`. */ const GH = `#!/usr/bin/env node import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs' @@ -127,27 +138,110 @@ if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vn process.stdout.write(text) process.exit(0) } +if (args[0] === 'api' && args[3] === '--method' && args[4] === 'POST' && args[5].startsWith('repos/octo/demo/actions/')) { + appendFileSync(join(here, 'reruns.jsonl'), args[5] + '\\n') + state.reruns = [...state.reruns ?? [], args[5]] + save() + process.exit(0) +} if (args[0] === 'auth' && args[1] === 'status') { process.stdout.write('github.com\\n Logged in to github.com account octo\\n') process.exit(0) } +const review = () => ({ pending: null, published: [], replies: {}, resolved: {}, bodies: {}, deleted: [], ...state.review }) +/** The signed-in reviewer, who did not open the pull requests. */ +const VIEWER = 'lin' +/** One review comment node by \`login\`, which the viewer may change when it is the viewer's own. */ +const commentNode = (id, body, login, pending) => ({ id, state: pending ? 'PENDING' : 'SUBMITTED', createdAt: '2026-10-09T01:00:00Z', + url: pending ? null : 'https://github.com/octo/demo/pull/7#discussion_' + id, body, + viewerCanUpdate: login === VIEWER, viewerCanDelete: login === VIEWER, author: { __typename: 'User', login, avatarUrl: null } }) +if (args[0] === 'api' && args[1] === 'graphql' && args.includes('--input')) { + const { query, variables } = JSON.parse(readFileSync(0, 'utf8')) + const field = query.match(/\\{\\s*(\\w+)\\(input:/)[1] + appendFileSync(join(here, 'mutations.jsonl'), JSON.stringify({ field, variables }) + '\\n') + const current = review() + const draft = thread => ({ id: 'new-' + (current.published.length + (current.pending?.threads.length ?? 0) + 1), + path: thread.path, side: thread.side, line: thread.line, startLine: thread.startLine ?? null, body: thread.body }) + let payload + if (field === 'markFileAsViewed' || field === 'unmarkFileAsViewed') { + if (existsSync(join(here, 'viewed.refused'))) { + process.stdout.write(JSON.stringify({ data: null, errors: [{ type: 'FORBIDDEN', message: readFileSync(join(here, 'viewed.refused'), 'utf8') }] })) + process.exit(0) + } + state.viewed = { ...state.viewed, [variables.path]: field === 'unmarkFileAsViewed' ? 'UNVIEWED' : 'VIEWED' } + payload = { clientMutationId: null } + } else if (field === 'requestReviews') { + // The reviewer lookup names each user \`user-\`. + state.requested = [...new Set([...state.requested ?? [], ...(variables.input.userIds ?? []).map(id => id.slice('user-'.length))])] + payload = { clientMutationId: null } + } else if (field === 'updatePullRequestBranch') { + if (variables.input.expectedHeadOid !== 'a'.repeat(40)) { + process.stdout.write(JSON.stringify({ data: null, errors: [{ type: 'UNPROCESSABLE', message: 'expected head sha did not match current head ref' }] })) + process.exit(0) + } + state.updated = variables.input.updateMethod + payload = { clientMutationId: null } + } else if (field === 'addPullRequestReview') { + current.pending = { id: 'review-1', commit: variables.commit, threads: [] } + for (const thread of variables.threads ?? []) current.pending.threads.push(draft(thread)) + payload = { pullRequestReview: { id: 'review-1' } } + } else if (field === 'addPullRequestReviewThread') { + current.pending.threads.push(draft(variables)) + payload = { thread: { id: current.pending.threads.at(-1).id } } + } else if (field === 'addPullRequestReviewThreadReply') { + const replies = current.replies[variables.thread] ??= [] + // As on GitHub, a reply joins the pending review whenever one exists. + replies.push({ id: variables.thread + '-reply-' + replies.length, body: variables.body, pending: variables.review !== null || current.pending !== null }) + payload = { comment: { id: replies.at(-1).id } } + } else if (field === 'resolveReviewThread' || field === 'unresolveReviewThread') { + current.resolved[variables.thread] = field === 'resolveReviewThread' + payload = { thread: { id: variables.thread } } + } else if (field === 'updatePullRequestReviewComment') { + current.bodies[variables.comment] = variables.body + payload = { pullRequestReviewComment: { id: variables.comment } } + } else if (field === 'deletePullRequestReviewComment') { + current.deleted.push(variables.comment) + payload = { clientMutationId: null } + } else if (field === 'submitPullRequestReview' || field === 'deletePullRequestReview') { + if (field === 'submitPullRequestReview') current.published.push(...current.pending.threads) + for (const replies of Object.values(current.replies)) { + for (const reply of replies) if (reply.pending && field === 'deletePullRequestReview') current.deleted.push(reply.id) + for (const reply of replies) reply.pending = false + } + current.pending = null + payload = { pullRequestReview: { id: variables.review } } + } + state.review = current + save() + process.stdout.write(JSON.stringify({ data: { [field]: payload } })) + process.exit(0) +} if (args[0] === 'api' && args[1] === 'graphql') { const query = args.find(arg => arg.startsWith('query=')).slice('query='.length) const check = (name, conclusion, completedAt, databaseId = 101) => ({ __typename: 'CheckRun', id: 'check-' + databaseId, name, status: 'COMPLETED', conclusion, databaseId, detailsUrl: 'https://github.com/octo/demo/actions/runs/1', startedAt: '2026-10-09T00:00:00Z', completedAt, - checkSuite: { app: { id: 'github-actions' }, workflowRun: { event: 'pull_request', workflow: { id: 'ci', name: 'CI' } } }, + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: 1, event: 'pull_request', workflow: { id: 'ci', name: 'CI' } } }, }) + const overview = existsSync(join(here, 'overview.json')) ? JSON.parse(readFileSync(join(here, 'overview.json'), 'utf8')) : {} + const none = { totalCount: 0, nodes: [] } + const requested = (state.requested ?? []).map(login => ({ asCodeOwner: false, requestedReviewer: { __typename: 'User', login, avatarUrl: null } })) + const requests = overview.reviewRequests ?? none + const reviewing = { totalCount: requests.totalCount + requested.length, nodes: [...requests.nodes, ...requested] } const pulls = { 7: { id: 'pull-7', number: 7, url: 'https://github.com/octo/demo/pull/7', title: 'Add the pull request panel', state: 'OPEN', isDraft: false, updatedAt: '2026-10-09T00:00:00Z', closedAt: null, author: { login: 'octo' }, headRefName: 'feat', headRefOid: 'a'.repeat(40), baseRefOid: BASE, baseRefName: 'main', additions: 128, deletions: 14, mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED', reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ isResolved: false }] }, - commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-7', state: 'FAILURE', contexts: { + commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-7', state: 'FAILURE', contexts: overview.checks ?? { pageInfo: { hasNextPage: true, endCursor: 'checks-100' }, nodes: Array.from({ length: 100 }, (_, i) => check('lint', 'FAILURE', '2026-10-08T00:00:42Z', i + 1)), } } } }] }, + viewerCanUpdateBranch: (overview.viewerCanUpdateBranch ?? false) && state.updated === undefined, canBeRebased: overview.canBeRebased ?? false, + reviewRequests: reviewing, latestReviews: overview.latestReviews ?? none, latestOpinionatedReviews: overview.latestOpinionatedReviews ?? none, + closingIssuesReferences: overview.closingIssues ?? none, + ...overview.mergeable === undefined ? {} : { mergeable: overview.mergeable }, }, 9: { id: 'pull-9', number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED', @@ -158,6 +252,8 @@ if (args[0] === 'api' && args[1] === 'graphql') { commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-9', state: 'SUCCESS', contexts: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z')], } } } }] }, + viewerCanUpdateBranch: false, canBeRebased: true, reviewRequests: none, latestReviews: none, latestOpinionatedReviews: none, + closingIssuesReferences: none, }, } if (query.includes('commits(first: $first')) { @@ -171,16 +267,74 @@ if (args[0] === 'api' && args[1] === 'graphql') { } } } } })) process.exit(0) } - if (query.includes('{ id headRefOid reviewThreads(first: $first)')) { + const number = Number(args.find(arg => arg.startsWith('number='))?.slice('number='.length)) + if (query.includes('files(first: $first')) { + if (existsSync(join(here, 'viewed.unreadable'))) { + process.stdout.write(JSON.stringify({ data: null, errors: [{ message: readFileSync(join(here, 'viewed.unreadable'), 'utf8') }] })) + process.exit(0) + } + const paths = readFileSync(join(here, 'pr-' + number + '.diff'), 'utf8').split('\\n') + .filter(line => line.startsWith('diff --git ')).map(line => line.split(' b/').at(-1)) + const marks = { ...existsSync(join(here, 'viewed.json')) ? JSON.parse(readFileSync(join(here, 'viewed.json'), 'utf8')) : {}, ...state.viewed } + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: pulls[number].headRefOid, files: { + totalCount: paths.length, pageInfo: { hasNextPage: false, endCursor: null }, + nodes: paths.map(path => ({ path, viewerViewedState: marks[path] ?? 'UNVIEWED' })), + } } } } })) + process.exit(0) + } + if (query.includes('user(login: $u0)')) { + const users = Object.fromEntries(args.flatMap(arg => /^u\\d+=/.test(arg) ? [[arg.split('=')[0], { id: 'user-' + arg.slice(arg.indexOf('=') + 1) }]] : [])) + process.stdout.write(JSON.stringify({ data: users })) + process.exit(0) + } + if (query.includes('assignableUsers')) { + const people = [['mona', 'Mona Lisa'], ['hubot', null], ['lin-reviewer', 'Lin']].map(([login, name]) => ({ login, name, avatarUrl: null })) + const search = args.find(arg => arg.startsWith('search=')).slice('search='.length) + process.stdout.write(JSON.stringify({ data: { repository: { + assignableUsers: { nodes: people.filter(person => person.login.includes(search)) }, + pullRequest: { author: { login: 'octo' }, suggestedReviewers: [{ reviewer: people[2] }] }, + } } })) + process.exit(0) + } + if (query.includes('viewer { login }')) { const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length)) - const threads = existsSync(join(here, 'threads.json')) ? JSON.parse(readFileSync(join(here, 'threads.json'), 'utf8')) : [] - process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { id: 'pull-' + number, - headRefOid: pulls[number].headRefOid, reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: threads } } } } })) + const current = review() + const page = nodes => ({ pageInfo: { hasNextPage: false, endCursor: null }, nodes }) + const written = (thread, pending) => ({ + id: thread.id, isOutdated: false, isResolved: false, path: thread.path, diffSide: thread.side, startDiffSide: thread.startLine === null ? null : thread.side, + line: thread.line, startLine: thread.startLine, originalLine: thread.line, originalStartLine: thread.startLine, subjectType: 'LINE', + viewerCanReply: true, viewerCanResolve: true, viewerCanUnresolve: false, + root: { nodes: [{ diffHunk: '@@ -1,5 +1,5 @@', commit: { oid: pulls[number].headRefOid }, originalCommit: { oid: pulls[number].headRefOid } }] }, + comments: page([commentNode(thread.id + '-0', thread.body, VIEWER, pending)]), + }) + const stored = existsSync(join(here, 'threads.json')) ? JSON.parse(readFileSync(join(here, 'threads.json'), 'utf8')) : [] + const threads = [...stored, ...current.published.map(thread => written(thread, false)), + ...(current.pending?.threads ?? []).map(thread => written(thread, true))].map((thread) => { + const replies = (current.replies[thread.id] ?? []).map(reply => commentNode(reply.id, reply.body, VIEWER, reply.pending)) + const comments = [...thread.comments.nodes, ...replies].filter(comment => !current.deleted.includes(comment.id)) + .map(comment => ({ ...comment, body: current.bodies[comment.id] ?? comment.body })) + return { ...thread, isResolved: current.resolved[thread.id] ?? thread.isResolved, comments: page(comments) } + }).filter(thread => thread.comments.nodes.length > 0) + const pendingComments = threads.flatMap(thread => thread.comments.nodes).filter(comment => comment.state === 'PENDING').length + process.stdout.write(JSON.stringify({ data: { viewer: { login: VIEWER }, repository: { isArchived: false, viewerPermission: 'WRITE', + pullRequest: { id: 'pull-' + number, headRefOid: pulls[number].headRefOid, locked: false, + reviews: { nodes: current.pending === null ? [] : [{ id: current.pending.id, viewerDidAuthor: true, comments: { totalCount: pendingComments } }] }, + reviewThreads: page(threads) } } } })) + process.exit(0) + } + if (query.includes('reviews(states: PENDING')) { + const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length)) + const pending = review().pending + // Every thread and comment the double serves belongs to the pull request it was read from. + const target = args.some(arg => arg.startsWith('target=')) ? { target: { pullRequest: { id: 'pull-' + number } } } : {} + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { id: 'pull-' + number, headRefOid: pulls[number].headRefOid, + reviews: { nodes: pending === null ? [] : [{ id: pending.id, viewerDidAuthor: true }] } } }, ...target } })) process.exit(0) } if (query.includes('pullRequest(number: $number)')) { - const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length)) - process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: pulls[number].headRefOid, baseRefOid: BASE } } } })) + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { + id: 'pull-' + number, headRefOid: pulls[number].headRefOid, baseRefOid: BASE, + } } } })) process.exit(0) } if (query.includes('node(id: $id)')) { @@ -191,7 +345,8 @@ if (args[0] === 'api' && args[1] === 'graphql') { process.exit(0) } const settings = { - squashMergeAllowed: true, mergeCommitAllowed: true, rebaseMergeAllowed: true, viewerPermission: 'WRITE', viewerDefaultMergeMethod: 'SQUASH', + squashMergeAllowed: true, mergeCommitAllowed: true, rebaseMergeAllowed: true, viewerPermission: overview.viewerPermission ?? 'WRITE', + viewerDefaultMergeMethod: 'SQUASH', } const data = {} let repository @@ -551,7 +706,7 @@ it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omi await header.click() 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.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor() + await change.getByText('等待评审', { exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'), await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE) await expect.poll(async () => { @@ -638,7 +793,7 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me const title = change.getByRole('link', { name: 'Add the pull request panel', exact: true }) await title.waitFor({ timeout: 20_000 }) // The only open change request starts expanded. - await change.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor() + await change.getByText('等待评审', { exact: true }).waitFor() // The random branch suffix can read as a duration, so the branch is replaced before the capture normalizes durations. await compareOrRefreshGolden(join(EXPECTED, 'panel.expected.md'), await captureStableAria(page, '[data-forge-panel]', scaffold.workspaceCwd, { replacements: [[branch, 'dsh-{{worktree}}']] }), MODE) @@ -647,7 +802,9 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me const checksRow = change.getByRole('button', { name: /^检查/ }) await checksRow.click() const checks = page.getByRole('menu') - await expect.poll(() => checks.getByRole('menuitem').allTextContents()).toEqual([expect.stringMatching(/^test/), expect.stringMatching(/^lint/)]) + // Failed checks are listed with the rerun; passed ones wait behind a toggle. + await expect.poll(() => checks.getByRole('menuitem').allTextContents()) + .toEqual(['重跑失败项', expect.stringMatching(/^test/), '显示其余 1 项(通过、跳过)']) const afterChecks = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[]) expect(afterChecks.filter(args => args.includes('id=rollup-7'))).toHaveLength(1) await page.keyboard.press('Escape') @@ -1028,7 +1185,10 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an expect(narrowComment.x + narrowComment.width).toBeLessThanOrEqual(390) await page.setViewportSize({ width: 1680, height: 1000 }) await panelFile.getByRole('button', { name: '开始评审', exact: true }).click() - await panelFile.locator('[data-forge-review-thread="pending"]').getByText('请核对边界条件', { exact: true }).waitFor() + // The comment starts the pending review on GitHub, and the threads read again show it there. + const pendingThread = panelFile.locator('[data-forge-thread="new-1"]') + await pendingThread.getByText('请核对边界条件', { exact: true }).waitFor({ timeout: 20_000 }) + await pendingThread.getByText('待提交', { exact: true }).waitFor() await page.setViewportSize({ width: 1680, height: 500 }) const changesScroll = view.locator('[data-forge-changes-scroll]') await changesScroll.evaluate((element) => { element.scrollTop = element.scrollHeight }) @@ -1059,11 +1219,16 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await captureStableAria(page, '[role="dialog"][aria-label="提交评审"]', scaffold.workspaceCwd), MODE) await reviewDialog.getByRole('button', { name: '提交评审', exact: true }).click() await page.getByRole('alert').filter({ hasText: '已提交评审' }).waitFor() - await panelFile.locator('[data-forge-review-thread="published"]').getByText('请核对边界条件', { exact: true }).waitFor() - await compareOrRefreshGolden(join(EXPECTED, 'review-record.expected.md'), await captureStableAria(page, '[data-forge-review-thread="published"]', scaffold.workspaceCwd), MODE) - const published: unknown = JSON.parse((await readFile(join(root, 'reviews.jsonl'), 'utf8')).trim()) - expect(published).toEqual({ endpoint: 'repos/octo/demo/pulls/7/reviews', body: { commit_id: HEAD7, event: 'REQUEST_CHANGES', body: '需要补充边界检查', - comments: [{ path: 'src/panel.ts', side: 'RIGHT', line: 4, start_line: 2, start_side: 'RIGHT', body: '请核对边界条件' }] } }) + await expect.poll(() => pendingThread.getByText('待提交', { exact: true }).count(), { timeout: 20_000 }).toBe(0) + await compareOrRefreshGolden(join(EXPECTED, 'review-record.expected.md'), + await captureStableAria(page, '[data-forge-thread="new-1"]', scaffold.workspaceCwd), MODE) + const mutations = (await readFile(join(root, 'mutations.jsonl'), 'utf8')).trim().split('\n').map((line): unknown => JSON.parse(line)) + expect(mutations).toEqual([ + { field: 'addPullRequestReview', variables: { pull: 'pull-7', commit: HEAD7, + threads: [{ path: 'src/panel.ts', body: '请核对边界条件', line: 4, side: 'RIGHT', startLine: 2, startSide: 'RIGHT' }] } }, + { field: 'submitPullRequestReview', variables: { review: 'review-1', event: 'REQUEST_CHANGES', body: '需要补充边界检查' } }, + ]) + expect(existsSync(join(root, 'reviews.jsonl'))).toBe(false) await page.getByRole('button', { name: '退出全屏', exact: true }).click() await panelFile.getByRole('button', { name: '6 行未变更', exact: true }).click() await panelFile.getByText('export const n6 = 6', { exact: true }).first().waitFor({ timeout: 20_000 }) @@ -1087,7 +1252,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an expect(await panelFile.evaluate((element, original) => element === original, originalFile)).toBe(true) await expect.poll(() => docsFile.getAttribute('data-expanded')).toBe(null) await expect.poll(() => scrollport.evaluate(element => element.scrollTop)).toBe(position) - expect(await panelFile.locator('[data-forge-review-thread="published"]').count()).toBe(1) + expect(await panelFile.locator('[data-forge-thread="new-1"]').count()).toBe(1) await page.setViewportSize({ width: 1680, height: 1000 }) await page.locator('[data-dockkit-tab]').filter({ hasText: '#7 的变更' }).locator('[data-dockkit-tab-close]').click() await expect.poll(() => view.count()).toBe(0) @@ -1360,7 +1525,9 @@ it.skipIf(MODE === 'record')('opens a comment from the hover plus in one press w expect(await file.getByRole('textbox').count()).toBe(0) await page.mouse.up() await file.getByRole('region', { name: '评论 R6–8', exact: true }).waitFor() - expect(await plus('R6').count()).toBe(0) + // The open editor leaves the hover plus for the next comment. + await code(3).hover() + expect(await plus('R3').isVisible()).toBe(true) await file.getByRole('button', { name: '取消', exact: true }).click() await file.getByRole('textbox').waitFor({ state: 'detached' }) @@ -1458,7 +1625,7 @@ it.skipIf(MODE === 'record')('keeps tall branch and changed-file menus aligned w expect(tripwire.warnings).toEqual([]) }) -it.skipIf(MODE === 'record')('keeps localized status columns separate and long file lists inside one vertical scroller', async () => { +it.skipIf(MODE === 'record')('aligns localized status rows by their glyphs and keeps long file lists inside one vertical scroller', async () => { const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-layout') await page.locator('[data-forge-current-branch]').waitFor() await compareOrRefreshGolden(join(EXPECTED, 'worktree-option.expected.md'), @@ -1514,38 +1681,36 @@ it.skipIf(MODE === 'record')('keeps localized status columns separate and long f for (const width of [1280, 390]) { await page.setViewportSize({ width, height: 700 }) await expect.poll(() => change.evaluate(element => element.getBoundingClientRect().right)).toBeLessThanOrEqual(width) - await change.getByText(labels[3], { exact: true }).hover() + // Each row names its fact for assistive technology only; the row starts with its glyph. + const rowOf = (label: string) => change.getByText(label, { exact: true }).locator('xpath=../..') + await rowOf(labels[3]).hover() + const offsets = new Set() for (const label of labels) { - const geometry = await change.getByText(label, { exact: true }).evaluate((element) => { - const value = element.nextElementSibling - if (value === null) throw new Error('Status label must have a value') - const range = document.createRange() - range.selectNodeContents(element) - const name = range.getBoundingClientRect() - const content = value.getBoundingClientRect() - const row = element.parentElement! - const icon = element.previousElementSibling! + const geometry = await rowOf(label).evaluate((row) => { + const icon = row.firstElementChild! + const cell = icon.nextElementSibling! + const value = cell.lastElementChild! + const trailing = cell.nextElementSibling?.matches('[class*="rowTrailing"]') === true ? cell.nextElementSibling : null const rowRect = row.getBoundingClientRect() + const content = value.getBoundingClientRect() return { - gap: content.left - name.right, iconInset: icon.getBoundingClientRect().left - rowRect.left, rowInset: rowRect.left - row.closest('[data-forge-change]')!.getBoundingClientRect().left, - labelWidth: element.getBoundingClientRect().width, valueOffset: content.left - rowRect.left, - right: content.right, + gap: trailing === null ? 8 : trailing.getBoundingClientRect().left - content.right, + right: Math.max(content.right, trailing?.getBoundingClientRect().right ?? 0), width: document.documentElement.clientWidth, } }) - expect(geometry.gap).toBeGreaterThanOrEqual(8) expect(geometry.iconInset).toBe(8) expect(geometry.rowInset).toBeGreaterThanOrEqual(6) expect(geometry.rowInset).toBeLessThanOrEqual(7) - if (locale === 'zh') { - expect(geometry.labelWidth).toBe(32) - expect(geometry.valueOffset).toBe(76) - } + offsets.add(geometry.valueOffset) + expect(geometry.gap).toBeGreaterThanOrEqual(8) expect(geometry.right).toBeLessThanOrEqual(geometry.width) } + // Every value starts in the same column after its glyph. + expect([...offsets]).toEqual([32]) } } expect(tripwire.pageErrors).toEqual([]) @@ -1726,7 +1891,7 @@ it.skipIf(MODE === 'record').each([120, 4000])('types a review comment beside %i expect(await file.getByRole('button', { name: '开始评审', exact: true }).isDisabled()).toBe(true) await input.fill('检查边界条件') await file.getByRole('button', { name: '开始评审', exact: true }).click() - await file.locator('[data-forge-review-thread="pending"]').getByText('检查边界条件', { exact: true }).waitFor() + await file.locator('[data-forge-thread]').getByText('检查边界条件', { exact: true }).waitFor({ timeout: 20_000 }) expect(tripwire.pageErrors).toEqual([]) }) @@ -1785,6 +1950,8 @@ it.skipIf(MODE === 'record')('reviews a change request by layer, hides test file await page.keyboard.press('v') await expect.poll(() => panel.getAttribute('data-viewed')).toBe('viewed') await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 2 / 3') + // Each mark stays disabled until GitHub saved it. + await expect.poll(() => view.getByRole('checkbox', { disabled: true }).count()).toBe(0) await compareOrRefreshGolden(join(EXPECTED, 'review-layers.expected.md'), await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE) @@ -1863,18 +2030,21 @@ it.skipIf(MODE === 'record')('keeps local viewed marks across reloads, clears a expect(tripwire.pageErrors).toEqual([]) }) -/** One review thread node of pull request 7 as the GraphQL thread read returns it, its comments by `lin` then `octo`. */ +/** + * One review thread node of pull request 7 as the GraphQL thread read returns it, its comments by `lin`, the viewer, then + * `octo`, the pull request's author; the viewer may reply, resolve, and change their own comments. + */ function threadNode( id: string, fields: Record, bodies: readonly string[], commit: string = HEAD7, ): Record { return { id, isOutdated: false, isResolved: false, path: 'src/panel.ts', diffSide: 'RIGHT', startDiffSide: null, line: null, startLine: null, - originalLine: null, originalStartLine: null, subjectType: 'LINE', ...fields, + originalLine: null, originalStartLine: null, subjectType: 'LINE', viewerCanReply: true, viewerCanResolve: true, viewerCanUnresolve: true, ...fields, root: { nodes: [{ diffHunk: '@@ -1,5 +1,5 @@\n export const n1 = 1\n-export const n2 = 2\n+export const n2 = \'two\'', commit: { oid: commit }, originalCommit: { oid: commit } }] }, comments: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: bodies.map((body, index) => ({ id: `${id}-${index}`, state: 'SUBMITTED', createdAt: '2026-10-09T00:00:00Z', url: `${PULL}#discussion_${id}_${index}`, body, - author: { __typename: 'User', login: index === 0 ? 'lin' : 'octo', avatarUrl: null }, + viewerCanUpdate: index === 0, viewerCanDelete: index === 0, author: { __typename: 'User', login: index === 0 ? 'lin' : 'octo', avatarUrl: null }, })) }, } } @@ -1897,10 +2067,14 @@ it.skipIf(MODE === 'record')('overlays the review threads of a change request an const panel = view.locator('[data-forge-diff-file="src/panel.ts"]') const onLine = panel.locator('[data-forge-thread="on-line"]') await onLine.getByText('two', { exact: true }).waitFor({ timeout: 20_000 }) - // The thread follows the row of its last line, under the new side. - expect(await onLine.evaluate(card => card.previousElementSibling?.querySelector('[data-new-line]')?.textContent)).toBe('export const n2 = \'two\'') - expect(await panel.locator('[data-forge-thread="old-side"]').evaluate(card => card.previousElementSibling?.querySelector('[data-old-line]')?.textContent)) - .toBe('export const n15 = 15') + // The thread follows the row of its last line, in the column of its side: under the new side and the old side. + const placement = (card: Element, number: string) => { + const row = card.closest('[data-forge-notes]') + const column = Array.from(row?.children ?? []).findIndex(cell => cell.contains(card)) + return { line: row?.previousElementSibling?.querySelector(number)?.textContent, column } + } + expect(await onLine.evaluate(placement, '[data-new-line]')).toEqual({ line: 'export const n2 = \'two\'', column: 1 }) + expect(await panel.locator('[data-forge-thread="old-side"]').evaluate(placement, '[data-old-line]')).toEqual({ line: 'export const n15 = 15', column: 0 }) await panel.locator('[data-forge-thread="resolved"]').getByText('已解决的讨论 · lin', { exact: true }).waitFor() await panel.locator('[data-forge-outdated-threads]').getByText('1 条讨论已过期:所在代码已被后续提交修改', { exact: true }).waitFor() await view.locator('[data-forge-diff-file="docs/panel.md"] [data-forge-thread="whole-file"]').getByText('文件级讨论', { exact: true }).waitFor() @@ -1955,12 +2129,75 @@ it.skipIf(MODE === 'record')('overlays the review threads of a change request an expect(quotes).toHaveLength(1) await compareOrRefreshGolden(join(EXPECTED, 'review-thread-message.expected.md'), quotes.join('').trimEnd(), MODE) const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[]) - const reads = calls.filter(args => args.some(arg => arg.startsWith('query=') && arg.includes('{ id headRefOid reviewThreads(first: $first)'))) + const reads = calls.filter(args => args.some(arg => arg.startsWith('query=') && arg.includes('viewer { login }'))) expect(reads.length).toBeGreaterThan(0) expect(reads[0]).toEqual(expect.arrayContaining(['owner=octo', 'name=demo', 'number=7', 'first=100'])) expect(tripwire.pageErrors).toEqual([]) }) +it.skipIf(MODE === 'record')('replies to, edits, deletes, and resolves review threads, and discards a pending review started from a reply', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-writes') + await writeFile(join(root, 'threads.json'), JSON.stringify(THREADS)) + await page.clock.setFixedTime(Date.parse('2026-10-09T02:00:00Z')) + const { view } = await openReview(page, scaffold) + const panel = view.locator('[data-forge-diff-file="src/panel.ts"]') + const onLine = panel.locator('[data-forge-thread="on-line"]') + await onLine.getByText('two', { exact: true }).waitFor({ timeout: 20_000 }) + + await onLine.getByRole('button', { name: '回复…', exact: true }).click() + await onLine.getByRole('textbox', { name: '回复…', exact: true }).fill('已改为字符串') + await compareOrRefreshGolden(join(EXPECTED, 'review-thread-reply.expected.md'), + await captureStableAria(page, '[data-forge-thread="on-line"]', scaffold.workspaceCwd), MODE) + await onLine.getByRole('button', { name: '回复', exact: true }).click() + await onLine.getByText('已改为字符串', { exact: true }).waitFor({ timeout: 20_000 }) + + await onLine.getByRole('button', { name: 'lin 的评论操作', exact: true }).first().click() + await page.getByRole('menuitem', { name: '编辑', exact: true }).click() + await onLine.getByRole('textbox', { name: '编辑评论', exact: true }).fill('Why a **word**?') + await onLine.getByRole('button', { name: '保存', exact: true }).click() + await onLine.getByText('word', { exact: true }).waitFor({ timeout: 20_000 }) + + await onLine.getByRole('button', { name: 'lin 的评论操作', exact: true }).last().click() + await page.getByRole('menuitem', { name: '删除', exact: true }).click() + await onLine.getByRole('group', { name: '删除这条评论?', exact: true }).getByRole('button', { name: '删除', exact: true }).click() + await expect.poll(() => onLine.getByText('已改为字符串', { exact: true }).count(), { timeout: 20_000 }).toBe(0) + + await onLine.getByRole('button', { name: '解决讨论', exact: true }).click() + await onLine.getByText('已解决的讨论 · lin', { exact: true }).waitFor({ timeout: 20_000 }) + + const oldSide = panel.locator('[data-forge-thread="old-side"]') + await oldSide.getByRole('button', { name: '回复…', exact: true }).click() + await oldSide.getByRole('textbox', { name: '回复…', exact: true }).fill('稍后一起提交') + await oldSide.getByRole('button', { name: '回复选项', exact: true }).click() + await page.getByRole('menuitem', { name: '开始评审', exact: true }).click() + await oldSide.getByText('待提交', { exact: true }).waitFor({ timeout: 20_000 }) + await view.getByRole('button', { name: '提交评审 (1)', exact: true }).click() + const dialog = page.getByRole('dialog', { name: '提交评审', exact: true }) + await dialog.getByRole('button', { name: '丢弃评审', exact: true }).click() + await compareOrRefreshGolden(join(EXPECTED, 'discard-review.expected.md'), + await captureStableAria(page, '[role="dialog"][aria-label="提交评审"]', scaffold.workspaceCwd), MODE) + await dialog.getByRole('group', { name: '丢弃评审', exact: true }).getByRole('button', { name: '丢弃评审', exact: true }).click() + await page.getByRole('alert').filter({ hasText: '已丢弃评审' }).waitFor() + await expect.poll(() => oldSide.getByText('稍后一起提交', { exact: true }).count(), { timeout: 20_000 }).toBe(0) + await view.getByRole('button', { name: '提交评审', exact: true }).waitFor() + + const mutations = (await readFile(join(root, 'mutations.jsonl'), 'utf8')).trim().split('\n').map((line): unknown => JSON.parse(line)) + expect(mutations).toEqual([ + { field: 'addPullRequestReviewThreadReply', variables: { thread: 'on-line', body: '已改为字符串', review: null } }, + { field: 'updatePullRequestReviewComment', variables: { comment: 'on-line-0', body: 'Why a **word**?' } }, + { field: 'deletePullRequestReviewComment', variables: { comment: 'on-line-reply-0' } }, + { field: 'resolveReviewThread', variables: { thread: 'on-line' } }, + { field: 'addPullRequestReview', variables: { pull: 'pull-7', commit: HEAD7, threads: null } }, + { field: 'addPullRequestReviewThreadReply', variables: { thread: 'old-side', body: '稍后一起提交', review: 'review-1' } }, + { field: 'deletePullRequestReview', variables: { review: 'review-1' } }, + ]) + // Every write checked the head of pull request 7 first. + const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[]) + expect(calls.filter(args => args.some(arg => arg.startsWith('query=') && arg.includes('reviews(states: PENDING') && !arg.includes('viewer { login }')))) + .toHaveLength(mutations.length - 1) + expect(tripwire.pageErrors).toEqual([]) +}) + it.skipIf(MODE === 'record')('keeps a narrow file header\'s viewed mark and menu inside its card and its name under the pointer', async () => { const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-narrow-header', 'normal', { branch: 'feat' }) const from = 'src/original-review-module-with-a-long-name.ts' @@ -2008,3 +2245,294 @@ it.skipIf(MODE === 'record')('keeps a narrow file header\'s viewed mark and menu await expect.poll(() => file.getAttribute('data-viewed')).toBe('viewed') expect(tripwire.pageErrors).toEqual([]) }) + +/** One GraphQL mutation the GitHub CLI double received: the mutation field and its variables. */ +interface GhMutation { + readonly field: string + readonly variables: Record +} + +/** GraphQL mutations the GitHub CLI double received, in order. */ +async function mutationsOf(root: string): Promise { + const text = await readFile(join(root, 'mutations.jsonl'), 'utf8').catch(() => '') + return text.split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as GhMutation) +} + +/** REST paths of the check reruns the GitHub CLI double received, in order. */ +async function rerunsOf(root: string): Promise { + return (await readFile(join(root, 'reruns.jsonl'), 'utf8').catch(() => '')).split('\n').filter(line => line.length > 0) +} + +it.skipIf(MODE === 'record')('reads and saves the viewed files of a change request on GitHub, keeping chosen commits in the browser', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-viewed-sync') + await writeReviewFixture(root) + await writeFile(join(root, 'viewed.json'), JSON.stringify({ 'docs/panel.md': 'VIEWED', 'src/panel.ts': 'DISMISSED' })) + const { view } = await openReview(page, scaffold) + const docs = view.locator('[data-forge-diff-file="docs/panel.md"]') + const panel = view.locator('[data-forge-diff-file="src/panel.ts"]') + const manifest = view.locator('[data-forge-diff-file="package.json"]') + const progress = view.getByRole('progressbar', { name: '已审阅的文件', exact: true }) + await expect.poll(() => docs.getAttribute('data-viewed')).toBe('viewed') + expect(await docs.getAttribute('data-expanded')).toBe(null) + await expect.poll(() => panel.getAttribute('data-viewed')).toBe('changed') + await panel.getByText('有新改动', { exact: true }).waitFor() + await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 1 / 6') + + await manifest.getByRole('checkbox', { name: '将 package.json 标记为已审阅', exact: true }).check() + await expect.poll(() => manifest.getAttribute('data-viewed')).toBe('viewed') + await expect.poll(async () => (await mutationsOf(root)).map(entry => [entry.field, entry.variables.path])) + .toEqual([['markFileAsViewed', 'package.json']]) + await docs.getByRole('checkbox', { name: '将 panel.md 标记为已审阅', exact: true }).uncheck() + await expect.poll(() => docs.getAttribute('data-viewed')).toBe('unviewed') + await expect.poll(async () => (JSON.parse(await readFile(join(root, 'state.json'), 'utf8')) as { readonly viewed?: Record }).viewed) + .toEqual({ 'package.json': 'VIEWED', 'docs/panel.md': 'UNVIEWED' }) + + // A refused mark returns to what GitHub keeps and says why. + await writeFile(join(root, 'viewed.refused'), 'Resource not accessible by integration') + const spec = view.locator('[data-forge-diff-file="src/panel.spec.ts"]') + await spec.getByRole('checkbox', { name: '将 panel.spec.ts 标记为已审阅', exact: true }).check() + await page.getByText('已审阅状态未能保存到 GitHub:Resource not accessible by integration', { exact: true }).waitFor() + await expect.poll(() => spec.getAttribute('data-viewed')).toBe('unviewed') + await rm(join(root, 'viewed.refused')) + + // GitHub keeps the marks, so a reload reads them again. + await page.reload() + await view.locator('[data-forge-diff-file="package.json"]').waitFor({ timeout: 20_000 }) + await expect.poll(() => manifest.getAttribute('data-viewed')).toBe('viewed') + await expect.poll(() => docs.getAttribute('data-viewed')).toBe('unviewed') + + // Without GitHub's marks no file can be marked, and the notice offers to read them again. + await writeFile(join(root, 'viewed.unreadable'), 'API rate limit exceeded') + await view.getByRole('button', { name: '刷新变更', exact: true }).click() + await view.getByText('未能读取 GitHub 上的已审阅状态,暂时不能标记文件:API rate limit exceeded', { exact: true }).waitFor({ timeout: 20_000 }) + expect(await manifest.getByRole('checkbox', { name: '将 package.json 标记为已审阅', exact: true }).isDisabled()).toBe(true) + await rm(join(root, 'viewed.unreadable')) + await view.getByRole('button', { name: '重试', exact: true }).click() + await expect.poll(() => manifest.getAttribute('data-viewed'), { timeout: 20_000 }).toBe('viewed') + expect(await manifest.getByRole('checkbox', { name: '将 package.json 标记为已审阅', exact: true }).isDisabled()).toBe(false) + + // Chosen commits keep their marks in the browser. + await view.getByRole('button', { name: '查看的提交:全部提交', exact: true }).click() + await page.locator(`[data-forge-commit="${'2'.repeat(40)}"]`).click() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['locale/zh.json', 'src/panel.spec.ts']) + const before = (await mutationsOf(root)).length + await spec.getByRole('checkbox', { name: '将 panel.spec.ts 标记为已审阅', exact: true }).check() + await expect.poll(() => spec.getAttribute('data-viewed')).toBe('viewed') + expect((await mutationsOf(root)).length).toBe(before) + + await page.setViewportSize({ width: 390, height: 844 }) + await view.getByRole('button', { name: '查看的提交:2222222', exact: true }).click() + await page.locator('[data-forge-commit-menu]').getByRole('menuitem', { name: /^全部提交/ }).click() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toHaveLength(6) + expect(tripwire.pageErrors).toEqual([]) +}) + +/** Pull request 7 with failed, running, passed, and skipped checks, five reviewers, a branch behind its base, and two closing issues. */ +const OVERVIEW = { + viewerPermission: 'WRITE', + viewerCanUpdateBranch: true, + canBeRebased: true, + checks: { + pageInfo: { hasNextPage: false, endCursor: null }, + nodes: [ + ...[['node 24 / static', 'FAILURE', 11], ['windows / coverage', 'FAILURE', 12], ['lint', 'SUCCESS', 13], ['typecheck', 'SUCCESS', 14], + ['docs', 'SKIPPED', 15]].map(([name, conclusion, id]) => ({ + __typename: 'CheckRun', id: `check-${String(id)}`, name, status: 'COMPLETED', conclusion, databaseId: id, + detailsUrl: `https://github.com/octo/demo/actions/runs/41/job/${String(id)}`, startedAt: '2026-10-09T00:00:00Z', completedAt: '2026-10-09T00:04:12Z', + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: 41, event: 'pull_request', workflow: { id: 'ci', name: 'CI' } } }, + })), + { + __typename: 'CheckRun', id: 'check-16', name: 'e2e / web', status: 'IN_PROGRESS', conclusion: null, databaseId: 16, + detailsUrl: 'https://github.com/octo/demo/actions/runs/42/job/16', startedAt: '2026-10-09T00:00:00Z', completedAt: null, + checkSuite: { app: { id: 'github-actions' }, workflowRun: { databaseId: 42, event: 'pull_request', workflow: { id: 'e2e', name: 'E2E' } } }, + }, + { __typename: 'StatusContext', context: 'ci/jenkins', state: 'FAILURE', targetUrl: 'https://ci.example.test/7', createdAt: '2026-10-09T00:01:00Z' }, + ], + }, + reviewRequests: { totalCount: 2, nodes: [ + { asCodeOwner: false, requestedReviewer: { __typename: 'User', login: 'lin-reviewer', avatarUrl: null } }, + { asCodeOwner: true, requestedReviewer: { __typename: 'Team', combinedSlug: 'octo/forge', avatarUrl: null } }, + ] }, + latestReviews: { totalCount: 1, nodes: [{ state: 'COMMENTED', commit: { oid: HEAD7 }, author: { __typename: 'Bot', login: 'review-bot', avatarUrl: null } }] }, + latestOpinionatedReviews: { totalCount: 2, nodes: [ + { state: 'CHANGES_REQUESTED', commit: { oid: '1'.repeat(40) }, author: { __typename: 'User', login: 'zhou-dev', avatarUrl: null } }, + { state: 'APPROVED', commit: { oid: HEAD7 }, author: { __typename: 'User', login: 'qian-dev', avatarUrl: null } }, + ] }, + closingIssues: { totalCount: 2, nodes: [ + { number: 6, title: 'Show review progress in the panel', state: 'OPEN', url: 'https://github.com/octo/demo/issues/6', + repository: { name: 'demo', owner: { login: 'octo' } } }, + { number: 12, title: 'Rerun failed checks from DSH', state: 'OPEN', url: 'https://github.com/octo/tracker/issues/12', + repository: { name: 'tracker', owner: { login: 'octo' } } }, + ] }, +} + +it.skipIf(MODE === 'record')('summarizes checks, reviewers, and the merge state in one line each and acts on them from their menus', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-overview') + await writeFile(join(root, 'overview.json'), JSON.stringify(OVERVIEW)) + const { settled } = await sendPrompt(page, scaffold) + const session = scaffold.ctx.sessions.get(await settled) + if (session === undefined) throw new Error('Session must stay loaded') + scaffold.ctx.forgeSession.track(session, PULL) + await page.locator('[data-forge-header]').click() + 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 }) + 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 项进行中') + await expect.poll(() => card.locator('[data-forge-threads]').getAttribute('data-forge-threads')).toBe('1') + + // The checks menu lists what needs attention and the rest on request; the external status names no rerun. + await checks.click() + const menu = page.getByRole('menu') + await expect.poll(() => menu.locator('[data-forge-check-group]').evaluateAll(nodes => nodes.map(node => node.getAttribute('data-forge-check-group')))) + .toEqual(['failed', 'running']) + await menu.getByRole('menuitem', { name: '显示其余 3 项(通过、跳过)', exact: true }).waitFor() + await menu.getByRole('menuitem', { name: '重跑失败项', exact: true }).click() + await page.getByText('已请求重跑 #7 的检查', { exact: true }).waitFor() + expect(await rerunsOf(root)).toEqual(['repos/octo/demo/actions/runs/41/rerun-failed-jobs']) + + // The review row shows the first avatars; its menu lists every reviewer and the requests. + const review = card.locator('[data-forge-review]') + await review.click() + await expect.poll(() => menu.locator('[data-forge-reviewer]').evaluateAll(nodes => nodes.map(node => node.getAttribute('data-forge-reviewer')))) + .toEqual(['lin-reviewer', 'octo/forge', 'review-bot', 'zhou-dev', 'qian-dev']) + await menu.getByRole('menuitem', { name: '请求其他人评审…', exact: true }).click() + await menu.getByRole('menuitem', { name: /lin-reviewer/ }).waitFor() + await page.keyboard.type('mon') + await menu.getByRole('menuitem', { name: /^mona/ }).click() + await page.getByText('已请求 mona 评审 #7', { exact: true }).waitFor() + await review.click() + await menu.getByRole('menuitem', { name: '重新请求 zhou-dev 评审', exact: true }).click() + await expect.poll(async () => (await mutationsOf(root)).filter(entry => entry.field === 'requestReviews').map(entry => entry.variables.input)) + .toEqual([ + { pullRequestId: 'pull-7', union: true, userIds: ['user-mona'] }, + { pullRequestId: 'pull-7', union: true, userIds: ['user-zhou-dev'] }, + ]) + + // The linked issues take one row, each a link named by its number with its title in the name. + const issues = card.locator('[data-forge-closing-issues]') + expect(await issues.textContent()).toBe('关联 issue #6、octo/tracker#12') + await issues.getByRole('link', { name: '打开 issue #6:Show review progress in the panel', exact: true }).waitFor() + await issues.getByRole('link', { name: '打开 issue octo/tracker#12:Rerun failed checks from DSH', exact: true }).waitFor() + + const update = card.locator('[data-forge-update-branch]') + await expect.poll(() => update.textContent()).toBe('合并无冲突 · 落后于 main更新分支') + await update.click() + await page.getByRole('menuitem', { name: /^变基更新/ }).click() + await page.getByRole('menuitem', { name: '确认更新', exact: true }).click() + await page.getByText('已开始更新 #7 的分支', { exact: true }).waitFor() + expect((await mutationsOf(root)).at(-1)?.variables.input).toEqual({ pullRequestId: 'pull-7', expectedHeadOid: HEAD7, updateMethod: 'REBASE' }) + await expect.poll(() => update.count(), { timeout: 20_000 }).toBe(0) + + expect(tripwire.pageErrors).toEqual([]) +}) + +/** + * Launch the panel on a branch whose README.md replaces its first line and adds eight more, so a side-by-side view + * pairs a deletion with an addition, then open the Session's local changes full screen. + * @param failureShot - screenshot name for a failure. + * @returns the launch and the local changes view. + */ +async function openLocalChanges(failureShot: string): Promise { + const launch = await launchPanel(failureShot) + const { scaffold, page, project } = launch + await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + await writeFile(join(project, 'README.md'), `changed\n${Array.from({ length: 8 }, (_, line) => `line ${line + 2}\n`).join('')}`) + await writeFile(join(project, 'notes.md'), 'note\n') + const { settled } = await sendPrompt(page, scaffold) + await settled + await page.locator('[data-forge-header]').click() + await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() + await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更/ }).click() + const view = page.locator('[data-forge-changes="local"]') + await view.locator('[data-forge-diff-file="README.md"]').waitFor() + await page.getByRole('button', { name: '全屏', exact: true }).click() + return { ...launch, view } +} + +it.skipIf(MODE === 'record')('keeps the changes toolbar and header on one line, folding view controls into the More menu as they narrow', async () => { + const { page, view, tripwire } = await openLocalChanges('web-e2e-forge-toolbar-fold') + const toolbar = view.locator('[data-fold]') + const more = toolbar.getByRole('button', { name: '更多视图选项', exact: true }) + const create = view.getByRole('button', { name: '创建变更请求', exact: true }) + const layout = () => toolbar.evaluate((row) => { + const header = row.closest('[data-forge-changes]')!.firstElementChild! + return { fold: row.getAttribute('data-fold'), overflow: row.scrollWidth - row.clientWidth, height: row.getBoundingClientRect().height, + header: header.getBoundingClientRect().height } + }) + // The button keeps a fixed height when its label wraps, so the label's own height tells one line from two. + const labelHeight = () => create.evaluate((button) => { + const range = document.createRange() + range.selectNodeContents(button) + return Math.round(range.getBoundingClientRect().height) + }) + const lineHeight = await labelHeight() + const seen: string[] = [] + for (const width of [1680, 700, 560, 390, 340]) { + await page.setViewportSize({ width, height: 800 }) + await expect.poll(async () => (await layout()).overflow).toBeLessThanOrEqual(0) + const { fold, height, header } = await layout() + // One 28px control row inside the toolbar's padding, and the header keeps its single-line height. + expect([width, height]).toEqual([width, 38]) + expect([width, header]).toEqual([width, 44]) + expect([width, await labelHeight()]).toEqual([width, lineHeight]) + seen.push(`${width}:${fold}`) + } + expect(seen[0]).toBe('1680:0') + expect(seen.at(-1)).toBe('340:3') + expect(await more.isVisible()).toBe(true) + + await page.setViewportSize({ width: 390, height: 800 }) + await expect.poll(() => toolbar.getAttribute('data-fold')).toBe('2') + // Folded controls leave the row; the progress turns into the ring and the bare count. + expect(await toolbar.getByRole('button', { name: '左右对比', exact: true }).isVisible()).toBe(false) + expect(await toolbar.getByRole('switch', { name: '隐藏测试文件', exact: true }).isVisible()).toBe(false) + expect(await toolbar.locator('[data-forge-progress="compact"]').innerText()).toBe('0/2') + await more.click() + const menu = page.getByRole('menu') + expect(await menu.getByRole('menuitem').allTextContents()).toEqual(['全部折叠', '左右对比', '自动换行', '隐藏测试文件']) + const code = view.locator('[data-forge-diff-file="README.md"] [data-review]') + expect(await code.getAttribute('data-split')).toBe('') + await menu.getByRole('menuitem', { name: '左右对比', exact: true }).click() + await expect.poll(() => code.getAttribute('data-split')).toBe(null) + expect(await page.getByRole('menu').count()).toBe(0) + await page.setViewportSize({ width: 1680, height: 800 }) + await expect.poll(() => toolbar.getAttribute('data-fold')).toBe('0') + expect(await more.isVisible()).toBe(false) + expect(await toolbar.getByRole('button', { name: '左右对比', exact: true }).getAttribute('aria-pressed')).toBe('false') + expect(tripwire.pageErrors).toEqual([]) +}) + +it.skipIf(MODE === 'record')('writes a left and a right comment at once, each inside its own column of the side-by-side row', async () => { + const { page, view, tripwire } = await openLocalChanges('web-e2e-forge-side-comments') + const readme = view.locator('[data-forge-diff-file="README.md"]') + const open = async (name: string) => { + await readme.getByRole('button', { name: `选择第 ${name} 行`, exact: true }).click() + await readme.getByRole('button', { name: '添加评论', exact: true }).click() + return readme.getByRole('region', { name: `评论 ${name}`, exact: true }) + } + const left = await open('L1') + const right = await open('R1') + await right.getByRole('textbox').fill('右侧的评论') + for (const width of [1680, 1000, 780]) { + await page.setViewportSize({ width, height: 900 }) + const boxes = await readme.evaluate((section) => { + const pair = section.querySelector('[data-diff-pair]')! + const [l, r] = Array.from(pair.children, cell => cell.getBoundingClientRect()) + const [a, b] = Array.from(section.querySelectorAll('[data-forge-comment]'), form => form.getBoundingClientRect()) + return { l: [l!.left, l!.right], r: [r!.left, r!.right], a: [a!.left, a!.right, a!.top], b: [b!.left, b!.right, b!.top] } + }) + // Each comment stays inside its side's column, and both share one row. + expect(boxes.a[0]!).toBeGreaterThan(boxes.l[0]!) + expect(boxes.a[1]!).toBeLessThan(boxes.l[1]!) + expect(boxes.b[0]!).toBeGreaterThan(boxes.r[0]!) + expect(boxes.b[1]!).toBeLessThan(boxes.r[1]!) + expect(boxes.a[2]).toBe(boxes.b[2]) + } + await left.getByRole('button', { name: '取消', exact: true }).click() + expect(await left.count()).toBe(0) + expect(await right.getByRole('textbox').inputValue()).toBe('右侧的评论') + expect(tripwire.pageErrors).toEqual([]) +}) diff --git a/apps/web/tests/markdown-cjk-strong.e2e.ts b/apps/web/tests/markdown-cjk-strong.e2e.ts index 4d9594d771..3da0d0df9b 100644 --- a/apps/web/tests/markdown-cjk-strong.e2e.ts +++ b/apps/web/tests/markdown-cjk-strong.e2e.ts @@ -125,6 +125,36 @@ describe('web e2e: CJK-adjacent Markdown strong emphasis', () => { expect(await page.getByText(paragraph, { exact: true }).count()).toBe(1) } + const viewport = page.viewportSize()! + try { + for (const size of [{ width: 390, height: 844 }, { width: 951, height: 669 }, { width: 669, height: 951 }]) { + await page.setViewportSize(size) + expect(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('-webkit-text-size-adjust'))) + .toBe('100%') + expect(await strong.evaluateAll(elements => elements.map(element => getComputedStyle(element).fontSize))) + .toEqual(CASES.map(() => '14px')) + } + const restoreFont = await page.evaluateHandle(() => { + const style = document.body.style + const before = style.getPropertyValue('--dsh-content-font-size') + const priority = style.getPropertyPriority('--dsh-content-font-size') + style.setProperty('--dsh-content-font-size', '18px') + return () => { + if (before) style.setProperty('--dsh-content-font-size', before, priority) + else style.removeProperty('--dsh-content-font-size') + } + }) + try { + expect(await strong.evaluateAll(elements => elements.map(element => getComputedStyle(element).fontSize))) + .toEqual(CASES.map(() => '18px')) + } finally { + await restoreFont.evaluate((restore) => { restore() }) + await restoreFont.dispose() + } + } finally { + await page.setViewportSize(viewport) + } + const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) .split(SEED_ID).join('{{seededId}}') await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) diff --git a/apps/web/tests/minimal-preset.snapshot.ts b/apps/web/tests/minimal-preset.snapshot.ts index c3d5ebe4c1..76b05241c2 100644 --- a/apps/web/tests/minimal-preset.snapshot.ts +++ b/apps/web/tests/minimal-preset.snapshot.ts @@ -27,7 +27,7 @@ import { webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts' +import { expandOwningTurnProcess, loadEarlierChatPage, newEnglishPage, saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/minimal-preset', import.meta.url)) const FIXTURE = join(SNAPSHOT_DIR, 'session.v3.jsonl') @@ -485,7 +485,7 @@ describe('minimal image reading', () => { page = await openSession(pagedId) await page.getByText('Later image-history message 53', { exact: true }).waitFor() expect(await page.locator('[data-tool="read_image"]').count()).toBe(0) - await page.getByRole('button', { name: 'Load earlier', exact: true }).click() + await loadEarlierChatPage(page) card = await imageCard(page) await expect.poll(() => card.locator('img').first().evaluate(img => img instanceof HTMLImageElement && img.naturalWidth)).toBe(1) diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index afc484f543..9efe21e8fd 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -796,7 +796,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { const callId = ToolCallId('long-ptc-result') const call = agent.session.append('tool/call', { turn: 3, step: 1, callId, name: 'run_code', - arguments: JSON.stringify({ code: 'console.log("PTC output")', description: 'Long program output' }), + arguments: JSON.stringify({ code: 'inspect("PTC output")', description: 'Long program output' }), }) await page.getByRole('tab', { name: 'Trajectory' }).click() await page.locator('tr[data-kind="tool"]').filter({ hasText: 'Long program output' }).click() diff --git a/apps/web/tests/official-subagent-bundle.e2e.ts b/apps/web/tests/official-subagent-bundle.e2e.ts index 8dad28b2a1..50ed955adc 100644 --- a/apps/web/tests/official-subagent-bundle.e2e.ts +++ b/apps/web/tests/official-subagent-bundle.e2e.ts @@ -141,7 +141,7 @@ describe.skipIf(MODE === 'record')('web snapshot: Official native subagent bundl const firstTurnEvents = agent.session.snapshotEvents() const toolResults = firstTurnEvents.filter(event => event.type === 'tool/result').map(event => event.data) expect(toolResults, `PTC execution must start the native child before waiting for its result: ${JSON.stringify(toolResults)}`) - .toMatchObject([{ message: { isError: false, content: [{ type: 'text', text: 'agent-1' }] } }]) + .toMatchObject([{ message: { isError: false, content: [{ type: 'text', text: 'agent-1\n' }] } }]) const dispatches = firstTurnEvents.filter(event => event.type === 'tool/ptc-dispatch').map(event => event.data) expect(dispatches).toMatchObject([{ name: 'subagent_claude_code', isError: false }]) const catalog = firstTurnEvents.filter(event => event.type === 'subagent/catalog').map(event => event.data) diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 66bd3cfb1d..0c355a4388 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -857,7 +857,7 @@ describe('web e2e: plugin manager', () => { && bundle.name !== '@deepseek-ai/dsh-experimental-liveshare' && bundle.official && (bundle.listedByDefault !== false || bundle.enabled || bundle.installed)).length) // Computer Use ships with the installation and is listed only on the macOS Hosts it supports. - const cuaSupported = process.platform === 'darwin' + const cuaSupported = process.platform === 'darwin' || process.platform === 'win32' expect(bundles.find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle')) .toMatchObject({ enabled: false, optional: true, availability: 'installation', ...cuaSupported ? {} : { listedByDefault: false } }) expect(await panel.locator('[data-plugin-group="more"] [data-plugin-package="@deepseek-ai/dsh-cua-bundle"]').count()) diff --git a/apps/web/tests/present.e2e.ts b/apps/web/tests/present.e2e.ts index c8d4abc172..ac732c5c54 100644 --- a/apps/web/tests/present.e2e.ts +++ b/apps/web/tests/present.e2e.ts @@ -57,7 +57,8 @@ fs.appendFileSync(${JSON.stringify(openLog)}, JSON.stringify({ path, action, con openInAppEnvironment: createLaunchEnvironmentSnapshot([{ source: 'process', values: { SSH_CONNECTION: '10.0.0.2 55000 10.0.0.9 22' } }]), extraOverlayPath: fileURLToPath(new URL('./present.overlay.yml', import.meta.url)), agentPresets: { default: 'ptc' }, compareReplaySession: true, - ...(MODE === 'record' ? {} : { replayFixture: FIXTURE }), + // The recorded UI includes decode throughput from an incremental stream. + ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }), }) // File associations belong to the desktop rather than the recorded Session. const controller = scaffold.ctx.get('sessionController') diff --git a/apps/web/tests/ptc-escalation.e2e.ts b/apps/web/tests/ptc-escalation.e2e.ts index 3f3a74a65a..e8a941216e 100644 --- a/apps/web/tests/ptc-escalation.e2e.ts +++ b/apps/web/tests/ptc-escalation.e2e.ts @@ -9,7 +9,7 @@ import type { SessionEvent } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-user-approval' import { assertFinalWorkspaceSnapshot, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, - launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold, + launchWebScaffold, recordFixture, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' @@ -19,7 +19,7 @@ const UI_EXPECTED = join(SNAPSHOT_DIR, 'approval.expected.md') const MODE = webSnapshotMode() const PROMPT = 'Use run_code with timeoutMs 120000 and direct Node filesystem access to create approved.txt in the working directory containing exactly "approved\\n". ' + 'Use await import("node:fs/promises") and writeFile; do not call nested tools. First attempt the write under the current read-only sandbox without escalation. ' - + 'In that first program, catch only filesystem errors with code EPERM, EACCES or EROFS and return exactly "EXPECTED_SANDBOX_DENIAL"; rethrow any other error. ' + + 'In that first program, catch only filesystem errors with code EPERM, EACCES or EROFS and use `inspect(...)` to display exactly "EXPECTED_SANDBOX_DENIAL"; rethrow any other error. ' + 'If the sandbox denies it, explicitly retry the program with sandbox_permissions "workspace-write" and justification "Create the file requested by the user". ' + 'I will answer the approval prompt. After the file is written, reply DONE and stop.' @@ -52,7 +52,7 @@ describe('web e2e: PTC program sandbox escalation', () => { it('keeps the file absent until approval and records the granted program', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-ptc-escalation')) - if (MODE !== 'record') expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT]) + if (MODE !== 'record') expect(fixtureUserPrompts(await readFile(await selectedSessionFixture(FIXTURE), 'utf8'))).toEqual([PROMPT]) const input = page.locator('[data-composer-input]').first() await input.waitFor({ timeout: 10_000 }) await page.locator('[aria-label^="Access mode"]').click() diff --git a/apps/web/tests/ptc-round.e2e.ts b/apps/web/tests/ptc-round.e2e.ts index 1a14c2fedc..6d86da1f9f 100644 --- a/apps/web/tests/ptc-round.e2e.ts +++ b/apps/web/tests/ptc-round.e2e.ts @@ -9,7 +9,7 @@ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import type { SessionEvent } from '@deepseek-ai/dsh-session' import { acknowledgeReloadConnectionLoss, captureExpandedTurnProcessAria, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, - launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold, + launchWebScaffold, recordFixture, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { connectFreshWorkspace, expandOwningTurnProcess, newEnglishPage, openSettings, saveFailureShot } from './support.ts' @@ -23,7 +23,7 @@ const MODE = webSnapshotMode() // Elicits the successful and failed sub-rows this scenario asserts. const PROMPT = 'Using ONE run_code program: run bash `echo CODE_ROUND_OK`, then read the file missing.txt ' - + 'catching its error in the program. Return an object with both outcomes. Then reply DONE and stop.' + + 'catching its error in the program. Use `inspect(...)` to display an object with both outcomes. Then reply DONE and stop.' describe('web e2e: PTC mode round renders nested sub-calls', () => { let scaffold: WebScaffold @@ -58,7 +58,7 @@ describe('web e2e: PTC mode round renders nested sub-calls', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-ptc-drive')) const requestStates: string[] = [] if (MODE !== 'record') { - expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT]) + expect(fixtureUserPrompts(await readFile(await selectedSessionFixture(FIXTURE), 'utf8'))).toEqual([PROMPT]) } const input = page.locator('[data-composer-input]').first() await input.waitFor({ timeout: 10_000 }) diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 461947ed21..79c72a683c 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -1045,9 +1045,11 @@ describe('web e2e: shipped right Sidebar', () => { await proseChip(page).click() await expect.poll(async () => await tabTitles(first)).toEqual(['Files', SAMPLE_NAME]) const order = await tabTitles(first) - // The insertion index is measured against chip midpoints, not strip width. - await dragTo(page, first.locator('[data-dockkit-tab]').last(), - await pointIn(first.locator('[data-dockkit-tab]').first(), 0.25, 0.5), + const tabs = first.locator('[data-dockkit-tab]') + const firstTab = tabs.first() + // Drag coordinates are viewport-relative. Wait for the strip to settle before measuring the first chip. + await firstTab.hover({ trial: true }) + await dragTo(page, tabs.last(), await pointIn(firstTab, 0.25, 0.5), strip.locator('[data-dockkit-caret="0"]')) await expect.poll(async () => await tabTitles(first)).toEqual([...order].reverse()) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index cda15bafaf..ecb8457bb7 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -233,6 +233,17 @@ export async function scrollIntoView(target: Locator): Promise { }), { timeout: 10_000 }).toBe(true) } +/** + * Request one earlier page without scrolling the transcript to its automatic pagination threshold. + * @param page - Page showing the English Chat history control. + */ +export async function loadEarlierChatPage(page: Page): Promise { + await page.getByRole('button', { name: 'Load earlier', exact: true }).evaluate((button) => { + button.focus({ preventScroll: true }) + }) + await page.keyboard.press('Enter') +} + /** * Expand every eligible Turn process and secondary group so a Tool-focused * scenario can exercise the original row contract beneath product-default diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index a70870d5ec..8f78803d4b 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -108,6 +108,7 @@ "tests/cua-optin.e2e.ts", "tests/bundle-platform.e2e.ts", "tests/cua-permissions.e2e.ts", + "tests/cua-run-code.e2e.ts", "tests/schedule-header.e2e.ts", "tests/schedule-phone.e2e.ts", "tests/schedule-pickers.e2e.ts", diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 4937fe4175..677823e639 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -886,6 +886,26 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-cua-windows` + +- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` +- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) +- `source`: [`packages/experimental/cua-windows/src/index.ts:32`](../packages/experimental/cua-windows/src/index.ts) + +```ts config-catalog +/** Windows native waiting policy, alongside shared CUA resource limits. */ +export interface Config extends CuaConfig { + /** Windows PowerShell executable used to query WSL interoperation and the Windows architecture. */ + windowsPowerShellPath: string + /** Milliseconds between application-readiness and clipboard-release observations. */ + pollIntervalMs: number +} +``` + + @@ -1163,7 +1183,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ @@ -1193,7 +1213,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:366`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:588`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1236,6 +1256,8 @@ export interface Config { maxReviewThreads?: number /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ maxCommits?: number + /** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */ + maxViewedFiles?: number } ``` @@ -1604,7 +1626,7 @@ export interface Config { ## `@deepseek-ai/dsh-file-reference-local` - `inject`: `agents` · `workingDirectory` -- `source`: [`packages/context/file-reference-local/src/index.ts:35`](../packages/context/file-reference-local/src/index.ts) +- `source`: [`packages/context/file-reference-local/src/index.ts:27`](../packages/context/file-reference-local/src/index.ts) ```ts config-catalog /** Local file-reference discovery configuration. */ @@ -2403,7 +2425,7 @@ export type Config = Readonly> ## `@deepseek-ai/dsh-lsp-stdio` - `inject`: `fs` · `lsp` · `subprocess` -- `source`: [`packages/lsp/lsp-stdio/src/index.ts:83`](../packages/lsp/lsp-stdio/src/index.ts) +- `source`: [`packages/lsp/lsp-stdio/src/index.ts:70`](../packages/lsp/lsp-stdio/src/index.ts) ```ts config-catalog /** Plugin configuration: provider id → local language-server configuration. */ @@ -2856,7 +2878,7 @@ export interface Config { ## `@deepseek-ai/dsh-ptc-runtime-node` - `inject`: `fs` · `subprocess` · `sandbox` · `sandboxPolicy` -- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:7`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts) +- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:8`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts) ```ts config-catalog /** Deployment-varying runtime bounds and launch choices. */ @@ -2867,6 +2889,11 @@ export interface Config { executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script' /** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */ scriptPersistence?: boolean + /** + * Run persistent-in-memory programs as scoped REPL statements whose later calls receive copies of earlier top-level bindings; + * omitted, it is `SCOPED_REPL_BY_DEFAULT` from configuration.ts, currently true, with persistent-in-memory and false otherwise. + */ + replScoped?: boolean /** Default elapsed deadline, including nested tool and approval waits. */ timeoutMs?: number /** Maximum numeric elapsed budget accepted by resolve. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0e854200ce..2fb5cbd4f8 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -888,6 +888,26 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-cua-windows` + +- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` +- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) +- `source`: [`packages/experimental/cua-windows/src/index.ts:32`](../packages/experimental/cua-windows/src/index.ts) + +```ts config-catalog +/** Windows native waiting policy, alongside shared CUA resource limits. */ +export interface Config extends CuaConfig { + /** Windows PowerShell executable used to query WSL interoperation and the Windows architecture. */ + windowsPowerShellPath: string + /** Milliseconds between application-readiness and clipboard-release observations. */ + pollIntervalMs: number +} +``` + + @@ -1165,7 +1185,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ @@ -1195,7 +1215,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:366`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:588`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1238,6 +1258,8 @@ export interface Config { maxReviewThreads?: number /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ maxCommits?: number + /** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */ + maxViewedFiles?: number } ``` @@ -1606,7 +1628,7 @@ export interface Config { ## `@deepseek-ai/dsh-file-reference-local` - `inject`: `agents` · `workingDirectory` -- `source`: [`packages/context/file-reference-local/src/index.ts:35`](../packages/context/file-reference-local/src/index.ts) +- `source`: [`packages/context/file-reference-local/src/index.ts:27`](../packages/context/file-reference-local/src/index.ts) ```ts config-catalog /** Local file-reference discovery configuration. */ @@ -2405,7 +2427,7 @@ export type Config = Readonly> ## `@deepseek-ai/dsh-lsp-stdio` - `inject`: `fs` · `lsp` · `subprocess` -- `source`: [`packages/lsp/lsp-stdio/src/index.ts:83`](../packages/lsp/lsp-stdio/src/index.ts) +- `source`: [`packages/lsp/lsp-stdio/src/index.ts:70`](../packages/lsp/lsp-stdio/src/index.ts) ```ts config-catalog /** Plugin configuration: provider id → local language-server configuration. */ @@ -2858,7 +2880,7 @@ export interface Config { ## `@deepseek-ai/dsh-ptc-runtime-node` - `inject`: `fs` · `subprocess` · `sandbox` · `sandboxPolicy` -- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:7`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts) +- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:8`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts) ```ts config-catalog /** Deployment-varying runtime bounds and launch choices. */ @@ -2869,6 +2891,11 @@ export interface Config { executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script' /** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */ scriptPersistence?: boolean + /** + * Run persistent-in-memory programs as scoped REPL statements whose later calls receive copies of earlier top-level bindings; + * omitted, it is `SCOPED_REPL_BY_DEFAULT` from configuration.ts, currently true, with persistent-in-memory and false otherwise. + */ + replScoped?: boolean /** Default elapsed deadline, including nested tool and approval waits. */ timeoutMs?: number /** Maximum numeric elapsed budget accepted by resolve. */ diff --git a/docs/deepseek-llm-api-wire-extensions.i18n.yaml b/docs/deepseek-llm-api-wire-extensions.i18n.yaml index c5248fa3f7..6af48b13b7 100644 --- a/docs/deepseek-llm-api-wire-extensions.i18n.yaml +++ b/docs/deepseek-llm-api-wire-extensions.i18n.yaml @@ -9,8 +9,8 @@ en: 1da81051addc4b47 zh: 3e8d7cd3f8c1cdba /official-deepseek-llm-api-wire-extensions/request-headers: - en: d3d6a2c8240b80e9 - zh: debf42ed01233728 + en: a55fbcd176b7a7a7 + zh: ed8b10f6e840cc44 /official-deepseek-llm-api-wire-extensions/body-extension-transaction: en: 48001cfd1281a23b zh: d410530ae8aa2823 diff --git a/docs/deepseek-llm-api-wire-extensions.md b/docs/deepseek-llm-api-wire-extensions.md index e9a270d98e..67b48bdd74 100644 --- a/docs/deepseek-llm-api-wire-extensions.md +++ b/docs/deepseek-llm-api-wire-extensions.md @@ -23,7 +23,7 @@ The [`DeepSeekLlmApiExtensionRegistry`](../packages/llm/deepseek-llm-api-extensi | Header | Presence | Value | |---|---|---| -| `user-agent` | Every provider HTTP request, including Files API operations | Application identity in `product/version (+url)` form; the default product is `deepseek-harness` | +| `user-agent` | Every provider HTTP request, including Files API operations | Application identity in `product/version (+url)` form, followed by `dsh-profile/` naming the booted profile, percent-encoded outside `tchar` and for `%` (for example `dsh-profile/desktop`, `dsh-profile/web`, `dsh-profile/sdk`); the default product is `deepseek-harness` | | `x-deepseek-harness-user-id` | Every authorized model request | The stable anonymous UUID for the resolved Harness home | | `x-deepseek-harness-session-id` | Model requests carrying a Session id | The exact request `sessionId` string | | `x-deepseek-harness-compact` | Model requests whose purpose is `compaction` | The literal string `1` | diff --git a/docs/deepseek-llm-api-wire-extensions.zh.md b/docs/deepseek-llm-api-wire-extensions.zh.md index d498e8f951..b1feaa0826 100644 --- a/docs/deepseek-llm-api-wire-extensions.zh.md +++ b/docs/deepseek-llm-api-wire-extensions.zh.md @@ -23,7 +23,7 @@ | 标头 | 出现条件 | 值 | |---|---|---| -| `user-agent` | 每个提供方 HTTP 请求,包括 Files API 操作 | 采用 `product/version (+url)` 形式的应用身份;默认产品为 `deepseek-harness` | +| `user-agent` | 每个提供方 HTTP 请求,包括 Files API 操作 | 采用 `product/version (+url)` 形式的应用身份,其后追加命名所启动 profile 的 `dsh-profile/`,`tchar` 以外的字节及 `%` 做百分号编码(例如 `dsh-profile/desktop`、`dsh-profile/web`、`dsh-profile/sdk`);默认产品为 `deepseek-harness` | | `x-deepseek-harness-user-id` | 每个已授权的模型请求 | 已解析 Harness home 的稳定匿名 UUID | | `x-deepseek-harness-session-id` | 携带会话 id 的模型请求 | 确切的请求 `sessionId` 字符串 | | `x-deepseek-harness-compact` | 用途为 `compaction` 的模型请求 | 字面字符串 `1` | diff --git a/docs/defensive-patterns/package-surface.i18n.yaml b/docs/defensive-patterns/package-surface.i18n.yaml index 5a3fb98e69..7cb7219d2f 100644 --- a/docs/defensive-patterns/package-surface.i18n.yaml +++ b/docs/defensive-patterns/package-surface.i18n.yaml @@ -12,8 +12,8 @@ en: bf79c6acf35c90a5 zh: 9f2ce6c7f6493b17 /package-surface-rules/package-json-exports-uses-the-standard-key-set: - en: 692ded0ff903609d - zh: c871ab58ca92ad70 + en: 37d7728d42231610 + zh: ba27dd3935f50572 /package-surface-rules/dependency-declarations-and-version-consistency-are-enforced-by-the-dependency-scan: en: e68bfcde70f845b4 zh: 73e5c4fb067c4fa1 diff --git a/docs/defensive-patterns/package-surface.md b/docs/defensive-patterns/package-surface.md index 8efe249f95..a511cf7d6b 100644 --- a/docs/defensive-patterns/package-surface.md +++ b/docs/defensive-patterns/package-surface.md @@ -79,6 +79,7 @@ A `package.json` `exports` map uses only the standard key set, in which every ke - Standard keys, each with one meaning repo-wide, across `packages/*/*/package.json` and `apps/*/package.json`: `.` (the package entry), `./package.json` (toolchain access, not a semantic export), `./src/*` (source passthrough for tests and tools, whose documented status is still open), `./client` (the browser entry, paired with the `dsh.client` declaration), `./types` (the type entry), `./typert` (the typert type runtime), `./remote` (the `@Remote` call surface), `./locale/*.json` (locale resources), `./cordis.patch.yml` (the bundle patch layer declared by `dsh.bundle`). Counts are not listed here because they rot on the next package; the recompute command below prints them. - Keys outside that set (`./brand` in 5 packages, `./worker` in 4, `./startup`, `./runner`, and `./protocol` in 2 each, plus many one-off keys) have no documented meaning; they are pending review, not a pattern to copy. - `dsh-tools` additionally exposes `./pipeline` for reusable invocation stages and batch scheduling. Its main and pipeline bundles share runtime chunks to preserve error-class identity; workspace constraints check the export targets and publication files. +- `dsh-tool-executor-ptc` exposes `./run-code` for the shared program-tool factory, explicit runtime and call limits, and private callable tool definitions. Workspace constraints check its export targets and publication files. - Judged condition: does a change add an export key outside the standard set? - Exception: none by default; a new key changes the owning document and the check first, with the domain owner's confirmation. - Recompute the distribution: diff --git a/docs/defensive-patterns/package-surface.zh.md b/docs/defensive-patterns/package-surface.zh.md index 2c7bc516b2..c5ef74b0f1 100644 --- a/docs/defensive-patterns/package-surface.zh.md +++ b/docs/defensive-patterns/package-surface.zh.md @@ -79,6 +79,7 @@ import { isSurfaceEligibleType } from '../../core/session/src/surface.ts' - 标准键,每个键在全仓只有一个含义,统计口径是 `packages/*/*/package.json` 与 `apps/*/package.json`:`.`(包主入口)、`./package.json`(工具链访问,不是语义导出)、`./src/*`(测试与工具的源码透传,文档状态仍待定)、`./client`(浏览器入口,与 `dsh.client` 声明配对)、`./types`(类型入口)、`./typert`(typert 类型运行时)、`./remote`(`@Remote` 调用面)、`./locale/*.json`(本地化资源)、`./cordis.patch.yml`(`dsh.bundle` 声明的 bundle 补丁层)。这里不列各键的包数,因为下一个包就会让它过期;下面的复算命令会打印当前数字。 - 集合之外的键(`./brand` 5 个包、`./worker` 4 个、`./startup`、`./runner`、`./protocol` 各 2 个,另有大量一次性键)没有文档含义,属待核项,不是可照抄的先例。 - `dsh-tools` 另行提供 `./pipeline`,用于复用调用阶段与批量调度。主入口与 pipeline bundle 共享运行时 chunk,以保持错误类的身份一致;工作区检查验证导出目标与发布文件。 +- `dsh-tool-executor-ptc` 提供 `./run-code`,用于共享程序工具工厂、显式指定运行时及调用上限,并传入私有可调用工具定义。工作区检查验证其导出目标与发布文件。 - 判定条件:改动是否新增了标准集合以外的 export 键? - 例外:无默认例外;新增键须先改正家文档与检查,并取得对应领域专家确认。 - 复算分布: diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index a395954f8d..8da70189ad 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -47,7 +47,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | -| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:28`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | | `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | @@ -56,7 +56,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | -| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | +| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 2df7e4df84..1484e33479 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -49,7 +49,7 @@ | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | -| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:28`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:29`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | | `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | @@ -58,7 +58,7 @@ | `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | -| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | +| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:113`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - | | `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` | | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:76`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 4f967d6034..78edb664c7 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -264,6 +264,7 @@ flowchart TD pkg_creation_recommendations["creation-recommendations"] pkg_cua["cua"] pkg_cua_bundle["cua-bundle"] + pkg_cua_windows["cua-windows"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] pkg_experimental_auto_review["experimental-auto-review"] pkg_experimental_badge_skill_bundle["experimental-badge-skill-bundle"] @@ -588,6 +589,7 @@ flowchart TD pkg_skill_badge --> pkg_skill pkg_host_product_telemetry_otel --> pkg_otel pkg_persona --> pkg_system_prompt + pkg_ptc_runtime --> pkg_attachment pkg_ptc_runtime --> pkg_error pkg_ptc_runtime --> pkg_sandbox pkg_sandbox_local --> pkg_llm @@ -962,10 +964,12 @@ flowchart TD pkg_creation_recommendations --> pkg_session pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools - pkg_cua --> pkg_attachment - pkg_cua --> pkg_ptc_runtime_node - pkg_cua --> pkg_scope - pkg_cua --> pkg_user_questions + pkg_cua_windows --> pkg_agent + pkg_cua_windows --> pkg_computer_use + pkg_cua_windows --> pkg_subprocess + pkg_cua_windows --> pkg_system_prompt + pkg_cua_windows --> pkg_tools + pkg_cua_windows --> pkg_user_questions pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt @@ -1134,6 +1138,12 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env + pkg_cua --> pkg_attachment + pkg_cua --> pkg_error + pkg_cua --> pkg_ptc_runtime_node + pkg_cua --> pkg_scope + pkg_cua --> pkg_tool_executor_ptc + pkg_cua --> pkg_user_questions pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions pkg_experimental_auto_review --> pkg_llm @@ -1759,7 +1769,7 @@ flowchart TD | [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) | | [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) | -| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) | +| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | | [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) | | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | @@ -1839,7 +1849,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | @@ -1873,6 +1883,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index fcd267f2f2..1a7cf824e5 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -266,6 +266,7 @@ flowchart TD pkg_creation_recommendations["creation-recommendations"] pkg_cua["cua"] pkg_cua_bundle["cua-bundle"] + pkg_cua_windows["cua-windows"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] pkg_experimental_auto_review["experimental-auto-review"] pkg_experimental_badge_skill_bundle["experimental-badge-skill-bundle"] @@ -590,6 +591,7 @@ flowchart TD pkg_skill_badge --> pkg_skill pkg_host_product_telemetry_otel --> pkg_otel pkg_persona --> pkg_system_prompt + pkg_ptc_runtime --> pkg_attachment pkg_ptc_runtime --> pkg_error pkg_ptc_runtime --> pkg_sandbox pkg_sandbox_local --> pkg_llm @@ -964,10 +966,12 @@ flowchart TD pkg_creation_recommendations --> pkg_session pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools - pkg_cua --> pkg_attachment - pkg_cua --> pkg_ptc_runtime_node - pkg_cua --> pkg_scope - pkg_cua --> pkg_user_questions + pkg_cua_windows --> pkg_agent + pkg_cua_windows --> pkg_computer_use + pkg_cua_windows --> pkg_subprocess + pkg_cua_windows --> pkg_system_prompt + pkg_cua_windows --> pkg_tools + pkg_cua_windows --> pkg_user_questions pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt @@ -1136,6 +1140,12 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env + pkg_cua --> pkg_attachment + pkg_cua --> pkg_error + pkg_cua --> pkg_ptc_runtime_node + pkg_cua --> pkg_scope + pkg_cua --> pkg_tool_executor_ptc + pkg_cua --> pkg_user_questions pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions pkg_experimental_auto_review --> pkg_llm @@ -1761,7 +1771,7 @@ flowchart TD | [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) | | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) | | [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) | -| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) | +| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | | [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) | | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | @@ -1841,7 +1851,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | @@ -1875,6 +1885,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | diff --git a/docs/subsystems/computer-use.i18n.yaml b/docs/subsystems/computer-use.i18n.yaml index 5d6db1a53a..82f79b8eb8 100644 --- a/docs/subsystems/computer-use.i18n.yaml +++ b/docs/subsystems/computer-use.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/computer-use.md /computer-use: - en: e02a2e4cc9970cba - zh: 29aac6c0530a582f + en: bf7dcc9124e8bce2 + zh: 4199c51e21dc9b0a /computer-use/choose-a-provider: en: fa2e0d7b41c0450b zh: af9a799711f901e6 diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index 7b1dbee236..4ae558452f 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -14,7 +14,7 @@ The CUA provider owns `ctx.cuaAccess` for system-permission status, explicit sys |---|---| | `CuaApplicationId`, `CuaApplicationGrant` | A platform-provided application identity and its displayed saved decision. | | `CuaSystemPermission` | Accessibility or Screen Recording, selected by the human. | -| `CuaPermissionProcess`, `CuaSystemPermissionState` | Native access observations tagged `darwin` or `win32`, with helper process identity. macOS includes permission checks, parent identity and responsible-application metadata when available (falling back to the helper’s own bundle); Windows includes desktop lock, capture availability and elevation status. | +| `CuaPermissionProcess`, `CuaSystemPermissionState` | Native access observations tagged `darwin` or `windows`, with the helper’s name and path when available. macOS includes permission checks, numeric helper and parent PIDs, and responsible-application metadata when available (falling back to the helper’s own bundle); Windows includes desktop lock, capture availability and elevation status, and omits the helper PID. | | `CuaApplicationState` | Saved grants, refused applications, and whether persistence is available. Session-only grants remain internal to the provider. System observations and application icons are queried separately so the page can display each result as it arrives. | The [shared object API](../../packages/experimental/cua/README.md) uses `connectCua` to select an application, then `app.getWindows()` and `app.getWindow(windowId)` to select a window for screenshots and pointer input. Accessibility operations use element IDs from the latest tree for that application handle. Providers declare keyboard scopes and application-level accessibility in `getCapabilities()`. diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index 1c35045383..982e9410d6 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -14,7 +14,7 @@ CUA provider 通过 `ctx.cuaAccess` 提供系统权限状态、用户主动申 |---|---| | `CuaApplicationId`、`CuaApplicationGrant` | 平台提供的应用身份,以及显示给用户的已保存决定。 | | `CuaSystemPermission` | 用户选择申请的辅助功能或屏幕录制权限。 | -| `CuaPermissionProcess`、`CuaSystemPermissionState` | 以 `darwin` 或 `win32` 标记的原生访问状态和 helper 进程身份。macOS 包含权限检查、父进程身份和责任应用信息(系统无法识别时使用 helper 自身的应用包);Windows 包含桌面锁定、截图可用性和提权状态。 | +| `CuaPermissionProcess`、`CuaSystemPermissionState` | 以 `darwin` 或 `windows` 标记的原生访问状态,包含可获取的 helper 名称和路径。macOS 包含权限检查、helper 和父进程的数字 PID,以及责任应用信息(系统无法识别时使用 helper 自身的应用包);Windows 包含桌面锁定、截图可用性和提权状态,省略 helper 的 PID。 | | `CuaApplicationState` | 持久授权、拒绝记录,以及能否持久保存。会话授权只保留在 provider 内部。系统权限和应用图标分别查询,页面在各项结果返回后分别显示。 | 调用[共享对象 API](../../packages/experimental/cua/README.zh.md) 时,通过 `connectCua` 连接,选择应用后用 `app.getWindows()` 和 `app.getWindow(windowId)` 选择要截图或进行鼠标操作的窗口。辅助功能操作使用该应用句柄最近一次读取的树中的元素 ID。提供方通过 `getCapabilities()` 声明键盘输入支持的范围,以及是否支持应用级辅助功能。 diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 194c6c26dd..9702f4429c 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -12,14 +12,17 @@ en: 26ccfa2e342e3e67 zh: fe6cc2a622757c48 /forges/change-request-actions: - en: 87d2c81d9514267f - zh: 1daf31c5b0127a1c + en: ae735fbdbdf2d870 + zh: 9903fcc571104ad8 /forges/review-threads: - en: 351af1e634f70a40 - zh: 2f0bba65d3b01277 + en: af729af6e59e915f + zh: 1b7d7671ec36a5b2 +/forges/overview-and-viewed-marks: + en: fd5928603c9375b1 + zh: 1a3bca55344ff385 /forges/session-bindings: en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: e3081af82f42354b - zh: 507eb461be8b81cf + en: 0e0348e9a38215ed + zh: affcc0231e15d682 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index b260ac321f..a84fb124a9 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -53,6 +53,12 @@ interface ForgeProvider { * Omission declares that this provider cannot read reviews. */ readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * Write to the review threads or the pending review of a change request while its head is `write.headSha`; once the + * head is another commit, the write resolves to `stale` without writing. A write is never retried. Omission declares + * that this provider cannot write reviews, and its `readReview` then reports no viewer permission. + */ + writeReview?(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise /** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */ repositoryFromRemote(url: string): ForgeRepository | undefined /** Map a change request web URL to its reference, or undefined when this provider does not serve it. */ @@ -95,6 +101,38 @@ interface ForgeProvider { * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. */ compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** + * Read the signed-in user's viewed marks on the change request's files at head commit `headSha`. The marks are + * returned only when the read names `headSha` as the head; once the head is another commit, the read resolves to a + * `stale` failure. A provider implements `viewedFiles` and `setViewed` together; omitting either declares that the + * host keeps no viewed marks. + */ + viewedFiles?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * Set or clear the signed-in user's viewed mark on one file while the head is still `request.headSha`, resolving to + * undefined once the host saved it. + */ + setViewed?(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** + * Rerun the failed checks of the head commit that name a `rerun` none of whose checks is pending, while the head is + * still `request.headSha`, resolving to undefined once the host accepted every rerun. Omission declares that the + * provider reruns no checks, and its snapshots then name none. + */ + rerunChecks?(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise + /** + * Request reviews from more reviewers, resolving to undefined once the host accepted the request. A provider implements + * `requestReviews` and `reviewerCandidates` together; omitting either declares that it requests no reviews, and its + * snapshots then deny `canRequestReviews`. + */ + requestReviews?(ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal): Promise + /** List accounts whose login or name matches `query`, the host's suggestions first, for a review request. */ + reviewerCandidates?(ref: ChangeRequestRef, query: string, signal: AbortSignal): Promise + /** + * Bring the base branch's new commits into the head branch while its head is still `request.headSha`, resolving to + * undefined once the host accepted the update. Omission declares that the provider updates no branches, and its + * snapshots then offer no `branchUpdates`. + */ + updateBranch?(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise } ``` @@ -167,6 +205,11 @@ interface ChangeRequestCheck { readonly startedAt: string | null /** ISO 8601 time the check completed, or null while it runs and when the host reports none. */ readonly completedAt: string | null + /** + * Identity a rerun of this check names, or null when the provider cannot rerun it, as for a commit status. Checks that + * name one identity rerun together, and their failed checks can be rerun once none of them is pending. + */ + readonly rerun: ForgeCheckId | null } ``` @@ -224,18 +267,36 @@ interface ChangeRequestSnapshot { readonly mergeReady: boolean /** Merge methods the repository accepts, the signed-in user's usual one first. */ readonly mergeMethods: readonly MergeMethod[] + /** + * Ways the signed-in user can bring the base branch's new commits into the head branch now; empty while the head is + * up to date, while the branches conflict, when the user cannot update the head branch, or when the provider cannot, + * so a head behind its base cannot be told apart from a current one for a user without the right to update it. + */ + readonly branchUpdates: readonly BranchUpdateMethod[] /** Aggregate review outcome. */ readonly reviewDecision: ReviewDecision + /** Reviewers whose review is requested, in host order, then other accounts that reviewed, each once; the author is never listed. */ + readonly reviewers: readonly ChangeRequestReviewer[] + /** Whether the host reported more review requests or reviews than the provider read, so `reviewers` may be incomplete. */ + readonly reviewersTruncated: boolean + /** Whether the signed-in user may request reviews of the change request through its provider. */ + readonly canRequestReviews: boolean /** Checks on the head commit in host order. */ readonly checks: readonly ChangeRequestCheck[] /** Combined check outcome. */ readonly checksRollup: ChecksRollup /** Whether the host reported more checks than `checks` contains. */ readonly checksTruncated: boolean + /** Whether the signed-in user may rerun the failed checks that name a `rerun`. */ + readonly canRerunChecks: boolean /** Number of counted review threads that are not resolved. */ readonly unresolvedThreads: number /** Whether the change request has more review threads than the provider counted, so `unresolvedThreads` is a lower bound. */ readonly threadsTruncated: boolean + /** Issues linked to the change request, which the host closes once it merges, in host order. */ + readonly closingIssues: readonly ChangeRequestIssue[] + /** Whether the host reported more closing issues than `closingIssues` holds. */ + readonly closingIssuesTruncated: boolean /** ISO 8601 time of the host's last update to the change request. */ readonly updatedAt: string /** ISO 8601 time the change request was merged or closed, or null while it is open. */ @@ -297,19 +358,21 @@ interface MergeRequest { ``` ```ts type-equiv -/** Why a provider could not change a change request. */ +/** Why a provider could not change a change request, or could not confirm that it did. */ interface ForgeActionFailure { /** * `unauthenticated`: credentials are missing or rejected; `stale`: the head - * moved past the confirmed commit; `failed`: the host refused or could not be reached. + * moved past the confirmed commit; `failed`: the host refused or could not be reached, so nothing changed; + * `unknown`: the request reached the host but its answer did not confirm the outcome, so the change may have been + * applied and must be checked on the host before it is tried again. */ - readonly code: 'unauthenticated' | 'stale' | 'failed' + readonly code: 'unauthenticated' | 'stale' | 'failed' | 'unknown' /** Human-readable cause, usually the host's own message. */ readonly message: string } ``` -`ctx.forge.submitReview` delegates an explicit comment or completed review to the provider. A provider that omits this capability returns unsupported. Consumers retain pending drafts and reconcile unknown write outcomes before resubmitting. +`ctx.forge.submitReview` delegates an explicit comment or completed review to the provider. A provider that omits this capability returns unsupported. Consumers reconcile unknown write outcomes before resubmitting; comments kept for a later review go to the code host's pending review through `ctx.forge.writeReview`. ```ts type-equiv /** One inline comment addressed to the old or new side of a pull request diff. */ @@ -329,12 +392,12 @@ type ForgeReviewRequest = { readonly headSha: string } & ( | { readonly kind: 'comment'; readonly comment: ForgeLineComment } - | { readonly kind: 'review'; readonly event: 'comment' | 'approve' | 'request-changes'; readonly body: string; readonly comments: readonly ForgeLineComment[] } + | { readonly kind: 'review'; readonly event: ForgeReviewEvent; readonly body: string; readonly comments: readonly ForgeLineComment[] } ) ``` ```ts type-equiv -/** Result of a review write; unknown outcomes must be checked on the host before another submission. */ +/** Result of a review submission; unknown outcomes must be checked on the host before another submission. */ type ForgeReviewResult = | { readonly ok: true; readonly url: string } | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } @@ -396,6 +459,10 @@ interface ForgeReviewComment { readonly pending: boolean /** Web page of the comment, or null when the host reports none. */ readonly url: string | null + /** Whether the signed-in user can replace the comment's text through `writeReview`; false for a provider without it. */ + readonly viewerCanEdit: boolean + /** Whether the signed-in user can delete the comment through `writeReview`; false for a provider without it. */ + readonly viewerCanDelete: boolean } ``` @@ -422,6 +489,13 @@ interface ForgeReviewThread { readonly diffHunk: string | null /** Whether the thread is marked resolved. */ readonly resolved: boolean + /** Whether the signed-in user can reply to the thread through `writeReview`; false for a provider without it. */ + readonly viewerCanReply: boolean + /** + * Whether the signed-in user can mark the thread resolved, or unresolved when `resolved`, through `writeReview`; false + * for a provider without it. + */ + readonly viewerCanResolve: boolean /** Comments oldest first; the first starts the thread. */ readonly comments: readonly ForgeReviewComment[] } @@ -432,10 +506,200 @@ interface ForgeReviewThread { interface ForgeReviewData { /** Head commit the threads were read at; `current` positions number its files. */ readonly headSha: string + /** Login of the signed-in user the provider read as, or null when the host does not name one. */ + readonly viewer: string | null /** Threads in host order, at most the provider's limit. */ readonly threads: readonly ForgeReviewThread[] /** Whether the change request has more threads than `threads` holds. */ readonly truncated: boolean + /** The signed-in user's pending review, or null without one. */ + readonly pendingReview: ForgePendingReview | null + /** + * Whether the signed-in user can add comments to a pending review and submit or discard it through `writeReview`; + * false for a provider without it. + */ + readonly viewerCanReview: boolean +} +``` + +`ctx.forge.writeReview(ref, write, signal)` writes to the review threads and the signed-in user's pending review: a reply, at once or with `pending` inside the pending review; resolving or unresolving a thread; editing or deleting a comment; a line comment at the head added to the pending review; and submitting or discarding the pending review. A pending reply or comment starts a pending review when the user has none. Every write carries the head commit the user saw; the provider checks it first and returns `stale` without writing once the head moved, which polls a watched change request as a stale read does, and the service polls a watched change request at once after any other result. Writes are never retried, and an `unknown` result must be checked on the host before the write is tried again. For a provider without `writeReview` the service returns `unsupported`. `ForgeReviewData` carries the pending review and the user's permissions for each thread, comment, and the pending review, which a provider without `writeReview` reports as absent, so consumers offer only the writes that can succeed. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns the GraphQL mutations and how their outcomes map onto these results. + +```ts type-equiv +/** Opaque host identity of one review. */ +type ForgeReviewId = Branded<'ForgeReviewId'> +``` + +```ts type-equiv +/** The signed-in user's review of a change request that is not submitted yet, which only that user sees. */ +interface ForgePendingReview { + /** Host identity of the review. */ + readonly id: ForgeReviewId + /** Comments the review holds. */ + readonly comments: number +} +``` + +```ts type-equiv +/** Decision a submitted review records. */ +type ForgeReviewEvent = 'comment' | 'approve' | 'request-changes' +``` + +```ts type-equiv +/** + * One write to the review threads and the pending review of a change request. `pending` replies and `add-pending` + * comments join the signed-in user's pending review, which is started when the user has none. A host that adds every + * reply to an existing pending review, as GitHub does, refuses a reply with `pending: false` while one exists. + */ +type ForgeReviewWrite = { + /** Head commit the user saw; providers check it before writing and refuse with `stale` once the head is another commit. */ + readonly headSha: string +} & ( + | { readonly kind: 'reply'; readonly thread: ForgeThreadId; readonly body: string; readonly pending: boolean } + | { readonly kind: 'resolve'; readonly thread: ForgeThreadId; readonly resolved: boolean } + | { readonly kind: 'edit-comment'; readonly comment: ForgeCommentId; readonly body: string } + /** Deleting the only comment of a thread deletes the thread. */ + | { readonly kind: 'delete-comment'; readonly comment: ForgeCommentId } + /** A comment on lines of `headSha`. */ + | { readonly kind: 'add-pending'; readonly comment: ForgeLineComment } + | { readonly kind: 'submit-pending'; readonly review: ForgeReviewId; readonly event: ForgeReviewEvent; readonly body: string } + /** Delete the pending review with every comment it holds. */ + | { readonly kind: 'discard-pending'; readonly review: ForgeReviewId } +) +``` + +```ts type-equiv +/** Result of a review write; an `unknown` outcome must be checked on the host before the write is tried again. */ +type ForgeReviewWriteResult = + | { readonly ok: true } + | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } +``` + +## Overview and viewed marks + +A snapshot also carries the overview of a change request: its `reviewers` with each one's latest verdict, the `closingIssues` the host closes once it merges, the `branchUpdates` that would bring a head behind its base up to date, whether the signed-in user may request reviews or rerun checks, and the `rerun` each check names. `ctx.forge.rerunChecks`, `ctx.forge.requestReviews`, and `ctx.forge.updateBranch` act on it and resolve to a `ForgeActionFailure` as the actions above do, `unknown` when the host's answer did not confirm the outcome, polling a watched change request once the provider answered; a rerun and an update name the head commit the user saw and are refused with `stale` once the head moved. A provider implements `requestReviews` together with `reviewerCandidates`, which `ctx.forge.reviewerCandidates` uses to list the accounts a review can be requested from; an action the provider lacks fails with `failed`, and `reviewerCandidates` returns `unsupported`. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns how GitHub fills and acts on each field. + +```ts type-equiv +/** Opaque host identity of a status check that a rerun names. */ +type ForgeCheckId = Branded<'ForgeCheckId'> +``` + +```ts type-equiv +/** How an update brings the base branch's new commits into the head branch: a merge commit, or a rebase of the head's commits. */ +type BranchUpdateMethod = 'merge' | 'rebase' +``` + +```ts type-equiv +/** Outcome of a reviewer's latest submitted review. */ +type ReviewVerdict = 'approved' | 'changes-requested' | 'commented' | 'dismissed' +``` + +```ts type-equiv +/** An account or team asked to review a change request, or an account that reviewed it. */ +interface ChangeRequestReviewer { + /** Whether the reviewer is a person's account, an app or bot account, or a team. */ + readonly kind: 'user' | 'bot' | 'team' + /** Login, or `organization/slug` for a team. */ + readonly login: string + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether a review from the reviewer is requested now. */ + readonly requested: boolean + /** Whether the host requested the review because the reviewer owns changed paths. */ + readonly codeOwner: boolean + /** Outcome of the reviewer's latest submitted review, or null before the first. */ + readonly verdict: ReviewVerdict | null + /** Commit the latest submitted review was on, or null before the first or when the host reports none. */ + readonly reviewedSha: string | null +} +``` + +```ts type-equiv +/** One issue linked to a change request, which the host closes once the change request merges. */ +interface ChangeRequestIssue { + /** Repository that holds the issue. */ + readonly repository: ForgeRepository + /** Host-assigned issue number. */ + readonly number: number + /** Title as the author wrote it. */ + readonly title: string + /** Whether the issue is still open. */ + readonly state: 'open' | 'closed' + /** Web page of the issue. */ + readonly url: string +} +``` + +```ts type-equiv +/** A rerun of the failed checks of the head commit whose checks the user saw. */ +interface ForgeRerunRequest { + /** Head commit whose checks the user saw; the provider refuses with `stale` once the head is another commit. */ + readonly headSha: string +} +``` + +```ts type-equiv +/** Reviewers to ask in addition to those whose review is requested now; one who already reviewed is asked again. */ +interface ForgeReviewersRequest { + /** The reviewers by kind and login, a team by `organization/slug`. */ + readonly reviewers: readonly Pick[] +} +``` + +```ts type-equiv +/** An account a review of the change request can be requested from. */ +interface ForgeReviewerCandidate { + /** Login as the host spells it. */ + readonly login: string + /** Display name, or null when the account shows none. */ + readonly name: string | null + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether the host suggests the account for this change request, as from the history of its changed files. */ + readonly suggested: boolean +} +``` + +```ts type-equiv +/** A branch update the user confirmed for the head commit they saw. */ +interface BranchUpdateRequest { + /** How the base branch's new commits enter the head branch. */ + readonly method: BranchUpdateMethod + /** Commit object name the head must still have; the update is refused once the head moves. */ + readonly headSha: string +} +``` + +`ctx.forge.viewedFiles` and `ctx.forge.setViewed` read and change the signed-in user's viewed marks on the files of a change request at one head commit. A provider keeps viewed marks only when it implements both methods; otherwise `viewedFiles` returns undefined and `setViewed` fails, so a consumer keeps marks itself. A `stale` answer polls a watched change request as a stale diff read does. + +```ts type-equiv +/** + * The signed-in user's review progress on one changed file: `viewed`, `unviewed`, or `dismissed` once the file + * changed after the user marked it viewed. + */ +type ForgeViewedState = 'viewed' | 'unviewed' | 'dismissed' +``` + +```ts type-equiv +/** The signed-in user's viewed marks on the files of a change request, read at one head commit. */ +interface ForgeViewedFiles { + /** Head commit the marks were read at. */ + readonly headSha: string + /** State of each changed file the host listed, by repository-relative path. */ + readonly files: Readonly> + /** Whether the change request has more files than `files` lists. */ + readonly truncated: boolean +} +``` + +```ts type-equiv +/** A viewed mark the user set or cleared on a file of the head commit they saw. */ +interface ForgeViewedRequest { + /** Repository-relative path of the changed file. */ + readonly path: string + /** Whether the file is viewed. */ + readonly viewed: boolean + /** Head commit whose changes the user saw; the provider refuses with `stale` once the head is another commit. */ + readonly headSha: string } ``` @@ -730,6 +994,10 @@ The changes view reads through the same Remote. `localDiff` reads one `ForgeLoca `changeRequestReview(session, url, headSha, fresh)` reads the threads of a bound change request at the head of the diff the view shows and refuses another head with `forgePanel/stale-head`, `forgePanel/review-unsupported` for a provider without review reads, and `forgePanel/review-failed` otherwise. It keeps one read per change request in memory, keyed by head commit and the status's update time and bounded by `maxCachedReviewBytes`, and reads again once the kept read is `reviewRefreshMs` old or when `fresh` asks for it, as the first read after the reader refreshes the view does: on GitHub a new comment or reply changes a pull request's update time, but resolving a thread does not. The changes view asks again at every status it receives while visible, and overlays the threads on the files the [panel README](../../packages/experimental/client-ui-forge/README.md#use-this-package) describes. +`changeRequestViewed(session, url, headSha)` reads the viewed marks of a bound change request at the head of the diff the view shows, returns null when the provider keeps none, and refuses another head with `forgePanel/stale-head` and any other failure with `forgePanel/viewed-failed`; `setFileViewed` saves one file's mark at that head. `rerunChecks`, `requestReviews`, and `updateBranch` act on a bound change request and refuse an outcome the host did not confirm with `forgePanel/action-unknown`, and `reviewerCandidates` lists accounts for a review request, refusing with `forgePanel/reviewers-failed` when the host lists none. The changes view reads the marks of a whole change request beside its diff and keeps the marks of local changes and chosen commits in the browser; the [panel README](../../packages/experimental/client-ui-forge/README.md#use-this-package) describes both and the card rows that offer the actions. + +`changeRequestReviewWrite(session, url, write)` passes one `ForgeReviewWrite` for a bound change request to `ctx.forge.writeReview` after checking its head commit, ids, text, and line range, and returns the `ForgeReviewWriteResult`. Once the provider answers, whatever the answer, it drops the kept threads of that change request and every read that started before, so the next `changeRequestReview` reads the host; `submitReview` drops them as well. The changes view sends one write at a time and reads the threads again after each write that may have changed them. + ```ts type-equiv /** * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order @@ -1006,6 +1274,49 @@ async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Rerun the failed checks of a change request's head commit while the head is still `request.headSha`, then poll it + * at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - the head commit whose checks the user saw. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the rerun, or why it did not; a provider that reruns no checks fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request from more reviewers, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - the reviewers to ask. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the request, or why it did not; a provider that requests no reviews fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async requestReviews( ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal, ): Promise + +/** + * List accounts a review of a change request can be requested from. + * @param ref - change request served by a registered provider. + * @param query - text the login or name contains; empty for the host's suggestions and first accounts. + * @param signal - cancellation of the read. + * @returns the accounts, the host's suggestions first, or why the host did not list them; a provider that requests no + * reviews returns `unsupported`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async reviewerCandidates( ref: ChangeRequestRef, query: string, signal: AbortSignal, ): Promise + +/** + * Bring the base branch's new commits into a change request's head branch while its head is still + * `request.headSha`, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - update method and the head commit the user confirmed. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the update, or why it did not; a provider that updates no branches fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise + /** * Read complete check details independently of periodic polling. * @param ref - change request served by a registered provider. @@ -1041,6 +1352,42 @@ async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise */ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise +/** + * Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then + * poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls + * it as a stale read does. + * @param ref - change request served by a registered provider. + * @param write - the write and the head commit the user saw. + * @param signal - cancellation of the write. + * @returns whether the host took the write; `unsupported` when the provider cannot write reviews, and `unknown` when the + * outcome must be checked on the host before the write is tried again. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise + +/** + * Read the signed-in user's viewed marks on the files of a change request at one head commit. A `stale` failure + * polls a watched change request again as {@link ForgeService.diff} does. + * @param ref - change request served by a registered provider. + * @param headSha - head commit the marks must be read at, usually the head of the displayed diff. + * @param signal - cancellation of the read. + * @returns the marks read at `headSha`, why the host did not provide them, or undefined when the provider keeps no + * viewed marks. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request while its head is still + * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * @param ref - change request served by a registered provider. + * @param request - the file, its mark, and the head commit the user saw. + * @param signal - cancellation of the request. + * @returns undefined once the host saved the mark, or why it did not; a provider that keeps no viewed marks fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async setViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** * List the commits of a change request at its current head. * @param ref - change request served by a registered provider. @@ -1311,11 +1658,39 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise +/** + * Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the + * whole change request. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param headSha - head commit of the shown diff; marks read at another head are refused. + * @param signal - request cancellation. + * @returns the marks at `headSha`, or null when the provider keeps no viewed marks. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `headSha`, which is then polled again; `forgePanel/viewed-failed` + * when the host does not provide the marks otherwise. + */ +@Remote async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request of a Session. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param request - the file, its mark, and the head commit of the shown diff. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's + * reason when the host refuses, cannot be reached, or keeps no viewed marks; `forgePanel/action-unknown` when the host + * did not confirm whether it saved the mark. + */ +@Remote async setFileViewed(session: Session, url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** * Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read * at the same head commit and update time are reused from memory, for any Session, until they are - * `reviewRefreshMs` old or `maxCachedReviewBytes` evicts them; a read again after that age, or a `fresh` read, - * shows threads resolved since, which do not change a GitHub pull request's update time. + * `reviewRefreshMs` old, `maxCachedReviewBytes` evicts them, or a review write through this panel drops them; a read + * again after that age, or a `fresh` read, shows threads resolved elsewhere since, which do not change a GitHub pull + * request's update time. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param headSha - head commit of the displayed diff. @@ -1331,7 +1706,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise /** - * Publish a line comment or completed review for a visible Session binding. + * Publish a line comment or completed review for a visible Session binding. The threads kept for the change request + * are dropped once the host answers, so the next read shows the comments. * @param session - Session retaining the change request. * @param url - visible binding URL. * @param request - reviewed head, ranges, plain text, and explicit review decision. @@ -1340,6 +1716,21 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise +/** + * Write to the review threads or the pending review of a change request of a Session while its head is still the + * head the user saw. The threads kept for the change request are dropped once the host answers, so the next read + * shows the write, which a resolve does not show through a GitHub pull request's update time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param write - the write and the head commit of the threads the user saw. + * @param signal - request cancellation. + * @returns whether the host took the write; `stale` once the head moved, which polls the change request again, and + * `unknown` when the outcome must be checked on the host before the write is tried again. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; an error + * for a write without text, a head that is not a commit object name, or an invalid line range. + */ +@Remote async changeRequestReviewWrite( session: Session, url: string, write: ForgeReviewWrite, signal: AbortSignal, ): Promise + /** * Mark a draft change request of a Session ready for review; the change * request is polled again once the host answers. @@ -1365,6 +1756,60 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async merge(session: Session, url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise +/** + * Rerun the failed checks of a change request of a Session while its head is still the commit whose checks the user + * saw; the change request is polled again once the host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param request - the head commit whose checks the user saw. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's + * reason when the host refuses, cannot be reached, or reruns no checks; `forgePanel/action-unknown` when the host did + * not confirm whether it started the rerun. + */ +@Remote async rerunChecks(session: Session, url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request of a Session from more reviewers; the change request is polled again once the + * host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param reviewers - the reviewers to ask, by kind and login. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/action-failed` with the host's reason when the host refuses, cannot be reached, or requests no reviews; + * `forgePanel/action-unknown` when the host did not confirm whether it requested the reviews. + */ +@Remote async requestReviews( session: Session, url: string, reviewers: readonly Pick[], signal: AbortSignal, ): Promise + +/** + * List accounts a review of a change request of a Session can be requested from. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param query - text the login or name contains; empty for the host's suggestions and first accounts. + * @param signal - request cancellation. + * @returns the accounts, the host's suggestions first. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/reviewers-failed` when the host does not list them. + */ +@Remote async reviewerCandidates(session: Session, url: string, query: string, signal: AbortSignal): Promise + +/** + * Bring the base branch's new commits into the head branch of a change request of a Session while its head is still + * `headSha`; the change request is polled again once the host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param method - merge commit or rebase. + * @param headSha - head commit the user confirmed. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `headSha`; `forgePanel/action-failed` with the host's reason when + * the host refuses, cannot be reached, or updates no branches; `forgePanel/action-unknown` when the host did not + * confirm whether it started the update. + */ +@Remote async updateBranch(session: Session, url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise + /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index c0b5f11fe0..6ef0264108 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -53,6 +53,12 @@ interface ForgeProvider { * Omission declares that this provider cannot read reviews. */ readReview?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * Write to the review threads or the pending review of a change request while its head is `write.headSha`; once the + * head is another commit, the write resolves to `stale` without writing. A write is never retried. Omission declares + * that this provider cannot write reviews, and its `readReview` then reports no viewer permission. + */ + writeReview?(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise /** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */ repositoryFromRemote(url: string): ForgeRepository | undefined /** Map a change request web URL to its reference, or undefined when this provider does not serve it. */ @@ -95,6 +101,38 @@ interface ForgeProvider { * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. */ compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** + * Read the signed-in user's viewed marks on the change request's files at head commit `headSha`. The marks are + * returned only when the read names `headSha` as the head; once the head is another commit, the read resolves to a + * `stale` failure. A provider implements `viewedFiles` and `setViewed` together; omitting either declares that the + * host keeps no viewed marks. + */ + viewedFiles?(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + /** + * Set or clear the signed-in user's viewed mark on one file while the head is still `request.headSha`, resolving to + * undefined once the host saved it. + */ + setViewed?(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** + * Rerun the failed checks of the head commit that name a `rerun` none of whose checks is pending, while the head is + * still `request.headSha`, resolving to undefined once the host accepted every rerun. Omission declares that the + * provider reruns no checks, and its snapshots then name none. + */ + rerunChecks?(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise + /** + * Request reviews from more reviewers, resolving to undefined once the host accepted the request. A provider implements + * `requestReviews` and `reviewerCandidates` together; omitting either declares that it requests no reviews, and its + * snapshots then deny `canRequestReviews`. + */ + requestReviews?(ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal): Promise + /** List accounts whose login or name matches `query`, the host's suggestions first, for a review request. */ + reviewerCandidates?(ref: ChangeRequestRef, query: string, signal: AbortSignal): Promise + /** + * Bring the base branch's new commits into the head branch while its head is still `request.headSha`, resolving to + * undefined once the host accepted the update. Omission declares that the provider updates no branches, and its + * snapshots then offer no `branchUpdates`. + */ + updateBranch?(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise } ``` @@ -167,6 +205,11 @@ interface ChangeRequestCheck { readonly startedAt: string | null /** ISO 8601 time the check completed, or null while it runs and when the host reports none. */ readonly completedAt: string | null + /** + * Identity a rerun of this check names, or null when the provider cannot rerun it, as for a commit status. Checks that + * name one identity rerun together, and their failed checks can be rerun once none of them is pending. + */ + readonly rerun: ForgeCheckId | null } ``` @@ -224,18 +267,36 @@ interface ChangeRequestSnapshot { readonly mergeReady: boolean /** Merge methods the repository accepts, the signed-in user's usual one first. */ readonly mergeMethods: readonly MergeMethod[] + /** + * Ways the signed-in user can bring the base branch's new commits into the head branch now; empty while the head is + * up to date, while the branches conflict, when the user cannot update the head branch, or when the provider cannot, + * so a head behind its base cannot be told apart from a current one for a user without the right to update it. + */ + readonly branchUpdates: readonly BranchUpdateMethod[] /** Aggregate review outcome. */ readonly reviewDecision: ReviewDecision + /** Reviewers whose review is requested, in host order, then other accounts that reviewed, each once; the author is never listed. */ + readonly reviewers: readonly ChangeRequestReviewer[] + /** Whether the host reported more review requests or reviews than the provider read, so `reviewers` may be incomplete. */ + readonly reviewersTruncated: boolean + /** Whether the signed-in user may request reviews of the change request through its provider. */ + readonly canRequestReviews: boolean /** Checks on the head commit in host order. */ readonly checks: readonly ChangeRequestCheck[] /** Combined check outcome. */ readonly checksRollup: ChecksRollup /** Whether the host reported more checks than `checks` contains. */ readonly checksTruncated: boolean + /** Whether the signed-in user may rerun the failed checks that name a `rerun`. */ + readonly canRerunChecks: boolean /** Number of counted review threads that are not resolved. */ readonly unresolvedThreads: number /** Whether the change request has more review threads than the provider counted, so `unresolvedThreads` is a lower bound. */ readonly threadsTruncated: boolean + /** Issues linked to the change request, which the host closes once it merges, in host order. */ + readonly closingIssues: readonly ChangeRequestIssue[] + /** Whether the host reported more closing issues than `closingIssues` holds. */ + readonly closingIssuesTruncated: boolean /** ISO 8601 time of the host's last update to the change request. */ readonly updatedAt: string /** ISO 8601 time the change request was merged or closed, or null while it is open. */ @@ -297,19 +358,21 @@ interface MergeRequest { ``` ```ts type-equiv -/** Why a provider could not change a change request. */ +/** Why a provider could not change a change request, or could not confirm that it did. */ interface ForgeActionFailure { /** * `unauthenticated`: credentials are missing or rejected; `stale`: the head - * moved past the confirmed commit; `failed`: the host refused or could not be reached. + * moved past the confirmed commit; `failed`: the host refused or could not be reached, so nothing changed; + * `unknown`: the request reached the host but its answer did not confirm the outcome, so the change may have been + * applied and must be checked on the host before it is tried again. */ - readonly code: 'unauthenticated' | 'stale' | 'failed' + readonly code: 'unauthenticated' | 'stale' | 'failed' | 'unknown' /** Human-readable cause, usually the host's own message. */ readonly message: string } ``` -`ctx.forge.submitReview` 将明确指定的评论或完整评审交给 provider;未实现此能力的 provider 返回不支持。消费者保存待提交草稿,并在再次提交前核对结果不明的写操作。 +`ctx.forge.submitReview` 将明确指定的评论或完整评审交给 provider;未实现此能力的 provider 返回不支持。消费者在再次提交前核对结果不明的写操作;留待之后一起提交的评论通过 `ctx.forge.writeReview` 写入代码托管平台的待提交评审。 ```ts type-equiv /** One inline comment addressed to the old or new side of a pull request diff. */ @@ -329,12 +392,12 @@ type ForgeReviewRequest = { readonly headSha: string } & ( | { readonly kind: 'comment'; readonly comment: ForgeLineComment } - | { readonly kind: 'review'; readonly event: 'comment' | 'approve' | 'request-changes'; readonly body: string; readonly comments: readonly ForgeLineComment[] } + | { readonly kind: 'review'; readonly event: ForgeReviewEvent; readonly body: string; readonly comments: readonly ForgeLineComment[] } ) ``` ```ts type-equiv -/** Result of a review write; unknown outcomes must be checked on the host before another submission. */ +/** Result of a review submission; unknown outcomes must be checked on the host before another submission. */ type ForgeReviewResult = | { readonly ok: true; readonly url: string } | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } @@ -396,6 +459,10 @@ interface ForgeReviewComment { readonly pending: boolean /** Web page of the comment, or null when the host reports none. */ readonly url: string | null + /** Whether the signed-in user can replace the comment's text through `writeReview`; false for a provider without it. */ + readonly viewerCanEdit: boolean + /** Whether the signed-in user can delete the comment through `writeReview`; false for a provider without it. */ + readonly viewerCanDelete: boolean } ``` @@ -422,6 +489,13 @@ interface ForgeReviewThread { readonly diffHunk: string | null /** Whether the thread is marked resolved. */ readonly resolved: boolean + /** Whether the signed-in user can reply to the thread through `writeReview`; false for a provider without it. */ + readonly viewerCanReply: boolean + /** + * Whether the signed-in user can mark the thread resolved, or unresolved when `resolved`, through `writeReview`; false + * for a provider without it. + */ + readonly viewerCanResolve: boolean /** Comments oldest first; the first starts the thread. */ readonly comments: readonly ForgeReviewComment[] } @@ -432,10 +506,202 @@ interface ForgeReviewThread { interface ForgeReviewData { /** Head commit the threads were read at; `current` positions number its files. */ readonly headSha: string + /** Login of the signed-in user the provider read as, or null when the host does not name one. */ + readonly viewer: string | null /** Threads in host order, at most the provider's limit. */ readonly threads: readonly ForgeReviewThread[] /** Whether the change request has more threads than `threads` holds. */ readonly truncated: boolean + /** The signed-in user's pending review, or null without one. */ + readonly pendingReview: ForgePendingReview | null + /** + * Whether the signed-in user can add comments to a pending review and submit or discard it through `writeReview`; + * false for a provider without it. + */ + readonly viewerCanReview: boolean +} +``` + +`ctx.forge.writeReview(ref, write, signal)` 写入评审讨论和当前登录用户的待提交评审:回复讨论,立即发布,或在 `pending` 时加入待提交评审;把讨论标记为已解决或取消解决;编辑或删除评论;在 head 上添加一条行内评论到待提交评审;以及提交或丢弃待提交评审。用户还没有待提交评审时,待提交的回复或评论会先开始一个评审。每个写操作都带有用户看到的 head 提交;提供方先检查它,head 已变化时不写入,直接返回 `stale`,并像读取遇到 `stale` 时那样重新轮询被关注的变更请求;其他结果之后,服务都会立即重新轮询被关注的变更请求。写操作从不重试;结果为 `unknown` 时,必须先在托管平台上核对,再重试。提供方没有实现 `writeReview` 时,服务返回 `unsupported`。`ForgeReviewData` 带有待提交评审,以及用户对每个讨论、每条评论和待提交评审的权限;未实现 `writeReview` 的提供方把这些权限报告为没有,使用方据此只提供能够成功的写操作。GraphQL mutation 以及它们的结果如何对应到这些返回值,由 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package) 说明。 + +```ts type-equiv +/** Opaque host identity of one review. */ +type ForgeReviewId = Branded<'ForgeReviewId'> +``` + +```ts type-equiv +/** The signed-in user's review of a change request that is not submitted yet, which only that user sees. */ +interface ForgePendingReview { + /** Host identity of the review. */ + readonly id: ForgeReviewId + /** Comments the review holds. */ + readonly comments: number +} +``` + +```ts type-equiv +/** Decision a submitted review records. */ +type ForgeReviewEvent = 'comment' | 'approve' | 'request-changes' +``` + +```ts type-equiv +/** + * One write to the review threads and the pending review of a change request. `pending` replies and `add-pending` + * comments join the signed-in user's pending review, which is started when the user has none. A host that adds every + * reply to an existing pending review, as GitHub does, refuses a reply with `pending: false` while one exists. + */ +type ForgeReviewWrite = { + /** Head commit the user saw; providers check it before writing and refuse with `stale` once the head is another commit. */ + readonly headSha: string +} & ( + | { readonly kind: 'reply'; readonly thread: ForgeThreadId; readonly body: string; readonly pending: boolean } + | { readonly kind: 'resolve'; readonly thread: ForgeThreadId; readonly resolved: boolean } + | { readonly kind: 'edit-comment'; readonly comment: ForgeCommentId; readonly body: string } + /** Deleting the only comment of a thread deletes the thread. */ + | { readonly kind: 'delete-comment'; readonly comment: ForgeCommentId } + /** A comment on lines of `headSha`. */ + | { readonly kind: 'add-pending'; readonly comment: ForgeLineComment } + | { readonly kind: 'submit-pending'; readonly review: ForgeReviewId; readonly event: ForgeReviewEvent; readonly body: string } + /** Delete the pending review with every comment it holds. */ + | { readonly kind: 'discard-pending'; readonly review: ForgeReviewId } +) +``` + +```ts type-equiv +/** Result of a review write; an `unknown` outcome must be checked on the host before the write is tried again. */ +type ForgeReviewWriteResult = + | { readonly ok: true } + | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } +``` + + + +## 概览与已审阅标记 + +快照还携带变更请求的概览:`reviewers` 及每位评审者最近的结论、合并后托管平台会关闭的 `closingIssues`、能让落后于基线的 head 更新到最新的 `branchUpdates`、当前登录用户能否请求评审或重跑检查,以及每个检查指出的 `rerun`。`ctx.forge.rerunChecks`、`ctx.forge.requestReviews` 与 `ctx.forge.updateBranch` 据此操作,并像上文的操作一样返回 `ForgeActionFailure`,主机的答复无法确认结果时为 `unknown`,提供方答复后立即轮询被监听的变更请求;重跑与更新指明用户看到的 head 提交,head 移动后以 `stale` 拒绝。提供方同时实现 `requestReviews` 与 `reviewerCandidates`,`ctx.forge.reviewerCandidates` 借后者列出可以请求评审的账号;提供方缺少的操作以 `failed` 失败,`reviewerCandidates` 则返回 `unsupported`。GitHub 如何填写各字段并执行这些操作见 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package)。 + +```ts type-equiv +/** Opaque host identity of a status check that a rerun names. */ +type ForgeCheckId = Branded<'ForgeCheckId'> +``` + +```ts type-equiv +/** How an update brings the base branch's new commits into the head branch: a merge commit, or a rebase of the head's commits. */ +type BranchUpdateMethod = 'merge' | 'rebase' +``` + +```ts type-equiv +/** Outcome of a reviewer's latest submitted review. */ +type ReviewVerdict = 'approved' | 'changes-requested' | 'commented' | 'dismissed' +``` + +```ts type-equiv +/** An account or team asked to review a change request, or an account that reviewed it. */ +interface ChangeRequestReviewer { + /** Whether the reviewer is a person's account, an app or bot account, or a team. */ + readonly kind: 'user' | 'bot' | 'team' + /** Login, or `organization/slug` for a team. */ + readonly login: string + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether a review from the reviewer is requested now. */ + readonly requested: boolean + /** Whether the host requested the review because the reviewer owns changed paths. */ + readonly codeOwner: boolean + /** Outcome of the reviewer's latest submitted review, or null before the first. */ + readonly verdict: ReviewVerdict | null + /** Commit the latest submitted review was on, or null before the first or when the host reports none. */ + readonly reviewedSha: string | null +} +``` + +```ts type-equiv +/** One issue linked to a change request, which the host closes once the change request merges. */ +interface ChangeRequestIssue { + /** Repository that holds the issue. */ + readonly repository: ForgeRepository + /** Host-assigned issue number. */ + readonly number: number + /** Title as the author wrote it. */ + readonly title: string + /** Whether the issue is still open. */ + readonly state: 'open' | 'closed' + /** Web page of the issue. */ + readonly url: string +} +``` + +```ts type-equiv +/** A rerun of the failed checks of the head commit whose checks the user saw. */ +interface ForgeRerunRequest { + /** Head commit whose checks the user saw; the provider refuses with `stale` once the head is another commit. */ + readonly headSha: string +} +``` + +```ts type-equiv +/** Reviewers to ask in addition to those whose review is requested now; one who already reviewed is asked again. */ +interface ForgeReviewersRequest { + /** The reviewers by kind and login, a team by `organization/slug`. */ + readonly reviewers: readonly Pick[] +} +``` + +```ts type-equiv +/** An account a review of the change request can be requested from. */ +interface ForgeReviewerCandidate { + /** Login as the host spells it. */ + readonly login: string + /** Display name, or null when the account shows none. */ + readonly name: string | null + /** Avatar image URL, or null when the host reports none. */ + readonly avatarUrl: string | null + /** Whether the host suggests the account for this change request, as from the history of its changed files. */ + readonly suggested: boolean +} +``` + +```ts type-equiv +/** A branch update the user confirmed for the head commit they saw. */ +interface BranchUpdateRequest { + /** How the base branch's new commits enter the head branch. */ + readonly method: BranchUpdateMethod + /** Commit object name the head must still have; the update is refused once the head moves. */ + readonly headSha: string +} +``` + +`ctx.forge.viewedFiles` 与 `ctx.forge.setViewed` 在一个 head 提交上读取和修改当前登录用户对变更请求各文件的已审阅标记。只有同时实现两个方法的提供方保存已审阅标记;否则 `viewedFiles` 返回 undefined,`setViewed` 失败,由使用方自行保存标记。`stale` 答复会像过期的 diff 读取一样立即轮询被监听的变更请求。 + +```ts type-equiv +/** + * The signed-in user's review progress on one changed file: `viewed`, `unviewed`, or `dismissed` once the file + * changed after the user marked it viewed. + */ +type ForgeViewedState = 'viewed' | 'unviewed' | 'dismissed' +``` + +```ts type-equiv +/** The signed-in user's viewed marks on the files of a change request, read at one head commit. */ +interface ForgeViewedFiles { + /** Head commit the marks were read at. */ + readonly headSha: string + /** State of each changed file the host listed, by repository-relative path. */ + readonly files: Readonly> + /** Whether the change request has more files than `files` lists. */ + readonly truncated: boolean +} +``` + +```ts type-equiv +/** A viewed mark the user set or cleared on a file of the head commit they saw. */ +interface ForgeViewedRequest { + /** Repository-relative path of the changed file. */ + readonly path: string + /** Whether the file is viewed. */ + readonly viewed: boolean + /** Head commit whose changes the user saw; the provider refuses with `stale` once the head is another commit. */ + readonly headSha: string } ``` @@ -730,6 +996,10 @@ type ForgeChangeRequestStatesFrame = `changeRequestReview(session, url, headSha, fresh)` 在视图所显示 diff 的 head 处读取已绑定变更请求的讨论;head 不同时以 `forgePanel/stale-head` 拒绝,提供方不支持读取讨论时返回 `forgePanel/review-unsupported`,其他失败返回 `forgePanel/review-failed`。每个变更请求在内存里保留一次读取结果,以 head 提交和状态的更新时间为键、受 `maxCachedReviewBytes` 约束,保留时间达到 `reviewRefreshMs` 后,或 `fresh` 要求时(读者刷新视图后的第一次读取就是这样)重新读取:在 GitHub 上,新评论和回复会改变 PR 的更新时间,解决讨论则不会。变更视图可见时,每收到一次状态就重新请求一次,并按[面板 README](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package) 所述把讨论叠加到文件上。 +`changeRequestViewed(session, url, headSha)` 在视图所示 diff 的 head 上读取已绑定变更请求的已审阅标记,提供方不保存标记时返回 null,head 不同时以 `forgePanel/stale-head` 拒绝,其他失败以 `forgePanel/viewed-failed` 拒绝;`setFileViewed` 在该 head 上保存一个文件的标记。`rerunChecks`、`requestReviews` 与 `updateBranch` 作用于已绑定的变更请求,托管平台未确认的结果以 `forgePanel/action-unknown` 拒绝,`reviewerCandidates` 列出可请求评审的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随 diff 一起读取整个变更请求的标记,本地变更与所选提交的标记保存在浏览器中;两者以及提供这些操作的卡片行见[面板 README](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package)。 + +`changeRequestReviewWrite(session, url, write)` 检查已绑定变更请求的一个 `ForgeReviewWrite` 的 head 提交、id、文字和行范围后,交给 `ctx.forge.writeReview`,并返回 `ForgeReviewWriteResult`。提供方给出答复后,无论结果如何,都会丢弃该变更请求保留的讨论,以及在此之前开始的所有读取,使下一次 `changeRequestReview` 从托管平台读取;`submitReview` 同样如此。变更视图一次只发送一个写操作,每个可能改变讨论的写操作之后都会重新读取讨论。 + ```ts type-equiv /** * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order @@ -1006,6 +1276,49 @@ async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Rerun the failed checks of a change request's head commit while the head is still `request.headSha`, then poll it + * at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - the head commit whose checks the user saw. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the rerun, or why it did not; a provider that reruns no checks fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async rerunChecks(ref: ChangeRequestRef, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request from more reviewers, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - the reviewers to ask. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the request, or why it did not; a provider that requests no reviews fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async requestReviews( ref: ChangeRequestRef, request: ForgeReviewersRequest, signal: AbortSignal, ): Promise + +/** + * List accounts a review of a change request can be requested from. + * @param ref - change request served by a registered provider. + * @param query - text the login or name contains; empty for the host's suggestions and first accounts. + * @param signal - cancellation of the read. + * @returns the accounts, the host's suggestions first, or why the host did not list them; a provider that requests no + * reviews returns `unsupported`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async reviewerCandidates( ref: ChangeRequestRef, query: string, signal: AbortSignal, ): Promise + +/** + * Bring the base branch's new commits into a change request's head branch while its head is still + * `request.headSha`, then poll it at once when it is watched. + * @param ref - change request served by a registered provider. + * @param request - update method and the head commit the user confirmed. + * @param signal - cancellation of the request. + * @returns undefined once the host accepted the update, or why it did not; a provider that updates no branches fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async updateBranch(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise + /** * Read complete check details independently of periodic polling. * @param ref - change request served by a registered provider. @@ -1041,6 +1354,42 @@ async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise */ async readReview(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise +/** + * Write to the review threads or the pending review of a change request while its head is still `write.headSha`, then + * poll the change request at once when it is watched, unless the provider cannot write reviews. A `stale` result polls + * it as a stale read does. + * @param ref - change request served by a registered provider. + * @param write - the write and the head commit the user saw. + * @param signal - cancellation of the write. + * @returns whether the host took the write; `unsupported` when the provider cannot write reviews, and `unknown` when the + * outcome must be checked on the host before the write is tried again. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async writeReview(ref: ChangeRequestRef, write: ForgeReviewWrite, signal: AbortSignal): Promise + +/** + * Read the signed-in user's viewed marks on the files of a change request at one head commit. A `stale` failure + * polls a watched change request again as {@link ForgeService.diff} does. + * @param ref - change request served by a registered provider. + * @param headSha - head commit the marks must be read at, usually the head of the displayed diff. + * @param signal - cancellation of the read. + * @returns the marks read at `headSha`, why the host did not provide them, or undefined when the provider keeps no + * viewed marks. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async viewedFiles(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request while its head is still + * `request.headSha`. A `stale` failure polls a watched change request again as {@link ForgeService.diff} does. + * @param ref - change request served by a registered provider. + * @param request - the file, its mark, and the head commit the user saw. + * @param signal - cancellation of the request. + * @returns undefined once the host saved the mark, or why it did not; a provider that keeps no viewed marks fails. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async setViewed(ref: ChangeRequestRef, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** * List the commits of a change request at its current head. * @param ref - change request served by a registered provider. @@ -1311,11 +1660,39 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise +/** + * Read the signed-in user's viewed marks on the files of a change request of a Session, which the host keeps for the + * whole change request. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param headSha - head commit of the shown diff; marks read at another head are refused. + * @param signal - request cancellation. + * @returns the marks at `headSha`, or null when the provider keeps no viewed marks. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `headSha`, which is then polled again; `forgePanel/viewed-failed` + * when the host does not provide the marks otherwise. + */ +@Remote async changeRequestViewed(session: Session, url: string, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request of a Session. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param request - the file, its mark, and the head commit of the shown diff. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's + * reason when the host refuses, cannot be reached, or keeps no viewed marks; `forgePanel/action-unknown` when the host + * did not confirm whether it saved the mark. + */ +@Remote async setFileViewed(session: Session, url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise + /** * Read the review threads of a change request of a Session at the head commit of its displayed diff. Threads read * at the same head commit and update time are reused from memory, for any Session, until they are - * `reviewRefreshMs` old or `maxCachedReviewBytes` evicts them; a read again after that age, or a `fresh` read, - * shows threads resolved since, which do not change a GitHub pull request's update time. + * `reviewRefreshMs` old, `maxCachedReviewBytes` evicts them, or a review write through this panel drops them; a read + * again after that age, or a `fresh` read, shows threads resolved elsewhere since, which do not change a GitHub pull + * request's update time. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param headSha - head commit of the displayed diff. @@ -1331,7 +1708,8 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async changeRequestReview(session: Session, url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise /** - * Publish a line comment or completed review for a visible Session binding. + * Publish a line comment or completed review for a visible Session binding. The threads kept for the change request + * are dropped once the host answers, so the next read shows the comments. * @param session - Session retaining the change request. * @param url - visible binding URL. * @param request - reviewed head, ranges, plain text, and explicit review decision. @@ -1340,6 +1718,21 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise +/** + * Write to the review threads or the pending review of a change request of a Session while its head is still the + * head the user saw. The threads kept for the change request are dropped once the host answers, so the next read + * shows the write, which a resolve does not show through a GitHub pull request's update time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param write - the write and the head commit of the threads the user saw. + * @param signal - request cancellation. + * @returns whether the host took the write; `stale` once the head moved, which polls the change request again, and + * `unknown` when the outcome must be checked on the host before the write is tried again. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; an error + * for a write without text, a head that is not a commit object name, or an invalid line range. + */ +@Remote async changeRequestReviewWrite( session: Session, url: string, write: ForgeReviewWrite, signal: AbortSignal, ): Promise + /** * Mark a draft change request of a Session ready for review; the change * request is polled again once the host answers. @@ -1365,6 +1758,60 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async merge(session: Session, url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise +/** + * Rerun the failed checks of a change request of a Session while its head is still the commit whose checks the user + * saw; the change request is polled again once the host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param request - the head commit whose checks the user saw. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `request.headSha`; `forgePanel/action-failed` with the host's + * reason when the host refuses, cannot be reached, or reruns no checks; `forgePanel/action-unknown` when the host did + * not confirm whether it started the rerun. + */ +@Remote async rerunChecks(session: Session, url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request of a Session from more reviewers; the change request is polled again once the + * host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param reviewers - the reviewers to ask, by kind and login. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/action-failed` with the host's reason when the host refuses, cannot be reached, or requests no reviews; + * `forgePanel/action-unknown` when the host did not confirm whether it requested the reviews. + */ +@Remote async requestReviews( session: Session, url: string, reviewers: readonly Pick[], signal: AbortSignal, ): Promise + +/** + * List accounts a review of a change request of a Session can be requested from. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param query - text the login or name contains; empty for the host's suggestions and first accounts. + * @param signal - request cancellation. + * @returns the accounts, the host's suggestions first. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/reviewers-failed` when the host does not list them. + */ +@Remote async reviewerCandidates(session: Session, url: string, query: string, signal: AbortSignal): Promise + +/** + * Bring the base branch's new commits into the head branch of a change request of a Session while its head is still + * `headSha`; the change request is polled again once the host answers. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param method - merge commit or rebase. + * @param headSha - head commit the user confirmed. + * @param signal - request cancellation. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past `headSha`; `forgePanel/action-failed` with the host's reason when + * the host refuses, cannot be reached, or updates no branches; `forgePanel/action-unknown` when the host did not + * confirm whether it started the update. + */ +@Remote async updateBranch(session: Session, url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise + /** * Ask for a new worktree before the Session's first turn, replacing an open * request and forgetting a failed attempt. While the next message waits in diff --git a/docs/subsystems/llm-streaming.i18n.yaml b/docs/subsystems/llm-streaming.i18n.yaml index 59d8d46494..49f34b6799 100644 --- a/docs/subsystems/llm-streaming.i18n.yaml +++ b/docs/subsystems/llm-streaming.i18n.yaml @@ -27,8 +27,8 @@ en: cbab49d689311d4d zh: 76246140eabaa55e /llm-streaming/appidentity-app-attribution: - en: e053f18c7dc070a8 - zh: 90ded9a892ed2fd5 + en: 2da6911c03ea8195 + zh: ae55da1a7e22be3a /llm-streaming/tokenusage: en: 33830f78fdb845fa zh: f43a4502c4c3bfff diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 565da04ff2..078f4f4700 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -311,7 +311,7 @@ Retry configuration resolves before route registration into an immutable discrim ## `AppIdentity` — app attribution -The static public application identity every adapter sends to providers ([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts)). `attributionHeaders(identity?)` maps it to the standard `User-Agent` header only; OpenRouter-specific app attribution headers are intentionally not supported by this contract. The default `APP_IDENTITY` sources its version from the package manifest; every field is a public product fact - no secrets, paths, session ids, or per-user identifiers, and nothing per-request may influence the values. +The static public application identity every adapter sends to providers ([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts)). `attributionHeaders(identity?)` maps it to the standard `User-Agent` header only; OpenRouter-specific app attribution headers are intentionally not supported by this contract. The default `APP_IDENTITY` sources its version from the package manifest; every field is a public product fact - no secrets, paths, session ids, or per-user identifiers, and nothing per-request may influence the values. `APP_IDENTITY.suffix` reads `DSH_USER_AGENT_SUFFIX` on each use, and `userAgent()` appends it after the comment; a value that is not an RFC 9110 product token fails the request. The `dsh` launcher sets it to `dsh-profile/` before any plugin loads, percent-encoding profile-name bytes outside `tchar` and `%` itself, so Desktop sends `deepseek-harness/ (+) dsh-profile/desktop` and a profile named `my web` sends `dsh-profile/my%20web`. A dsh subagent child reports its own profile, because child processes do not inherit `DSH_*` variables. ```ts type-equiv /** @@ -328,6 +328,8 @@ interface AppIdentity { version: string /** Repository home URL of the app, used as the `User-Agent` comment. */ url: string + /** RFC 9110 product token appended after the comment, such as `dsh-profile/web`. */ + suffix?: string | undefined } ``` diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 2f360b8f8f..dcebebf666 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -313,7 +313,7 @@ interface LlmImageRequestPricing { ## `AppIdentity`:应用归属 -每个适配器都会向提供方发送的静态公开应用标识([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts))。`attributionHeaders(identity?)` 只把它映射到标准 `User-Agent` header;该约定有意不支持 OpenRouter 特有的应用归属 header。默认 `APP_IDENTITY` 从包 manifest(元数据清单)获取版本;每个字段都是公开产品事实——不含 secret、路径、会话 id 或逐用户标识,且任何逐请求信息都不得影响这些值。 +每个适配器都会向提供方发送的静态公开应用标识([`packages/llm/llm/src/attribution.ts`](../../packages/llm/llm/src/attribution.ts))。`attributionHeaders(identity?)` 只把它映射到标准 `User-Agent` header;该约定有意不支持 OpenRouter 特有的应用归属 header。默认 `APP_IDENTITY` 从包 manifest(元数据清单)获取版本;每个字段都是公开产品事实——不含 secret、路径、会话 id 或逐用户标识,且任何逐请求信息都不得影响这些值。`APP_IDENTITY.suffix` 在每次使用时读取 `DSH_USER_AGENT_SUFFIX`,`userAgent()` 将其追加在注释之后;不是 RFC 9110 product token 的值使请求失败。`dsh` 启动器在任何插件加载前将其设为 `dsh-profile/`,并对 profile 名中 `tchar` 以外的字节及 `%` 本身做百分号编码,因此 Desktop 发送 `deepseek-harness/ (+) dsh-profile/desktop`,名为 `my web` 的 profile 发送 `dsh-profile/my%20web`。dsh 子代理子进程报告自己的 profile,因为子进程不继承 `DSH_*` 变量。 ```ts type-equiv /** @@ -330,6 +330,8 @@ interface AppIdentity { version: string /** Repository home URL of the app, used as the `User-Agent` comment. */ url: string + /** RFC 9110 product token appended after the comment, such as `dsh-profile/web`. */ + suffix?: string | undefined } ``` diff --git a/docs/subsystems/ptc-runtime.i18n.yaml b/docs/subsystems/ptc-runtime.i18n.yaml index b9a617739e..a7b7310228 100644 --- a/docs/subsystems/ptc-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -6,14 +6,14 @@ en: 337a6580d7571274 zh: f4ae98899120d122 /ptc-runtime/the-run-request-in-result-out: - en: 6dfa7da8b13a4f17 - zh: 09a3c8c4922239ef + en: 94ba725bef6684b7 + zh: f113745a4a07952a /ptc-runtime/bindings-host-functions-as-program-globals: en: 182147ddf388c600 zh: c0a7d77602c78bcd /ptc-runtime/captured-output-and-the-failure-taxonomy: - en: 8eb1607888ab6efc - zh: 580c852d17b9413f + en: ef553620e77bd638 + zh: 40ff2f5ba3de5ed5 /ptc-runtime/the-service: en: a82f828fa006c7e9 zh: 2279d36867335b57 diff --git a/docs/subsystems/ptc-runtime.md b/docs/subsystems/ptc-runtime.md index e4d299abfe..8c716cd1f9 100644 --- a/docs/subsystems/ptc-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -19,13 +19,15 @@ interface PtcRunRequest { /** * The program source, in the runtime's {@link ../index.ts | language}. It * follows the provider's programFormat: an async function body supports - * top-level `await` and `return`; REPL and Script programs support top-level + * top-level `await` and `return`; REPL (`repl`, `scoped-repl`) and Script programs support top-level * declarations, `await`, and a final expression, but not top-level `return`. * The Script provider lowers top-level await; its executionInstructions and * documentation define retained-binding semantics. The completion value * becomes {@link PtcRunResult.value}. */ program: string + /** Discard the completion without JSON validation when true; omission preserves the completion value. */ + discardCompletion?: boolean /** * Object-identity owner for optional in-memory state. Omission requests a fresh * environment. Consumers must await runtime.release(owner) when the owner ends. @@ -93,11 +95,12 @@ interface PtcRunResult { */ value?: PtcJsonValue /** - * Captured text. Each source channel preserves emission order; interleaving + * Captured text fragments retain their emitted line breaks. Concatenate adjacent text without separators. + * Each source channel preserves emission order; interleaving * across independent channels is backend-dependent. Bounded only as part of * the outer result. */ - logs: string[] + output: PtcOutput[] /** Present iff the run failed; see {@link PtcRunFailure} for the taxonomy. */ error?: PtcRunFailure } @@ -105,10 +108,10 @@ interface PtcRunResult { ```ts type-equiv /** Source evaluation form, independent of retained program state. */ -type PtcProgramFormat = 'function-body' | 'repl' | 'script' +type PtcProgramFormat = 'function-body' | 'repl' | 'script' | 'scoped-repl' ``` -`programFormat` distinguishes async function bodies, REPL statements, and scripts. REPL and Script programs accept top-level `await`, declarations, and a final expression; top-level `return` is not supported. The Node Script provider lowers top-level await and awaits the completion value; its [declaration limitations](../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work) apply to transformed programs. `retainsState` reports memory retention independently of source syntax. `stateOwner` is an in-process object identity for optional retained memory; distinct objects remain isolated. Consumers await `release(owner)` when that owner ends; cleanup failures reject that call. Omitted owners are one-shot, and stateless providers ignore ownership. The [persistent Node provider](../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) defines reset and recovery behavior; no retained object enters the durable Session format. +`programFormat` distinguishes async function bodies, REPL statements, scoped REPL statements, and scripts. REPL, scoped REPL, and Script programs accept top-level `await`, declarations, and a final expression; top-level `return` is not supported. Retained REPL calls share one scope, while each scoped REPL call starts with copies of the top-level bindings that earlier calls left, so it can declare those names again without changing earlier code. The Node Script provider lowers top-level await and awaits the completion value; its [declaration limitations](../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work) apply to transformed programs. `retainsState` reports memory retention independently of source syntax. `stateOwner` is an in-process object identity for optional retained memory; distinct objects remain isolated. Consumers await `release(owner)` when that owner ends; cleanup failures reject that call. Omitted owners are one-shot, and stateless providers ignore ownership. The [persistent Node provider](../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) defines reset and recovery behavior; no retained object enters the durable Session format. ## Bindings: host functions as program globals @@ -150,7 +153,7 @@ interface PtcBindingNamespace { * words, so the same namespace list works against every backend regardless * of `language` — a JS-only spelling like `$tools` is rejected by design, * not just by the Python backend. Names that satisfy the identifier rule but - * name a backend-owned slot (`RESERVED_BINDING_GLOBALS`, e.g. `console`, + * name a backend-owned slot (`RESERVED_BINDING_GLOBALS`, e.g. `inspect`, `console`, `Image`, * `__dsh_main__`) are also refused everywhere; see its declaration for the * exact set and why each entry is reserved. */ @@ -171,7 +174,7 @@ type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | { [key: /** * One host-side function exposed to the program as an async callable. The * runtime bridges calls to it (possibly across a serialization boundary), so - * `args` and the resolution value MUST be lossless JSON. A runtime rejects a + * `args` must be lossless JSON; resolutions also support host-issued PtcImage values. A runtime rejects a * lossy or non-cloneable value with a descriptive error rather than corrupting * the run. No seam-level byte cap applies to a binding resolution. A rejection * of this function surfaces inside the program as a rejection of the @@ -182,7 +185,29 @@ type PtcBindingFunction = (args: unknown) => Promise ## Captured output and the failure taxonomy -Logs are plain strings. Each source channel preserves emission order, while interleaving across independent channels is backend-dependent because channel metadata is not part of the seam. The runtime captures the program's console and stream output, and consumers render only the text. Implementations cap the serialized outer log-array plus completion-value or failure-message payload; fixed result-envelope syntax and consumer presentation whitespace are not part of that variable-payload ledger. Overflow is an explicit failure rather than in-band value substitution. +`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. + +```ts public-api +/** A stored image readable from the program's execution environment. */ +declare class PtcImage { + readonly [key: string]: PtcJsonValue; + /** Absolute attachment file path readable in the execution world. */ + readonly path: string; + /** Stored image selected when the program inspects this value. */ + readonly attachment: Readonly; + /** + * Describe one immutable image file in the execution world. + * @param path - Absolute path to the stored image. + * @param attachment - Reference to the immutable stored image. + */ + constructor(path: string, attachment: ImageAttachmentRef); +} +``` + +```ts type-equiv +/** Raw text fragments and inspected images in emission order; concatenate adjacent text without separators. */ +type PtcOutput = { type: 'text'; text: string } | { type: 'image'; attachment: ImageAttachmentRef } +``` Failure kinds are **orthogonal outcomes reported independently** (per [defensive-patterns](../defensive-patterns/general.md)): a budget expiry is not an exception, an abort is not a timeout, and a substrate death (e.g. OOM) is neither: @@ -237,6 +262,21 @@ Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and subst */ release(owner: object): Promise +/** + * Register source evaluated once when each execution environment is created. + * Registration must precede the first run admission; only one initializer may + * be registered. Current bindings are installed before initialization. Its + * completion is discarded; logs, timeout, cancellation and output bounds share + * the first run. Initialization failure discards the environment without + * executing the user program or rolling back external effects. + * @param program - Initialization source in the provider's language and format. + * @returns An idempotent async disposer that stops admission, cancels and drains + * admitted runs, and releases environments. Failed cleanup blocks execution + * until the disposer succeeds on retry. The caller owns this disposer. + * @throws When unsupported, registered twice, registered after admission, or invalid. + */ +registerEnvironmentInitializer(program: string): () => Promise + /** * Resolve supported options and provider defaults before execution. * @param request - Program, bindings, cancellation and optional execution choices. diff --git a/docs/subsystems/ptc-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md index 2760112064..350c4d20b3 100644 --- a/docs/subsystems/ptc-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -19,13 +19,15 @@ interface PtcRunRequest { /** * The program source, in the runtime's {@link ../index.ts | language}. It * follows the provider's programFormat: an async function body supports - * top-level `await` and `return`; REPL and Script programs support top-level + * top-level `await` and `return`; REPL (`repl`, `scoped-repl`) and Script programs support top-level * declarations, `await`, and a final expression, but not top-level `return`. * The Script provider lowers top-level await; its executionInstructions and * documentation define retained-binding semantics. The completion value * becomes {@link PtcRunResult.value}. */ program: string + /** Discard the completion without JSON validation when true; omission preserves the completion value. */ + discardCompletion?: boolean /** * Object-identity owner for optional in-memory state. Omission requests a fresh * environment. Consumers must await runtime.release(owner) when the owner ends. @@ -93,11 +95,12 @@ interface PtcRunResult { */ value?: PtcJsonValue /** - * Captured text. Each source channel preserves emission order; interleaving + * Captured text fragments retain their emitted line breaks. Concatenate adjacent text without separators. + * Each source channel preserves emission order; interleaving * across independent channels is backend-dependent. Bounded only as part of * the outer result. */ - logs: string[] + output: PtcOutput[] /** Present iff the run failed; see {@link PtcRunFailure} for the taxonomy. */ error?: PtcRunFailure } @@ -105,10 +108,10 @@ interface PtcRunResult { ```ts type-equiv /** Source evaluation form, independent of retained program state. */ -type PtcProgramFormat = 'function-body' | 'repl' | 'script' +type PtcProgramFormat = 'function-body' | 'repl' | 'script' | 'scoped-repl' ``` -`programFormat` 区分异步函数体、REPL 语句与脚本。REPL 与 Script 程序接受顶层 `await`、声明和末尾表达式,不支持顶层 `return`。Node Script 提供方转换顶层 await 并等待完成值;其[声明限制](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)适用于转换后的程序。`retainsState` 独立于源码语法报告是否保留内存。`stateOwner` 是标识可选保留内存的进程内对象身份;不同对象相互隔离。消费者在所有者结束时等待 `release(owner)`;清理失败时该调用拒绝。省略所有者时仅执行一次,无状态提供方忽略所有权。[持久 Node 提供方](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)定义重置和恢复行为;保留对象不会进入持久 Session 格式。 +`programFormat` 区分异步函数体、REPL 语句、scoped REPL 语句与脚本。REPL、scoped REPL 与 Script 程序接受顶层 `await`、声明和末尾表达式,不支持顶层 `return`。保留状态的 REPL 各次调用共用一个作用域;scoped REPL 每次调用开始时拿到之前调用留下的顶层绑定的拷贝,因此可以再次声明这些名字,而不改变之前的代码。Node Script 提供方转换顶层 await 并等待完成值;其[声明限制](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)适用于转换后的程序。`retainsState` 独立于源码语法报告是否保留内存。`stateOwner` 是标识可选保留内存的进程内对象身份;不同对象相互隔离。消费者在所有者结束时等待 `release(owner)`;清理失败时该调用拒绝。省略所有者时仅执行一次,无状态提供方忽略所有权。[持久 Node 提供方](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)定义重置和恢复行为;保留对象不会进入持久 Session 格式。 ## 绑定:宿主函数作为程序全局变量 @@ -150,7 +153,7 @@ interface PtcBindingNamespace { * words, so the same namespace list works against every backend regardless * of `language` — a JS-only spelling like `$tools` is rejected by design, * not just by the Python backend. Names that satisfy the identifier rule but - * name a backend-owned slot (`RESERVED_BINDING_GLOBALS`, e.g. `console`, + * name a backend-owned slot (`RESERVED_BINDING_GLOBALS`, e.g. `inspect`, `console`, `Image`, * `__dsh_main__`) are also refused everywhere; see its declaration for the * exact set and why each entry is reserved. */ @@ -171,7 +174,7 @@ type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | { [key: /** * One host-side function exposed to the program as an async callable. The * runtime bridges calls to it (possibly across a serialization boundary), so - * `args` and the resolution value MUST be lossless JSON. A runtime rejects a + * `args` must be lossless JSON; resolutions also support host-issued PtcImage values. A runtime rejects a * lossy or non-cloneable value with a descriptive error rather than corrupting * the run. No seam-level byte cap applies to a binding resolution. A rejection * of this function surfaces inside the program as a rejection of the @@ -182,7 +185,29 @@ type PtcBindingFunction = (args: unknown) => Promise ## 捕获的输出与失败分类体系 -日志是纯字符串。每个来源通道保留自身的发出顺序;由于通道元数据不属于 seam,相互独立的通道如何交错由后端决定。运行时捕获程序的 console 与流输出,Consumer 只渲染文本。实现会对序列化后的外层日志数组,以及完成值或失败消息的组合载荷设置上限;固定的结果封装语法与 Consumer 展示空白不计入这份可变载荷计量。超限会显式失败,而不会在值中插入替代内容。 +`output` 按发出顺序保存文本和图片条目:文本使用 `{ type: 'text', text }`,图片使用 `{ type: 'image', attachment }`。文本条目保留实际输出的换行,相邻文本直接拼接,不额外插入分隔符。每个来源通道都保留发出顺序;独立通道之间的交错顺序由后端决定。宿主绑定返回 `PtcImage` 描述符,包含附件引用和可在执行环境读取的 `path`;程序收到带有该路径和存储像素尺寸的 `Image`。Node 提供方对序列化文本、图片描述符、完成值或诊断一起计量;超限会显式失败。 + +```ts public-api +/** A stored image readable from the program's execution environment. */ +declare class PtcImage { + readonly [key: string]: PtcJsonValue; + /** Absolute attachment file path readable in the execution world. */ + readonly path: string; + /** Stored image selected when the program inspects this value. */ + readonly attachment: Readonly; + /** + * Describe one immutable image file in the execution world. + * @param path - Absolute path to the stored image. + * @param attachment - Reference to the immutable stored image. + */ + constructor(path: string, attachment: ImageAttachmentRef); +} +``` + +```ts type-equiv +/** Raw text fragments and inspected images in emission order; concatenate adjacent text without separators. */ +type PtcOutput = { type: 'text'; text: string } | { type: 'image'; attachment: ImageAttachmentRef } +``` 失败类型是**正交的结果,独立报告**(见 [defensive-patterns](../defensive-patterns/general.zh.md)):预算耗尽不是异常,中止不是超时,基底崩溃(如 OOM)也不是二者中的任何一个: @@ -237,6 +262,21 @@ Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and subst */ release(owner: object): Promise +/** + * Register source evaluated once when each execution environment is created. + * Registration must precede the first run admission; only one initializer may + * be registered. Current bindings are installed before initialization. Its + * completion is discarded; logs, timeout, cancellation and output bounds share + * the first run. Initialization failure discards the environment without + * executing the user program or rolling back external effects. + * @param program - Initialization source in the provider's language and format. + * @returns An idempotent async disposer that stops admission, cancels and drains + * admitted runs, and releases environments. Failed cleanup blocks execution + * until the disposer succeeds on retry. The caller owns this disposer. + * @throws When unsupported, registered twice, registered after admission, or invalid. + */ +registerEnvironmentInitializer(program: string): () => Promise + /** * Resolve supported options and provider defaults before execution. * @param request - Program, bindings, cancellation and optional execution choices. diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 54f6107f2b..b895e59451 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -72,8 +72,8 @@ en: 8c8643ef46fd075f zh: 8c8643ef46fd075f /tool-schema-catalog/deepseek-ai-dsh-tool-executor-ptc/run-code: - en: 7917e16cbc2c366f - zh: c39eb0420544f04a + en: 2c7a3166dfd9751c + zh: 1b52ae2d0f33b9a4 /tool-schema-catalog/deepseek-ai-dsh-plan-mode: en: b500b530845e26a9 zh: b500b530845e26a9 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 16c42b6393..26b450193a 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -623,7 +623,7 @@ ask_user_question keeps the original blocking behavior by default; set `mode: ti ### `run_code` -Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run. The program is the body of an async TypeScript function; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level await and return are supported. Emit output with console.log(...) or return a lossless JSON value. Only printed values and the returned value become program output. Each call runs in a fresh Node process. Node APIs are available through await import(...). Relative paths use the supplied working directory; process.env starts empty. Direct filesystem access follows this execution's sandbox policy. 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. +Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). The program is the body of an async TypeScript function; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level await and return are supported. Use inspect(...values) to display output. Do not use console. Each call runs in a fresh Node process. Node APIs are available through await import(...). Relative paths use the supplied working directory; process.env starts empty. Direct filesystem access follows this execution's sandbox policy. 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. ```json { diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index bf9a8255bb..f093165b20 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -627,7 +627,7 @@ ask_user_question 默认保持原有阻塞行为;设置 `mode: timed` 后才 ### `run_code` -针对可用工具执行 TypeScript 程序。接受两个必填参数:`code`,异步函数的函数体(仅限可擦除语法,支持顶层 `await` 和 `return`);以及 `description`,简要说明程序做什么。请按系统提示词中的声明,以 `await tools.name(args)` 调用工具。只有打印或返回的内容构成程序输出,请筛选这些内容。含图片的子工具结果会在运行结束后附加。程序是异步 TypeScript 函数的函数体,只接受可擦除语法,不支持 enum 或 namespace。类型标注只作提示。支持顶层 await 和 return。使用 console.log(...) 或返回无损 JSON 值来输出。只有打印值和返回值成为程序输出。每次调用在新的 Node 进程中运行,可通过 await import(...) 使用 Node API。相对路径以传入的工作目录为准;process.env 初始为空。直接文件系统访问遵循本次执行的沙箱策略。每个程序从 Session 的当前目录启动,运行中保留初始目录。沙箱提权只为本次完整程序执行授权。嵌套工具保留自身策略与审批。只有在获得拒绝证据后才请求更宽访问。先前效果可能已经发生,请在显式重试前检查。程序不会自动重放。 +针对可用工具执行 TypeScript 程序。接受两个必填参数:`code`,异步函数的函数体(仅限可擦除语法,支持顶层 `await` 和 `return`);以及 `description`,简要说明程序做什么。请按系统提示词中的声明,以 `await tools.name(args)` 调用工具。使用 inspect(...values) 展示选定的文本和图片。程序是异步 TypeScript 函数的函数体,只接受可擦除语法,不支持 enum 或 namespace。类型标注只作提示。支持顶层 await 和 return。使用 inspect(...values) 展示输出。不要使用 console。每次调用在新的 Node 进程中运行,可通过 await import(...) 使用 Node API。相对路径以传入的工作目录为准;process.env 初始为空。直接文件系统访问遵循本次执行的沙箱策略。每个程序从 Session 的当前目录启动,运行中保留初始目录。沙箱提权只为本次完整程序执行授权。嵌套工具保留自身策略与审批。只有在获得拒绝证据后才请求更宽访问。先前效果可能已经发生,请在显式重试前检查。程序不会自动重放。 ```json { diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.i18n.yaml new file mode 100644 index 0000000000..aa355c3d62 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.i18n.yaml @@ -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.1/cua-ax-read-limits/guide.md +/: + en: a8ca814cf60ea12e + zh: f068d1ee13e80594 +/macos-ax-tree-read-limits: + en: a7eed0c191ff2b32 + zh: 15291798ba91329b +/macos-ax-tree-read-limits/change: + en: e4281d86095b950f + zh: 684ddf2957443ace +/macos-ax-tree-read-limits/migration: + en: 97a3885f5d1cb907 + zh: 19313c56eff68835 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.md new file mode 100644 index 0000000000..8eab347bb2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "macOS reads more AX nodes by default and accepts per-read overrides of configured traversal budgets." +--- + +# macOS AX tree read limits + +English | [中文](guide.zh.md) + +## Change + +The default macOS node count rises from 2000 to 5000 and the default depth from 25 to 50. Reading a large window can take longer and emit more text to the model. + +Configured `maxElements` and `maxDepth` now supply defaults independently for omitted arguments. Callers can request larger or smaller values for one read. Paste menu discovery continues to use the configured limits. + +## Migration + +1. To keep the previous budgets for ordinary reads, find the `@deepseek-ai/dsh-experimental-cua-macos` entry in your `cordis.yml` or profile patch. Set `maxElements: 2000` and `maxDepth: 25` in its existing `config`. +2. Restart the profile and confirm both defaults in the Computer Use model instructions. +3. If a script depends on specific traversal budgets, pass them explicitly to `getAccessibilityTree()`. An override applies only to that call. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.zh.md new file mode 100644 index 0000000000..e6f392c7aa --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-ax-read-limits/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "macOS 默认读取更多 AX 节点,调用方可为单次读取覆盖配置值。" +--- + +# macOS AX 树读取范围 + +[English](guide.md) | 中文 + +## 变更 + +macOS 的默认节点数从 2000 增至 5000,默认深度从 25 增至 50。窗口中有更多节点可访问时,读取可能耗时更长,输出到模型的文本也可能增加。 + +`maxElements` 和 `maxDepth` 分别决定省略对应参数时的读取范围。调用方可以为一次读取指定高于或低于配置的值。查找粘贴菜单始终使用配置值。 + +## 迁移 + +1. 如需沿用原先的常规读取范围,在 `cordis.yml` 或配置补丁中找到 `@deepseek-ai/dsh-experimental-cua-macos`,在现有的 `config` 下设置 `maxElements: 2000` 和 `maxDepth: 25`。 +2. 重启配置,确认 Computer Use 模型说明中的两个默认值与配置一致。 +3. 如果脚本依赖特定的遍历范围,在 `getAccessibilityTree()` 的调用处显式传入这两个参数。一次调用的覆盖值不会影响后续读取。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml index a017e7f82b..174952b0fb 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 207c515390c5e529 zh: bd4d90881efb011d /native-cua-application-and-window-api/change: - en: e5d1027faa55adba - zh: 4b88ad6a70977fb3 + en: 43ace3409e7976b8 + zh: da185b705dfe600a /native-cua-application-and-window-api/migration: - en: a63e88dce467d6ee - zh: fc25bb283ca0eaff + en: 33bdef11cad75c53 + zh: 0d576c6160278b7b diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md index 2675699a71..1ed51c3164 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md @@ -9,15 +9,15 @@ English | [中文](guide.zh.md) ## Change -CUA scripts use an explicit window for screenshots and pointer input. App and Window objects share the latest accessibility snapshot for their application handle. Their identifiers are `appHandle` and `windowId` respectively. Application discovery still reports the PID of a running match. +Screenshots and pointer input require explicit windows. App (`appHandle`) and Window (`windowId`) objects share their application handle's latest accessibility snapshot. Window IDs are opaque strings. macOS retains running application PIDs and permission `helper.pid` and `parent.pid`. Windows permission metadata omits PIDs. -Providers supply startup capabilities alongside their platform guidance. The native helper reports runtime permissions and session lock state. The Host combines both in `getCapabilities()`. Human-facing permission responses carry a `darwin` or `win32` platform tag. +Providers supply startup capabilities and implement `getGuidance(kind)` instead of supplying a `guidance` string. `raw` selects instructions for the raw `cua` tool; `standalone` selects instructions for `cua_run_code`. The native helper reports runtime permissions and session lock state; the Host combines these with startup capabilities in `getCapabilities()`. Human-facing permission responses carry a `darwin` or `windows` platform tag. ## Migration -1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action. -2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Selection reads the initial tree silently for a window, and for an app when `appLevelAccessibility` is true. Read the tree explicitly to display it. +1. Pass a current `app.getWindows()` ID unchanged to `app.getWindow(windowId)`. Rediscover saved numeric IDs. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action. +2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Application and window selection does not read AX. Before using element IDs, call `getAccessibilityTree()` explicitly. To display the tree in TypeScript PTC, pass its return value to `inspect`. A screenshot does not require a successful AX read. Before coordinate input, including relative coordinates, obtain a successful AX observation covering the window or a screenshot; absolute coordinates require a screenshot. See [macOS AX read limits](../cua-ax-read-limits/guide.md) for changes to traversal defaults and configuration. 3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active. -4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` to hold a key across tool calls. To request one repeat, send another down for a non-modifier key held by that execution. Returning, throwing or pausing releases any remaining keys. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying. -5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID. -6. For a custom provider, replace `CuaBackend.description` with `capabilities` and pass `guidance` and `permissionParameters` to `installCua`. Rebuild any custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart the provider, inspect its advertised methods and keyboard scopes, and open the Computer Use permission page to verify its platform controls. +4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` or `cua_run_code` to hold a key across tool calls. Repeat a held non-modifier with another down. Returning, throwing or pausing releases any remaining keys. Replace `NATIVE_ERROR` with `INVALID_ARGUMENT` for unknown macOS keys and correct the key before retrying. +5. Read `dispatched`, then observe the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Pass a Windows application ID unchanged. For a specific macOS instance, use `getApp(String(row.pid))`. Update permission readers that test for `win32` to use `windows`. +6. Custom providers replace `CuaBackend.description` with `capabilities` and `guidance` with `getGuidance(kind)`. Supply `permissionParameters`. Set `acceptsPidSelector: true` if `getApp` accepts process IDs. Rebuild custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart. Verify both tool forms’ guidance, advertised methods, keyboard scopes and permission controls. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md index b4551f624b..35c5005477 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md @@ -9,15 +9,15 @@ description: "迁移 CUA 脚本和自定义原生提供方,使用显式窗口 ## 变更 -CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享同一应用句柄最近读取的辅助功能快照。App 用 `appHandle` 标识,Window 用 `windowId` 标识。查找应用时,运行中的匹配项仍提供 PID。 +截图和指针输入要求显式选择窗口。App(`appHandle`)和 Window(`windowId`)对象共享所属应用句柄的最新辅助功能快照。窗口 ID 是不透明字符串,macOS 应用发现保留运行进程的 PID,权限诊断保留 `helper.pid` 和 `parent.pid`。Windows 权限诊断不提供 PID。 -提供方在安装时声明固定的平台能力并提供操作指引。原生 helper 返回实际的权限和会话锁定状态。Host 合并两者,作为 `getCapabilities()` 的结果。供权限页面使用的响应带有 `darwin` 或 `win32` 平台标记。 +提供方声明启动能力,并实现 `getGuidance(kind)`,不再传入 `guidance` 字符串。`raw` 选择原始 `cua` 工具的指引,`standalone` 选择 `cua_run_code` 的指引。原生 helper 返回运行时权限和会话锁定状态,Host 将其与启动能力合并到 `getCapabilities()` 中。供权限页面使用的响应带有 `darwin` 或 `windows` 平台标记。 ## 迁移 -1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。 -2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择窗口时会静默读取初始树。选择应用时,只有 `appLevelAccessibility` 为真才读取。要显示树,请显式读取。 +1. 从 `app.getWindows()` 返回的列表选定目标,把原始字符串传给 `app.getWindow(windowId)`。曾以数字保存的窗口 ID 需要重新获取。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。 +2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择应用或窗口不读取 AX。使用元素 ID 前须显式调用 `getAccessibilityTree()`。在 TypeScript PTC 中,将返回值传给 `inspect` 即可展示这棵树。截图不要求 AX 读取成功。所有坐标输入(包括相对坐标)之前都须成功读取覆盖该窗口的 AX 或取得截图;绝对坐标要求截图。[读取上限的迁移说明](../cua-ax-read-limits/guide.zh.md)列出了 macOS 默认值和配置含义的变化。 3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。 -4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 中可调用此方法跨工具调用保持按键。如果需要一次重复按下,可在这次执行中对已按住的普通键再发一次 `down`。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。 -5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。 -6. 自定义提供方需将 `CuaBackend.description` 改为 `capabilities`,并向 `installCua` 传入 `guidance` 和 `permissionParameters`。如配置了 `helperPath`,请按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建 helper。重启提供方,检查它声明的方法和键盘输入范围,再打开 Computer Use 权限页确认平台控件。 +4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 或 `cua_run_code` 中可调用此方法跨工具调用保持按键。如果需要一次重复按下,可在这次执行中对已按住的普通键再发一次 `down`。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。 +5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。Windows 应用 ID 原样传递。需要选择某个 macOS 进程时,使用 `getApp(String(row.pid))`。读取权限状态时,将原先判断 `win32` 的代码改为判断 `windows`。 +6. 自定义提供方将 `CuaBackend.description` 改为 `capabilities`,将 `guidance` 改为 `getGuidance(kind)`,并向 `installCua` 传入 `permissionParameters`。若 `getApp` 接受进程 ID,设置 `acceptsPidSelector: true`。按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建自定义 `helperPath` 对应的 helper。重启后验证两种工具形态的指引、声明的方法、键盘输入范围及 Computer Use 权限页的平台控件。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.i18n.yaml new file mode 100644 index 0000000000..932fdd9720 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.i18n.yaml @@ -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.1/forge-change-request-overview/guide.md +/: + en: 5788ee9fab8253cf + zh: c8f8da46139d3aec +/forge-snapshots-carry-the-change-request-overview-and-actions-report-unknown-outcomes: + en: a3a5753044d1188b + zh: 16562b29b23a3fea +/forge-snapshots-carry-the-change-request-overview-and-actions-report-unknown-outcomes/change: + en: a571055593a2aa44 + zh: 405b322b9863f841 +/forge-snapshots-carry-the-change-request-overview-and-actions-report-unknown-outcomes/migration: + en: 92213118a4373782 + zh: d41450b2776c59ea diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md new file mode 100644 index 0000000000..3725460565 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "ChangeRequestSnapshot gains required overview fields, ChangeRequestCheck gains the required rerun field, and ForgeActionFailure gains the unknown code." +--- + +# Forge snapshots carry the change request overview, and actions report unknown outcomes + +English | [中文](guide.zh.md) + +## Change + +`ChangeRequestSnapshot` gains seven required fields: `reviewers` and `reviewersTruncated`, `closingIssues` and `closingIssuesTruncated`, `branchUpdates`, `canRequestReviews`, and `canRerunChecks`. `ChangeRequestCheck` gains the required `rerun: ForgeCheckId | null`, which names how the provider reruns the check. The change request card reads these fields to list reviewers, linked issues, and the branch update, and to offer rerunning failed checks, requesting reviews, and updating the branch. + +`ForgeActionFailure['code']` gains `unknown`: the host's answer did not confirm the outcome, so the change may have been applied. The GitHub provider returns it for viewed marks, review requests, and branch updates GitHub did not confirm; `ctx.forge.markReady` and `ctx.forge.merge` return it only from a provider that does. + +`ForgeProvider` also gains optional `viewedFiles` with `setViewed`, `rerunChecks`, `requestReviews` with `reviewerCandidates`, and `updateBranch`; a provider without them keeps working, and the card then offers none of those actions. + +This affects third-party `ForgeProvider` implementations registered with `ctx.forge.register` and other code that builds `ChangeRequestSnapshot` or `ChangeRequestCheck` values. All types come from `@deepseek-ai/dsh-experimental-forge`. + +## Migration + +1. In every `ChangeRequestCheck` a provider builds, set `rerun: null` unless the provider implements `rerunChecks`; a provider that does names each rerunnable check with a branded `ForgeCheckId` it can resolve again, as [`actionsRun`](../../../../packages/experimental/forge-github/src/graphql.ts) does for GitHub Actions runs. +2. In every `ChangeRequestSnapshot`, set the overview fields the host reports. Without host data, use `reviewers: []`, `reviewersTruncated: false`, `closingIssues: []`, `closingIssuesTruncated: false`, `branchUpdates: []`, `canRequestReviews: false`, and `canRerunChecks: false`; the card then shows the review decision alone and offers no overview action. +3. Optionally implement the new provider methods; [`GitHubProvider`](../../../../packages/experimental/forge-github/src/provider.ts) shows each one, and the [forge subsystem page](../../../subsystems/forge.md#overview-and-viewed-marks) states their contract. +4. Handle `unknown` wherever code switches exhaustively over `ForgeActionFailure['code']`: show that the outcome must be checked on the host, and do not try the change again before it is. +5. Run your type check; it succeeds when every snapshot and check a provider builds sets the new fields and no `ForgeActionFailure` code is unhandled. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md new file mode 100644 index 0000000000..6c7ac4933f --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-change-request-overview/guide.zh.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "ChangeRequestSnapshot 新增必填的概览字段,ChangeRequestCheck 新增必填的 rerun 字段,ForgeActionFailure 新增 unknown 代码。" +--- + +# Forge 快照携带变更请求概览,操作报告结果不明 + +[English](guide.md) | 中文 + +## 变更 + +`ChangeRequestSnapshot` 新增七个必填字段:`reviewers` 与 `reviewersTruncated`、`closingIssues` 与 `closingIssuesTruncated`、`branchUpdates`、`canRequestReviews`,以及 `canRerunChecks`。`ChangeRequestCheck` 新增必填的 `rerun: ForgeCheckId | null`,指出提供方如何重跑该检查。变更请求卡片读取这些字段,列出评审者、关联 issue 与分支更新,并提供重跑失败检查、请求评审与更新分支。 + +`ForgeActionFailure['code']` 新增 `unknown`:主机的答复无法确认结果,改动可能已经生效。GitHub 提供方在 GitHub 未确认已审阅标记、评审请求与分支更新的结果时返回它;`ctx.forge.markReady` 与 `ctx.forge.merge` 只在提供方返回它时才会返回。 + +`ForgeProvider` 还新增可选的 `viewedFiles` 与 `setViewed`、`rerunChecks`、`requestReviews` 与 `reviewerCandidates`,以及 `updateBranch`;未实现它们的提供方照常工作,卡片不提供对应操作。 + +受影响的是通过 `ctx.forge.register` 注册的第三方 `ForgeProvider` 实现,以及其他构造 `ChangeRequestSnapshot` 或 `ChangeRequestCheck` 值的代码。所有类型都来自 `@deepseek-ai/dsh-experimental-forge`。 + +## 迁移 + +1. 在提供方构造的每个 `ChangeRequestCheck` 中设置 `rerun: null`,除非提供方实现了 `rerunChecks`;实现了的提供方为每个可重跑的检查给出能再次解析的品牌化 `ForgeCheckId`,GitHub Actions 运行的做法见 [`actionsRun`](../../../../packages/experimental/forge-github/src/graphql.ts)。 +2. 在每个 `ChangeRequestSnapshot` 中设置托管平台报告的概览字段。没有平台数据时,使用 `reviewers: []`、`reviewersTruncated: false`、`closingIssues: []`、`closingIssuesTruncated: false`、`branchUpdates: []`、`canRequestReviews: false` 与 `canRerunChecks: false`;卡片随后只显示评审结论,不提供概览操作。 +3. 可选地实现新的提供方方法;[`GitHubProvider`](../../../../packages/experimental/forge-github/src/provider.ts) 展示了每个方法,契约见 [forge 子系统页面](../../../subsystems/forge.zh.md#overview-and-viewed-marks)。 +4. 在所有对 `ForgeActionFailure['code']` 做穷举的地方处理 `unknown`:提示需要到主机上核对结果,核对之前不要再次尝试该改动。 +5. 运行类型检查;提供方构造的每个快照与检查都设置了新字段、且没有未处理的 `ForgeActionFailure` 代码时即通过。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.i18n.yaml new file mode 100644 index 0000000000..e2d67f1a38 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.i18n.yaml @@ -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.1/package-export-cleanup/guide.md +/: + en: 5048dc7fc046e7ab + zh: 7845cb3ba5a543d4 +/replace-internal-plugin-root-imports: + en: 65af277d1f4ed1a0 + zh: 9d2b980fb6fabe89 +/replace-internal-plugin-root-imports/change: + en: fcb1af4db4d0edd5 + zh: 6cc6ed79d0100eac +/replace-internal-plugin-root-imports/migration: + en: 01c24ef3fa9273f6 + zh: cd5ae3b6f0218aba diff --git a/docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.md new file mode 100644 index 0000000000..5b0d68f641 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: Internal helper values are removed from three published plugin-root entries. +--- + +# Replace internal plugin-root imports + +English | [中文](guide.zh.md) + +## Change + +After upgrading from v0.2.2-rc.1, the following plugin-root values are no longer exported. Their implementations remain inside the packages. Consumers importing these values from a package root must change their imports or use the owning service. + +| Package suffix (`@deepseek-ai/dsh-`) | Removed root helpers | +|---|---| +| `file-reference-local` | `DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES`, `DEFAULT_FILE_SEARCH_MAX_ENTRIES`, `DEFAULT_FILE_SEARCH_MAX_RESULTS`, `WorkspaceFileSearch`, `FILE_REFERENCE_PROMPT`, `activeAtToken`, `formatFileMention` | +| `llm-pi-ai` | `recordKeyFor` | +| `lsp-stdio` | `LspConnection`, `LspInstance`, `MessageDecoder`, `canonicalizeWorkspace`, `encodeMessage`, `negotiatePositionEncoding`, `normalizeHover`, `normalizeLocations`, `readHostSource`, `requestMethod`, `supportsOperation`, `supportsTransientOpen` | + +Brand constructors, package subpaths, persisted values and Session formats are unchanged. + +## Migration + +1. Stop importing the listed helper values from plugin roots. Package-owned tests can use relative imports from the corresponding internal modules. +2. Application code should use the injected `fileReferences` or `lsp` service instead of provider implementation classes or protocol helpers. File-reference grammar remains at `@deepseek-ai/dsh-file-reference/grammar`; `FILE_REFERENCE_PROMPT` remains at `@deepseek-ai/dsh-file-reference`. `recordKeyFor` has no replacement public entry. +3. Compile the application and run its tests. Load any plain-JavaScript consumers under Node as well: TypeScript checking alone does not cover missing ESM named exports in `.mjs` files. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.zh.md new file mode 100644 index 0000000000..8ecaaf6f42 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/package-export-cleanup/guide.zh.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: 三个已发布插件的根入口移除内部辅助实体的值导出。 +--- + +# 替换内部插件根导入 + +[English](guide.md) | 中文 + +## 变更 + +从 v0.2.2-rc.1 升级后,以下插件根入口不再导出这些值。对应实现在包内保留。从包根入口导入这些值的消费方需要更改导入或改用所属服务。 + +| 包名后缀(`@deepseek-ai/dsh-`) | 移除的根辅助实体 | +|---|---| +| `file-reference-local` | `DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES`、`DEFAULT_FILE_SEARCH_MAX_ENTRIES`、`DEFAULT_FILE_SEARCH_MAX_RESULTS`、`WorkspaceFileSearch`、`FILE_REFERENCE_PROMPT`、`activeAtToken`、`formatFileMention` | +| `llm-pi-ai` | `recordKeyFor` | +| `lsp-stdio` | `LspConnection`、`LspInstance`、`MessageDecoder`、`canonicalizeWorkspace`、`encodeMessage`、`negotiatePositionEncoding`、`normalizeHover`、`normalizeLocations`、`readHostSource`、`requestMethod`、`supportsOperation`、`supportsTransientOpen` | + +品牌构造器、包子路径、持久化值和 Session 格式不变。 + +## 迁移 + +1. 停止从插件根入口导入上表的辅助实体值。包内测试可以相对导入对应内部模块。 +2. 应用代码应使用注入的 `fileReferences` 或 `lsp` 服务,而不是提供方的实现类或协议辅助函数。文件引用语法仍在 `@deepseek-ai/dsh-file-reference/grammar`;`FILE_REFERENCE_PROMPT` 仍在 `@deepseek-ai/dsh-file-reference`。`recordKeyFor` 没有替代的公开入口。 +3. 编译应用并运行其测试,同时用 Node 加载纯 JavaScript 消费方:仅检查 TypeScript 无法覆盖 `.mjs` 文件中缺少 ESM 命名导出的错误。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.i18n.yaml new file mode 100644 index 0000000000..94629a6c5e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.i18n.yaml @@ -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.1/ptc-bootstrap-protocol/guide.md +/: + en: cee454924a9ab1f8 + zh: 2d7cbdcc398fa914 +/node-ptc-bootstrap-protocol-version-3-and-the-scoped-repl-format: + en: 541c4f16c0107c90 + zh: edda22e2ebf01992 +/node-ptc-bootstrap-protocol-version-3-and-the-scoped-repl-format/change: + en: f9b071385a270a1e + zh: e664c70b769579e9 +/node-ptc-bootstrap-protocol-version-3-and-the-scoped-repl-format/migration: + en: 350de9ad88b43420 + zh: 8b8bfe380cbf6fe8 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.md new file mode 100644 index 0000000000..e6a55bfa27 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.md @@ -0,0 +1,25 @@ +--- +kind: upgrade-guide +description: "Update custom Node PTC bootstraps to protocol version 3 before running them with the upgraded Host, and handle the new scoped-repl program format." +--- + +# Node PTC bootstrap protocol version 3 and the scoped-repl format + +English | [中文](guide.zh.md) + +## Change + +The Node PTC Host requires bootstrap protocol version 3 instead of version 2. It rejects an older bootstrap before dispatching a program, with `bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host`. This affects custom `launch.bootstrapPath` deployments in every execution mode, including `@deepseek-ai/dsh-ssh` hosts with a `node-script` launch that set `launch.bootstrapPath` and `launch.bootstrapHash`. The bootstrap bundled with DSH updates with the Host and needs no configuration change. + +Version 3 carries optional `ProgramBootData.initialization` source for each new environment. The bootstrap evaluates it separately after installing current bindings, then awaits the Host's `initialized()` RPC acceptance and rechecks cancellation before running the model program. Initialization failure discards the environment and prevents model execution. The Node provider supports initializer registration only in `persistent-in-memory` mode. + +Version 3 also carries `ProgramBootData.discardCompletion` to discard completion values before JSON validation and serialization. The bootstrap provides `inspect` and sends selected images through `HostMethods.image(id)` in output order. Custom bootstraps must support these fields and methods alongside environment initialization. + +Version 3 also adds the `scoped-repl` program format. `PtcProgramFormat` in `@deepseek-ai/dsh-ptc-runtime` now includes `'scoped-repl'`, which `@deepseek-ai/dsh-ptc-runtime-node` reports as `PtcRuntime.programFormat` when `replScoped: true` is set with `executionMode: persistent-in-memory`. Code that matches the union exhaustively stops compiling until it handles the new value. + +## Migration + +1. If your Node PTC configuration sets `launch.bootstrapPath`, deploy the matching version of `@deepseek-ai/dsh-ptc-runtime-node` in its execution environment. Use the package's built `lib/process.js` or REPL-default `lib/persistent-process.js` with its dependencies. Keep the Host and bootstrap versions aligned; changing only the advertised version is insufficient. +2. Update `launch.bootstrapPath` to the matching entry and restart the provider. For `@deepseek-ai/dsh-ssh` with a `node-script` launch, copy the new bootstrap to the remote `launch.bootstrapPath` and set `launch.bootstrapHash` to its lowercase SHA-256, for example from `sha256sum`. For local deployments that need no custom bootstrap, remove that override to use the installed default. The [Node runtime documentation](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) describes retained execution and remote launch. +3. Handle `'scoped-repl'` wherever code switches over `PtcProgramFormat` or keys a record by it. A `scoped-repl` program is REPL statements whose final expression is the result; top-level `return` is not supported, and a final Promise is not awaited. +4. Run a program in each configured execution mode and confirm that it completes without the protocol error. Consumers using `registerEnvironmentInitializer(program)` must also verify that initialization runs once per new environment and that an initialization error prevents the model program's effects. Typecheck the code that uses `PtcProgramFormat`. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.zh.md new file mode 100644 index 0000000000..cfd7243451 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/ptc-bootstrap-protocol/guide.zh.md @@ -0,0 +1,25 @@ +--- +kind: upgrade-guide +description: "自定义 Node PTC bootstrap 必须升级到协议版本 3,才能与新版 Host 一起运行;还要处理新增的 scoped-repl 程序格式。" +--- + +# Node PTC bootstrap 协议版本 3 与 scoped-repl 格式 + +[English](guide.md) | 中文 + +## 变更 + +Node PTC Host 要求 bootstrap 协议版本从 2 升至 3。它会在派发程序前拒绝旧 bootstrap,并报告 `bootstrap protocol mismatch; upgrade launch.bootstrapPath with the host`。这影响所有执行模式下自定义 `launch.bootstrapPath` 的部署,包括使用 `node-script` 启动、设置了 `launch.bootstrapPath` 和 `launch.bootstrapHash` 的 `@deepseek-ai/dsh-ssh` 宿主。DSH 内置 bootstrap 随 Host 更新,无需修改配置。 + +版本 3 为每个新环境携带可选的 `ProgramBootData.initialization` 源码。bootstrap 安装本次绑定后独立执行初始化,随后等待 Host 对 `initialized()` RPC 的确认,再次检查取消状态后才执行模型程序。初始化失败会丢弃环境并阻止模型代码执行。Node 提供方仅在 `persistent-in-memory` 模式下支持注册初始化程序。 + +版本 3 还携带 `ProgramBootData.discardCompletion`,用于在 JSON 校验和序列化前丢弃完成值。bootstrap 提供 `inspect`,并通过 `HostMethods.image(id)` 按输出顺序发送选中的图片。自定义 bootstrap 必须同时支持这些字段、方法和环境初始化。 + +版本 3 还新增了 `scoped-repl` 程序格式。`@deepseek-ai/dsh-ptc-runtime` 的 `PtcProgramFormat` 新增 `'scoped-repl'`;`@deepseek-ai/dsh-ptc-runtime-node` 在 `executionMode: persistent-in-memory` 下设置 `replScoped: true` 时,`PtcRuntime.programFormat` 报告这个值。对这个联合类型做穷尽匹配的代码,处理新值之前无法通过编译。 + +## 迁移 + +1. 如果 Node PTC 配置设置了 `launch.bootstrapPath`,请在其执行环境中部署匹配版本的 `@deepseek-ai/dsh-ptc-runtime-node`。使用包内构建产物 `lib/process.js`,或默认采用 REPL 的 `lib/persistent-process.js`,并保留其依赖。Host 与 bootstrap 版本必须匹配;只修改声明的版本号并不够。 +2. 将 `launch.bootstrapPath` 指向匹配的入口并重启提供方。使用 `node-script` 启动的 `@deepseek-ai/dsh-ssh`:把新的 bootstrap 复制到远端的 `launch.bootstrapPath`,并把 `launch.bootstrapHash` 设为它的小写 SHA-256,例如用 `sha256sum` 计算。本地部署若不需要自定义 bootstrap,可以移除此覆盖项以使用安装默认值。[Node 运行时文档](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)说明状态保留和远程启动方式。 +3. 在按 `PtcProgramFormat` 分支或以它为键的地方处理 `'scoped-repl'`。`scoped-repl` 程序是 REPL 语句,最后一条表达式就是结果;不支持顶层 `return`,末尾的 Promise 不会被等待。 +4. 在每种已配置的执行模式中运行一个程序,确认正常完成且没有协议错误。使用 `registerEnvironmentInitializer(program)` 的消费方还须验证:初始化在每个新环境中只执行一次,且初始化出错时模型程序不会产生效果。再对使用 `PtcProgramFormat` 的代码做类型检查。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.i18n.yaml new file mode 100644 index 0000000000..dfe1a064d7 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.i18n.yaml @@ -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.1/ptc-inspect-output/guide.md +/: + en: aa6195ec0952307e + zh: 1d80177284309ac6 +/explicit-output-in-typescript-ptc-programs: + en: 064ec0081b5c2946 + zh: 4b67a513ea949220 +/explicit-output-in-typescript-ptc-programs/change: + en: a4b3d449a4eedd9f + zh: ae9b0ba7f9f4acbd +/explicit-output-in-typescript-ptc-programs/migration: + en: 0953d3ac2f2f01e3 + zh: b3614bf85d3d2fcf diff --git a/docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.md new file mode 100644 index 0000000000..c1e7dda122 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.md @@ -0,0 +1,48 @@ +--- +kind: upgrade-guide +description: "TypeScript PTC programs display selected values through inspect and return ordered text and image output." +--- + +# Explicit output in TypeScript PTC programs + +English | [中文](guide.zh.md) + +## Change + +TypeScript `run_code` programs display selected values through `inspect(...values)`. Function return values and final expressions previously appeared in the result; they are now omitted. Each inspected argument is rendered independently: strings appear directly, and other values use Node's object formatting without depth, array-length or string-length preview limits. Undefined properties, Error objects and circular references remain visible. + +CUA observations previously produced output automatically. `getCapabilities()`, `listApps()`, `findApps(query)`, `getState()`, `app.getWindows()` and app or window `getAccessibilityTree()` now return their results to the program. Use `inspect` to display the values you need. + +Only CUA screenshots and `read_image` return ordinary `Image` values in TypeScript programs. Their `path` points to an attachment file readable in the execution environment; `width` and `height` describe its stored pixels. Pass selected images to `inspect` alongside explanatory text, including images in arrays, Map entries, Set values and enumerable object properties. Nested image selection follows Node's custom formatting. Read CUA window IDs from the window object’s `windowId`. + +Other image-producing tools retain their declared program values and automatically attach their pictures to the model context. Image adaptation requires a readable attachment path in the program filesystem. `fs-ssh` does not provide this mapping, so `read_image` and CUA screenshot bindings fail in that composition. Use a local filesystem composition for program Images. + +Formatting selected values can require more memory than the retained output; see the [Node formatting memory limit](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work). + +## Migration + +1. Update programs that rely on completion values to explicitly inspect the values they need: + + ```js + const result = await tools.bash({ command: 'pwd', description: 'Show current directory' }) + inspect(result) + ``` + +2. Remove output callbacks from `connectCua` and `createCuaApi`, the `emit` observation option and the unused `disableDiffing` AX option. Pass observations you want to display to `inspect`, for example `inspect(await app.getWindows())`. A custom dispatcher must return a program Image for screenshot operations. + + ```js + const { connectCua } = await import("") + const cua = connectCua(() => tools.cua) + const app = await cua.getApp("TextEdit") + const windows = await app.getWindows() + const win = await app.getWindow(windows[0].windowId) + const before = await win.getScreenshot() + await app.pressKey("Tab") + const after = await win.getScreenshot() + inspect("before", { windowId: win.windowId }, before, "after", after) + ``` + +3. Direct runtime consumers can set `discardCompletion: true` to select the same explicit-output behavior. +4. Third-party `PtcRuntime` providers replace returned `logs` arrays with `output: PtcOutput[]`; direct runtime consumers read `result.output`. Text entries are `{ type: 'text', text }`, image entries are `{ type: 'image', attachment }`, and array order is display order. Preserve emitted line breaks and concatenate adjacent text entries without separators. +5. For custom `launch.bootstrapPath` deployments, follow the [Node PTC bootstrap upgrade guide](../ptc-bootstrap-protocol/guide.md). +6. Run an updated program and verify that inspected values appear once and its final expression adds no output. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.zh.md new file mode 100644 index 0000000000..ebee5e38b5 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/ptc-inspect-output/guide.zh.md @@ -0,0 +1,48 @@ +--- +kind: upgrade-guide +description: "TypeScript PTC 程序通过 inspect 展示选定的值,并返回有序的文本与图片输出。" +--- + +# TypeScript PTC 程序的显式输出 + +[English](guide.md) | 中文 + +## 变更 + +TypeScript `run_code` 程序通过 `inspect(...values)` 展示选定的值。此前函数返回值和末尾表达式的值会进入结果,现在会被省略。各个 inspect 参数独立渲染:字符串直接展示,其他值使用 Node 的对象格式,不限制预览深度、数组项数或字符串长度。undefined 属性、Error 对象和循环引用均会展示。 + +此前,CUA 观察方法默认会输出结果。现在,`getCapabilities()`、`listApps()`、`findApps(query)`、`getState()`、`app.getWindows()` 以及应用或窗口的 `getAccessibilityTree()` 都将结果返回给程序。需要展示哪些值,就把它们传给 `inspect`。 + +只有 CUA 截图与 `read_image` 在 TypeScript 程序中返回普通 `Image`,其 `path` 指向执行环境可读取的附件文件,`width` 与 `height` 为该文件的像素尺寸。使用 `inspect` 将选中的图片与说明一起展示;图片可嵌入数组、Map 条目、Set 的值以及可枚举的对象属性。嵌套图片的选择遵循 Node 的自定义格式化。CUA 窗口 ID 从窗口对象的 `windowId` 读取。 + +其他图片工具保留其声明的程序返回值,并将图片自动附加到模型上下文。图片适配要求附件在程序文件系统中有可读路径。`fs-ssh` 未提供这项映射,因此该组合中的 `read_image` 与 CUA 截图绑定会失败。需要程序 Image 时,使用本地文件系统组合。 + +格式化选定的值所需内存可能大于保留的输出;参见 [Node 格式化的内存限制](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)。 + +## 迁移 + +1. 将依赖完成值的程序,改为显式 inspect 所需的值: + + ```js + const result = await tools.bash({ command: 'pwd', description: 'Show current directory' }) + inspect(result) + ``` + +2. 删除 `connectCua` 和 `createCuaApi` 的输出回调、观察选项 `emit` 和已无作用的 AX 选项 `disableDiffing`。将要展示的观察结果传给 `inspect`,例如 `inspect(await app.getWindows())`。自定义分派器须为截图操作直接返回程序可用的 `Image`。 + + ```js + const { connectCua } = await import("") + const cua = connectCua(() => tools.cua) + const app = await cua.getApp("TextEdit") + const windows = await app.getWindows() + const win = await app.getWindow(windows[0].windowId) + const before = await win.getScreenshot() + await app.pressKey("Tab") + const after = await win.getScreenshot() + inspect("before", { windowId: win.windowId }, before, "after", after) + ``` + +3. 直接调用运行时的消费方可设置 `discardCompletion: true`,选择相同的显式输出行为。 +4. 第三方 `PtcRuntime` 提供方将返回的 `logs` 数组替换为 `output: PtcOutput[]`;直接消费运行时结果的调用方改为读取 `result.output`。文本条目为 `{ type: 'text', text }`,图片条目为 `{ type: 'image', attachment }`,数组顺序就是展示顺序。保留实际输出的换行,相邻文本条目直接拼接,不额外插入分隔符。 +5. 使用自定义 `launch.bootstrapPath` 的部署,请按 [Node PTC bootstrap 升级指南](../ptc-bootstrap-protocol/guide.zh.md)更新。 +6. 运行更新后的程序,确认 inspect 的值只出现一次,且末尾表达式不额外输出。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.i18n.yaml new file mode 100644 index 0000000000..c86b88ee99 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.i18n.yaml @@ -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.1/ptc-scoped-repl-default/guide.md +/: + en: cff145a993d30f0a + zh: 784a2ce78146a563 +/retained-node-ptc-runs-the-scoped-repl-by-default: + en: 60119ea304ce7bad + zh: c0724f1da0e4590c +/retained-node-ptc-runs-the-scoped-repl-by-default/change: + en: 1ca349eed9a54b9b + zh: 5dc5ba17ec953f0e +/retained-node-ptc-runs-the-scoped-repl-by-default/migration: + en: 5d1e1f1bf7ce7821 + zh: aafa439b6080acb4 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.md new file mode 100644 index 0000000000..4ffe048571 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.md @@ -0,0 +1,45 @@ +--- +kind: upgrade-guide +description: "Node PTC persistent-in-memory execution runs the scoped REPL unless replScoped is false." +--- + +# Retained Node PTC runs the scoped REPL by default + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-ptc-runtime-node` previously ran `executionMode: persistent-in-memory` programs in Node's REPL evaluator when `replScoped` was omitted. It now runs them as scoped REPL statements and reports program format `scoped-repl`. Each call is a separate strict-mode script that starts with copies of the top-level bindings left by earlier calls, so a later call may declare a `let`, `const`, or `class` name again. `require`, `_`, `_error`, and globals created by assigning an undeclared name are unavailable. The model guidance describes this behavior; the package README lists its [known limitations](../../../../packages/ptc-runtime/ptc-runtime-node/README.md#known-limitations-and-deferred-work). + +This affects: + +- profiles whose `ptc-runtime` entry sets `executionMode: persistent-in-memory` without `replScoped`, including workflow-ptc scripts that run on that runtime; +- persistent PTC enabled from the Computer Use detail page, which now writes `replScoped: true`; +- the Computer Use `cua_run_code` tool, whose dedicated runtime omits `replScoped` unless `standaloneRunCode.runtime.replScoped` is set; +- profile editors that merge `resolvePersistentExecution` from `@deepseek-ai/dsh-ptc-runtime-node/configuration`, which now returns `replScoped: true` for function bodies and REPL statements. + +`per-call` and `vm-script` execution, including the default profile, are unchanged, and entries that set `replScoped: false` keep Node's REPL evaluator. + +## Migration + +1. To keep the scoped REPL, replace REPL-only code: use `await import(...)` instead of `require`, assign `globalThis.name` for an intentional global, and use a new name instead of reading a name's earlier value in its own `let` or `const` initializer. +2. To restore Node's REPL evaluator, set `replScoped: false` in `$DSH_HOME/profiles//cordis.patch.yml`; to move an entry that sets `false` to the scoped REPL, delete the key or set `true`. Each patch below replaces that entry's whole `config`, so copy the entry's existing fields into it, for the `cua` entry including `agentPreset`, `allowedApps`, and the other `standaloneRunCode` fields: + + ```yaml + - id: ptc-runtime + config: + executionMode: persistent-in-memory + replScoped: false + ``` + + For `cua_run_code`, set it on the Computer Use provider entry: + + ```yaml + - id: cua + config: + standaloneRunCode: + runtime: + replScoped: false + ``` + +3. Restart the profile and run `const probe = 1` in two consecutive calls. The scoped REPL accepts both calls; Node's REPL evaluator reports that `probe` has already been declared in the second. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.zh.md new file mode 100644 index 0000000000..b7c1d7ccef --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/ptc-scoped-repl-default/guide.zh.md @@ -0,0 +1,45 @@ +--- +kind: upgrade-guide +description: "Node PTC 的 persistent-in-memory 执行默认使用 scoped REPL,replScoped 为 false 时除外。" +--- + +# 保留状态的 Node PTC 默认使用 scoped REPL + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-ptc-runtime-node` 在 `executionMode: persistent-in-memory` 下省略 `replScoped` 时,原先用 Node 的 REPL 求值器运行程序;现在按 scoped REPL 语句运行,并报告程序格式 `scoped-repl`。每次调用是独立的严格模式脚本,开始时拿到之前调用留下的顶层绑定的拷贝,因此之后的调用可以再次声明同名的 `let`、`const` 或 `class`。`require`、`_`、`_error`,以及给未声明的名字赋值而产生的全局变量都不可用。模型说明描述了这些行为;包 README 列出了它的[已知限制](../../../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#known-limitations-and-deferred-work)。 + +受影响的有: + +- `ptc-runtime` 条目设置了 `executionMode: persistent-in-memory` 但没写 `replScoped` 的 profile,包括在该运行时上运行的 workflow-ptc 脚本; +- 在 Computer Use 详情页打开的持久化 PTC,现在会写入 `replScoped: true`; +- Computer Use 的 `cua_run_code` 工具,其专用运行时在没有设置 `standaloneRunCode.runtime.replScoped` 时省略 `replScoped`; +- 合并 `@deepseek-ai/dsh-ptc-runtime-node/configuration` 中 `resolvePersistentExecution` 结果的 profile 编辑器,该函数现在对函数体和 REPL 语句返回 `replScoped: true`。 + +`per-call` 和 `vm-script` 执行(包括默认 profile)不变,设置了 `replScoped: false` 的条目继续使用 Node 的 REPL 求值器。 + +## 迁移 + +1. 如果保留 scoped REPL,替换只在 REPL 下可用的代码:用 `await import(...)` 代替 `require`,有意的全局变量赋给 `globalThis.name`,不要在 `let` 或 `const` 的初始化表达式里读取同名的旧值,改用新名字。 +2. 如果要恢复 Node 的 REPL 求值器,在 `$DSH_HOME/profiles//cordis.patch.yml` 里设置 `replScoped: false`;要让设为 `false` 的条目改用 scoped REPL,删除这个键或改为 `true`。下面每个 patch 都会替换该条目的整个 `config`,所以要把条目已有的字段一并写进去,`cua` 条目还包括 `agentPreset`、`allowedApps` 和 `standaloneRunCode` 的其他字段: + + ```yaml + - id: ptc-runtime + config: + executionMode: persistent-in-memory + replScoped: false + ``` + + 对 `cua_run_code`,在 Computer Use 提供方条目上设置: + + ```yaml + - id: cua + config: + standaloneRunCode: + runtime: + replScoped: false + ``` + +3. 重启 profile,在连续两次调用里运行 `const probe = 1`。scoped REPL 两次都接受;Node 的 REPL 求值器在第二次报告 `probe` 已经声明过。 diff --git a/package.json b/package.json index 37b86b60d5..afa89fcf07 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-root", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "license": "MIT", "private": true, "type": "module", @@ -301,6 +301,7 @@ "@deepseek-ai/dsh-experimental-worktree": "workspace:*", "@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*", "@deepseek-ai/dsh-cua-bundle": "workspace:*", + "@deepseek-ai/dsh-cua-windows": "workspace:*", "@deepseek-ai/dsh-experimental-subagent-oar": "workspace:*", "@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*", "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*", diff --git a/packages/acp/acp/package.json b/packages/acp/acp/package.json index 9a54c5dd58..c38b8c70a0 100644 --- a/packages/acp/acp/package.json +++ b/packages/acp/acp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-acp", "description": "Automation-only Agent Client Protocol server for driving DeepSeek Harness agents over JSON-RPC stdio", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/acp/acp/tests/model-control.spec.ts b/packages/acp/acp/tests/model-control.spec.ts index 59a5f6a422..0578e836d1 100644 --- a/packages/acp/acp/tests/model-control.spec.ts +++ b/packages/acp/acp/tests/model-control.spec.ts @@ -32,7 +32,7 @@ function llmRuntime(overrides: Partial = {}): LlmRuntime { }, }), ...overrides, - } as unknown as LlmRuntime + } as LlmRuntime } async function createControl(runtime: LlmRuntime, initial?: ModelSelection) { diff --git a/packages/api/gateway/package.json b/packages/api/gateway/package.json index 99c310776c..500b8b3b56 100644 --- a/packages/api/gateway/package.json +++ b/packages/api/gateway/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-gateway", "description": "Typert Remote Host dispatcher and Client API endpoint", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/api/job-controller/package.json b/packages/api/job-controller/package.json index cfd09bcfb5..459328cca9 100644 --- a/packages/api/job-controller/package.json +++ b/packages/api/job-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-job-controller", "description": "Job Remote observation stream and the reference-counted client job-output service", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/api/remote-access/package.json b/packages/api/remote-access/package.json index 5d9c311210..25dd274c9c 100644 --- a/packages/api/remote-access/package.json +++ b/packages/api/remote-access/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-remote-access", "description": "Method-level Remote access control for non-owner Peers and the per-Peer access snapshot", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index 25718e223b..e26f92ee09 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-remotes", "description": "Remote BFF assembly for application-selected Host capabilities", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/api/session-controller/package.json b/packages/api/session-controller/package.json index 4f29e46eac..9061f1be29 100644 --- a/packages/api/session-controller/package.json +++ b/packages/api/session-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-session-controller", "description": "Session Remote commands, cold reads, and live control transport", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/api/settings-controller/package.json b/packages/api/settings-controller/package.json index 7c16a75482..e4a5820703 100644 --- a/packages/api/settings-controller/package.json +++ b/packages/api/settings-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-settings-controller", "description": "Remote owner for the configuration surfaces over the settings-domain seams", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/api/terminal-controller/package.json b/packages/api/terminal-controller/package.json index 873fb7dc94..fc4e67729d 100644 --- a/packages/api/terminal-controller/package.json +++ b/packages/api/terminal-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-terminal-controller", "description": "Session-owned interactive terminals with shell discovery, screen recovery and typed Remote control", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/api/workspace-controller/package.json b/packages/api/workspace-controller/package.json index a534bfeb96..e842cff5da 100644 --- a/packages/api/workspace-controller/package.json +++ b/packages/api/workspace-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-workspace-controller", "description": "Workspace Remote commands and reconnect-safe state transport", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/api/workspace-files/package.json b/packages/api/workspace-files/package.json index 0c501b990a..550f678be9 100644 --- a/packages/api/workspace-files/package.json +++ b/packages/api/workspace-files/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-workspace-files", "description": "Workspace file service and Client resource provider: bounded reads, directory listing, and live metadata over the workspaceFiles Remote namespace", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/attachment/attachment-local/package.json b/packages/attachment/attachment-local/package.json index 28aae50c7b..96582b26b7 100644 --- a/packages/attachment/attachment-local/package.json +++ b/packages/attachment/attachment-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-attachment-local", "description": "Private content-addressed DSH_HOME attachment storage", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/attachment/attachment/package.json b/packages/attachment/attachment/package.json index dc831253b1..6e03e13d70 100644 --- a/packages/attachment/attachment/package.json +++ b/packages/attachment/attachment/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-attachment", "description": "Durable immutable attachment storage seam for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/boot/app-boot/package.json b/packages/boot/app-boot/package.json index 8437f3debb..04e1220030 100644 --- a/packages/boot/app-boot/package.json +++ b/packages/boot/app-boot/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-app-boot", "description": "Shared boot glue for the app bins: .env loading, fail-loud Loader guards, snapshot-aware config resolution, and the Loader boot sequence", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/boot/app-boot/tests/profile.spec.ts b/packages/boot/app-boot/tests/profile.spec.ts index 238f316dc9..7122ff80f3 100644 --- a/packages/boot/app-boot/tests/profile.spec.ts +++ b/packages/boot/app-boot/tests/profile.spec.ts @@ -80,7 +80,7 @@ it('skips an unsupported saved bundle before composing any runtime overrides and const unsupported = process.platform === 'darwin' ? 'win32' : 'darwin' const anchor = stageInstallation({ base: { patch: '- insert:\n - id: ptc-runtime\n name: runtime\n config: { executionMode: isolated }\n' }, - restricted: { platforms: [unsupported], patch: '- id: ptc-runtime\n config: { executionMode: persistent-in-memory }\n' }, + restricted: { platforms: [unsupported], patch: '- id: ptc-runtime\n config: { executionMode: persistent-in-memory, replScoped: false }\n' }, }) const dir = join(tmp(), 'profile') initProfile(dir, ['base', 'restricted']) diff --git a/packages/boot/cmdline/package.json b/packages/boot/cmdline/package.json index 9a50bff2a0..e40c96b5ad 100644 --- a/packages/boot/cmdline/package.json +++ b/packages/boot/cmdline/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-cmdline", "description": "Immutable command-line handoff from a dsh launcher to any app plugin that injects cmdlineArgs", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/boot/config-editor/package.json b/packages/boot/config-editor/package.json index 1560233646..6f1273f1a2 100644 --- a/packages/boot/config-editor/package.json +++ b/packages/boot/config-editor/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-config-editor", "description": "Persist plugin configuration through profile patches and Loader reconciliation", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/boot/hmr/package.json b/packages/boot/hmr/package.json index 5e6a517cd7..1b82bb68ad 100644 --- a/packages/boot/hmr/package.json +++ b/packages/boot/hmr/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-hmr", "description": "Coordinated module and profile configuration hot reload", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/boot/plugin-manager/package.json b/packages/boot/plugin-manager/package.json index 257eb8544d..165ffe8938 100644 --- a/packages/boot/plugin-manager/package.json +++ b/packages/boot/plugin-manager/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-plugin-manager", "description": "Current-profile plugin and bundle management shared by dsh CLI, Web and agent tools", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/boot/plugin-manager/tests/github-connection.spec.ts b/packages/boot/plugin-manager/tests/github-connection.spec.ts index 1d76e1eaf1..d1d292fc2c 100644 --- a/packages/boot/plugin-manager/tests/github-connection.spec.ts +++ b/packages/boot/plugin-manager/tests/github-connection.spec.ts @@ -118,8 +118,14 @@ it('ends a silent proxy connection and its Git child at the connection deadline' await transport.connected const result = await running expect(result?.kind).toBe('timeout') - // The result records the status the terminated Git is read as; only the streamed run reports no exit code. - expect(result).toMatchObject({ exitCode: 1, timedOut: true, argv: checkArgv('https://github.com/acme/plugin.git') }) + // Git's termination status varies by platform; preserve the observed status, or the fallback when absent. + const childRun = vi.mocked(subprocess.execa).mock.results.at(-1) + if (childRun?.type !== 'return') throw new Error('Git probe did not return a child process') + const childResult = await childRun.value + expect(childResult.timedOut).toBe(true) + expect(result).toMatchObject({ + exitCode: childResult.exitCode ?? 1, timedOut: true, argv: checkArgv('https://github.com/acme/plugin.git'), + }) expect(result!.output).toContain('connection to github.com timed out after 3000ms') await transport.disconnected expect(transport.sockets.size).toBe(0) @@ -137,6 +143,18 @@ it('cancels a connected Git probe and closes its transport before the deadline', expect(transport.sockets.size).toBe(0) }) +it.each([128, undefined])('reports a timeout while retaining Git exit status %s', async (exitCode) => { + const { check } = await fixture() + const run = vi.spyOn(subprocess, 'execa').mockResolvedValue({ + failed: true, timedOut: true, exitCode, + } as Awaited>) + onTestFinished(() => { run.mockRestore() }) + const result = await check('github:acme/plugin') + expect(result).toMatchObject({ exitCode: exitCode ?? 1, timedOut: true, kind: 'timeout' }) + expect(result!.output).toContain('connection to github.com timed out after 3000ms') + expect(await readFile(result!.logPath, 'utf8')).toBe(result!.output) +}) + it.each([undefined, 'Git could not start'])('retains a diagnostic when Git writes no stderr (%s)', async (shortMessage) => { const { check } = await fixture() const run = vi.spyOn(subprocess, 'execa').mockResolvedValue({ failed: true, shortMessage } as Awaited>) diff --git a/packages/boot/plugin-market/package.json b/packages/boot/plugin-market/package.json index d02b84882f..e02249a482 100644 --- a/packages/boot/plugin-market/package.json +++ b/packages/boot/plugin-market/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-plugin-market", "description": "Configured plugin market indexes for the Web Discover page and the plugin_market agent tool", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/browser-use/browser-use/package.json b/packages/browser-use/browser-use/package.json index e2e8fa0edd..02dcf989e5 100644 --- a/packages/browser-use/browser-use/package.json +++ b/packages/browser-use/browser-use/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-browser-use", "description": "Exclusive named browser-use provider registration", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/acp-app/package.json b/packages/bundle/acp-app/package.json index 82bb315e7c..53c165c2d6 100644 --- a/packages/bundle/acp-app/package.json +++ b/packages/bundle/acp-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-acp-app", "description": "The dsh ACP profile bundle: automation-only JSON-RPC stdio and process lifecycle over dsh-base", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/base/package.json b/packages/bundle/base/package.json index 4ab644e138..538c61162c 100644 --- a/packages/bundle/base/package.json +++ b/packages/bundle/base/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-base", "description": "The shared dsh core as a profile bundle: the first patch layer of base-backed profiles, inserting core rows over the empty profile root", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/headless/package.json b/packages/bundle/headless/package.json index d47abd4ca9..cf7db74b0a 100644 --- a/packages/bundle/headless/package.json +++ b/packages/bundle/headless/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-headless", "description": "The dsh one-shot bundle: a direct core Agent/Session runner over dsh-base with no Host, HTTP, or browser layer", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/sdk-app/package.json b/packages/bundle/sdk-app/package.json index c683538d68..100c596286 100644 --- a/packages/bundle/sdk-app/package.json +++ b/packages/bundle/sdk-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-sdk-app", "description": "The dsh SDK profile bundle: stdio JSON-RPC serving and process lifecycle over dsh-base", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/sdk-minimal/package.json b/packages/bundle/sdk-minimal/package.json index 262dc98be8..6d40c3ed62 100644 --- a/packages/bundle/sdk-minimal/package.json +++ b/packages/bundle/sdk-minimal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-sdk-minimal", "description": "The standalone minimal SDK profile bundle: JSON-RPC, one DeepSeek adapter, persistent shell, and JSONL sessions", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index 2858130d13..eccc864be4 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-web-app", "description": "The dsh browser-surface bundle: the web patch layer over dsh-base plus the runtime glue plugin (frontend dist serving, bash runtime variables, URL line)", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/connection/package.json b/packages/client/connection/package.json index d2dd72b601..2edb7ed618 100644 --- a/packages/client/connection/package.json +++ b/packages/client/connection/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-connection", "description": "Authenticated RPC transport and generation lifecycle", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/file-upload/package.json b/packages/client/file-upload/package.json index ef19d8c3c5..9a5a3d4705 100644 --- a/packages/client/file-upload/package.json +++ b/packages/client/file-upload/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-file-upload", "description": "Agent-scoped browser file upload, streaming intake, and staged receipt service", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/hmr/package.json b/packages/client/hmr/package.json index d92121c57e..c98f742a6f 100644 --- a/packages/client/hmr/package.json +++ b/packages/client/hmr/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-hmr", "description": "Web client graph synchronization and rebuilt-bundle reload transport", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/locale/package.json b/packages/client/locale/package.json index 3e21127719..a23c2cb4b7 100644 --- a/packages/client/locale/package.json +++ b/packages/client/locale/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-locale", "description": "Locale plugin: Host-backed preference, extensible language catalog, browser fallback, and typed built-in dictionaries", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/modules/package.json b/packages/client/modules/package.json index a30a066c12..69bbe7dc16 100644 --- a/packages/client/modules/package.json +++ b/packages/client/modules/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-modules", "description": "Client module system, dual-face: node half composes the __DSH_BOOT__ entry graph (incremental dsh.client scan, bundle route, index tap, webPlugins service); browser half is the lazy-CJS module table the vendored cordis Loader consumes as its internal seam", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/product-analytics/package.json b/packages/client/product-analytics/package.json index 7baf25596d..05477b0e69 100644 --- a/packages/client/product-analytics/package.json +++ b/packages/client/product-analytics/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-product-analytics", "description": "Desktop product event collection and authenticated Host reporting", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/resources/package.json b/packages/client/resources/package.json index c554b2a178..612bbc8e27 100644 --- a/packages/client/resources/package.json +++ b/packages/client/resources/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-resources", "description": "Unified client resource model: protocol-registered providers turn URL addresses into live values, consumed through the useResource global standard hook", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/shortcuts/package.json b/packages/client/shortcuts/package.json index c4fe99087f..a4a00cb906 100644 --- a/packages/client/shortcuts/package.json +++ b/packages/client/shortcuts/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-shortcuts", "description": "Application keyboard command registry and physical-key routing", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/store/package.json b/packages/client/store/package.json index 64e7f1c38c..70f0e515ee 100644 --- a/packages/client/store/package.json +++ b/packages/client/store/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-store", "description": "React-free observable and snapshot-store contracts with the shared Zustand/Immer engine", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-account-notifications/package.json b/packages/client/ui-account-notifications/package.json index de3bd6aa8b..b505223976 100644 --- a/packages/client/ui-account-notifications/package.json +++ b/packages/client/ui-account-notifications/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-account-notifications", "description": "Display account notifications and refresh localized content", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-agent-preset/package.json b/packages/client/ui-agent-preset/package.json index d60ad24bef..a8ae5feb19 100644 --- a/packages/client/ui-agent-preset/package.json +++ b/packages/client/ui-agent-preset/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-agent-preset", "description": "Agent-preset surfaces: the default for later sessions, this session's seat, and the composition editor", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-agent-team/package.json b/packages/client/ui-agent-team/package.json index 32fb78c0ec..596ae73e3a 100644 --- a/packages/client/ui-agent-team/package.json +++ b/packages/client/ui-agent-team/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-agent-team", "description": "Web shared task board for a subagent tree", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-approval/package.json b/packages/client/ui-approval/package.json index d0889ea071..364ec07e77 100644 --- a/packages/client/ui-approval/package.json +++ b/packages/client/ui-approval/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-approval", "description": "Approval composer takeover over the scoped Remote Event waterfall", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-attachment/package.json b/packages/client/ui-attachment/package.json index f9484bfcb2..bb4bbacff0 100644 --- a/packages/client/ui-attachment/package.json +++ b/packages/client/ui-attachment/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-attachment", "description": "Dynamic attachment presentation plugin for conversation input, message-image, and trajectory image slots", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-brand-official/package.json b/packages/client/ui-brand-official/package.json index b4f23db76e..2ec4de313f 100644 --- a/packages/client/ui-brand-official/package.json +++ b/packages/client/ui-brand-official/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-brand-official", "description": "Official DeepSeek Harness brand artwork and click-triggered home background", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-chat/package.json b/packages/client/ui-chat/package.json index 18667520c5..76ab087eaa 100644 --- a/packages/client/ui-chat/package.json +++ b/packages/client/ui-chat/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-chat", "description": "Chat Conversation target, node definitions, renderers, and details surface", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml b/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml index 518b9a75f9..6dc1b81ecd 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml +++ b/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml @@ -54,11 +54,11 @@ en: 131811a8a12c9d81 zh: f8a8c1e02a5787f8 /chat-conversation-node-rules/activity-summaries/tool-name-classification: - en: a962c232f916bfff - zh: 2e80754623c3f14d + en: 28760f1caab0763b + zh: 2d0eb175509096e7 /chat-conversation-node-rules/activity-summaries/subagents-background-jobs-and-nested-calls: - en: e7796e7ba825c3d6 - zh: c377d9eab0a8869f + en: da0c896564c0d78e + zh: 6ff7b8a3b2f2de8c /chat-conversation-node-rules/activity-summaries/live-activity-and-detail: en: e0ca09c305690be7 zh: fb35d0238b1a827b diff --git a/packages/client/ui-chat/src/client/conversation-nodes/README.md b/packages/client/ui-chat/src/client/conversation-nodes/README.md index e62de7dfbd..2a65f9e20e 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/README.md +++ b/packages/client/ui-chat/src/client/conversation-nodes/README.md @@ -269,7 +269,7 @@ Classification uses the recorded tool name exactly: no case folding, namespace s | `write` | `write` | | `edit` | `edit`, `apply_patch` | | `commands` | `bash`, `pwsh`, `exec_command`, `write_stdin`, or prefix `terminal_` | -| `code` | `run_code` | +| `code` | `run_code`, `cua_run_code` | | `webSearch` | `web_search` | | `webFetch` | `web_fetch` | | `subagents` | `subagent` or prefix `subagent_` | @@ -290,7 +290,7 @@ A subagent tool follows ordinary group boundaries: it does not create a group me | Background subagent startup has returned its tool result, while the child is still running | Keep its category count, but remove that call from running-activity candidates. The child does not keep the parent's group in the subagent activity state. | | Tool calls recorded only in a child Session | Do not include them in the parent group's counts or live detail. Only calls actually attached to a member's `subCalls` participate recursively. | -A `run_code` root counts once as `code`; its recorded PTC subcalls each count in their own categories. The wrapper is not replaced by leaf-call counts, and children are not all classified as `code`. With distinct call ids, `run_code → [read, bash, subagent_codex]` produces `code=1, read=1, commands=1, subagents=1`, in that tie order. A subcall can supply the live category while the outer `run_code` remains running. +A `run_code` or `cua_run_code` root counts once as `code`; its recorded PTC subcalls each count in their own categories. The wrapper is not replaced by leaf-call counts, and children are not all classified as `code`. With distinct call ids, `run_code → [read, bash, subagent_codex]` produces `code=1, read=1, commands=1, subagents=1`, in that tie order. A subcall can supply the live category while the outer `run_code` remains running. Exact-name rules also mean that a recorded name such as `functions.read`, `mcp.read`, or `Read` falls into `tools`, while `browser_inspect` falls into `search`. A `terminal_*` name follows the command rule even when its operation only inspects or closes a terminal, unless the earlier `_inspect` rule matches. diff --git a/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md b/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md index 41a69c3423..7f8638bf5a 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md +++ b/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md @@ -269,7 +269,7 @@ description: "Chat 过程分组与活动摘要的明细业务规则。" | `write` | `write` | | `edit` | `edit`、`apply_patch` | | `commands` | `bash`、`pwsh`、`exec_command`、`write_stdin`,或以 `terminal_` 开头 | -| `code` | `run_code` | +| `code` | `run_code`、`cua_run_code` | | `webSearch` | `web_search` | | `webFetch` | `web_fetch` | | `subagents` | `subagent`,或以 `subagent_` 开头 | @@ -290,7 +290,7 @@ Subagent 工具遵循普通分组边界,不会仅因委派任务就单独成 | 后台 subagent 的启动调用已返回工具结果,但子代理仍在运行 | 保留类别次数,但该调用不再参与运行中活动选择;子代理的执行不会维持父组的 subagent 活动状态。 | | 工具调用只记录在子 Session 中 | 不纳入父组计数或实时详情;只有实际附在本组成员 `subCalls` 中的调用才递归参与。 | -`run_code` 根调用自身计一次 `code`,已记录的每个 PTC 子调用另按自己的类别计数。不会用叶子调用替代包装调用,也不会把子调用统一归为 `code`。各调用 id 不同时,`run_code → [read, bash, subagent_codex]` 得到 `code=1, read=1, commands=1, subagents=1`,同次数时按此顺序排列。外层 `run_code` 仍在运行时,组的实时类别可以由子调用决定。 +`run_code` 或 `cua_run_code` 根调用自身计一次 `code`,已记录的每个 PTC 子调用另按自己的类别计数。不会用叶子调用替代包装调用,也不会把子调用统一归为 `code`。各调用 id 不同时,`run_code → [read, bash, subagent_codex]` 得到 `code=1, read=1, commands=1, subagents=1`,同次数时按此顺序排列。外层 `run_code` 仍在运行时,组的实时类别可以由子调用决定。 精确名称规则也意味着:记录为 `functions.read`、`mcp.read` 或 `Read` 的名称归 `tools`,`browser_inspect` 归 `search`。`terminal_*` 即使只检查或关闭终端,也按命令规则分类,除非先命中 `_inspect` 规则。 diff --git a/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts b/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts index 81d0085a78..bf2ef3341a 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts @@ -13,7 +13,7 @@ function activity(name: string): RunningProcessActivity { if (name === 'write') return 'write' if (name === 'edit' || name === 'apply_patch') return 'edit' if (['bash', 'pwsh', 'exec_command', 'write_stdin'].includes(name) || name.startsWith('terminal_')) return 'commands' - if (name === 'run_code') return 'code' + if (name === 'run_code' || name === 'cua_run_code') return 'code' if (name === 'web_search') return 'webSearch' if (name === 'web_fetch') return 'webFetch' if (name === 'subagent' || name.startsWith('subagent_')) return 'subagents' diff --git a/packages/client/ui-chat/tests/process-groups.client.spec.ts b/packages/client/ui-chat/tests/process-groups.client.spec.ts index d5aa99599d..125a8728e0 100644 --- a/packages/client/ui-chat/tests/process-groups.client.spec.ts +++ b/packages/client/ui-chat/tests/process-groups.client.spec.ts @@ -211,6 +211,7 @@ describe('Definition-owned Chat process groups', () => { it.each([ ['read', 'read'], ['read_image', 'readImage'], ['write', 'write'], ['edit', 'edit'], ['apply_patch', 'edit'], + ['run_code', 'code'], ['cua_run_code', 'code'], ['todo_write', 'plan'], ['create_goal', 'plan'], ['update_goal', 'plan'], ['get_goal', 'plan'], ['list_mcp_resources', 'tools'], ['list_mcp_resource_templates', 'tools'], ['read_mcp_resource', 'tools'], ] as const)('%s keeps its activity category through preparation, dispatch, and result', (name, kind) => { diff --git a/packages/client/ui-commands/package.json b/packages/client/ui-commands/package.json index be40237c4a..591ae98347 100644 --- a/packages/client/ui-commands/package.json +++ b/packages/client/ui-commands/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-commands", "description": "Client command surface: global directory cache, '/' source, three command UI kinds, popupSelect registry", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-context-menu/package.json b/packages/client/ui-context-menu/package.json index 6ddabec73f..c839e300f8 100644 --- a/packages/client/ui-context-menu/package.json +++ b/packages/client/ui-context-menu/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-context-menu", "description": "Typed, plugin-extensible context menus with captured targets and shared Web presentation", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index 612f987620..330dad8d18 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-conversation", "description": "Target-neutral Conversation assembly, shell, composer, queue, and view navigation", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-deliverables/package.json b/packages/client/ui-deliverables/package.json index bd7b325586..1ddba30dc3 100644 --- a/packages/client/ui-deliverables/package.json +++ b/packages/client/ui-deliverables/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-deliverables", "description": "Changed-files card with per-file comparison tabs, delivery cards, and clickable final-response file references for Web", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx b/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx index 9f8ed1d7b1..27a6238bde 100644 --- a/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx @@ -22,6 +22,7 @@ import type { ConversationViewNode, TurnLocation, } from '@deepseek-ai/dsh-client-ui-conversation/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { GlobalStandardProps, SessionStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' import type { ChatFileMentions, TurnTailOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client' import { makeTranslate, stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' @@ -40,6 +41,38 @@ import { en, zh } from '../src/client/locales.ts' import { SessionId } from '@deepseek-ai/dsh-session/types' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' +const unusedStandardHook = (): never => { throw new Error('isolated deliverables fixture does not consume this framework hook') } +const standardProps: GlobalStandardProps & Omit = { + useSession: unusedStandardHook, + useProjection: unusedStandardHook, + useAccess: unusedStandardHook, + useRemoteAccess: unusedStandardHook, + useSessionAccess: unusedStandardHook, + useWorkspaceAccess: unusedStandardHook, + useConversation: unusedStandardHook, + useInput: unusedStandardHook, + useChat: unusedStandardHook, + useTrajectory: unusedStandardHook, + usePanelInfo: unusedStandardHook, + useSessions: unusedStandardHook, + useSessionStatus: unusedStandardHook, + useSessionRetainInfo: unusedStandardHook, + useResource: unusedStandardHook, + useWorkspaces: unusedStandardHook, + useContextMenu: contextMenuHook(), + inputActions: { + insertQuote: () => false, + captureInsertion: unusedStandardHook, + insertText: unusedStandardHook, + setDraft: unusedStandardHook, + persistDraft: unusedStandardHook, + addAttachments: unusedStandardHook, + removeAttachment: unusedStandardHook, + pruneAttachments: unusedStandardHook, + submit: unusedStandardHook, + }, +} + function openProps(controller = new PresentedOpenController(), summaries = new ChangesSummaryStore()) { controller.host.set({ name: 'desktop', available: true, fileManager: 'finder' }) const diffs = new ChangesDiffStore() @@ -926,7 +959,7 @@ describe('plugin registration', () => { } expect(preview.mock.calls).toEqual(Array.from({ length: 4 }, () => ['out/report.docx'])) expect(fetcher).not.toHaveBeenCalled() - const face = entry!.inject!(SessionId('child-session') as never) as unknown as DeliverablesInjected + const face: DeliverablesInjected = entry!.inject!(SessionId('child-session') as never) as Record & DeliverablesInjected fetcher.mockResolvedValueOnce(Response.json({ name: 'desktop', available: true, fileManager: 'finder' })) await face.reloadPresentedHost() expect(face.hooks.presentedHost.getSnapshot()).toMatchObject({ name: 'desktop' }) @@ -944,7 +977,7 @@ describe('plugin registration', () => { face.openChangesReview({ sessionId: SessionId('child-session'), seq: 5, turn: 3 }, 1) expect(openResource).toHaveBeenCalledWith('dsh-resource://changes-review/session/child-session/5/3', { params: { index: 1 } }) expect((registered as { title(address: string): string }).title('dsh-resource://changes-review/session/child-session/5/3')).toBe('Review · turn 3') - const tabFace = tabEntry!.inject!(SessionId('child-session') as never) as unknown as ReviewInjected + const tabFace: ReviewInjected = tabEntry!.inject!(SessionId('child-session') as never) as Record & ReviewInjected fetcher.mockResolvedValueOnce(Response.json({ turn: 3, files: [], total: 0, added: 0, deleted: 0 })) await tabFace.loadChangesSummary(SessionId('child-session'), 6) expect(tabFace.hooks.changesSummary.getSnapshot()['api/changes.summary?sessionId=child-session&seq=6']).toEqual({ turn: 3, files: [], total: 0, added: 0, deleted: 0 }) @@ -1146,7 +1179,13 @@ it('loads desktop information once the tail renders and not again while it is kn it('contributes file artifacts to the tail list only for turns with deliveries', () => { const owner = tailOwner(undefined, 3) - const props = { ...openProps(), ...owner, sessionId: SessionId('session'), t: makeTranslate(en) } as unknown as Parameters[0] + const props: Parameters[0] = { + ...standardProps, + ...openProps(), + ...owner, + sessionId: SessionId('session'), + t: makeTranslate(en), + } const view = render() expect(view.container.innerHTML).toBe('') const withFile = tailOwner({ produced: [], presented: [{ path: 'report.md', seq: 2, index: 0 }] }, 3) diff --git a/packages/client/ui-directory-picker-browse/package.json b/packages/client/ui-directory-picker-browse/package.json index 034cd4647f..4fe0384054 100644 --- a/packages/client/ui-directory-picker-browse/package.json +++ b/packages/client/ui-directory-picker-browse/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-directory-picker-browse", "description": "In-app directory browsing surface: the workspace directory-flow owner rendering the host's listing and creation primitives", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-directory-picker-native/package.json b/packages/client/ui-directory-picker-native/package.json index daa2eb6b35..4ad554e0b3 100644 --- a/packages/client/ui-directory-picker-native/package.json +++ b/packages/client/ui-directory-picker-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-directory-picker-native", "description": "Native directory-picker surface: the renderless workspace directory-flow occupant driving the local Desktop or Host OS chooser", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-dockkit/package.json b/packages/client/ui-dockkit/package.json index 87b424dfd9..c96df661ab 100644 --- a/packages/client/ui-dockkit/package.json +++ b/packages/client/ui-dockkit/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-dockkit", "description": "Docking layout kit: split-tree engine with invertible operations, and the React components that render and drive it (zero cordis)", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-entry-customization/package.json b/packages/client/ui-entry-customization/package.json index 0d64c29522..0ad5b24943 100644 --- a/packages/client/ui-entry-customization/package.json +++ b/packages/client/ui-entry-customization/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-entry-customization", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "description": "Customize plugin entries in the left sidebar, conversation views, and right sidebar, and quickly create new plugins.", "publishConfig": { "access": "public" }, "repository": { diff --git a/packages/client/ui-file-actions/package.json b/packages/client/ui-file-actions/package.json index 07f9612828..a605a36224 100644 --- a/packages/client/ui-file-actions/package.json +++ b/packages/client/ui-file-actions/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-file-actions", "description": "Original-file saving and image clipboard actions for Web and Desktop", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-file-drag/package.json b/packages/client/ui-file-drag/package.json index 18225f7c99..9002817731 100644 --- a/packages/client/ui-file-drag/package.json +++ b/packages/client/ui-file-drag/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-file-drag", "description": "Application-owned file drag transfers and localized failure feedback", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-goal/package.json b/packages/client/ui-goal/package.json index c46c077c89..6cf9f3f3c1 100644 --- a/packages/client/ui-goal/package.json +++ b/packages/client/ui-goal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-goal", "description": "Session goal surface: GoalBar docked above the composer, read from the goal session projection", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-input-trigger/package.json b/packages/client/ui-input-trigger/package.json index 469efd796f..0a1bd70788 100644 --- a/packages/client/ui-input-trigger/package.json +++ b/packages/client/ui-input-trigger/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-input-trigger", "description": "Input trigger pipeline: '/' and '@' detection, candidate menu, pick routing to registered sources", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-jobs/package.json b/packages/client/ui-jobs/package.json index 2c8943e4c7..4c22829922 100644 --- a/packages/client/ui-jobs/package.json +++ b/packages/client/ui-jobs/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-jobs", "description": "Session-header background-job list with on-demand streaming record panels", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "type": "module", "main": "lib/index.js", "types": "lib/types/index.d.ts", diff --git a/packages/client/ui-layout/package.json b/packages/client/ui-layout/package.json index b418ce3e95..d00ca63a52 100644 --- a/packages/client/ui-layout/package.json +++ b/packages/client/ui-layout/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-layout", "description": "Shell plugin: three-column AppFrame with drag handles, ctx.layout viewing-state service (navigation + panels)", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-message-feedback/package.json b/packages/client/ui-message-feedback/package.json index 5c67e2ce03..9963c064fa 100644 --- a/packages/client/ui-message-feedback/package.json +++ b/packages/client/ui-message-feedback/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-message-feedback", "description": "The Web feedback surface: per-message Like/Dislike in the assistant-message action strip and the feedback dialog behind both ratings and /feedback, backed by the messageFeedback and sessionFeedback Host Remotes", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-model-selection/package.json b/packages/client/ui-model-selection/package.json index 549bcfab73..0ca23e506b 100644 --- a/packages/client/ui-model-selection/package.json +++ b/packages/client/ui-model-selection/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-model-selection", "description": "Model selection over the shared model catalog, Session projection, and session.selectModel", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-open-in-app/package.json b/packages/client/ui-open-in-app/package.json index 8e12ef41e6..490226ba8d 100644 --- a/packages/client/ui-open-in-app/package.json +++ b/packages/client/ui-open-in-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-open-in-app", "description": "Session application submenus and native opening controls for directories and previewed files", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-permission-presets/package.json b/packages/client/ui-permission-presets/package.json index 0b49d98e4c..7a0cc0b15a 100644 --- a/packages/client/ui-permission-presets/package.json +++ b/packages/client/ui-permission-presets/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-permission-presets", "description": "Permission surfaces: a new-session default in General settings and a current-session /permission popup over the permissions projection", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-plan/package.json b/packages/client/ui-plan/package.json index 4c87c9a9f8..0c94f46c61 100644 --- a/packages/client/ui-plan/package.json +++ b/packages/client/ui-plan/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-plan", "description": "Plan mode controls, persistent transcript plan cards, and sidebar Markdown previews", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-plugin-manager/package.json b/packages/client/ui-plugin-manager/package.json index 633f76347e..5f6a0ec16d 100644 --- a/packages/client/ui-plugin-manager/package.json +++ b/packages/client/ui-plugin-manager/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-plugin-manager", "description": "Plugin management for the dsh web client: the sidebar Plugins panel installs, enables, disables, retries, and composes installed plugin packages", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-plugin-market/package.json b/packages/client/ui-plugin-market/package.json index aae48bfb81..14c8e68dc4 100644 --- a/packages/client/ui-plugin-market/package.json +++ b/packages/client/ui-plugin-market/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-plugin-market", "description": "Discover tab of the dsh web Plugins page: browse configured plugin market indexes and install their bundles", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-primitives/package.json b/packages/client/ui-primitives/package.json index 02bb00cae3..8135385a77 100644 --- a/packages/client/ui-primitives/package.json +++ b/packages/client/ui-primitives/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-primitives", "description": "Pure React atoms for the dsh web UI: controls, icons, markdown, and JSON inspectors (zero cordis)", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-primitives/src/FileTypeIcon.tsx b/packages/client/ui-primitives/src/FileTypeIcon.tsx index 1fbcee6750..fc2e3c2667 100644 --- a/packages/client/ui-primitives/src/FileTypeIcon.tsx +++ b/packages/client/ui-primitives/src/FileTypeIcon.tsx @@ -44,7 +44,9 @@ export type FileTypeIconProps = IconProps & ( } ) -const EXTENSION_TYPES: Readonly> = { +// Maps, not objects: a basename or extension equal to an `Object.prototype` key +// (`constructor`, `__proto__`) must miss instead of resolving the inherited member. +const EXTENSION_TYPES: ReadonlyMap = new Map(Object.entries({ scss: 'code', sass: 'code', less: 'code', @@ -101,13 +103,13 @@ const EXTENSION_TYPES: Readonly> = { ots: 'excel', fods: 'excel', numbers: 'excel', -} +})) -const NAME_TYPES: Readonly> = { +const NAME_TYPES: ReadonlyMap = new Map(Object.entries({ changelog: 'markdown', contributing: 'markdown', readme: 'markdown', -} +})) function basename(path: string): string { return path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1) @@ -140,8 +142,8 @@ export function classifyFileType( const name = basename(path).toLowerCase() const extension = fileExtension(name).toLowerCase() return classifyCodeFileType(name, extension, context) - ?? NAME_TYPES[name] - ?? EXTENSION_TYPES[extension] + ?? NAME_TYPES.get(name) + ?? EXTENSION_TYPES.get(extension) ?? 'other' } diff --git a/packages/client/ui-primitives/src/code-file-types.ts b/packages/client/ui-primitives/src/code-file-types.ts index 9b5ce75459..5bb1a5a628 100644 --- a/packages/client/ui-primitives/src/code-file-types.ts +++ b/packages/client/ui-primitives/src/code-file-types.ts @@ -61,7 +61,9 @@ export interface FileTypeProjectContext { const CODE_FILE_TYPE_SET = new Set(CODE_FILE_TYPES) -const FILE_NAME_TYPES: Readonly> = { +// Maps, not objects: a basename or extension equal to an `Object.prototype` key +// (`constructor`, `__proto__`) must miss instead of resolving the inherited member. +const FILE_NAME_TYPES: ReadonlyMap = new Map(Object.entries({ '.bash_profile': 'shell', '.bashrc': 'shell', '.env': 'env', @@ -90,7 +92,7 @@ const FILE_NAME_TYPES: Readonly> = { 'package.json': 'node', 'podfile': 'ruby', 'rakefile': 'ruby', -} +})) const FILE_NAME_PREFIX_TYPES: readonly (readonly [string, CodeFileType])[] = [ ['dockerfile.', 'docker'], @@ -109,7 +111,7 @@ const FILE_NAME_SUFFIX_TYPES: readonly (readonly [string, CodeFileType])[] = [ ['.dockerfile', 'docker'], ] -const EXTENSION_TYPES: Readonly> = { +const EXTENSION_TYPES: ReadonlyMap = new Map(Object.entries({ 'bash': 'shell', 'c': 'c', 'c++': 'cpp', @@ -217,7 +219,7 @@ const EXTENSION_TYPES: Readonly> = { 'yml': 'yaml', 'zig': 'zig', 'zsh': 'shell', -} +})) const LINK_CODE_EXTENSIONS = new Set([ 'ts', @@ -322,7 +324,7 @@ export function classifyCodeFileType( extension: string, context?: FileTypeProjectContext, ): CodeFileType | null { - const exact = FILE_NAME_TYPES[name] + const exact = FILE_NAME_TYPES.get(name) if (exact !== undefined) return exact for (const [prefix, type] of FILE_NAME_PREFIX_TYPES) { if (name.startsWith(prefix)) return type @@ -334,5 +336,5 @@ export function classifyCodeFileType( const pubspec = Object.entries(context.files).find(([path]) => basename(path).toLowerCase() === 'pubspec.yaml')?.[1] if (pubspec?.includes('flutter:') === true) return 'flutter' } - return EXTENSION_TYPES[extension] ?? null + return EXTENSION_TYPES.get(extension) ?? null } diff --git a/packages/client/ui-primitives/tests/file-type-icon.client.spec.tsx b/packages/client/ui-primitives/tests/file-type-icon.client.spec.tsx index b39b22f0f2..e9c8367d59 100644 --- a/packages/client/ui-primitives/tests/file-type-icon.client.spec.tsx +++ b/packages/client/ui-primitives/tests/file-type-icon.client.spec.tsx @@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { classifyFileType, fileExtension, FileTypeIcon, type FileTypeKind, } from '@deepseek-ai/dsh-client-ui-primitives' +import { classifyCodeFileType } from '../src/code-file-types.ts' import css from '../src/FileTypeIcon.module.css' afterEach(cleanup) @@ -58,6 +59,30 @@ describe('classifyFileType', () => { }) }) +describe('Object.prototype key names', () => { + const keys = ['constructor', '__proto__', 'toString', 'hasOwnProperty'] + + it.each(keys.flatMap(key => [ + [key, 'other'], + [`src/${key.toUpperCase()}`, 'other'], + [`archive.${key}`, 'other'], + [`${key}.md`, 'markdown'], + [`${key}.ts`, 'typescript'], + ] as [string, Exclude][]))('%s → %s', (path, type) => { + expect(classifyFileType(path)).toBe(type) + }) + + it.each(keys)('%s misses the code-file name and extension tables', (key) => { + expect(classifyCodeFileType(key, key)).toBeNull() + expect(classifyCodeFileType(key, 'ts')).toBe('typescript') + }) + + it.each(keys.flatMap(key => [key, `notes.${key}`]))('%s renders the generic file glyph', (path) => { + const { container } = render() + expect(container.querySelector('svg')!.classList.contains(css.other!)).toBe(true) + }) +}) + describe('FileTypeIcon', () => { const types: FileTypeKind[] = [ 'code', 'excel', 'folder', 'html', 'image', 'markdown', 'other', 'pdf', 'ppt', 'video', 'word', diff --git a/packages/client/ui-reference/package.json b/packages/client/ui-reference/package.json index c452aa5d22..4dfc1a305c 100644 --- a/packages/client/ui-reference/package.json +++ b/packages/client/ui-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-reference", "description": "Unified Web @file and @session reference source", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-renderer/package.json b/packages/client/ui-renderer/package.json index 862fcfea75..2d1d543b75 100644 --- a/packages/client/ui-renderer/package.json +++ b/packages/client/ui-renderer/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-renderer", "description": "Browser UI renderer: React slot bindings, ctx.uiRenderer, and the assembled application root", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-schedule/package.json b/packages/client/ui-schedule/package.json index a87a770379..e8a002b1ca 100644 --- a/packages/client/ui-schedule/package.json +++ b/packages/client/ui-schedule/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-schedule", "description": "Host task management page and Session reminder catalog", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "type": "module", "main": "lib/index.js", "types": "lib/types/index.d.ts", diff --git a/packages/client/ui-secret-mask/package.json b/packages/client/ui-secret-mask/package.json index 584abad79b..e58278b6a8 100644 --- a/packages/client/ui-secret-mask/package.json +++ b/packages/client/ui-secret-mask/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-secret-mask", "description": "Web display masking for recognized credentials in sent user text", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-session/package.json b/packages/client/ui-session/package.json index 11996a36b7..9fb6bda901 100644 --- a/packages/client/ui-session/package.json +++ b/packages/client/ui-session/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-session", "description": "Session Controller adapter for React and session-scoped slots", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-account/package.json b/packages/client/ui-settings-account/package.json index c4086a3ef2..16bdf0111f 100644 --- a/packages/client/ui-settings-account/package.json +++ b/packages/client/ui-settings-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-account", "description": "Manage DeepSeek login and open Platform billing pages", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-agent-loop/package.json b/packages/client/ui-settings-agent-loop/package.json index b61c80d26d..bf9b907b2d 100644 --- a/packages/client/ui-settings-agent-loop/package.json +++ b/packages/client/ui-settings-agent-loop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-agent-loop", "description": "Settings page of the agent loop on the dsh web client's Plugins page: the parallel tool-call cap of the agent-loop namespace", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-general/package.json b/packages/client/ui-settings-general/package.json index 0e804d9563..71d53abcef 100644 --- a/packages/client/ui-settings-general/package.json +++ b/packages/client/ui-settings-general/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-general", "description": "Settings ownerless-copy and product onboarding plugin: the General section, shell trigger/header chrome content, settings dictionaries, and the versioned welcome notice", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-models/package.json b/packages/client/ui-settings-models/package.json index b0c740304a..7713bd60d1 100644 --- a/packages/client/ui-settings-models/package.json +++ b/packages/client/ui-settings-models/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-models", "description": "Models settings and shared product-onboarding dialogs over existing settings and credential joins", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-plugin-inventory/package.json b/packages/client/ui-settings-plugin-inventory/package.json index a3a36dc550..059efb9c8e 100644 --- a/packages/client/ui-settings-plugin-inventory/package.json +++ b/packages/client/ui-settings-plugin-inventory/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-plugin-inventory", "description": "Read-only Cordis Loader inventory tab in Web Plugins settings", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-plugins/package.json b/packages/client/ui-settings-plugins/package.json index def5c9a3be..6e646fc07f 100644 --- a/packages/client/ui-settings-plugins/package.json +++ b/packages/client/ui-settings-plugins/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-plugins", "description": "Built-in plugins settings section for the dsh web client: the Settings navigation entry and the tab chrome feature-owned tabs register into", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-session-log/package.json b/packages/client/ui-settings-session-log/package.json index 87ce57d76d..3ffdcf5953 100644 --- a/packages/client/ui-settings-session-log/package.json +++ b/packages/client/ui-settings-session-log/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-session-log", "description": "General settings control for Session-log upload with DeepSeek API requests", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-shell/package.json b/packages/client/ui-settings-shell/package.json index cacc9935b5..5aea5a0ad6 100644 --- a/packages/client/ui-settings-shell/package.json +++ b/packages/client/ui-settings-shell/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-shell", "description": "Settings page of the shell executor on the dsh web client's Plugins page: the command timeout and the per-stream output cap of the shell namespace", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-subagent/package.json b/packages/client/ui-settings-subagent/package.json index 0e0c728546..8bc89487d0 100644 --- a/packages/client/ui-settings-subagent/package.json +++ b/packages/client/ui-settings-subagent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-subagent", "description": "Settings page of Subagent delegation on the dsh web client's Plugins page: recursion depth, parallel capacity, and the models agents may choose for subagents", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-web-search/package.json b/packages/client/ui-settings-web-search/package.json index 9d62ee7e83..5371a10782 100644 --- a/packages/client/ui-settings-web-search/package.json +++ b/packages/client/ui-settings-web-search/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-web-search", "description": "Settings page for web search and fetch on the dsh web client's Plugins page: the Search and Fetch provider menus, the DeepSeek Search API result count, DeepSeek Search and Fetch API billing, and legacy Messages search settings", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings/package.json b/packages/client/ui-settings/package.json index 1b9b299d5c..06ba6ab951 100644 --- a/packages/client/ui-settings/package.json +++ b/packages/client/ui-settings/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings", "description": "Settings domain base plugin: shared configuration forms and the canonical settings slot-type contract", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-shortcuts/package.json b/packages/client/ui-shortcuts/package.json index 2de1bc435b..58b6d5815c 100644 --- a/packages/client/ui-shortcuts/package.json +++ b/packages/client/ui-shortcuts/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-shortcuts", "description": "Keyboard shortcut reference, recording, and local preference editing", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-browser/package.json b/packages/client/ui-sidebar-browser/package.json index ee0979c3ea..1f006bfda3 100644 --- a/packages/client/ui-sidebar-browser/package.json +++ b/packages/client/ui-sidebar-browser/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-browser", "description": "Sandboxed Web browser tabs for the right Sidebar", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-documentpreview/package.json b/packages/client/ui-sidebar-documentpreview/package.json index 4824c20d60..aadd67fd70 100644 --- a/packages/client/ui-sidebar-documentpreview/package.json +++ b/packages/client/ui-sidebar-documentpreview/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-documentpreview", "description": "Extensible Sidebar previews for Office documents, spreadsheets, Markdown, code, images, PDF, HTML, and plain text", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-files/package.json b/packages/client/ui-sidebar-files/package.json index 371267467a..28a0d8fe27 100644 --- a/packages/client/ui-sidebar-files/package.json +++ b/packages/client/ui-sidebar-files/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-files", "description": "The workspace files page and one workspace directory tree per pane beside docked and floating file previews, listed lazily over the workspaceFiles Remote namespace", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-right/package.json b/packages/client/ui-sidebar-right/package.json index d01fdf16ff..0de2aa4a47 100644 --- a/packages/client/ui-sidebar-right/package.json +++ b/packages/client/ui-sidebar-right/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-right", "description": "Right Sidebar: the docking surface's session-bound state, its panel and header expand control, and the navigation service over it", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-terminal/package.json b/packages/client/ui-sidebar-terminal/package.json index 82dd31cc04..8fbb67c504 100644 --- a/packages/client/ui-sidebar-terminal/package.json +++ b/packages/client/ui-sidebar-terminal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-terminal", "description": "Interactive shell tabs for the right Sidebar", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar/package.json b/packages/client/ui-sidebar/package.json index 25fdb3d76b..536d17c8e6 100644 --- a/packages/client/ui-sidebar/package.json +++ b/packages/client/ui-sidebar/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar", "description": "Sidebar plugin: session multi-level tree, search, grouping, state dots", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-skill/package.json b/packages/client/ui-skill/package.json index bec902998b..9babd70d63 100644 --- a/packages/client/ui-skill/package.json +++ b/packages/client/ui-skill/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-skill", "description": "Web skill references and the dedicated skill tool row", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-slots/package.json b/packages/client/ui-slots/package.json index 8220bc664f..5a88f2967b 100644 --- a/packages/client/ui-slots/package.json +++ b/packages/client/ui-slots/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-slots", "description": "Slot registry pure core: typed ordinary Slots and reusable Component Factories, derived props, Store seats, and renderer installation", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index ade2634518..9f008dd598 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-subagent", "description": "Subagent conversation catalog, continuation routing UI, and '@' reference source", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-theme/package.json b/packages/client/ui-theme/package.json index b40ea1cdcf..3124ac013b 100644 --- a/packages/client/ui-theme/package.json +++ b/packages/client/ui-theme/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-theme", "description": "Theme plugin: Host bootstrap for the pre-plugin palette; ThemeRuntime for light/dark/system state and icon replacements; --dsw-* token styles and Appearance settings row", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts new file mode 100644 index 0000000000..e65cb1a16a --- /dev/null +++ b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts @@ -0,0 +1,32 @@ +/** Tests for the package-tree scan helpers that the stylesheet contracts range over. */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { packageFiles } from './stylesheet-scan.ts' + +const roots: string[] = [] + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +it('skips dot directories holding transient roots', () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-stylesheet-scan-')) + roots.push(root) + mkdirSync(join(root, 'pkg', 'nested'), { recursive: true }) + writeFileSync(join(root, 'pkg', 'package.json'), '{}') + writeFileSync(join(root, 'pkg', 'nested', 'package.json'), '{}') + mkdirSync(join(root, '.typert-worker-failure-probe')) + writeFileSync(join(root, '.typert-worker-failure-probe', 'package.json'), '{}') + + // The helper reports `/`-separated paths on every platform, so the Windows + // temporary root's separators must not reach the expectation. Traversal + // reports the nested manifest before its parent, and directory order is not + // guaranteed, so both sides are compared sorted. + const normalized = root.replaceAll('\\', '/') + expect(packageFiles(name => name === 'package.json', root).sort()).toEqual([ + `${normalized}/pkg/nested/package.json`, + `${normalized}/pkg/package.json`, + ]) +}) diff --git a/packages/client/ui-theme/tests/stylesheet-scan.ts b/packages/client/ui-theme/tests/stylesheet-scan.ts index 91311945bf..ce796bc62c 100644 --- a/packages/client/ui-theme/tests/stylesheet-scan.ts +++ b/packages/client/ui-theme/tests/stylesheet-scan.ts @@ -73,22 +73,28 @@ export function varReferences(value: string): string[] { /** * Every file shipped as package source whose name the predicate accepts, - * excluding build output and installed dependencies. + * excluding build output, installed dependencies, and dot directories. + * Dot directories hold VCS metadata and per-test temporary roots rather than + * shipped source, and their owner can remove one while a scan reads it. * @param accepts - filename predicate. - * @returns absolute paths under packages/, `/`-separated on every platform so + * @param root - tree to walk, the packages directory by default. + * @returns absolute paths under `root`, `/`-separated on every platform so * specs can match repo-relative suffixes verbatim. */ -export function packageFiles(accepts: (name: string) => boolean): string[] { +export function packageFiles(accepts: (name: string) => boolean, root: string = PACKAGES_DIR): string[] { const found: string[] = [] const walk = (dir: string): void => { for (const entry of readdirSync(dir, { withFileTypes: true })) { const path = join(dir, entry.name) if (entry.isDirectory()) { - if (entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path) + // Dot directories hold VCS metadata and the temporary roots each spec + // creates inside the package tree, never shipped package source; a + // concurrent owner can remove one while a scan reads it. + if (!entry.name.startsWith('.') && entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path) } else if (accepts(entry.name)) found.push(path.replaceAll('\\', '/')) } } - walk(PACKAGES_DIR) + walk(root) return found } diff --git a/packages/client/ui-tool/README.i18n.yaml b/packages/client/ui-tool/README.i18n.yaml index 59dfd47110..47c516bed1 100644 --- a/packages/client/ui-tool/README.i18n.yaml +++ b/packages/client/ui-tool/README.i18n.yaml @@ -18,8 +18,8 @@ en: 4d8cb38024095705 zh: 1baf6fa42f3fb80f /deepseek-ai-dsh-client-ui-tool/use-this-package/registering-a-business-tool-view: - en: e458aff61e634190 - zh: 650e417f450b3edf + en: 3dd6bd71dfc5527d + zh: 9fe3c2135014bb7b /deepseek-ai-dsh-client-ui-tool/use-this-package/built-in-views: en: 33f41ad70d0728f7 zh: b7c65108c5921134 diff --git a/packages/client/ui-tool/README.md b/packages/client/ui-tool/README.md index 448a4e197b..04b2254d47 100644 --- a/packages/client/ui-tool/README.md +++ b/packages/client/ui-tool/README.md @@ -47,7 +47,7 @@ ctx.slots.inject('tool.call.toolview', () => }, BusinessToolRow)) ``` -The owner payload is `ToolCallOwnerProps`: `callId`, `toolName`, the `phase` discriminant and its stage-specific `block`, optional `cwd` and `home`, the Gateway-authorized `loadImage` loader (for a view whose result carries durable images), and plain `openFile`/`inspect` callbacks. A PTC dispatch block retains its event's `parentCallId`; a root Session call has no such field, so descendants route through the same keyed dispatch — a registered view such as `read_image` renders its card there, and unregistered descendants keep the generic flattened form. Path summaries relativize to the Session cwd first, then replace a leftover POSIX Host home with `~`; `filePath` and Host open prefer the operation-time absolute result path while displayed labels keep the authored argument. Successful older root results retain their argument fallback; pending relative paths wait for a result. The registration receives the normal Session slot runtime share but no React node or Runtime service. +The owner payload is `ToolCallOwnerProps`: `callId`, `toolName`, the `phase` discriminant and its stage-specific `block`, optional `cwd` and `home`, the Gateway-authorized `loadImage` loader (for a view whose result carries durable images), and plain `openFile`/`inspect` callbacks. A PTC dispatch block retains its event's `parentCallId`; a root Session call has no such field, so descendants route through the same keyed dispatch — a registered view such as `read_image` renders its card there, and unregistered descendants keep the generic flattened form. Path summaries relativize to the Session cwd first, then replace a leftover POSIX Host home with `~`; `filePath` and Host open prefer the operation-time absolute result path while displayed labels keep the authored argument. Successful older root results retain their argument fallback; pending relative paths wait for a result. The registration receives the normal Session slot runtime share but no React node or Runtime service. Generic result output preserves block order and displays image attachment names or IDs with dimensions and byte counts. ### Built-in views diff --git a/packages/client/ui-tool/README.zh.md b/packages/client/ui-tool/README.zh.md index 37757c47a7..65f23151d7 100644 --- a/packages/client/ui-tool/README.zh.md +++ b/packages/client/ui-tool/README.zh.md @@ -47,7 +47,7 @@ ctx.slots.inject('tool.call.toolview', () => }, BusinessToolRow)) ``` -owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、`phase` 判别字段及对应阶段的 `block`、可选 `cwd` 与 `home`、经 Gateway 授权的 `loadImage` loader(供结果携带持久图像的视图使用),以及普通的 `openFile`/`inspect` 回调。PTC dispatch 块保留事件的 `parentCallId`;根会话调用没有该字段,因此后代调用都走同一条按 key 分发路径:已注册视图的调用(如 `read_image`)也会在嵌套处渲染对应卡片,未注册的后代调用则保持通用压平形式。路径摘要先相对会话 cwd 缩短,再把剩余的 POSIX Host home 写成 `~`;`filePath` 与 Host 打开优先使用操作发生时记录的绝对结果路径,显示标签仍保留原始参数。成功的旧根调用结果继续回退到原参数;运行中的相对路径等待结果。注册项会收到常规的会话 slot 运行时共享数据,但不会收到 React 节点或运行时服务。 +owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、`phase` 判别字段及对应阶段的 `block`、可选 `cwd` 与 `home`、经 Gateway 授权的 `loadImage` loader(供结果携带持久图像的视图使用),以及普通的 `openFile`/`inspect` 回调。PTC dispatch 块保留事件的 `parentCallId`;根会话调用没有该字段,因此后代调用都走同一条按 key 分发路径:已注册视图的调用(如 `read_image`)也会在嵌套处渲染对应卡片,未注册的后代调用则保持通用压平形式。路径摘要先相对会话 cwd 缩短,再把剩余的 POSIX Host home 写成 `~`;`filePath` 与 Host 打开优先使用操作发生时记录的绝对结果路径,显示标签仍保留原始参数。成功的旧根调用结果继续回退到原参数;运行中的相对路径等待结果。注册项会收到常规的会话 slot 运行时共享数据,但不会收到 React 节点或运行时服务。 通用结果输出保留块的顺序,并以附件名称或 ID、尺寸和字节数展示图片引用。 ### 内置视图 diff --git a/packages/client/ui-tool/package.json b/packages/client/ui-tool/package.json index 5e30dc91b5..bfe5348675 100644 --- a/packages/client/ui-tool/package.json +++ b/packages/client/ui-tool/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-tool", "description": "Client Tool call-tree renderer and keyed per-tool presentation slot", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts b/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts index ae96145b03..9f81138d3b 100644 --- a/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts @@ -62,6 +62,7 @@ const TOOL_VARIANTS: Record = { edit: 'edit', apply_patch: 'edit', run_code: 'code', + cua_run_code: 'code', cordis_package_inspect: 'read', cordis_runtime_inspect: 'read', // The three run-control verbs take one package id and produce a receipt, so @@ -202,21 +203,26 @@ function deriveAutoReviewDenial(block: ToolCallBlock): AutoReviewDenial | null { /** * Flatten a settled result's content blocks to display text: text blocks - * verbatim, other block shapes as pretty JSON. Empty content on a failed call - * falls back to the structured error's `name: code` line. + * verbatim, images through the supplied formatter, and other blocks + * as pretty JSON. Empty failure content falls back to the structured error's + * `name: code` line. * @param node - the settled result node. + * @param formatImage - Optional formatter for unvalidated image attachments; omission or undefined preserves image JSON. * @returns the flattened result text (may be empty). */ -export function resultText(node: ToolResultNode): string { +export function resultText(node: ToolResultNode, formatImage?: (image: unknown) => string | undefined): string { const parts: string[] = [] for (const block of node.content) { if (block.type === 'text') parts.push(block.text) - else parts.push(JSON.stringify(block, null, 2)) + else { + const image = block.type === 'image' ? formatImage?.(block.attachment) : undefined + parts.push(image ?? JSON.stringify(block, null, 2)) + } } if (parts.length === 0 && node.error !== undefined) { parts.push(`${node.error.name}: ${node.error.code}`) } - return parts.join('\n') + return parts.reduce((text, part, index) => text + (index === 0 || text.endsWith('\n') ? '' : '\n') + part, '') } function parseArgs(argsRaw: string): unknown { @@ -367,9 +373,13 @@ export function formatToolBody(variant: ToolRowVariant, argsRaw: string): string * @param block - preparing call, dispatched call, or result from the snapshot. * @param cwd - session workspace root; workspace-rooted path summaries display relative to it. * @param home - host account home; a leftover POSIX home path displays as `~`. + * @param formatImage - Optional image formatter; omission preserves image JSON. * @returns the row model. */ -export function toolRowModel(toolName: string, block: ToolCallBlock, cwd?: string, home?: string): ToolRowModel { +export function toolRowModel( + toolName: string, block: ToolCallBlock, cwd?: string, home?: string, + formatImage?: (image: unknown) => string | undefined, +): ToolRowModel { const variant = classifyTool(toolName) const titleKey = toolTitleKey(toolName) const done = 'kind' in block @@ -403,7 +413,7 @@ export function toolRowModel(toolName: string, block: ToolCallBlock, cwd?: strin // The empty string is "no text" for both derived result fields: a settled // call with blank content has nothing to expand, and a blank first line // would erase the collapsed error row's summary slot. - const output = done ? (resultText(block) || null) : null + const output = done ? (resultText(block, formatImage) || null) : null const errorSummary = state === 'error' && output !== null ? firstLine(output) : null const bodyRaw = argsRaw === '' ? null : argsRaw return { diff --git a/packages/client/ui-tool/src/client/tool/toolviews/GenericToolCard.tsx b/packages/client/ui-tool/src/client/tool/toolviews/GenericToolCard.tsx index 6ce48b990f..f5cf72d95d 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/GenericToolCard.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/GenericToolCard.tsx @@ -36,7 +36,14 @@ export type GenericToolCardProps = ToolCallOwnerProps & { export function GenericToolCard({ toolName, block, cwd, home, openFile, getFileTriggerProps, inspect, useDisclosure, t, }: GenericToolCardProps) { - const model = toolRowModel(toolName, block, cwd, home) + const model = toolRowModel(toolName, block, cwd, home, (image) => { + if (typeof image !== 'object' || image === null || Array.isArray(image)) return undefined + const { attachmentId, name, width, height, bytes } = image as Record + if (typeof attachmentId !== 'string' || attachmentId === '' + || name !== undefined && typeof name !== 'string' + || ![width, height, bytes].every(value => typeof value === 'number' && Number.isInteger(value) && value > 0)) return undefined + return `${name ?? attachmentId} (${t('row.imageSize', { width, height, bytes })})` + }) const autoReview = model.autoReviewDenial === null ? null : localizeAutoReviewDenial(model.autoReviewDenial, t) diff --git a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx index 18c3d6937b..91cf3bc474 100644 --- a/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx +++ b/packages/client/ui-tool/tests/chat-ptc-subcalls.client.spec.tsx @@ -45,17 +45,17 @@ beforeEach(() => { const PROGRAM = 'const listing = await tools.bash({ command: "ls notes", description: "List notes" })\nreturn listing' const RUN_CODE_ARGS = JSON.stringify({ code: PROGRAM, description: 'List the notes directory' }) -const codeResult = (seq: number, callId: string): ToolResultNode => ({ +const codeResult = (seq: number, callId: string, name = 'run_code', argsRaw = RUN_CODE_ARGS): ToolResultNode => ({ kind: 'tool-result', seq, time: seq * 1_000, callId, - name: 'run_code', args: PartialArguments.fromText(RUN_CODE_ARGS), - call: { name: 'run_code', argsRaw: RUN_CODE_ARGS }, + name, args: PartialArguments.fromText(argsRaw), + call: { name, argsRaw }, callTime: seq * 1_000 - 500, content: [{ type: 'text', text: 'demo.txt' }], isError: false, subCalls: [], }) -const runningCode = (callId: string): StartedToolCall => ({ - phase: 'start' as const, args: PartialArguments.fromText(RUN_CODE_ARGS), callId, name: 'run_code', argsRaw: RUN_CODE_ARGS, turn: 9, step: 0, time: 9_000, +const runningCode = (callId: string, name = 'run_code', argsRaw = RUN_CODE_ARGS): StartedToolCall => ({ + phase: 'start' as const, args: PartialArguments.fromText(argsRaw), callId, name, argsRaw, turn: 9, step: 0, time: 9_000, subCalls: [], }) @@ -155,7 +155,24 @@ function mountApp(runtime: SlotTestRuntime) { return runtime.renderRoot() } -describe('run_code sub-calls through the real chat machinery', () => { +describe('program sub-calls through the real chat machinery', () => { + it.each([false, true])('renders the CUA program and its nested calls while running=%s', async (running) => { + const parent = 'cua-program' + const program = "var app = await cua.getApp('Calculator')\nconsole.log(app)" + const argsRaw = JSON.stringify({ code: program, description: 'Select Calculator' }) + const child = subCall(11, parent, 1, 'cua', { method: 'getApp', params: { selector: 'Calculator' } }, 'Calculator') + const b = await bench(snapshotWith( + running ? [] : [codeResult(10, parent, 'cua_run_code', argsRaw)], [child], + running ? [runningCode(parent, 'cua_run_code', argsRaw)] : [], + )) + const view = mountApp(b.runtime) + expect(view.getByText('Code')).toBeTruthy() + expect(view.getByText('Select Calculator')).toBeTruthy() + expect(view.container.querySelector('[data-subcalls] [data-tool="cua"]')).not.toBeNull() + fireEvent.click(view.getByText('Select Calculator')) + expect(view.container.querySelector('pre.shiki')?.textContent).toBe(program) + }) + it('renders the code-variant parent row with the description summary and nested sub-rows', async () => { const parent = 'call-64' const subCalls = [ diff --git a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts index 1b92e65a1f..a3e0a43a42 100644 --- a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts +++ b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts @@ -62,7 +62,7 @@ async function executeShell(text: string, nested: boolean, name = 'bash', maxInl if (tool === undefined) throw new Error('missing fixture binding') const blocks = await tool(shellArgs) expect(blocks).toEqual([{ type: 'text', text }]) - return { logs: [], value: true } + return { output: [{ type: 'text', text: 'true' }] } } } await ctx.plugin(BindingRuntime) @@ -86,7 +86,7 @@ async function executeShell(text: string, nested: boolean, name = 'bash', maxInl signal: new AbortController().signal, name: nested ? 'run_code' : name, arguments: nested ? { - code: `const blocks = await tools.${name}(${JSON.stringify(shellArgs)}); return blocks[0].text === ${JSON.stringify(text)};`, + code: `const blocks = await tools.${name}(${JSON.stringify(shellArgs)}); inspect(blocks[0].text === ${JSON.stringify(text)});`, description: 'Dispatch shell fixture through the tool pipeline', } : shellArgs, }) @@ -95,7 +95,7 @@ async function executeShell(text: string, nested: boolean, name = 'bash', maxInl let block: ToolResultNode if (nested) { - expect(result.value).toMatchObject({ result: true }) + expect(result.value).toMatchObject({ logs: ['true'] }) const dispatches = session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch') expect(dispatches).toHaveLength(1) const event = dispatches[0]! diff --git a/packages/client/ui-tool/tests/tool-row.client.spec.tsx b/packages/client/ui-tool/tests/tool-row.client.spec.tsx index beadba5f5e..a65f0f4179 100644 --- a/packages/client/ui-tool/tests/tool-row.client.spec.tsx +++ b/packages/client/ui-tool/tests/tool-row.client.spec.tsx @@ -1,4 +1,5 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { AttachmentId } from '@deepseek-ai/dsh-attachment' // @vitest-environment jsdom import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -14,7 +15,7 @@ import { } from '../src/client/tool/models/tool-call-model.ts' import { ToolRow } from '../src/client/tool/components/ToolRow.tsx' import { GenericToolCard, type GenericToolCardProps } from '../src/client/tool/toolviews/GenericToolCard.tsx' -import { zh } from '@deepseek-ai/dsh-client-ui-conversation/src/client/locales.ts' +import { en, zh } from '@deepseek-ai/dsh-client-ui-conversation/src/client/locales.ts' import { PartialArguments } from '@deepseek-ai/dsh-util-values' afterEach(() => { @@ -53,6 +54,9 @@ describe('tool-call-model', () => { expect(classifyTool('grep')).toBe('search') expect(classifyTool('write')).toBe('write') expect(classifyTool('edit')).toBe('edit') + expect(classifyTool('run_code')).toBe('code') + expect(classifyTool('cua_run_code')).toBe('code') + expect(classifyTool('cua_run_code_extra')).toBe('others') expect(classifyTool('cordis_runtime_inspect')).toBe('read') // The v3 run-control verbs: `others` is the decided intent, not an // unclassified default (there is no program to show and no file to open). @@ -235,21 +239,50 @@ describe('tool-call-model', () => { .toBe('{\n "code": ""\n}') }) - it('resultText flattens text blocks verbatim, other shapes as JSON, empty error content to name: code', () => { + it('resultText retains text and image JSON and uses the structured failure when content is empty', () => { expect(resultText(result({ content: [{ type: 'text', text: 'a\nb' }] }))).toBe('a\nb') - expect(resultText(result({ content: [{ type: 'text', text: 'a' }, { type: 'image', data: 'x' } as never] }))) - .toBe(`a\n${JSON.stringify({ type: 'image', data: 'x' }, null, 2)}`) + const image = { type: 'image' as const, attachment: { attachmentId: AttachmentId('sha256:image'), mediaType: 'image/png' as const, width: 8, height: 4, bytes: 64 } } + expect(resultText(result({ content: [image] }))).toBe(JSON.stringify(image, null, 2)) + const reasoning = { type: 'reasoning' as const, text: 'detail' } + expect(resultText(result({ content: [reasoning] }))).toBe(JSON.stringify(reasoning, null, 2)) expect(resultText(result({ content: [], isError: true, error: { name: 'ToolError', code: 'denied' } }))) .toBe('ToolError: denied') expect(resultText(result({ content: [] }))).toBe('') }) + it('preserves image JSON when the formatter declines', () => { + for (const content of ['[{"type":"image"}]', '[{"type":"image","attachment":null}]', + '[{"type":"image","attachment":{"width":"8"}}]']) { + const blocks = JSON.parse(content) as ToolResultNode['content'] + expect(resultText(result({ content: blocks }), () => undefined)).toBe(JSON.stringify(blocks[0], null, 2)) + } + }) + + it('separates image references without duplicating an emitted newline', () => { + const attachment = { attachmentId: AttachmentId('sha256:image'), mediaType: 'image/png' as const, width: 8, height: 4, bytes: 64 } + for (const text of ['a', 'a\n']) { + expect(resultText(result({ content: [{ type: 'text', text }, { type: 'image', attachment }] }), () => 'sha256:image')) + .toBe('a\nsha256:image') + } + expect(resultText(result({ content: [{ type: 'text', text: 'a\n\n' }, { type: 'image', attachment }] }), () => 'sha256:image')) + .toBe('a\n\nsha256:image') + }) + it('derives output from the settled result and null while running or blank', () => { expect(toolRowModel('bash', result({ content: [{ type: 'text', text: 'out' }] })).output).toBe('out') expect(toolRowModel('bash', running()).output).toBeNull() expect(toolRowModel('bash', result({ content: [] })).output).toBeNull() }) + it.each([false, true])('shares formatted image output with its error summary, failure=%s', (isError) => { + const image = { type: 'image' as const, attachment: { attachmentId: AttachmentId('sha256:image'), mediaType: 'image/png' as const, width: 8, height: 4, bytes: 64 } } + const formatImage = vi.fn(() => 'selected image') + const model = toolRowModel('run_code', result({ content: [image], isError }), undefined, undefined, formatImage) + expect(model.output).toBe('selected image') + expect(model.errorSummary).toBe(isError ? 'selected image' : null) + expect(formatImage).toHaveBeenCalledOnce() + }) + it('derives errorSummary as the first output line on error rows only', () => { const failed = result({ content: [{ type: 'text', text: 'boom\ndetail' }], isError: true }) expect(toolRowModel('bash', failed).errorSummary).toBe('boom') @@ -588,6 +621,33 @@ describe('GenericToolCard', () => { useDisclosure, callId: 'c1', toolName, ...('kind' in block ? { phase: 'result' as const, block: block } : { phase: block.phase, block: block }), openFile: vi.fn(), t, }) + it.each([ + [t, 'sha256:image (8x4px,64 字节)'], + [makeTranslate(en), 'sha256:image (8x4px, 64 bytes)'], + ] as const)('localizes compact image references in the generic card', (translate, expected) => { + const attachment = { attachmentId: AttachmentId('sha256:image'), mediaType: 'image/png' as const, width: 8, height: 4, bytes: 64 } + const block = result({ content: [{ type: 'text', text: 'before\n' }, { type: 'image', attachment }] }) + const view = render() + fireEvent.click(view.getByRole('button')) + expect(view.container.textContent).toContain(expected) + expect(view.container.querySelector('[class*="output"]')?.textContent ?? view.container.textContent).not.toContain('before\n\nsha256:') + }) + + it.each([ + '{"type":"image"}', + '{"type":"image","attachment":null}', + '{"type":"image","attachment":[]}', + '{"type":"image","attachment":{"attachmentId":"image","width":"8","height":4,"bytes":64}}', + '{"type":"image","attachment":{"attachmentId":"image","width":8,"height":4,"bytes":0}}', + '{"type":"image","attachment":{"attachmentId":"image","name":12,"width":8,"height":4,"bytes":64}}', + '{"type":"image","attachment":{"width":8,"height":4,"bytes":64}}', + ])('renders malformed image references as JSON: %s', (json) => { + const content = JSON.parse(`[${json}]`) as ToolResultNode['content'] + const view = render() + fireEvent.click(view.getByRole('button')) + expect(view.container.textContent).toContain(JSON.stringify(content[0], null, 2)) + }) + it('renders the classified variant row from the frozen slice', () => { const view = render( ({})} />) diff --git a/packages/client/ui-trajectory/README.i18n.yaml b/packages/client/ui-trajectory/README.i18n.yaml index 262d052c0b..073194c2a3 100644 --- a/packages/client/ui-trajectory/README.i18n.yaml +++ b/packages/client/ui-trajectory/README.i18n.yaml @@ -18,8 +18,8 @@ en: 4bd17d05b8385675 zh: 5174e27f754f2a03 /deepseek-ai-dsh-client-ui-trajectory/use-this-package/inspecting-records: - en: 4bf16077921c643c - zh: 08ded05f8f0afded + en: dc86f133fbc74633 + zh: 289fa88898ac3e55 /deepseek-ai-dsh-client-ui-trajectory/use-this-package/the-timing-overview: en: 0f4ee2189324ac06 zh: 12e76fed22c09bc1 diff --git a/packages/client/ui-trajectory/README.md b/packages/client/ui-trajectory/README.md index 265c6fffd9..2cba341eee 100644 --- a/packages/client/ui-trajectory/README.md +++ b/packages/client/ui-trajectory/README.md @@ -31,7 +31,7 @@ Open the Trajectory tab in the conversation's view ring to inspect agent activit The toolbar folds turns, calls, and subcalls independently. Subcalls fold into a summary beneath their parent tool; click the summary or press Enter or Space to expand it. Search includes folded subcalls, and cross-view inspection expands the requested call. Toolbar controls and search wrap onto additional lines when the pane is narrow. -Calls are identified by their recorded tool name. For `run_code`, the row shows the program description and the inspector opens numbered, highlighted source. The Code tab provides wrapping, a `{}` toggle for the original JSON arguments, and exact source copying, including trailing newlines. Copying the original arguments retains their recorded JSON whitespace. Each newly opened code view takes the last wrapping choice; changing it leaves other open views as they are. Output preserves the recorded text, using a tree for complete JSON objects or arrays. Highlighting reads the leading `Execute a program in` language declaration and the legacy `code` parameter description from the recorded tool schema. Only TypeScript and Python are supported. Missing or conflicting hints, or an explicit declaration of another language, leave plain source; later examples in the tool description do not affect language selection. +Calls are identified by their recorded tool name. For `run_code` and `cua_run_code`, the row shows the program description and the inspector opens numbered, highlighted source. The Code tab provides wrapping, a `{}` toggle for the original JSON arguments, and exact source copying, including trailing newlines. Copying the original arguments retains their recorded JSON whitespace. Each newly opened code view takes the last wrapping choice; changing it leaves other open views as they are. Output preserves the recorded text, using a tree for complete JSON objects or arrays. Highlighting reads the leading `Execute a program in` language declaration and the legacy `code` parameter description from the recorded tool schema. Only TypeScript and Python are supported. Missing or conflicting hints, or an explicit declaration of another language, leave plain source; later examples in the tool description do not affect language selection. Selection, timeline navigation, folding, and search cover the React-visible window. Request numbers and cumulative usage cover the complete resident snapshot. Selecting a record opens a local inspector for token usage, duration, Input, Output, Timing, and durable images. Image URLs use the Conversation-owned per-session cache, so Chat and Trajectory share one authorized read per attachment. The Trajectory view declares `conversation.trajectory.images`; ledger children call this Slot through the framework `renderSlot` seat, passing image references, display options, and the authorized loader explicitly. Its official `MessageImages` entry calls the shared `conversation.images.content` Factory. A user record shows both nonzero image and ordinary-file counts beside its text, including attachment-only records. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn. diff --git a/packages/client/ui-trajectory/README.zh.md b/packages/client/ui-trajectory/README.zh.md index bed828aa7f..5290ba8c83 100644 --- a/packages/client/ui-trajectory/README.zh.md +++ b/packages/client/ui-trajectory/README.zh.md @@ -31,7 +31,7 @@ Trajectory 标签页让你以按轮次组织的事件记录表和交互式时间 工具栏可以分别折叠轮次、调用和子调用。子调用收起后,在父工具下保留一条摘要;点击摘要或按 Enter、空格键即可展开。搜索包含已折叠的子调用,从其他视图检查调用时会自动展开目标调用。 面板较窄时,工具栏按钮与搜索框会自动换行。 -调用按已记录的工具名识别。对于 `run_code`,记录行展示程序说明,检查器显示带行号和语法高亮的源码。“代码”页提供换行、查看原始 JSON 参数的 `{}` 切换按钮,以及保留末尾换行的源码原样复制。复制原始参数时保留记录中 JSON 的空白。每个新打开的代码视图采用上次选择的换行状态;切换时,其他已打开视图保持原状。输出保留记录中的文本,完整 JSON 对象或数组使用树形展示。高亮从已记录的工具 Schema 中读取开头的 `Execute a program in` 语言声明及旧式 `code` 参数说明,仅支持 TypeScript 和 Python。提示缺失或冲突,或明确声明了其他语言时,显示纯文本源码;工具说明后文的示例不影响语言选择。 +调用按已记录的工具名识别。对于 `run_code` 和 `cua_run_code`,记录行展示程序说明,检查器显示带行号和语法高亮的源码。“代码”页提供换行、查看原始 JSON 参数的 `{}` 切换按钮,以及保留末尾换行的源码原样复制。复制原始参数时保留记录中 JSON 的空白。每个新打开的代码视图采用上次选择的换行状态;切换时,其他已打开视图保持原状。输出保留记录中的文本,完整 JSON 对象或数组使用树形展示。高亮从已记录的工具 Schema 中读取开头的 `Execute a program in` 语言声明及旧式 `code` 参数说明,仅支持 TypeScript 和 Python。提示缺失或冲突,或明确声明了其他语言时,显示纯文本源码;工具说明后文的示例不影响语言选择。 选择、时间线导航、折叠与搜索只覆盖 React 可见窗口。请求编号与累计用量覆盖完整的驻留快照。选择记录会打开局部检查器,查看 token 用量、耗时、输入、输出、计时与持久保留的图片。图片 URL 使用 Conversation 拥有的逐会话缓存,因此 Chat 与 Trajectory 对每个附件共享一次已授权读取。Trajectory 视图声明 `conversation.trajectory.images`;账本子组件通过框架 `renderSlot` 席位调用该 Slot,显式传入图片引用、显示参数及授权 loader。官方 `MessageImages` 条目调用共享的 `conversation.images.content` Factory。用户记录会在文本旁同时显示非零的图片与普通文件数量,仅含附件的记录也显示这些数量。独立运行的压缩请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。 diff --git a/packages/client/ui-trajectory/package.json b/packages/client/ui-trajectory/package.json index efee2c8c57..a0d6689e43 100644 --- a/packages/client/ui-trajectory/package.json +++ b/packages/client/ui-trajectory/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-trajectory", "description": "Trajectory event ledger and timing overview with live tool-result inspection", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx index 6b7acc0dca..b76c1a08d4 100644 --- a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx +++ b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx @@ -42,7 +42,7 @@ import type { TrajectoryTurnModel } from './layout.ts' import { trajectoryPreviewText } from './trajectory-preview.ts' import type { TrajectoryKey, TrajectoryTranslate } from './locales.ts' import { COMPACTION_INTERRUPTED_ERROR } from './copy-codes.ts' -import { codeProgram, PTC_TOOL_NAME, type CodeProgram } from './code-program.ts' +import { codeProgram, isProgramTool, type CodeProgram } from './code-program.ts' import css from './TrajectoryTable.module.css' const BOTTOM_FOLLOW_THRESHOLD_PX = 2 @@ -1030,7 +1030,7 @@ function detailTabs(record: TableRecord): readonly DetailTabItem[] { function recordDisplayText(cell: TrajectoryCellProps, t: TrajectoryTranslate): string { if (isToolCallOnly(cell, t)) return '' const program = codeProgram(cell) - if (program !== undefined) return `${PTC_TOOL_NAME} · ${program.description.replace(/\s+/g, ' ')}` + if (program !== undefined) return `${cell.toolName} · ${program.description.replace(/\s+/g, ' ')}` if (cell.previewMarkdown !== undefined) { const preview = trajectoryPreviewText(cell.previewMarkdown) if (cell.text === '') return preview @@ -1056,7 +1056,7 @@ function toolCallTextParts( text: string, ): ToolCallTextParts | undefined { if (cell.kind !== 'tool' && cell.kind !== 'subtool') return undefined - const program = cell.toolName === PTC_TOOL_NAME + const program = isProgramTool(cell.toolName) const separator = text.indexOf(' · ') if (separator === -1) return { name: text, program } return { diff --git a/packages/client/ui-trajectory/src/client/code-program.ts b/packages/client/ui-trajectory/src/client/code-program.ts index fc618cf843..13dafc6309 100644 --- a/packages/client/ui-trajectory/src/client/code-program.ts +++ b/packages/client/ui-trajectory/src/client/code-program.ts @@ -1,10 +1,16 @@ -/** Read replayable PTC source and language hints from recorded tool arguments and schemas. */ +/** Read program source and language hints from recorded tool arguments and schemas. */ import type { TrajectoryCellProps } from './trajectory-record.ts' -/** Recorded name of the programmatic tool-calling entry point. */ -export const PTC_TOOL_NAME = 'run_code' +/** + * Identify tools supported by the trajectory code inspector. + * @param name - Recorded tool name, absent when the call is outside the loaded window. + * @returns Whether this tool executes a program shown by the code inspector. + */ +export function isProgramTool(name: string | undefined): boolean { + return name === 'run_code' || name === 'cua_run_code' +} -/** Validated source and original arguments for one recorded run_code call. */ +/** Validated source and original arguments for one recorded program call. */ export interface CodeProgram { rawInput: string source: string @@ -46,14 +52,14 @@ function recordedLanguage(schemaRaw: string | undefined): CodeProgram['language' } /** - * Resolve a PTC program without guessing its language from source or current runtime settings. + * Resolve a program without guessing its language from source or current runtime settings. * Unknown explicit languages or conflicting recorded hints leave the source unhighlighted. * @param cell - Recorded tool arguments and the schema visible at call time. * @returns The program, or undefined for another tool or unsupported arguments. */ export function codeProgram(cell: TrajectoryCellProps): CodeProgram | undefined { if (cell.kind !== 'tool' && cell.kind !== 'subtool') return undefined - if (cell.toolName !== PTC_TOOL_NAME || cell.inputDetail === undefined) return undefined + if (!isProgramTool(cell.toolName) || cell.inputDetail === undefined) return undefined const args = parseRecord(cell.inputDetail) if (typeof args?.code !== 'string') return undefined if (args.description !== undefined && typeof args.description !== 'string') return undefined diff --git a/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx b/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx index a92d13659a..3300190e39 100644 --- a/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx @@ -143,10 +143,10 @@ describe('PTC trajectory inspector', () => { } }) - it('shows the description, numbered source, original arguments, and verbatim output', () => { - const view = render() + it.each(['run_code', 'cua_run_code'])('shows the %s description, numbered source, original arguments, and verbatim output', (toolName) => { + const view = render() const ui = within(view.container) - fireEvent.click(ui.getByRole('row', { name: /run_code Read the working directory/ })) + fireEvent.click(ui.getByRole('row', { name: new RegExp(`${toolName} Read the working directory`) })) expect(ui.getAllByRole('tab').map(tab => tab.textContent)).toEqual(['Summary', 'Code', 'Result', 'Schema', 'Timing']) expect(ui.getByRole('tabpanel').textContent).toContain('Read the working directory') expect(view.container.querySelector('[data-line-numbers] pre')?.textContent).toBe(SOURCE.trimEnd()) diff --git a/packages/client/ui-trajectory/tests/code-program.client.spec.ts b/packages/client/ui-trajectory/tests/code-program.client.spec.ts index 435eaa3c6a..848fe3d52b 100644 --- a/packages/client/ui-trajectory/tests/code-program.client.spec.ts +++ b/packages/client/ui-trajectory/tests/code-program.client.spec.ts @@ -9,8 +9,8 @@ const CELL: TrajectoryCellProps = { } describe('recorded code programs', () => { - it('keeps the program and arguments verbatim', () => { - expect(codeProgram(CELL)).toEqual({ + it.each(['run_code', 'cua_run_code'])('keeps the %s program and arguments verbatim', (toolName) => { + expect(codeProgram({ ...CELL, toolName })).toEqual({ rawInput: CELL.inputDetail, source: 'return 42\n', description: 'Compute the answer', arguments: { code: 'return 42\n', description: 'Compute the answer' }, language: undefined, @@ -122,6 +122,7 @@ describe('recorded code programs', () => { it('does not specialize other tools or non-tool records', () => { expect(codeProgram({ ...CELL, kind: 'message' })).toBeUndefined() expect(codeProgram({ ...CELL, toolName: 'run_code_extra' })).toBeUndefined() + expect(codeProgram({ ...CELL, toolName: 'cua_run_code_extra' })).toBeUndefined() expect(codeProgram({ ...CELL, kind: 'subtool' })?.source).toBe('return 42\n') }) }) diff --git a/packages/client/ui-user-questions/package.json b/packages/client/ui-user-questions/package.json index 7dedfd4a26..a0d3b61aa0 100644 --- a/packages/client/ui-user-questions/package.json +++ b/packages/client/ui-user-questions/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-user-questions", "description": "Web ask_user_question composer takeover and plan-review presentation UI", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-workflow-run/package.json b/packages/client/ui-workflow-run/package.json index 812639e8c0..c097a340a7 100644 --- a/packages/client/ui-workflow-run/package.json +++ b/packages/client/ui-workflow-run/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-workflow-run", "description": "Durable workflow-run Conversation Node and nested member disclosure for dsh web", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index f495f14fb7..e67c5242a6 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-workspace", "description": "Workspace picker plugin: one WorkspacePicker registered into the sidebar and empty-state workspace slots", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/web/README.i18n.yaml b/packages/client/web/README.i18n.yaml index 6667e00fa7..082c0ab024 100644 --- a/packages/client/web/README.i18n.yaml +++ b/packages/client/web/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-web/use-this-package: - en: 3105391bad2e9f06 - zh: fe0c5af5db6c241c + en: 01c1354d946e456e + zh: 33c672b64e9e33fb /deepseek-ai-dsh-client-web/use-this-package/what-boot-looks-like: en: f3b01aa878764e5c zh: f02eab65d441bfe0 diff --git a/packages/client/web/README.md b/packages/client/web/README.md index 8aaabbf2cf..e42719dcac 100644 --- a/packages/client/web/README.md +++ b/packages/client/web/README.md @@ -29,7 +29,7 @@ Use it when you assemble the browser application: `apps/web`'s Vite entry runs ` Static application pages install `__DSH_BOOT_READY__` before the entry runs. The boot page renders immediately while `run()` waits; the page owner applies the Host rows with `applyIndexInjections` (also exported from `./injections`) and resolves the deferred after all scripts finish. A rejected deferred renders a boot failure unless the caller supplies `run(onFailure)` to present the error externally while retaining the loading page. Desktop uses this callback to request native recovery. Desktop and WebWorker share the injection interpreter; server-side `tapIndex` HTML transforms apply only to served documents. -The shell base styles apply automatic CJK/Latin spacing to ordinary content in supporting browsers. Semantic code and terminal, diff, read, and search output containers retain literal source spacing and column alignment; browsers without `text-autospace` support ignore both declarations. +The shell base styles preserve authored text sizes when mobile browsers rotate or unfold. Browser zoom and the appearance font-size setting remain available. They also apply automatic CJK/Latin spacing to ordinary content in supporting browsers. Semantic code and terminal, diff, read, and search output containers retain literal source spacing and column alignment; browsers without `text-autospace` support ignore both declarations. Web and Desktop mathematical rendering requires WOFF2 support. The [Web build](../../../apps/web/katex-fonts.ts) retains every KaTeX font face in WOFF2 and omits WOFF/TTF fallbacks; a face without WOFF2 rejects the build. Font glyphs, weights, styles, and layout rules are preserved. diff --git a/packages/client/web/README.zh.md b/packages/client/web/README.zh.md index 0b94a8e60a..8fed19ba82 100644 --- a/packages/client/web/README.zh.md +++ b/packages/client/web/README.zh.md @@ -29,7 +29,7 @@ kind: "package-library" 静态应用页面在入口运行前安装 `__DSH_BOOT_READY__`。`run()` 等待期间会立即显示启动页;页面所有者通过 `applyIndexInjections`(也从 `./injections` 导出)应用 Host 注入项,并在所有脚本完成后兑现延迟对象。延迟对象拒绝时显示启动失败;若调用方提供 `run(onFailure)`,则由外部呈现错误并保留加载页。Desktop 使用该回调请求原生恢复。Desktop 与 WebWorker 共享注入解释器;服务端 `tapIndex` HTML 转换仅适用于服务端提供的文档。 -外壳基础样式会在支持的浏览器中为普通内容自动添加中西文间距。语义化代码以及终端、diff、读取和搜索输出容器会保留源码中的原始间距和列对齐;不支持 `text-autospace` 的浏览器会忽略这两项声明。 +外壳基础样式会在移动浏览器旋转或展开屏幕时保持页面设定的字号,浏览器缩放和外观字号设置仍可使用。它还会在支持的浏览器中为普通内容自动添加中西文间距。语义化代码以及终端、diff、读取和搜索输出容器会保留源码中的原始间距和列对齐;不支持 `text-autospace` 的浏览器会忽略这两项声明。 Web 和 Desktop 的数学公式渲染要求支持 WOFF2。[Web 构建](../../../apps/web/katex-fonts.ts)以 WOFF2 保留全部 KaTeX 字体样式,并排除 WOFF/TTF 后备格式;任一字体样式缺少 WOFF2 都会使构建失败。字体的字形、字重、样式和布局规则保持不变。 diff --git a/packages/client/web/package.json b/packages/client/web/package.json index b342335bec..65143f34e9 100644 --- a/packages/client/web/package.json +++ b/packages/client/web/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-web", "description": "Web boot kernel: static module table, Cordis loader, framework-free boot page, and UI-renderer handoff", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/client/web/src/base.css b/packages/client/web/src/base.css index c2de24767c..57e47357f1 100644 --- a/packages/client/web/src/base.css +++ b/packages/client/web/src/base.css @@ -8,6 +8,12 @@ body, margin: 0; } +/* Preserve authored text sizes when mobile browsers rotate or unfold. */ +html { + -webkit-text-size-adjust: 100%; + text-size-adjust: 100%; +} + body { font-family: var( --dsw-font-family, diff --git a/packages/compaction/command-compact/package.json b/packages/compaction/command-compact/package.json index 957921e87a..7ed4cf70d2 100644 --- a/packages/compaction/command-compact/package.json +++ b/packages/compaction/command-compact/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-command-compact", "description": "Human-facing slash command for explicit session compaction", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/compaction/compaction-basic/package.json b/packages/compaction/compaction-basic/package.json index 80d9f30987..2e4d7e54e1 100644 --- a/packages/compaction/compaction-basic/package.json +++ b/packages/compaction/compaction-basic/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction-basic", "description": "Token-meter-driven compaction policy and LLM summarization backend for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/compaction/compaction-image-offload/package.json b/packages/compaction/compaction-image-offload/package.json index 0249347ffb..ef745bfd88 100644 --- a/packages/compaction/compaction-image-offload/package.json +++ b/packages/compaction/compaction-image-offload/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction-image-offload", "description": "Durable image offload for image-capable routes: replace over-budget request images with placeholders and retry", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/compaction/compaction-tool-result-pruner/package.json b/packages/compaction/compaction-tool-result-pruner/package.json index a6f78944fb..43f47c8f44 100644 --- a/packages/compaction/compaction-tool-result-pruner/package.json +++ b/packages/compaction/compaction-tool-result-pruner/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction-tool-result-pruner", "description": "Replay-safe model-free head/middle/tail pruning for tool-result surface nodes", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/compaction/compaction/package.json b/packages/compaction/compaction/package.json index 113a5a257c..4f3d6cb72b 100644 --- a/packages/compaction/compaction/package.json +++ b/packages/compaction/compaction/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction", "description": "Abstract compaction service seam (ctx.compaction) for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/computer-use/computer-use/package.json b/packages/computer-use/computer-use/package.json index 0f7f00eb31..9a5cd7c85f 100644 --- a/packages/computer-use/computer-use/package.json +++ b/packages/computer-use/computer-use/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-computer-use", "description": "Exclusive named computer-use provider registration", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/context/agent-instructions/package.json b/packages/context/agent-instructions/package.json index dd95de6641..06a08c0ce7 100644 --- a/packages/context/agent-instructions/package.json +++ b/packages/context/agent-instructions/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-instructions", "description": "Workspace context loader for AGENTS.md/CLAUDE.md instruction files", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/context/file-reference-local/package.json b/packages/context/file-reference-local/package.json index 72d0bc3d0f..60d29be9f6 100644 --- a/packages/context/file-reference-local/package.json +++ b/packages/context/file-reference-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-file-reference-local", "description": "Local-filesystem ctx.fileReferences provider with bounded fuzzy indexes", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/context/file-reference-local/src/index.ts b/packages/context/file-reference-local/src/index.ts index a179cebafb..7cbf68fb48 100644 --- a/packages/context/file-reference-local/src/index.ts +++ b/packages/context/file-reference-local/src/index.ts @@ -21,15 +21,7 @@ import { type FileSearchConfig, } from './search.ts' -export { - DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES, - DEFAULT_FILE_SEARCH_MAX_ENTRIES, - DEFAULT_FILE_SEARCH_MAX_RESULTS, - WorkspaceFileSearch, -} from './search.ts' export type { FileSearchConfig } from './search.ts' -export { FILE_REFERENCE_PROMPT } from '@deepseek-ai/dsh-file-reference' -export { activeAtToken, formatFileMention } from '@deepseek-ai/dsh-file-reference/grammar' /** Local file-reference discovery configuration. */ export interface Config { diff --git a/packages/context/file-reference-local/tests/service.spec.ts b/packages/context/file-reference-local/tests/service.spec.ts index df94c8ab64..14859f5881 100644 --- a/packages/context/file-reference-local/tests/service.spec.ts +++ b/packages/context/file-reference-local/tests/service.spec.ts @@ -14,7 +14,8 @@ import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' import ToolRegistry from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' import { FILE_REFERENCE_PROMPT } from '@deepseek-ai/dsh-file-reference' -import LocalFileReferenceService, { WorkspaceFileSearch } from '../src/index.ts' +import LocalFileReferenceService from '../src/index.ts' +import { WorkspaceFileSearch } from '../src/search.ts' const roots: string[] = [] diff --git a/packages/context/file-reference/package.json b/packages/context/file-reference/package.json index 30f4217c8e..bb6feaf609 100644 --- a/packages/context/file-reference/package.json +++ b/packages/context/file-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-file-reference", "description": "File-reference discovery contract and shared @file grammar", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/context/harness-dev-context/package.json b/packages/context/harness-dev-context/package.json index d0faa968ab..c071165338 100644 --- a/packages/context/harness-dev-context/package.json +++ b/packages/context/harness-dev-context/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-harness-dev-context", "description": "Model context naming the DeepSeek Harness checkout and Web GUI URL without letting either change the system prompt", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/context/session-reference/package.json b/packages/context/session-reference/package.json index b53b90d171..d3b5a060da 100644 --- a/packages/context/session-reference/package.json +++ b/packages/context/session-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-session-reference", "description": "Cross-session snapshot references and durable untrusted model context (ctx.sessionReferenceResolver)", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/context/time-context/package.json b/packages/context/time-context/package.json index 2c831d5c3f..3d8939bc4b 100644 --- a/packages/context/time-context/package.json +++ b/packages/context/time-context/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-time-context", "description": "Durable per-step context with the current time and elapsed time", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/context/tmux-context/package.json b/packages/context/tmux-context/package.json index 92bbaa76ae..5d52599f5a 100644 --- a/packages/context/tmux-context/package.json +++ b/packages/context/tmux-context/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tmux-context", "description": "Opt-in durable per-step context with this agent's tmux pane and window location", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/agent-default-model/package.json b/packages/core/agent-default-model/package.json index 1366189505..9675d2437c 100644 --- a/packages/core/agent-default-model/package.json +++ b/packages/core/agent-default-model/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-default-model", "description": "Default model selection shared by Agent entry points", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/agent-loop/package.json b/packages/core/agent-loop/package.json index f2555c5f81..2098fb375b 100644 --- a/packages/core/agent-loop/package.json +++ b/packages/core/agent-loop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-loop", "description": "The concrete agent loop plugin for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/agent-loop/tests/tool-calls.spec.ts b/packages/core/agent-loop/tests/tool-calls.spec.ts index 3ea1089e61..f479363062 100644 --- a/packages/core/agent-loop/tests/tool-calls.spec.ts +++ b/packages/core/agent-loop/tests/tool-calls.spec.ts @@ -942,7 +942,7 @@ describe('PTC mode native-tool denial through the agent loop', () => { readonly language = 'typescript' readonly isolation = 'fake' as const async run(_request: PtcRunRequest): Promise { - return { logs: [] } + return { output: [] } } } diff --git a/packages/core/agent-tool-presentation/package.json b/packages/core/agent-tool-presentation/package.json index 53cc5041c7..14c7b39825 100644 --- a/packages/core/agent-tool-presentation/package.json +++ b/packages/core/agent-tool-presentation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-tool-presentation", "description": "Deprecated tool presentation selector; use dsh-tool-executor-native or dsh-tool-executor-ptc directly", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts b/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts index 4f43b87f08..2ce71441bc 100644 --- a/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts +++ b/packages/core/agent-tool-presentation/tests/agent-tool-presentation.spec.ts @@ -25,7 +25,7 @@ class StubRuntime extends PtcRuntime { readonly isolation = 'stub' run(_request: PtcRunRequest): Promise { - return Promise.resolve({ logs: [] }) + return Promise.resolve({ output: [] }) } } diff --git a/packages/core/agent/package.json b/packages/core/agent/package.json index 445a7d0646..9540b7fe34 100644 --- a/packages/core/agent/package.json +++ b/packages/core/agent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent", "description": "Agent interface, registry, initiator scope, and event vocabulary for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/scope/package.json b/packages/core/scope/package.json index 73e41943b3..dd91932508 100644 --- a/packages/core/scope/package.json +++ b/packages/core/scope/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-scope", "description": "Scoped-context registration primitive (scope tags, scope-filtered event dispatch) for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/session/package.json b/packages/core/session/package.json index 0800cab3c2..fa4b8e831a 100644 --- a/packages/core/session/package.json +++ b/packages/core/session/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-session", "description": "Event-sourced session store for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/session/tests/session.spec.ts b/packages/core/session/tests/session.spec.ts index ccd152b777..8226361c0a 100644 --- a/packages/core/session/tests/session.spec.ts +++ b/packages/core/session/tests/session.spec.ts @@ -1168,13 +1168,15 @@ describe('Session', () => { 'detached', )).toThrow(/not a plain JSON record/) } - expect(() => Session.create(SessionId('header-invalid'), undefined, { + const nonJsonHeader: SessionHeader = { version: SESSION_FORMAT_VERSION, id: SessionId('header-invalid'), createdAt: 123, isSeeded: false, - parentSession: 1n, - } as unknown as SessionHeader)).toThrow(/not losslessly JSON-serializable/) + } + Reflect.set(nonJsonHeader, 'parentSession', 1n) + expect(() => Session.create(SessionId('header-invalid'), undefined, nonJsonHeader)) + .toThrow(/not losslessly JSON-serializable/) expect(() => Session.create(SessionId('header-invalid'), undefined, { version: SESSION_FORMAT_VERSION, id: SessionId('other'), diff --git a/packages/core/system-prompt/package.json b/packages/core/system-prompt/package.json index d5cb602afa..e6e9b0a2c5 100644 --- a/packages/core/system-prompt/package.json +++ b/packages/core/system-prompt/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-system-prompt", "description": "System prompt assembly registry for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/tool-executor-native/package.json b/packages/core/tool-executor-native/package.json index 184dc63a1d..5719c424ee 100644 --- a/packages/core/tool-executor-native/package.json +++ b/packages/core/tool-executor-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-executor-native", "description": "Native tool execution plugin", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/core/tool-executor-ptc/README.i18n.yaml b/packages/core/tool-executor-ptc/README.i18n.yaml index 4a9b5223ee..71e8b2faa1 100644 --- a/packages/core/tool-executor-ptc/README.i18n.yaml +++ b/packages/core/tool-executor-ptc/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-tool-executor-ptc/use-this-package: - en: 2db07bc05f05d202 - zh: 4efdaab79fcc00af + en: 90ceb23f80ce7b26 + zh: 01ecb606d4e8fb6f /deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation: en: 78708b3779d999a9 zh: ad6173f9f01630de /deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation/ptc-mode: - en: 9b4bce1edd565a03 - zh: e167fb6fa9036b54 + en: 129e1a149bd42218 + zh: 97aec4e64d26dd7f /deepseek-ai-dsh-tool-executor-ptc/further-exploration: en: ee69078c38c655a9 zh: fb0873407f23c8c5 @@ -33,8 +33,8 @@ en: eaefd7303f22977d zh: 9c425f9501128224 /deepseek-ai-dsh-tool-executor-ptc/model-experience/ptc-mode-schema-and-system-prompt/what-the-model-sees: - en: 3c4ee15c38a82543 - zh: c032ede27425f917 + en: e2f91d6cb1140eb5 + zh: 39f30237b11349c6 /deepseek-ai-dsh-tool-executor-ptc/model-experience/ptc-mode-schema-and-system-prompt/what-the-model-sees/typescript-ptc-mode-sdk-instructions-with-bash: en: 3a8df15e4ae32f9e zh: fc4a800ba363e835 @@ -47,9 +47,21 @@ /deepseek-ai-dsh-tool-executor-ptc/model-experience/ptc-mode-schema-and-system-prompt/kv-cache-effect: en: 4bf1cd2890cfe6c4 zh: 5b230b0adc09ddfb +/deepseek-ai-dsh-tool-executor-ptc/model-experience/registered-program-tools: + en: 9253b0d52c38cad9 + zh: e2d41d32791c46b1 +/deepseek-ai-dsh-tool-executor-ptc/model-experience/registered-program-tools/what-the-model-sees: + en: 71ee0ac3a10cd438 + zh: cc8a730e4589510a +/deepseek-ai-dsh-tool-executor-ptc/model-experience/registered-program-tools/token-effect: + en: b9f8f6c9ee03641c + zh: 64e2a8d7f6f58021 +/deepseek-ai-dsh-tool-executor-ptc/model-experience/registered-program-tools/kv-cache-effect: + en: f4703836365dc3d4 + zh: a09ff48a6550fd69 /deepseek-ai-dsh-tool-executor-ptc/known-limitations-and-deferred-work: - en: 86d79fbb28aced73 - zh: aac0ffa1c3ad5e9a + en: 8f4d0fca8c212bd9 + zh: 79483de4548f7737 /deepseek-ai-dsh-tool-executor-ptc/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/core/tool-executor-ptc/README.md b/packages/core/tool-executor-ptc/README.md index b37ad3d995..37fb10073c 100644 --- a/packages/core/tool-executor-ptc/README.md +++ b/packages/core/tool-executor-ptc/README.md @@ -42,6 +42,10 @@ This package declares `ctx.ptcRuntime` and `ctx.systemPrompt` as required inject Shared dispatch events and the `ptc-mode` message-source declaration live in `@deepseek-ai/dsh-tool-executor-ptc/types`; Client code imports the same declarations through `@deepseek-ai/dsh-tool-executor-ptc/client`. Both entries exclude Host service declarations. Host policy extensions use `import type` from the package entry for `PtcDispatchLog` and `tools/ptc-dispatch-log` without mounting the executor. +The `/run-code` entry exports `createRunCodeTool` for plugins that register a named program tool alongside native tools. Supply an explicit runtime and the complete private `ToolDefinition` list, then register the returned definition in the owning scope. Programs can call only that list, even when the Agent can call other native tools; the private definitions do not enter the tool registry. Nested calls retain normal approvals, guards, dispatch logs, screenshots, deferred context, and turn completion. `RunCodeConfig` exposes the same validated call-allowance and concurrency settings as this executor. + +The caller owns the supplied runtime and must keep it available until the factory's context finishes disposal. For runtimes that retain state or enforce a sandbox, disposal cancels active Agent programs and waits for nested calls; Agent disposal releases its retained environment. Environment initialization belongs to the supplied [runtime's registration API](../../ptc-runtime/ptc-runtime/README.md#choose-a-backend); register it before exposing the program tool. The factory appends runtime syntax and execution guidance to the caller's description; the caller supplies instructions for the private bindings. + [Configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-tool-executor-ptc) ----- @@ -60,7 +64,7 @@ The PTC executor exposes the reserved `run_code` transport and a deterministic S New sub-calls use `:ptc:` ids. Consumers treat these ids as opaque and correlate events by exact equality; restored historical ids retain their original bytes. The [PTC mode decision](../../../.agents/notes/implemented/feature/2026-06-15-ptc.md) owns durable naming and restoration rules. -Successful image-bearing subcall results become deferred user-message context with `source.kind` set to `ptc-mode`. Other additional contexts retain their producing tool's attribution. +TypeScript bindings for `read_image` and CUA screenshot operations return an `Image` with a readable `path`, `width`, and `height`. 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. @@ -91,7 +95,7 @@ Custom host integrations retain their `PtcExecutor` instance and call `reset(age #### What the model sees -PTC mode exposes the generated [`run_code` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-executor-ptc), the SDK instructions below, and the generated exact SDK block for the loaded runtime's language. Both runtime languages list `code` before `description`; this is presentation order, not an enforced JSON member order. REPL and Script runtimes share the generic tool description and SDK instructions; their `executionInstructions` supply syntax and state rules. The TypeScript bash example returns a value for function-body runtimes, and prints output for REPL and Script runtimes. The instructions identify generated declarations as program-only bindings. When the current `bash` parameter schema accepts the example arguments, they also show a complete `run_code` call around `tools.bash(...)`. The `tools:sdk` section uses first-party order 5000 and disables prompt-variable interpolation, preserving literal `{{…}}` text in tool descriptions and schemas for both runtime languages. Under `ptc`, the prompt also carries the `tools:ptc-only` rule earlier in the first-party order, so the model reads which tools it may call before it reads what each one is for. Exhausting the tool-call allowance returns a failed `run_code` result with the limit, rejected call number, termination notice, and possible infinite-loop warning. Runtime cleanup diagnostics and captured output remain visible. +PTC mode exposes the generated [`run_code` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-executor-ptc), the SDK instructions below, and the generated exact SDK block for the loaded runtime's language. Both runtime languages list `code` before `description`; this is presentation order, not an enforced JSON member order. REPL and Script runtimes share the generic tool description and SDK instructions; their `executionInstructions` supply syntax and state rules. The TypeScript SDK declares `inspect(...values)` and uses it in the bash example for every execution mode. The instructions identify generated declarations as program-only bindings. When the current `bash` parameter schema accepts the example arguments, they also show a complete `run_code` call around `tools.bash(...)`. The `tools:sdk` section uses first-party order 5000 and disables prompt-variable interpolation, preserving literal `{{…}}` text in tool descriptions and schemas for both runtime languages. Under `ptc`, the prompt also carries the `tools:ptc-only` rule earlier in the first-party order, so the model reads which tools it may call before it reads what each one is for. Exhausting the tool-call allowance returns a failed `run_code` result with the limit, rejected call number, termination notice, and possible infinite-loop warning. Runtime cleanup diagnostics and captured output remain visible. TypeScript programs show selected values with `inspect(...values)`. Each argument is rendered independently. The executor omits function returns and final expression values. The Node provider retains the complete native console and captures its stdout and stderr writes; model instructions direct programs to use `inspect`. ##### TypeScript PTC mode SDK instructions with bash @@ -100,14 +104,14 @@ PTC mode exposes the generated [`run_code` schema](../../../docs/tool-catalog.md `run_code` takes two required arguments: `code`, the body of an async TypeScript function (erasable syntax only — no `enum` or namespaces; type annotations are advisory, the code runs type-stripped), and `description`, a short summary of what the program does. The declarations below are SDK bindings for this program. A declaration does not make its name a directly callable tool; only names supplied as separate tool schemas may be called directly. When no separate `bash` schema is supplied, invoke a declared `bash` binding inside `run_code`: -`run_code({ code: "return await tools.bash({ description: 'Show current directory', command: 'pwd' })", description: "Show current directory" })` +`run_code({ code: "inspect(await tools.bash({ description: 'Show current directory', command: 'pwd' }))", description: "Show current directory" })` Inside the program: -- Call tools as `await tools.name(args)` — quoted access for exotic names: `tools["my-tool"](args)`. Every call resolves to the tool's typed canonical JSON value. Tool arguments must be lossless JSON. +- Call tools as `await tools.name(args)` — quoted access for exotic names: `tools["my-tool"](args)`. Every call resolves to its declared value, which may be an Image. Tool arguments must be lossless JSON. - A FAILED tool call rejects with `ToolCallError`, whose `toolName` identifies the failed tool and whose `message` is human-readable — `try/catch` it to handle and continue. - Independent read-only calls MAY overlap under `Promise.all` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with `await`. -- Emit results with `return` and/or `console.log(...)`. Only what you print or return is program output. A successful tool result containing an image is attached after the run so you can inspect it on the next step; every other intermediate result stays out of the conversation, so extract just what you need. +- Show selected values and images with `inspect(...values)`; every other intermediate result stays out of the conversation, so extract just what you need. Program-only SDK bindings: ``` @@ -126,16 +130,32 @@ Fixed per-request cost proportional to the visible definitions. PTC mode trades Prefix-stable while the PTC mode selection, generated SDK, transport schema, and visible tool set are unchanged. Mode or filter changes may invalidate reuse from the first changed prompt or schema token. Changing `maxSubCallsPerMinute` does not change prompt or schema tokens. +### Registered program tools + +#### What the model sees + +A factory-created tool presents its caller-supplied name and description with the same program parameters, runtime instructions, and result rendering as `run_code`. Its private bindings do not produce direct tool schemas or an SDK prompt section. The consumer owns its binding guidance. + +#### Token effect + +One program tool schema joins the existing native schemas. The caller's binding guidance adds its own prompt cost; intermediate values remain outside model history unless the program emits them or a nested tool defers context. + +#### KV Cache effect + +The schema remains stable while the caller's description and runtime settings remain unchanged. Initialization runs inside the runtime and does not add program source to model requests. + ## Known Limitations and Deferred Work These constraints apply to the host integration and accepted calls. +- **Program Images cover read_image and CUA screenshots** — other image-producing tools keep their declared values and automatically attach their pictures as additional model context. +- **Program Images require attachment path mapping** — the filesystem must map stored host attachments to readable program paths. `fs-ssh` has no such mapping, so image adaptation rejects in that composition. - **No built-in reset control** — the shipped Loader plugin does not expose its executor instance through a service, GUI control or SDK endpoint. Hosts needing reset must mount and retain `PtcExecutor` in their own composition; that integration owns retries after a failed reset. - **PTC mode's SDK language follows the one loaded runtime, and a presentation is per agent rather than per tool** — PTC execution rejects prompt assembly unless `ctx.ptcRuntime.language` has a registered SDK renderer; within one agent no tool can be native-only while another is ptc-only. - **PTC mode intermediate values are execution-local and unbounded by bytes** — they cannot be reconstructed from session replay and may exhaust process or worker memory; only the outer `run_code` output has the worker's configurable hard cap. -- **State depends on the runtime**: the default backend starts fresh; the Node REPL and Script mode with `scriptPersistence: true` retain memory per live Agent. Agent disposal awaits release. Restart and execution failures can clear memory; model-visible guidance explains how to recreate missing variables. Programs and results remain in the Session log, without serializing live objects. +- **State depends on the runtime**: the default backend starts fresh; Node `persistent-in-memory` execution and Script mode with `scriptPersistence: true` retain memory per live Agent. Agent disposal awaits release. Restart and execution failures can clear memory; model-visible guidance explains how to recreate missing variables. Programs and results remain in the Session log, without serializing live objects. ### Dev Note diff --git a/packages/core/tool-executor-ptc/README.zh.md b/packages/core/tool-executor-ptc/README.zh.md index 16d7bc65ca..a3db3b361a 100644 --- a/packages/core/tool-executor-ptc/README.zh.md +++ b/packages/core/tool-executor-ptc/README.zh.md @@ -42,6 +42,10 @@ kind: "package-reference" 共享分派事件与 `ptc-mode` 消息来源声明位于 `@deepseek-ai/dsh-tool-executor-ptc/types`;Client 代码通过 `@deepseek-ai/dsh-tool-executor-ptc/client` 导入同一组声明。两个入口都不引入 Host 服务声明。Host 策略扩展通过包主入口的 `import type` 获取 `PtcDispatchLog` 与 `tools/ptc-dispatch-log`,无需挂载执行器。 +`/run-code` 入口导出 `createRunCodeTool`,供插件在原生工具旁注册具名程序工具。调用方显式传入运行时及完整的私有 `ToolDefinition` 列表,再将返回的定义注册到所属作用域。即使 Agent 能直接调用其他原生工具,程序也只能调用该列表中的工具;私有定义不进入工具注册表。嵌套调用保留正常审批、guard、派发日志、截图、延后上下文和轮次结束行为。`RunCodeConfig` 提供与本执行器相同且经过校验的调用额度与并发设置。 + +调用方拥有传入的运行时,必须使其可用至工厂上下文完成销毁。对于保留状态或实施沙箱的运行时,销毁会取消活动的 Agent 程序并等待嵌套调用;Agent 销毁时释放其保留环境。环境初始化由传入[运行时的注册 API](../../ptc-runtime/ptc-runtime/README.zh.md#choose-a-backend)负责;应在提供程序工具前完成注册。工厂将运行时语法和执行说明追加到调用方提供的描述后;私有绑定的说明由调用方提供。 + [配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-tool-executor-ptc) ----- @@ -60,7 +64,7 @@ PTC 执行器公开保留的 `run_code` 传输,以及按所加载运行时语 新子调用使用 `:ptc:` 标识。消费方将这些标识视为不透明值,并通过精确相等关联事件;恢复的历史标识保留原始字节。[PTC mode 决策](../../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md) 负责持久化命名与恢复规则。 -成功且包含图片的子调用结果会成为延后的 user-message 上下文,其 `source.kind` 为 `ptc-mode`。其他 additional context 保留其生产工具的归属。 +TypeScript 中的 `read_image` 与 CUA 截图操作返回 `Image`,其中包含可读取的 `path`、`width` 和 `height`。将其传给 `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` 失败。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。 @@ -91,7 +95,7 @@ PTC 执行器公开保留的 `run_code` 传输,以及按所加载运行时语 #### 模型看到什么 -PTC mode 会公开生成的 [`run_code` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-executor-ptc)、下方 SDK 说明,以及按所加载运行时语言生成的精确 SDK 块。两种运行时语言都将 `code` 列在 `description` 前;这是呈现顺序,不强制 JSON 成员顺序。REPL 与 Script 运行时共用通用工具描述和 SDK 说明;语法与状态规则由各自的 `executionInstructions` 提供。TypeScript bash 示例对函数体运行时返回值,对 REPL 和 Script 运行时打印输出。说明将生成声明明确标为只能在程序内使用的绑定。当当前 `bash` 参数 schema 接受示例参数时,说明还会给出以 `run_code` 包住 `tools.bash(...)` 的完整调用。`tools:sdk` 段使用 first-party 顺序 5000,并关闭提示词变量插值,使两种运行时语言都原样保留工具描述和 schema 中的 `{{…}}` 文本。在 `ptc` 下,提示词还会带上处于更早 first-party 顺序的 `tools:ptc-only` 规则,让模型先读到「可以调用哪些工具」再读「每个工具做什么」。 工具调用额度耗尽时,`run_code` 返回失败结果,说明额度、被拒绝的调用序号、程序已终止,以及可能存在死循环。运行时清理诊断和已捕获的输出仍然可见。 +PTC mode 会公开生成的 [`run_code` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-tool-executor-ptc)、下方 SDK 说明,以及按所加载运行时语言生成的精确 SDK 块。两种运行时语言都将 `code` 列在 `description` 前;这是呈现顺序,不强制 JSON 成员顺序。REPL 与 Script 运行时共用通用工具描述和 SDK 说明;语法与状态规则由各自的 `executionInstructions` 提供。TypeScript SDK 声明 `inspect(...values)`,并在所有执行模式的 bash 示例中使用它。说明将生成声明明确标为只能在程序内使用的绑定。当当前 `bash` 参数 schema 接受示例参数时,说明还会给出以 `run_code` 包住 `tools.bash(...)` 的完整调用。`tools:sdk` 段使用 first-party 顺序 5000,并关闭提示词变量插值,使两种运行时语言都原样保留工具描述和 schema 中的 `{{…}}` 文本。在 `ptc` 下,提示词还会带上处于更早 first-party 顺序的 `tools:ptc-only` 规则,让模型先读到「可以调用哪些工具」再读「每个工具做什么」。 工具调用额度耗尽时,`run_code` 返回失败结果,说明额度、被拒绝的调用序号、程序已终止,以及可能存在死循环。运行时清理诊断和已捕获的输出仍然可见。 TypeScript 程序通过 `inspect(...values)` 展示选定的值。每个参数独立渲染。执行器省略函数返回值和末尾表达式的值。Node 提供方保留完整的原生 console,并捕获其 stdout 和 stderr 写入;模型指引要求程序使用 `inspect`。 ##### 带 bash 的 TypeScript PTC mode SDK 说明 @@ -100,14 +104,14 @@ PTC mode 会公开生成的 [`run_code` schema](../../../docs/tool-catalog.zh.md `run_code` takes two required arguments: `code`, the body of an async TypeScript function (erasable syntax only — no `enum` or namespaces; type annotations are advisory, the code runs type-stripped), and `description`, a short summary of what the program does. The declarations below are SDK bindings for this program. A declaration does not make its name a directly callable tool; only names supplied as separate tool schemas may be called directly. When no separate `bash` schema is supplied, invoke a declared `bash` binding inside `run_code`: -`run_code({ code: "return await tools.bash({ description: 'Show current directory', command: 'pwd' })", description: "Show current directory" })` +`run_code({ code: "inspect(await tools.bash({ description: 'Show current directory', command: 'pwd' }))", description: "Show current directory" })` Inside the program: -- Call tools as `await tools.name(args)` — quoted access for exotic names: `tools["my-tool"](args)`. Every call resolves to the tool's typed canonical JSON value. Tool arguments must be lossless JSON. +- Call tools as `await tools.name(args)` — quoted access for exotic names: `tools["my-tool"](args)`. Every call resolves to its declared value, which may be an Image. Tool arguments must be lossless JSON. - A FAILED tool call rejects with `ToolCallError`, whose `toolName` identifies the failed tool and whose `message` is human-readable — `try/catch` it to handle and continue. - Independent read-only calls MAY overlap under `Promise.all` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with `await`. -- Emit results with `return` and/or `console.log(...)`. Only what you print or return is program output. A successful tool result containing an image is attached after the run so you can inspect it on the next step; every other intermediate result stays out of the conversation, so extract just what you need. +- Show selected values and images with `inspect(...values)`; every other intermediate result stays out of the conversation, so extract just what you need. Program-only SDK bindings: ``` @@ -126,16 +130,32 @@ Error: code run failed (abort): run_code exceeded its limit of 2048 tool calls ( 只要 PTC mode 选择、生成的 SDK、传输 schema 与可见工具集合不变,前缀就保持稳定。模式或筛选器变更可能从第一个改变的提示词或 schema token 起使复用失效。修改 `maxSubCallsPerMinute` 不会改变提示词或 schema token。 +### 注册的程序工具 + +#### 模型可见内容 + +工厂创建的工具显示调用方提供的名称和描述,并使用与 `run_code` 相同的程序参数、运行时说明和结果渲染。私有绑定不生成直接工具 schema 或 SDK 提示词段落。绑定指引由消费方负责。 + +#### Token 影响 + +现有原生工具 schema 中加入一个程序工具 schema。调用方的绑定指引产生相应提示词成本;中间值只有在程序输出它们或嵌套工具提供延后上下文时才进入模型历史。 + +#### KV Cache 影响 + +只要调用方描述和运行时设置不变,schema 就保持稳定。初始化在运行时内部执行,不向模型请求添加程序源码。 + ## 已知限制与延期工作 以下约束适用于宿主集成及已开始的调用。 +- **程序 Image 仅覆盖 read_image 与 CUA 截图**:其他图片工具保留其声明的返回值,并将图片自动附加到模型的额外上下文。 +- **程序 Image 要求附件路径映射**:文件系统必须将宿主存储的附件映射为程序可读的路径。`fs-ssh` 没有这项映射,因此该组合中的图片适配会拒绝。 - **没有内置重置控件**:自带的 Loader 插件不通过服务、GUI 控件或 SDK 端点暴露执行器实例。需要重置的宿主必须在自己的组合中挂载并保留 `PtcExecutor`,该集成负责失败后的重试。 - **PTC mode 的 SDK 语言由当前加载的运行时决定,且呈现方式按 agent 而非按工具**:PTC 会拒绝组装提示词,除非 `ctx.ptcRuntime.language` 有已注册的 SDK 渲染器;同一个 agent 内不能让一个工具仅使用 Native,而另一个仅使用 PTC。 - **PTC mode 中间值只存在于执行局部,且没有字节上限**:它们无法从会话回放重建,并可能耗尽进程或 worker 内存;只有外层 `run_code` 输出受 worker 可配置的硬上限约束。 -- **状态由运行时决定**:默认后端每次重新开始;Node REPL 和启用 `scriptPersistence: true` 的 Script 模式按存活 Agent 保留内存。Agent 销毁时等待环境释放。重启与执行失败可能清除内存;模型说明会指导重新创建缺失变量。程序与结果仍写入 Session 日志,不序列化运行中的对象。 +- **状态由运行时决定**:默认后端每次重新开始;Node 的 `persistent-in-memory` 执行和启用 `scriptPersistence: true` 的 Script 模式按存活 Agent 保留内存。Agent 销毁时等待环境释放。重启与执行失败可能清除内存;模型说明会指导重新创建缺失变量。程序与结果仍写入 Session 日志,不序列化运行中的对象。 ### 开发备注 diff --git a/packages/core/tool-executor-ptc/package.json b/packages/core/tool-executor-ptc/package.json index 16c9c14acb..fe663d7ae0 100644 --- a/packages/core/tool-executor-ptc/package.json +++ b/packages/core/tool-executor-ptc/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-executor-ptc", "description": "PTC program execution, tool bindings, and generated SDK prompts", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, @@ -19,6 +19,10 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./run-code": { + "types": "./lib/types/run-code.d.ts", + "default": "./lib/run-code.js" + }, "./types": { "types": "./lib/types/types.d.ts", "default": "./lib/types/types.js" @@ -34,6 +38,8 @@ "files": [ "locale/*.json", "lib/index.js", + "lib/run-code.js", + "lib/_chunks/*.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", @@ -69,6 +75,7 @@ "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tool-executor-native": "workspace:*", "@deepseek-ai/dsh-tool-testkit": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", diff --git a/packages/core/tool-executor-ptc/src/errors.ts b/packages/core/tool-executor-ptc/src/errors.ts index 003f7ae8ae..9017e34d49 100644 --- a/packages/core/tool-executor-ptc/src/errors.ts +++ b/packages/core/tool-executor-ptc/src/errors.ts @@ -8,14 +8,15 @@ import { HarnessError } from '@deepseek-ai/dsh-llm' export class ToolCallLimitExceededError extends Error { /** * Describe the rejected call and how to correct the program. - * @param limit - Timeout-derived maximum tool-call attempts for one run_code invocation. + * @param limit - Timeout-derived maximum tool-call attempts for one program. * @param callNumber - One-based attempt rejected without invoking the tool. - * @param callsPerMinute - Attempts granted per minute of run_code timeout. + * @param callsPerMinute - Attempts granted per minute of program timeout. + * @param toolName - Program tool name. */ - constructor(limit: number, callNumber: number, callsPerMinute: number) { - super(`run_code exceeded its limit of ${limit} tool calls (${callsPerMinute} per minute of its timeout); ` - + `call ${callNumber} was not dispatched. The run_code program may contain an infinite loop. ` - + 'Check loop termination or split the work into smaller run_code calls.') + constructor(limit: number, callNumber: number, callsPerMinute: number, toolName: string) { + super(`${toolName} exceeded its limit of ${limit} tool calls (${callsPerMinute} per minute of its timeout); ` + + `call ${callNumber} was not dispatched. The ${toolName} program may contain an infinite loop. ` + + `Check loop termination or split the work into smaller ${toolName} calls.`) this.name = 'ToolCallLimitExceededError' } } @@ -36,8 +37,9 @@ export type CodeRunErrorCode = typeof CODE_RUN_ERROR_CODES[number] * could not start. Caller cancellation uses the shared `AbortError` / * `ABORTED` tool outcome. Extends {@link HarnessError} with a code from * {@link CODE_RUN_ERROR_CODES}; the registry's execution pipeline converts it - * into a structured `isError` result whose text carries the failure kind plus - * the captured logs, so the model can self-correct. + * into a structured `isError` result with the failure kind. Captured text and + * images accompany the original diagnostic; outer result replacements remain + * authoritative. */ export class CodeRunFailedError extends HarnessError { override readonly code: CodeRunErrorCode diff --git a/packages/core/tool-executor-ptc/src/index.ts b/packages/core/tool-executor-ptc/src/index.ts index 42ce40cd8f..b64338da1b 100644 --- a/packages/core/tool-executor-ptc/src/index.ts +++ b/packages/core/tool-executor-ptc/src/index.ts @@ -6,7 +6,7 @@ import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime' import { RUN_CODE_NAME, ToolNotFoundError, projectToolSchema } from '@deepseek-ai/dsh-tools' import type { ToolDefinition, ToolExecutor, ToolModelInput, ToolPromptSection, ToolBatchInput, ToolBatchResult } from '@deepseek-ai/dsh-tools' import { ToolExecutionPipeline, executeToolBatch, toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline' -import { createRunCodeTool, requirePtcRuntime, type PtcSdkLanguage } from './ptc.ts' +import { createRunCodeTransport, requirePtcRuntime, type PtcSdkLanguage } from './ptc.ts' import { renderToolsSdk, type ToolSdkSchema } from './ts-types.ts' import { renderToolsSdkPy } from './py-types.ts' import { Config } from './config.ts' @@ -87,7 +87,7 @@ export class PtcExecutor implements ToolExecutor { /** Keep the reserved transport outside registered capabilities and their restrictions. */ private requirePtcTransport(): ToolDefinition { - this.ptcTransport ??= createRunCodeTool(this.ctx, this.pipeline, this.config, this.calls) + this.ptcTransport ??= createRunCodeTransport(this.ctx, this.pipeline, this.config, this.calls) return this.ptcTransport } } diff --git a/packages/core/tool-executor-ptc/src/ptc.ts b/packages/core/tool-executor-ptc/src/ptc.ts index 1805a08fca..928fb7996d 100644 --- a/packages/core/tool-executor-ptc/src/ptc.ts +++ b/packages/core/tool-executor-ptc/src/ptc.ts @@ -1,17 +1,20 @@ /** - * PTC mode `run_code` transport. Programs call the registry's agent-visible - * tools through nested executions scheduled under the native concurrency - * contract; each sub-dispatch is logged for reconstruction, while only the - * outer curated result enters model history. + * Shared program transport. Programs call their admitted tools through nested + * executions scheduled under the native concurrency contract; each sub-dispatch + * is logged for reconstruction, while only the outer curated result enters model + * history. * @module */ +import { isDeepStrictEqual } from 'node:util' import type { PtcDispatchLog } from './runtime-types.ts' import { symbols, type Context } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' -import { createUserMessage, HarnessError } from '@deepseek-ai/dsh-llm' +import { createUserMessage, HarnessError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId, ToolSchema } from '@deepseek-ai/dsh-llm' +import { PtcImage } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcOutput } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcBindingFunction, PtcRunResult, PtcRunSandbox, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import { approveEscalation, ESCALATION_TARGETS, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' @@ -20,7 +23,8 @@ import type {} from '@deepseek-ai/dsh-working-directory' import type {} from '@deepseek-ai/dsh-sandbox-policy' import { deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values' import { - defineTool, parameterSchemaSpecToJsonSchema, RUN_CODE_NAME, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError, + defineTool, parameterSchemaSpecToJsonSchema, projectToolSchema, RUN_CODE_NAME, TOOL_ABORTED, ToolArgsError, + ToolContextUnavailableError, } from '@deepseek-ai/dsh-tools' import type { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline' import { toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline' @@ -28,7 +32,8 @@ import { scopeTarget } from '@deepseek-ai/dsh-scope' import type { PtcCalls } from './ptc-calls.ts' import { CodeRunFailedError, ToolCallLimitExceededError } from './errors.ts' import type { Config } from './config.ts' -import type { ToolDefinition, ToolExecutionResult, ToolRunContext } from '@deepseek-ai/dsh-tools' +import type { RunCodeToolOptions } from './run-code.ts' +import type { ToolDefinition, ToolExecution, ToolExecutionFailure, ToolExecutionResult, ToolRunContext } from '@deepseek-ai/dsh-tools' import type {} from './types.ts' /** The model-facing name of the PTC mode tool. */ @@ -43,27 +48,26 @@ interface RunCodeFlavor { } /** Keep tool-call rules here; the runtime owns evaluation syntax and state retention. */ -function runCodeFlavor(language: string, execution = { +function runCodeFlavor(language: string, outputInstruction: string, execution = { programDescription: 'the program to execute', - outputInstruction: 'Curate the program output.', codeDescription: `The ${language} program to execute, following this tool's execution instructions.`, }): RunCodeFlavor { return { description: `Execute a ${language} program against the available tools. Takes two required arguments: ` + `\`code\`, ${execution.programDescription}, and \`description\`, a short summary of what the program does. ` + 'Call tools as `await tools.name(args)` per the declarations in the system prompt. ' - + `${execution.outputInstruction} Image-bearing subtool results are attached after the run.`, + + outputInstruction, codeDescription: execution.codeDescription, } } -const TYPESCRIPT_FLAVOR = runCodeFlavor('TypeScript') -const TYPESCRIPT_FUNCTION_FLAVOR = runCodeFlavor('TypeScript', { +const TYPESCRIPT_OUTPUT_INSTRUCTION = 'Show selected text and images with inspect(...values).' +const TYPESCRIPT_FLAVOR = runCodeFlavor('TypeScript', TYPESCRIPT_OUTPUT_INSTRUCTION) +const TYPESCRIPT_FUNCTION_FLAVOR = runCodeFlavor('TypeScript', TYPESCRIPT_OUTPUT_INSTRUCTION, { programDescription: 'the BODY of an async function (erasable syntax only; top-level `await` and `return` work)', - outputInstruction: 'Only what you print or return is program output — curate it.', codeDescription: 'The program: the body of an async TypeScript function.', }) -const PYTHON_FLAVOR = runCodeFlavor('Python') +const PYTHON_FLAVOR = runCodeFlavor('Python', 'Curate the program output. Image-bearing subtool results are attached after the run.') /** Languages with both a transport schema and an SDK renderer. */ export type PtcSdkLanguage = 'typescript' | 'python' @@ -85,6 +89,11 @@ export function requirePtcRuntime(ctx: Context): SupportedPtcRuntime { if (runtime === undefined) { throw new ToolContextUnavailableError('dsh-tools: mode "ptc" requires a PTC runtime — load a ctx.ptcRuntime implementation (e.g. @deepseek-ai/dsh-ptc-runtime-node) or load @deepseek-ai/dsh-tool-executor-native') } + return requireRuntimeLanguage(runtime) +} + +/** Resolve the SDK flavor for a mounted or explicitly supplied provider. */ +function requireRuntimeLanguage(runtime: PtcRuntime): SupportedPtcRuntime { if (!Object.hasOwn(RUN_CODE_FLAVORS, runtime.language)) { const known = Object.keys(RUN_CODE_FLAVORS).map(name => JSON.stringify(name)).join(', ') throw new ToolContextUnavailableError(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`) @@ -256,6 +265,33 @@ function isCancellation(error: unknown, signal: AbortSignal): boolean { /** Canonical value returned by the outer PTC mode transport. */ type RunCodeOutput = { logs: string[]; result?: JsonValue; sandbox?: PtcRunSandbox } +/** Render captured text, selected images, and the applied file policy in emission order. */ +function renderRunOutput( + value: RunCodeOutput, + guidance: string, + output: PtcOutput[] = value.logs.map(text => ({ type: 'text', text })), + toolName: string, +): ContentBlock[] { + const content: ContentBlock[] = [] + const appendText = (text: string): void => { if (text.length > 0) content.push({ type: 'text', text }) } + const remaining: string[] = [] + for (const block of output) { + if (block.type === 'text') remaining.push(block.text) + else { + appendText(remaining.join('')) + remaining.length = 0 + content.push(block) + } + } + appendText(remaining.join('')) + const details: string[] = [] + if (value.result !== undefined) details.push(renderValue(value.result)) + 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')) + return content.length > 0 ? content : [{ type: 'text', text: `(${toolName} completed with no output)` }] +} + /** Unowned programs do not require Session directory state. */ async function resolveWorkingDirectory(ctx: Context, exec: ToolRunContext): Promise { if (exec.agent === undefined) return undefined @@ -272,20 +308,24 @@ function resolveSandboxPolicy(ctx: Context, exec: ToolRunContext): SandboxExecut } /** - * Build the reserved `run_code` transport outside registered capabilities. + * Build a program transport using the shared nested-call scheduler. * @param ctx - executor context owning policy listeners and active program cleanup. * @param executor - shared invocation pipeline for nested calls. * @param config - validated timeout-based tool-call allowance and concurrency limits. * @param calls - Executor-owned cancellation and reset coordination. + * @param options - Fixed runtime and tools for a registered program tool; omission selects PTC's visible registry and current runtime. * @returns the transport definition with runtime-dependent schema text. */ -export function createRunCodeTool( +export function createRunCodeTransport( ctx: Context, executor: ToolExecutionPipeline, config: Config, calls: PtcCalls, + options?: Omit, ): ToolDefinition { const { maxSubCallsPerMinute, maxParallelSubCalls: maxParallel } = config + const toolName = options?.name ?? RUN_CODE_NAME + const getRuntime = options === undefined ? () => requirePtcRuntime(ctx) : () => requireRuntimeLanguage(options.runtime) // Retain services for log settlement after the executor context becomes inactive. const tools = ctx.tools const logger = ctx.logger @@ -303,9 +343,23 @@ export function createRunCodeTool( } } + type ImageRef = Extract['attachment'] + const inspections = new WeakMap + output: PtcOutput[] + }>() + const programImage = (ref: ImageRef): PtcImage => { + const attachments = ctx.get('attachments') + const fs = ctx.get('fs') + const access = attachments === undefined || fs === undefined ? undefined + : resolveImageAttachmentAccess(attachments, path => fs.processPathFromHostPath(path), ref) + if (access === undefined) throw new Error('Image storage must expose a readable path in the program filesystem') + return new PtcImage(access.readonlyPath, ref) + } const stateOwners = new WeakMap>() const definition = defineTool({ - name: RUN_CODE_NAME, + name: toolName, // The description and `code` parameter description are placeholders here: // the language-aware getters installed below replace both, resolving the // loaded runtime's flavor at schema-emission time so the schema the MODEL @@ -340,19 +394,14 @@ export function createRunCodeTool( }, }, }, - render: (_args, value) => { - const rendered = value.result === undefined ? '' : renderValue(value.result) - const parts = [value.logs.join('\n'), rendered].filter(part => part.length > 0) - if (value.sandbox?.enforcement === 'partial') parts.push('File sandbox enforcement is partial on this host.') - if (value.sandbox?.denied) parts.push(`The ${value.sandbox.mode} file sandbox denied an operation.${escalationGuidance(ctx.get('ptcRuntime')?.sandboxMode)}`) - return [{ type: 'text', text: parts.length > 0 ? parts.join('\n') : '(run_code completed with no output)' }] - }, + render: (_args, value) => renderRunOutput(value, + escalationGuidance(options === undefined ? ctx.get('ptcRuntime')?.sandboxMode : options.runtime.sandboxMode), undefined, toolName), }, async execute(args, exec): Promise { if (args.description.trim().length === 0) { throw new ToolArgsError(['invalid description: expected a non-empty string']) } - const runtime = requirePtcRuntime(ctx) + const runtime = getRuntime() const run = async (callSignal: AbortSignal): Promise => { validateEscalationArgs(args.sandbox_permissions, args.justification) if (args.timeoutMs !== undefined && runtime.timeout === undefined) { @@ -372,7 +421,7 @@ export function createRunCodeTool( subject: 'program', }, { approver: ctx.get('approval'), agent: exec.agent, callId: exec.callId, - toolName: RUN_CODE_NAME, signal: callSignal, + toolName, signal: callSignal, }) policy = { ...standingPolicy, mode: approvedMode } } @@ -512,13 +561,15 @@ export function createRunCodeTool( const binding = (schema: ToolSchema): PtcBindingFunction => async (rawArgs: unknown): Promise => { const { name } = schema + // FIXME: Let image-producing tools declare their program result adaptation. + const usesProgramImage = runtime.language === 'typescript' && (name === 'read_image' || name === 'cua') if (runOver()) { - throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`) + throw new Error(`${toolName} run is over (${String(runController.signal.reason)}); ${name} not dispatched`) } // Count before validation and queuing so repeated failed calls also exhaust the allowance. const n = ++toolCallAttempts if (n > maxSubCalls) { - const error = new ToolCallLimitExceededError(maxSubCalls, n, maxSubCallsPerMinute) + const error = new ToolCallLimitExceededError(maxSubCalls, n, maxSubCallsPerMinute, toolName) runController.abort(error) throw error } @@ -535,13 +586,14 @@ export function createRunCodeTool( parent: exec.token, signal: runController.signal, } - type DispatchOutcome = { isError: true; message: string } | { isError: false; value: JsonValue } + type DispatchOutcome = { isError: true; message: string } + | { isError: false; value: JsonValue; content: ContentBlock[]; imageRemoved: boolean } const outcome = await new Promise((resolve, reject) => { // Set by the dispatch stage (or start() for a pre-settled result): what commit() finalizes in submission order. let parked: | { kind: 'post-result' | 'final-result'; exec: ToolRunContext; result: ToolExecutionResult } | undefined - const settle = (result: ToolExecutionResult): void => { + const settle = (result: ToolExecutionResult, imageRemoved: boolean): void => { // The program gets its value NOW: the log-content listener (for // example, a spill backend) must never delay the binding or occupy // a dispatch slot. The event append is tracked side work; the run's @@ -550,7 +602,7 @@ export function createRunCodeTool( // chain cannot reject). resolve(result.isError ? { isError: true, message: result.error.message } - : { isError: false, value: result.value }) + : { isError: false, value: result.value, content: result.content, imageRemoved }) const agent = exec.agent if (agent === undefined) return const task: Promise = (async () => { @@ -588,7 +640,7 @@ export function createRunCodeTool( // declared; fail-closed exclusive when undeclared/invalid. classify: () => executor.executionMode(input).kind, abandon: () => { - reject(new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} tool call abandoned`)) + reject(new Error(`${toolName} run is over (${String(runController.signal.reason)}); ${name} tool call abandoned`)) }, async start(): Promise { exec.agent?.session.append('tool/ptc-dispatch-start', { @@ -616,7 +668,7 @@ export function createRunCodeTool( /* v8 ignore next -- commit() runs only after `settled` flipped, which set parked. */ if (parked === undefined) return const result = await executor.complete(parked.exec, parked) - if (!result.isError && result.content.some(block => block.type === 'image')) { + if (!usesProgramImage && !result.isError && result.content.some(block => block.type === 'image')) { exec.deferContext(createUserMessage({ content: result.content, source: { kind: 'ptc-mode' }, @@ -631,7 +683,8 @@ export function createRunCodeTool( // (ToolExecutionFailure types it never), so a policy-converted // failure cannot stop the turn through a recovering program. if (result.concludesTurn) exec.concludeTurn() - settle(result) + settle(result, parked.result.content.some(block => block.type === 'image') + && !result.content.some(block => block.type === 'image')) // Backpressure on pending event-append tasks: each task retains // a full result while a slow backend stores it, so the pool cap // bounds their count. Beyond the cap, the @@ -647,12 +700,22 @@ export function createRunCodeTool( // flight already aborted the dispatch; stop the program now rather // than hand it a result from a run that is over. if (runOver()) { - throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} result discarded`) + throw new Error(`${toolName} run is over (${String(runController.signal.reason)}); ${name} result discarded`) } // The worker turns a binding rejection into ToolCallError and adds // only the binding name. Native content and internal error metadata // stay outside the program-facing failure contract. if (outcome.isError) throw new Error(outcome.message) + if (usesProgramImage) { + const images = outcome.content.filter(block => block.type === 'image') + const first = images[0] + if (first !== undefined && images.length === 1) return programImage(first.attachment) + if (outcome.imageRemoved) { + throw new Error('Image output was removed by a tool output policy.\n' + + outcome.content.filter(block => block.type === 'text').map(block => block.text).join('\n')) + } + if (name === 'read_image' || images.length > 1) throw new Error('Image-producing tools must return exactly one image') + } return outcome.value } @@ -662,11 +725,11 @@ export function createRunCodeTool( // silently dropping the binding), and the runtime host resolves // binding names as own properties only. const functions: Record = Object.create(null) as Record - // Enumerate the CALLING AGENT's visible set (scoped tools join, - // restricted globals vanish) — the same view the SDK section declared, - // so a program can bind exactly what its prompt promised; sub-dispatch - // re-resolves per call through the same view (exec.agent threads down). - for (const schema of tools.schemas(exec.agent, exec.toolSet)) { + // PTC uses step-admitted registry tools; a registered program tool uses + // only its private definitions, resolved by its own pipeline on each call. + const schemas = options === undefined ? tools.schemas(exec.agent, exec.toolSet) + : options.tools.map(definition => projectToolSchema(definition, true)) + for (const schema of schemas) { Object.defineProperty(functions, schema.name, { enumerable: true, value: binding(deepFreeze(schema)) }) } @@ -691,6 +754,7 @@ export function createRunCodeTool( } const spec = runtime.resolve({ program: args.code, + ...runtime.language === 'typescript' ? { discardCompletion: true } : {}, ...exec.agent === undefined || policy?.mode !== standingPolicy?.mode ? {} : { stateOwner: exec.agent }, bindings: [{ global: 'tools', @@ -714,31 +778,45 @@ export function createRunCodeTool( // Abort sub-dispatches and drain every in-flight dispatch before // closing the turn (queued-unstarted ones are abandoned unlogged). // Binding failures remain observable through their individual promises. - runController.abort('run_code settled') + runController.abort(`${toolName} settled`) await drainDispatches() } + const logs = result.output.flatMap(block => block.type === 'text' ? [block.text] : []) + const hasImages = result.output.some(block => block.type === 'image') if (result.error) { const limitError = runController.signal.reason instanceof ToolCallLimitExceededError ? 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 error = new HarnessError(message, TOOL_ABORTED) - error.name = 'AbortError' - throw error + failure = new HarnessError(message, TOOL_ABORTED) + failure.name = 'AbortError' + } else { + const logsText = logs.length > 0 && !hasImages + ? `\nCaptured output:\n${logs.join('')}` : '' + const sandboxText = result.sandbox === undefined ? '' + : `${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 logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join('\n')}` : '' - const sandboxText = result.sandbox === undefined ? '' - : `\nFile 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}` - throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${failureText}${logsText}${sandboxText}${result.sandbox?.denied ? escalationGuidance(runtime.sandboxMode) : ''}`) + if (hasImages) inspections.set(exec, { + failure: { + error: { message: failure.message, info: { name: failure.name, code: failure.code } }, + content: [{ type: 'text', text: `Error: ${failure.message}` }], + }, + output: result.output, + }) + throw failure } - return { - logs: result.logs, + const value: RunCodeOutput = { + logs, ...result.sandbox === undefined ? {} : { sandbox: result.sandbox }, - ...result.value !== undefined ? { result: result.value } : {}, + ...runtime.language !== 'typescript' && result.value !== undefined ? { result: result.value } : {}, } + if (hasImages) inspections.set(exec, { value, output: result.output }) + return value } finally { callSignal.removeEventListener('abort', onOuterAbort) } @@ -747,6 +825,18 @@ export function createRunCodeTool( : calls.run(exec.agent.session.id, exec.signal, () => runtime.sandboxMode === undefined ? undefined : resolveSandboxPolicy(ctx, exec).mode, run) }, + projectContent(exec, result) { + const selected = inspections.get(exec) + inspections.delete(exec) + if (selected === undefined) return undefined + if (result.isError) { + if (!isDeepStrictEqual(selected.failure, { error: result.error, content: result.content })) return undefined + return [...result.content, ...renderRunOutput({ logs: [] }, '', selected.output, toolName)] + } + if (selected.value === undefined || !isDeepStrictEqual(selected.value, result.value)) return undefined + return renderRunOutput(selected.value, + escalationGuidance(options === undefined ? ctx.get('ptcRuntime')?.sandboxMode : options.runtime.sandboxMode), selected.output, toolName) + }, // The model-authored description is the call's always-visible UI label // (the bash `description` precedent); the program itself rides rawInput. presentCall: args => ({ @@ -763,9 +853,9 @@ export function createRunCodeTool( Object.defineProperty(definition, 'description', { enumerable: true, get: () => { - const runtime = requirePtcRuntime(ctx) + const runtime = getRuntime() const instructions = runtime.executionInstructions - return resolveFlavor(runtime).description + return (options?.description ?? resolveFlavor(runtime).description) + (instructions ? ` ${instructions}` : '') + " Each program starts in the Session's current directory. Running programs keep their initial directory." + escalationGuidance(runtime.sandboxMode) @@ -776,7 +866,7 @@ export function createRunCodeTool( // Recompile through the same spec→schema projection defineTool used, so // the emitted schema always matches the validated specification. get: () => { - const runtime = requirePtcRuntime(ctx) + const runtime = getRuntime() return parameterSchemaSpecToJsonSchema({ code: { type: 'string', required: true, description: resolveFlavor(runtime).codeDescription }, description: { type: 'string', required: true, description: RUN_CODE_DESCRIPTION_PARAM_DESCRIPTION }, diff --git a/packages/core/tool-executor-ptc/src/run-code.ts b/packages/core/tool-executor-ptc/src/run-code.ts new file mode 100644 index 0000000000..14a07d77ca --- /dev/null +++ b/packages/core/tool-executor-ptc/src/run-code.ts @@ -0,0 +1,47 @@ +/** Registered program tools with an explicit runtime and private tool bindings. @module */ +import type { Context } from '@deepseek-ai/cordis' +import type { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import type { ToolDefinition } from '@deepseek-ai/dsh-tools' +import { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline' +import { Config } from './config.ts' +import { PtcCalls } from './ptc-calls.ts' +import { createRunCodeTransport } from './ptc.ts' + +export { Config as RunCodeConfig } from './config.ts' + +/** Fixed capabilities and presentation for one registered program tool. */ +export interface RunCodeToolOptions { + /** Model-facing tool name, distinct from the reserved `run_code` transport. */ + readonly name: string + /** Capability instructions; runtime syntax, working directory, and escalation guidance are appended. */ + readonly description: string + /** Caller-owned provider; the factory never selects or replaces the scope's shared runtime. */ + readonly runtime: PtcRuntime + /** Complete private binding set, with unique names; definitions need not be registered. */ + readonly tools: readonly ToolDefinition[] + /** Nested-call limits; omitted fields use RunCodeConfig defaults. */ + readonly limits?: Partial +} + +/** + * Create a tool whose programs can call only the supplied private definitions. + * Nested calls retain approvals, guards, result policy, dispatch logs, and deferred contexts. + * The owning context cancels and drains active Agent programs when disposed if the runtime + * retains state or enforces a sandbox. Agent disposal releases retained runtime state. + * @param ctx - Context with tools, lifecycle ownership, and policies; Agent calls also require workingDirectory. + * @param options - Fixed runtime, tools, presentation, and configurable limits. + * @returns An unregistered definition; register it in the owning scope with ctx.tools.register. + * @throws Error if private tool names repeat or configured limits are invalid. + */ +export function createRunCodeTool(ctx: Context, options: RunCodeToolOptions): ToolDefinition { + const definitions = new Map() + for (const definition of options.tools) { + if (definitions.has(definition.name)) throw new Error(`Program tool ${options.name} has duplicate binding ${definition.name}`) + definitions.set(definition.name, definition) + } + const pipeline = new ToolExecutionPipeline(ctx, { get: name => definitions.get(name) }) + return createRunCodeTransport(ctx, pipeline, Config(options.limits ?? {}), new PtcCalls(ctx), { + ...options, + tools: [...definitions.values()], + }) +} diff --git a/packages/core/tool-executor-ptc/src/ts-types.ts b/packages/core/tool-executor-ptc/src/ts-types.ts index 8026c847d2..a2fcfd57a2 100644 --- a/packages/core/tool-executor-ptc/src/ts-types.ts +++ b/packages/core/tool-executor-ptc/src/ts-types.ts @@ -258,16 +258,13 @@ function renderSdkInstructions(programFormat: PtcProgramFormat): string { } /** Render tool execution and output instructions for the selected execution syntax. */ -function renderSdkProgramInstructions(programFormat: PtcProgramFormat): string { - const outputInstruction = programFormat === 'function-body' - ? 'Emit results with `return` and/or `console.log(...)`. Only what you print or return is program output.' - : 'Only values emitted as program output enter the conversation.' +function renderSdkProgramInstructions(): string { return `Inside the program: -- Call tools as \`await tools.name(args)\` — quoted access for exotic names: \`tools["my-tool"](args)\`. Every call resolves to the tool's typed canonical JSON value. Tool arguments must be lossless JSON. +- Call tools as \`await tools.name(args)\` — quoted access for exotic names: \`tools["my-tool"](args)\`. Every call resolves to its declared value, which may be an Image. Tool arguments must be lossless JSON. - A FAILED tool call rejects with \`ToolCallError\`, whose \`toolName\` identifies the failed tool and whose \`message\` is human-readable — \`try/catch\` it to handle and continue. - Independent read-only calls MAY overlap under \`Promise.all\` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with \`await\`. -- ${outputInstruction} A successful tool result containing an image is attached after the run so you can inspect it on the next step; every other intermediate result stays out of the conversation, so extract just what you need. +- Show selected values and images with \`inspect(...values)\`; every other intermediate result stays out of the conversation, so extract just what you need. Program-only SDK bindings:` } @@ -280,7 +277,7 @@ function acceptsExampleString(schema: JsonSchemaNode | undefined, value: string) } /** Render the bash example only when its literal arguments satisfy the current parameter schema. */ -function renderBashExample(schemas: ToolSdkSchema[], programFormat: PtcProgramFormat): string { +function renderBashExample(schemas: ToolSdkSchema[]): string { const bash = schemas.find(schema => schema.name === 'bash') if (bash === undefined) return '' const parameters = bash.parameters as JsonSchemaNode @@ -291,9 +288,7 @@ function renderBashExample(schemas: ToolSdkSchema[], programFormat: PtcProgramFo const needsDescription = required.includes('description') if (needsDescription && !acceptsExampleString(parameters.properties?.description, 'Show current directory')) return '' const description = needsDescription ? "description: 'Show current directory', " : '' - const program = programFormat === 'function-body' - ? `return await tools.bash({ ${description}command: 'pwd' })` - : `console.log(await tools.bash({ ${description}command: 'pwd' }))` + const program = `inspect(await tools.bash({ ${description}command: 'pwd' }))` return ` When no separate \`bash\` schema is supplied, invoke a declared \`bash\` binding inside \`run_code\`:\n\n\`run_code({ code: "${program}", description: "Show current directory" })\`` } @@ -317,11 +312,16 @@ export function renderToolsSdk(schemas: readonly ToolSdkSchema[], programFormat: for (const schema of sorted) { argsMembers.push(...docLines(schema.description, 1)) argsMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.parameters, 1)};`) - outputMembers.push(`${pad(1)}${renderKey(schema.name)}: ${jsonSchemaToTs(schema.output, 1)};`) + // FIXME: Derive program return types from tool-declared adaptations, together with the binding adapter in ptc.ts. + const output = schema.name === 'read_image' ? 'Image' + : `${schema.name === 'cua' ? 'Image | ' : ''}${jsonSchemaToTs(schema.output, 1)}` + outputMembers.push(`${pad(1)}${renderKey(schema.name)}: ${output};`) } const argsMap = `interface ToolArgsMap {${argsMembers.length > 0 ? `\n${argsMembers.join('\n')}\n` : ''}}` const outputMap = `interface ToolOutputMap {${outputMembers.length > 0 ? `\n${outputMembers.join('\n')}\n` : ''}}` const declaration = [ + 'declare class Image { private constructor(); readonly attachmentId: string; readonly path: string; readonly width: number; readonly height: number; }', + 'declare function inspect(...values: unknown[]): void;', argsMap, outputMap, 'type ToolName = keyof ToolOutputMap', @@ -330,6 +330,6 @@ export function renderToolsSdk(schemas: readonly ToolSdkSchema[], programFormat: ].join('\n\n') const jsonValue = 'type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }' const instructions = renderSdkInstructions(programFormat) - const programInstructions = renderSdkProgramInstructions(programFormat) - return `${instructions}${renderBashExample(sorted, programFormat)}\n\n${programInstructions}\n\n\`\`\`ts\n${jsonValue}\n\n${declaration}\n\`\`\`` + const programInstructions = renderSdkProgramInstructions() + return `${instructions}${renderBashExample(sorted)}\n\n${programInstructions}\n\n\`\`\`ts\n${jsonValue}\n\n${declaration}\n\`\`\`` } diff --git a/packages/core/tool-executor-ptc/tests/exports.built.e2e.ts b/packages/core/tool-executor-ptc/tests/exports.built.e2e.ts new file mode 100644 index 0000000000..98374e716d --- /dev/null +++ b/packages/core/tool-executor-ptc/tests/exports.built.e2e.ts @@ -0,0 +1,62 @@ +/** Published program-tool and plugin entries share configuration and error identities. */ +import { execFile } from 'node:child_process' +import { existsSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { expect, it } from 'vitest' + +const packageRoot = fileURLToPath(new URL('..', import.meta.url)) +const factoryBundle = fileURLToPath(new URL('../lib/run-code.js', import.meta.url)) +const execFileAsync = promisify(execFile) +const probe = String.raw` +import assert from 'node:assert/strict' +import { Context } from '@deepseek-ai/cordis' +import * as ptc from '@deepseek-ai/dsh-tool-executor-ptc' +import { createRunCodeTool, RunCodeConfig } from '@deepseek-ai/dsh-tool-executor-ptc/run-code' +import Tools, { defineTool } from '@deepseek-ai/dsh-tools' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' + +assert.equal(Object.hasOwn(ptc, 'createRunCodeTool'), false) +assert.equal(RunCodeConfig, ptc.Config) +const ctx = new Context() +try { + await ctx.plugin(SystemPrompt) + await ctx.plugin(Tools) + const runtime = { + language: 'typescript', programFormat: 'repl', retainsState: false, + resolve(request) { return { ...request, cwd: process.cwd(), timeoutMs: 60000 } }, + async run() { return { output: [], error: { kind: 'exception', message: 'probe failure' } } }, + } + const capability = defineTool({ + name: 'private_probe', description: 'Probe private binding.', parameters: {}, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute() { return 'private result' }, + }) + const definition = createRunCodeTool(ctx, { + name: 'program_probe', description: 'Run the probe program.', runtime, tools: [capability], + }) + const execution = { + name: 'program_probe', callId: 'probe', rootCallId: 'probe', token: Symbol('probe'), + signal: new AbortController().signal, deferContext() {}, concludeTurn() {}, + } + 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 (spec) => { + assert.deepEqual(Object.keys(spec.bindings[0].functions), ['private_probe']) + assert.equal(spec.discardCompletion, true) + assert.equal(await spec.bindings[0].functions.private_probe({}), 'private result') + return { output: [{ type: 'text', text: 'private result' }] } + } + const result = await definition.execute({ code: 'probe', description: 'Check the private binding' }, execution) + assert.deepEqual(result, { logs: ['private result'] }) + assert.equal(ctx.tools.get('private_probe'), undefined) +} finally { + await ctx.fiber.dispose() +} +console.log('shared program entries verified') +` + +it.skipIf(!existsSync(factoryBundle))('loads private program tools through published exports with shared errors', { retry: 0 }, async ({ signal }) => { + const { stdout } = await execFileAsync(process.execPath, ['--input-type=module', '-e', probe], { cwd: packageRoot, signal }) + expect(stdout.trim()).toBe('shared program entries verified') +}) diff --git a/packages/core/tool-executor-ptc/tests/ptc.spec.ts b/packages/core/tool-executor-ptc/tests/ptc.spec.ts index 2709e5993d..5f1c6c44fc 100644 --- a/packages/core/tool-executor-ptc/tests/ptc.spec.ts +++ b/packages/core/tool-executor-ptc/tests/ptc.spec.ts @@ -49,7 +49,7 @@ class FakeRuntime extends PtcRuntime { readonly language: string readonly isolation = 'fake' - behavior: (request: PtcRunRequest) => Promise = () => Promise.resolve({ logs: [] }) + behavior: (request: PtcRunRequest) => Promise = () => Promise.resolve({ output: [] }) lastRequest?: PtcRunRequest constructor(ctx: Context, config: { language?: string } = {}) { @@ -63,6 +63,11 @@ class FakeRuntime extends PtcRuntime { } } +/** Output from a program that explicitly prints a selected JSON value. */ +function printed(value: JsonValue): PtcRunResult { + return { output: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }] } +} + interface SetupOptions { mode?: 'native' | 'ptc' maxSubCallsPerMinute?: number @@ -188,7 +193,7 @@ it('logs detached frozen nested metadata without changing the binding value or l expect(value).toBe('original contents') metadata.cwd = '/later' metadata.path = '/later/other.txt' - return { logs: [], value } + return printed(value) } const result = await runCode(ctx, 'return await tools.location({})', { agent }) expect(result.isError).toBe(false) @@ -234,7 +239,7 @@ describe('mode-aware wire contribution', () => { ctx.tools.register(definition, { when: () => true }) await expect(functions.conditional!({})).rejects.toThrow('unknown tool "conditional"') } - return { logs: [] } + return { output: [] } } const result = await executeCall(ctx, { agent, toolSet, signal: testToolSignal, callId: ToolCallId('conditional-program'), @@ -423,10 +428,7 @@ describe('mode-aware wire contribution', () => { expect(sdk).toContain('echo: {') expect(sdk).not.toContain('hidden:') - runtime.behavior = request => Promise.resolve({ - logs: [], - value: Object.keys(request.bindings[0]!.functions).sort().join(','), - }) + runtime.behavior = request => Promise.resolve(printed(Object.keys(request.bindings[0]!.functions).sort().join(','))) const result = await runCode(ctx, 'return Object.keys(tools)', { agent }) expect(result.isError).toBe(false) expect(result.content).toEqual([{ type: 'text', text: 'echo' }]) @@ -450,10 +452,7 @@ describe('mode-aware wire contribution', () => { expect(sdk).not.toContain('denied:') expect(sdk).toContain('kept: {') - runtime.behavior = request => Promise.resolve({ - logs: [], - value: Object.keys(request.bindings[0]!.functions).sort().join(','), - }) + runtime.behavior = request => Promise.resolve(printed(Object.keys(request.bindings[0]!.functions).sort().join(','))) const result = await runCode(ctx, 'return Object.keys(tools)', { agent }) expect(result.isError).toBe(false) expect(result.content).toEqual([{ type: 'text', text: 'kept' }]) @@ -519,15 +518,12 @@ describe('mode-aware wire contribution', () => { memberNameProperty: 'toolName', }) const functions = request.bindings[0]!.functions - return Promise.resolve({ - logs: [], - value: JSON.stringify({ - names: Object.keys(functions).sort(), - // Own-property AND prototype-chain reads both come back empty — - // there is no handle a program could re-enter run_code through. - runCode: String(functions[RUN_CODE_NAME]), - }), - }) + return Promise.resolve(printed(JSON.stringify({ + names: Object.keys(functions).sort(), + // Own-property AND prototype-chain reads both come back empty — + // there is no handle a program could re-enter run_code through. + runCode: String(functions[RUN_CODE_NAME]), + }))) } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) @@ -688,7 +684,7 @@ describe('the per-program tool-call limit', () => { await expect(echo({ value: 'rejected' })).rejects.toThrow(message) expect(request.signal?.aborted).toBe(true) await expect(echo({ value: 'caught the error' })).rejects.toThrow('run_code run is over') - return { logs: [], error: { kind: 'abort', message } } + return { output: [], error: { kind: 'abort', message } } } const result = await runCode(ctx, 'program', { agent }) expect(result.error).toMatchObject({ info: { code: 'CODE_RUN_FAILED' } }) @@ -697,7 +693,7 @@ describe('the per-program tool-call limit', () => { expect(events.filter(event => event.type === 'tool/ptc-dispatch-start')).toHaveLength(2048) expect(events.filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(2048) - runtime.behavior = async request => ({ logs: [], value: await request.bindings[0]!.functions.echo!({ value: 'next run' }) }) + runtime.behavior = async request => (printed(await request.bindings[0]!.functions.echo!({ value: 'next run' }))) expect((await runCode(ctx, 'next program', { agent })).isError).toBe(false) expect(calls).toHaveLength(2049) }) @@ -721,7 +717,7 @@ describe('the per-program tool-call limit', () => { for (let n = 0; n < limit; n++) await echo({ value: String(n) }) await expect(echo({ value: 'rejected' })).rejects.toThrow(`limit of ${limit} tool calls (4 per minute of its timeout); call ${limit + 1} was not dispatched`) expect(request.signal?.aborted).toBe(true) - return { logs: [], error: { kind: 'abort', message: String(request.signal?.reason) } } + return { output: [], error: { kind: 'abort', message: String(request.signal?.reason) } } } expect((await runCode(ctx, 'program', { timeoutMs: requestedMs })).isError).toBe(true) expect(calls).toHaveLength(limit) @@ -737,7 +733,7 @@ describe('the per-program tool-call limit', () => { const calls = registerEcho(ctx) runtime.behavior = async (request) => { for (let n = 0; n < 3; n++) await request.bindings[0]!.functions.echo!({ value: String(n) }) - return { logs: [] } + return { output: [] } } expect((await runCode(ctx, 'program')).isError).toBe(false) expect(calls).toHaveLength(3) @@ -769,7 +765,7 @@ describe('the per-program tool-call limit', () => { void functions.queued!({ value: 'queued' }).catch(() => { outcomes.push('queued abandoned') }) await expect(functions.queued!({ value: 'excess' })).rejects.toThrow('limit of 2 tool calls (1 per minute of its timeout); call 3 was not dispatched') expect(request.signal?.aborted).toBe(true) - return { logs: [], error: { kind: 'abort', message: 'execution canceled' } } + return { output: [], error: { kind: 'abort', message: 'execution canceled' } } } const result = await runCode(ctx, 'program', { agent }) expect(result.error).toMatchObject({ info: { code: 'CODE_RUN_FAILED' } }) @@ -798,7 +794,7 @@ describe('the per-program tool-call limit', () => { await expect(echo({ value: 'excess' })).rejects.toThrow('limit of 2 tool calls') expect(request.signal?.aborted).toBe(true) if (cancelCaller) controller.abort('later caller cancellation') - return { logs: ['before termination'], error: failure } + return { output: [{ type: 'text', text: 'before termination' }], error: failure } } const result = await runCode(ctx, 'program', { signal: controller.signal }) expect(result.error).toMatchObject({ info: { code: 'CODE_RUN_FAILED' } }) @@ -827,7 +823,7 @@ describe('the per-program tool-call limit', () => { await expect(functions.fail!({})).rejects.toThrow('tool failed') await expect(functions.echo!({ value: 'rejected' })).rejects.toThrow('limit of 3 tool calls (3 per minute of its timeout); call 4 was not dispatched') expect(request.signal?.aborted).toBe(true) - return { logs: [], error: { kind: 'abort', message: String(request.signal?.reason) } } + return { output: [], error: { kind: 'abort', message: String(request.signal?.reason) } } } expect((await runCode(ctx, 'program')).isError).toBe(true) expect(calls).toEqual([]) @@ -885,13 +881,13 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { // All three must be START-able without any completion (overlap proof). await expect.poll(() => gated.pending()).toBe(3) gated.releaseAll() - return { logs: [], value: (await all).map(String).join(',') } + return printed((await all).map(String).join(',')) } const result = await runCode(ctx, 'program', { agent }) expect(result.isError).toBe(false) expect(gated.peakLive()).toBe(3) if (result.isError) throw new Error('expected success') - expect(result.value).toMatchObject({ result: 'safe_read:a,safe_read:b,safe_read:c' }) + expect(result.value).toMatchObject({ logs: ['safe_read:a,safe_read:b,safe_read:c'] }) // One start per dispatch, paired with its settle by subCallId, starts in submission order. const starts = events.filter(event => event.type === 'tool/ptc-dispatch-start').map(event => event.data as { subCallId: string }) const settles = events.filter(event => event.type === 'tool/ptc-dispatch').map(event => event.data as { subCallId: string }) @@ -919,7 +915,7 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { await expect.poll(() => safe.pending()).toBe(1) safe.releaseAll() await Promise.all([...reads, write, tail]) - return { logs: [], value: 'ordered' } + return printed('ordered') } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) @@ -941,9 +937,9 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { await release.promise return next() }) - runtime.behavior = async request => ({ logs: [], value: await Promise.all( + runtime.behavior = async request => (printed(await Promise.all( [0, 1, 2, 3].map(value => request.bindings[0]!.functions.echo!({ value: String(value) })), - ) }) + ))) const running = runCode(ctx, 'program', { agent }) try { await blocked.promise @@ -967,7 +963,7 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { await expect.poll(() => gated.pending()).toBe(2) gated.releaseAll() await all - return { logs: [], value: 'capped' } + return printed('capped') } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) @@ -997,12 +993,12 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { dispose() const message = await request.bindings[0]!.functions.ephemeral!({}) .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error)) - return { logs: [], value: message } + return printed(message) } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) if (result.isError) throw new Error('expected success') - expect(result.value).toMatchObject({ result: 'unknown tool "ephemeral"' }) + expect(result.value).toMatchObject({ logs: ['unknown tool "ephemeral"'] }) expect(calls).toEqual([]) }) @@ -1032,7 +1028,7 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { await expect.poll(() => gated.pending()).toBe(2) gated.releaseAll() await all - return { logs: [], value: 'ordered-prepare' } + return printed('ordered-prepare') } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) @@ -1072,7 +1068,7 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { await expect.poll(() => reader.pending()).toBe(1) reader.releaseAll() await r - return { logs: [], value: 'barrier-through-commit' } + return printed('barrier-through-commit') } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) @@ -1098,7 +1094,7 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { gated.release() await expect.poll(() => releasePost !== undefined).toBe(true) queueMicrotask(() => { releasePost!() }) - return { logs: [], value: 'returned-early' } + return printed('returned-early') } const result = await runCode(ctx, 'program', { agent }) expect(result.isError).toBe(false) @@ -1138,7 +1134,7 @@ describe('the sub-dispatch scheduler (native concurrency contract)', () => { gated.release() // releases a (FIFO gate) — invert: release twice reversed is not possible; gated.releaseAll() await all - return { logs: [], value: 'ordered-commit' } + return printed('ordered-commit') } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) @@ -1210,7 +1206,7 @@ describe('the run_code dispatch bridge', () => { await releaseFirst.promise } const value = await request.bindings[0]!.functions.probe!({ value: request.program }) - return { logs: [], value: JSON.stringify(value) } + return printed(JSON.stringify(value)) } const first = runCode(ctx, 'first') try { @@ -1237,12 +1233,12 @@ describe('the run_code dispatch bridge', () => { const first = await tools.echo!({ value: 'one' }) const second = await tools.echo!({ value: 'two' }) if (typeof first !== 'string' || typeof second !== 'string') throw new Error('echo returned a non-string') - return { logs: [`saw ${first}`], value: second } + return { output: [{ type: 'text', text: `saw ${first}\n` }, { type: 'text', text: second }] } } const result = await runCode(ctx, 'const …: string = …', { agent }) expect(result.isError).toBe(false) if (result.isError) throw new Error('expected run_code success') - expect(result.value).toEqual({ logs: ['saw echo:one'], result: 'echo:two' }) + expect(result.value).toEqual({ logs: ['saw echo:one\n', 'echo:two'] }) expect(result.content).toEqual([{ type: 'text', text: 'saw echo:one\necho:two' }]) expect(calls).toEqual([{ value: 'one' }, { value: 'two' }]) const dispatches = events.filter(event => event.type === 'tool/ptc-dispatch') @@ -1264,7 +1260,7 @@ describe('the run_code dispatch bridge', () => { registerEcho(ctx) runtime.behavior = async (request) => { await request.bindings[0]!.functions.echo!({ value: 'nested' }) - return { logs: [], value: 'done' } + return printed('done') } // Freeze the nested observer's parent correlation. If that were the live @@ -1303,7 +1299,7 @@ describe('the run_code dispatch bridge', () => { })) runtime.behavior = async (request) => { await request.bindings[0]!.functions.finalize!({}) - return { logs: [], value: 'program complete' } + return printed('program complete') } const concluded = await runCode(ctx, 'await tools.finalize({})') @@ -1318,7 +1314,7 @@ describe('the run_code dispatch bridge', () => { }) runtime.behavior = async (request) => { await request.bindings[0]!.functions.finalize!({}).catch(() => undefined) - return { logs: [], value: 'recovered' } + return printed('recovered') } const recovered = await runCode(ctx, 'await tools.finalize({}).catch(() => {})') veto() @@ -1352,7 +1348,7 @@ describe('the run_code dispatch bridge', () => { const tools = request.bindings[0]!.functions const values = await Promise.all([tools.probe!({ id: 'a' }), tools.probe!({ id: 'b' }), tools.probe!({ id: 'c' })]) if (!values.every(value => typeof value === 'string')) throw new Error('probe returned a non-string') - return { logs: [], value: values.join(',') } + return printed(values.join(',')) } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) @@ -1375,9 +1371,9 @@ describe('the run_code dispatch bridge', () => { runtime.behavior = async (request) => { try { await request.bindings[0]!.functions.fail!({}) - return { logs: [], value: 'unreachable' } + return printed('unreachable') } catch (error: unknown) { - return { logs: [], value: `caught: ${error instanceof Error ? error.message : String(error)}` } + return printed(`caught: ${error instanceof Error ? error.message : String(error)}`) } } const result = await runCode(ctx, 'program') @@ -1409,7 +1405,7 @@ describe('the run_code dispatch bridge', () => { firstLog.resolve(undefined) expect(await third).toBe('echo:three') secondLog.resolve(undefined) - return { logs: [], value: 'complete' } + return printed('complete') } try { const result = await runCode(ctx, 'program', { agent }) @@ -1428,7 +1424,7 @@ describe('the run_code dispatch bridge', () => { const { agent, events } = fakeAgent() runtime.behavior = async (request) => { const value = await request.bindings[0]!.functions.echo!({ value: 'x' }) - return { logs: [], value: value as string } + return printed(value) } const result = await runCode(ctx, 'program', { agent }) expect(result.isError).toBe(false) @@ -1452,12 +1448,12 @@ describe('the run_code dispatch bridge', () => { runtime.behavior = async (request) => { const message = await request.bindings[0]!.functions.echo!({ value: 'x' }) .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error)) - return { logs: [], value: message } + return printed(message) } const result = await runCode(ctx, 'program', { agent }) expect(result.isError).toBe(false) if (result.isError) throw new Error('expected success') - expect(result.value).toMatchObject({ result: 'gate exploded' }) + expect(result.value).toMatchObject({ logs: ['gate exploded'] }) // The pipeline failure is final: the body never ran and post-execute was // skipped, yet the settle event still carries the error outcome. expect(calls).toEqual([]) @@ -1488,9 +1484,9 @@ describe('the run_code dispatch bridge', () => { runtime.behavior = async (request) => { try { await request.bindings[0]!.functions.echo!({ value: 'x' }) - return { logs: [], value: 'unreachable' } + return printed('unreachable') } catch (error: unknown) { - return { logs: [], value: `denied: ${error instanceof Error ? error.message : String(error)}` } + return printed(`denied: ${error instanceof Error ? error.message : String(error)}`) } } const result = await runCode(ctx, 'program', { agent }) @@ -1539,7 +1535,7 @@ describe('the run_code dispatch bridge', () => { const { agent, events } = fakeAgent() runtime.behavior = async (request) => { await request.bindings[0]!.functions.echo!({ value: 'x' }) - return { logs: [], value: 'unreachable' } + return printed('unreachable') } const result = await runCode(ctx, 'await tools.echo({ value: "x" })', { agent }) @@ -1567,9 +1563,9 @@ describe('the run_code dispatch bridge', () => { runtime.behavior = async (request) => { try { await request.bindings[0]!.functions.echo!({ value: 'x' }) - return { logs: [], value: 'unreachable' } + return printed('unreachable') } catch (error: unknown) { - return { logs: [], value: error instanceof Error ? error.message : String(error) } + return printed(error instanceof Error ? error.message : String(error)) } } @@ -1593,9 +1589,9 @@ describe('the run_code dispatch bridge', () => { runtime.behavior = async (request) => { try { await request.bindings[0]!.functions.echo!({ value: 'x', big: 1n }) - return { logs: [], value: 'unreachable' } + return printed('unreachable') } catch (error: unknown) { - return { logs: [], value: error instanceof Error ? error.message : String(error) } + return printed(error instanceof Error ? error.message : String(error)) } } const result = await runCode(ctx, 'program', { agent }) @@ -1611,7 +1607,7 @@ describe('the run_code dispatch bridge', () => { runtime.behavior = async (request) => { const args = Object.assign(Object.create(null) as Record, { value: 'x', nested: ['same'] }) await request.bindings[0]!.functions.echo!(args) - return { logs: [] } + return { output: [] } } await runCode(ctx, 'program', { agent }) expect(calls).toEqual([{ value: 'x', nested: ['same'] }]) @@ -1637,7 +1633,7 @@ describe('the run_code dispatch bridge', () => { runtime.behavior = async (request) => { await request.bindings[0]!.functions.echo!({ value: 'x' }) await request.bindings[0]!.functions.echo!({ value: 'y' }) - return { logs: [], value: 'done' } + return printed('done') } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) @@ -1655,8 +1651,8 @@ describe('the run_code dispatch bridge', () => { ]) }) - it('defers image-bearing final sub-call content onto the outer run_code result', async () => { - const { ctx, runtime } = await setup({ mode: 'ptc' }) + it.each(['typescript', 'python'])('records image-bearing sub-call results for a %s runtime', async (language) => { + const { ctx, runtime } = await setup({ mode: 'ptc', runtime: { language } }) ctx.tools.register(defineContentToolFixture({ name: 'image_result', description: 'Return one durable image.', @@ -1674,19 +1670,90 @@ describe('the run_code dispatch bridge', () => { })) runtime.behavior = async (request) => { await request.bindings[0]!.functions.image_result!({}) - return { logs: [], value: 'done' } + return printed('done') } const result = await runCode(ctx, 'program') expect(result.additionalContexts).toMatchObject([{ - role: 'user', source: { kind: 'ptc-mode' }, content: [ { type: 'text', text: 'image result' }, - { type: 'image', attachment: { mediaType: 'image/png', bytes: 1, width: 1, height: 1 } }, + { type: 'image', attachment: { attachmentId: 'sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' } }, ], }]) + expect(result.content).toEqual([{ type: 'text', text: 'done' }]) + }) + + it.each([ + { name: 'read_image', count: 0, message: 'Image-producing tools must return exactly one image' }, + { name: 'read_image', count: 2, message: 'Image-producing tools must return exactly one image' }, + { name: 'cua', count: 2, message: 'Image-producing tools must return exactly one image' }, + { name: 'read_image', count: 1, message: 'Image storage must expose a readable path in the program filesystem' }, + ])('rejects $name with $count images when its program image is unavailable', async ({ name, count, message }) => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + onTestFinished(() => ctx.fiber.dispose()) + ctx.tools.register(defineContentToolFixture({ + name, description: 'Return image content.', parameters: {}, + execute: () => Promise.resolve(Array.from({ length: count }, () => ({ + type: 'image' as const, + attachment: { + attachmentId: 'sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' as never, + mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1, + }, + }))), + })) + runtime.behavior = async (request) => { + await request.bindings[0]!.functions[name]!({}) + return { output: [] } + } + + const result = await runCode(ctx, 'program') + expect(result.isError).toBe(true) + expect(result.content).toEqual([{ type: 'text', text: expect.stringContaining(message) as string }]) + }) + + it('returns CUA text observations as program values', async () => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + onTestFinished(() => ctx.fiber.dispose()) + ctx.tools.register(defineContentToolFixture({ + name: 'cua', description: 'Return a text observation.', parameters: {}, + execute: () => Promise.resolve([{ type: 'text', text: 'Window selected' }]), + })) + runtime.behavior = async request => printed(await request.bindings[0]!.functions.cua!({})) + + const result = await runCode(ctx, 'program') + expect(result.isError).toBe(false) + expect(result.content).toEqual([{ type: 'text', text: JSON.stringify([{ type: 'text', text: 'Window selected' }], null, 2) }]) + }) + + it.each(['read_image', 'cua'])('reports the policy notice when %s image output is removed', async (name) => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + ctx.tools.register(defineContentToolFixture({ + name, description: 'Return image content.', parameters: {}, + execute: () => Promise.resolve([{ + type: 'image', attachment: { + attachmentId: 'sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' as never, + mediaType: 'image/png', bytes: 1, width: 1, height: 1, + }, + }]), + })) + ctx.on('tools/post-execute', async (exec, _result, next): Promise => { + const decision = await next() + return exec.name === name && decision.kind === 'accept' + ? { kind: 'accept', content: [{ type: 'text', text: 'image omitted; read the saved result' }] } + : decision + }) + runtime.behavior = async (request) => { + await expect(request.bindings[0]!.functions[name]!({})).rejects.toThrow( + 'Image output was removed by a tool output policy.\nimage omitted; read the saved result', + ) + return printed('recovered') + } + const result = await runCode(ctx, 'program') + expect(result.isError).toBe(false) + expect(result.content).toEqual([{ type: 'text', text: 'recovered' }]) + expect(result.additionalContexts).toBeUndefined() }) it('does not defer images removed by a nested post-execute decision', async () => { @@ -1712,7 +1779,7 @@ describe('the run_code dispatch bridge', () => { }) runtime.behavior = async (request) => { await request.bindings[0]!.functions.image_result!({}).catch(() => undefined) - return { logs: [], value: 'done' } + return printed('done') } const result = await runCode(ctx, 'program') @@ -1737,7 +1804,7 @@ describe('the run_code dispatch bridge', () => { }) runtime.behavior = async (request) => { await request.bindings[0]!.functions.echo!({ value: 'x' }) - return { logs: [], error: { kind: 'exception', message: 'program failed later' } } + return { output: [], error: { kind: 'exception', message: 'program failed later' } } } const result = await runCode(ctx, 'program') @@ -1751,13 +1818,24 @@ describe('the run_code dispatch bridge', () => { }]) }) + it.each([false, true])('preserves raw text fragments, failure=%s', async (failed) => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + runtime.behavior = () => Promise.resolve({ + output: ['sel', 'ected\n', 'log\n', 'warn\n', 'after\n'].map(text => ({ type: 'text' as const, text })), + ...failed ? { error: { kind: 'exception' as const, message: 'stopped' } } : {}, + }) + const result = await runCode(ctx, 'program') + expect(result.isError).toBe(failed) + expect(result.content).toEqual([{ type: 'text', text: `${failed ? 'Error: code run failed (exception): stopped\nCaptured output:\n' : ''}selected\nlog\nwarn\nafter\n` }]) + }) + it.each([ ['before code started', []], ['during execution', ['got this far']], ] as const)('reports a timeout %s with its captured output', async (phase, logs) => { const { ctx, runtime } = await setup({ mode: 'ptc' }) runtime.behavior = () => Promise.resolve({ - logs: [...logs], + output: logs.map(text => ({ type: 'text' as const, text })), error: { kind: 'timeout', message: `execution timed out ${phase} (300ms); retained variables were cleared` }, }) const result = await runCode(ctx, 'program') @@ -1801,7 +1879,7 @@ describe('the run_code dispatch bridge', () => { await Promise.all(calls) // A real runtime would be terminated by the abort; the fake honors the // contract by reporting the abort as the run failure. - return { logs: [], error: { kind: 'abort', message: 'user-cancel' } } + return { output: [], error: { kind: 'abort', message: 'user-cancel' } } } const result = await runCode(ctx, 'program', { signal: controller.signal }) expect(result.isError).toBe(true) @@ -1850,7 +1928,7 @@ describe('the run_code dispatch bridge', () => { const calls = registerEcho(ctx) runtime.behavior = async (request) => { await request.bindings[0]!.functions.echo!({ value: 'x' }) - return { logs: [], value: 'ok' } + return printed('ok') } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) @@ -1881,7 +1959,7 @@ describe('the run_code dispatch bridge', () => { const { agent, events } = fakeAgent() runtime.behavior = async (request) => { await request.bindings[0]!.functions.echo!({ value: 'blocked' }) - return { logs: [] } + return { output: [] } } const result = await runCode(ctx, 'return await tools.echo({ value: "blocked" })', { agent }) @@ -1953,10 +2031,10 @@ describe('the run_code dispatch bridge', () => { }) it.each([ - ['logs only', { logs: ['printed'] }, 'printed'], - ['result only', { logs: [], value: 'returned' }, 'returned'], - ['logs plus result', { logs: ['printed'], value: 'returned' }, 'printed\nreturned'], - ['no output', { logs: [] }, '(run_code completed with no output)'], + ['logs only', { output: [{ type: 'text', text: 'printed' }] }, 'printed'], + ['completion only', { output: [], value: 'returned' }, '(run_code completed with no output)'], + ['logs plus completion', { output: [{ type: 'text', text: 'printed' }], value: 'returned' }, 'printed'], + ['no output', { output: [] }, '(run_code completed with no output)'], ] as [string, PtcRunResult, string][])('keeps %s in durable content without a result presenter', async (_name, output, text) => { const { ctx, runtime } = await setup({ mode: 'ptc' }) runtime.behavior = () => Promise.resolve(output) @@ -1974,7 +2052,7 @@ describe('the run_code dispatch bridge', () => { it('keeps a post-policy spill preview in durable content without a result presenter', async () => { const { ctx, runtime } = await setup({ mode: 'ptc' }) const preview = 'HEAD\n\n(Omitted 100 bytes. Full formatted result stored at: /tmp/run-code.txt.)\n\nTAIL' - runtime.behavior = () => Promise.resolve({ logs: ['printed'], value: 'returned' }) + runtime.behavior = () => Promise.resolve({ output: [{ type: 'text', text: 'printed' }], value: 'returned' }) ctx.on('tools/post-execute', (exec, _result, next): Promise => { if (exec.name !== RUN_CODE_NAME) return next() return Promise.resolve({ kind: 'accept', content: [{ type: 'text', text: preview }] }) @@ -1990,7 +2068,7 @@ describe('the run_code dispatch bridge', () => { it('keeps canonical failure content durable without a result presenter', async () => { const { ctx, runtime } = await setup({ mode: 'ptc' }) runtime.behavior = () => Promise.resolve({ - logs: ['captured before failure'], + output: [{ type: 'text', text: 'captured before failure' }], error: { kind: 'output-limit', message: 'outer output exceeded 8 bytes' }, }) @@ -2026,7 +2104,7 @@ describe('the run_code dispatch bridge', () => { })) runtime.behavior = async (request) => { const value = await request.bindings[0]!.functions.mixed!({}) - return { logs: [], value } + return printed(value) } const result = await runCode(ctx, 'program', { agent }) expect(result.isError).toBe(false) @@ -2045,19 +2123,16 @@ describe('the run_code dispatch bridge', () => { runtime.behavior = async (request) => { const echo = request.bindings[0]!.functions.echo! const catchMessage = (promise: Promise) => promise.then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error)) - return { - logs: [], - value: [ - // Root undefined must reject up front: the event log rejects it as - // data, and nothing may execute unlogged. - await catchMessage(echo(undefined)), - await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw 'raw-throw' } }))), - await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('error-throw') } }))), - await catchMessage(echo(new Date(0))), - // A bare function is a value JSON cannot represent at all. - await catchMessage(echo(() => 1)), - ].join(' | '), - } + return printed([ + // Root undefined must reject up front: the event log rejects it as + // data, and nothing may execute unlogged. + await catchMessage(echo(undefined)), + await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw 'raw-throw' } }))), + await catchMessage(echo(Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('error-throw') } }))), + await catchMessage(echo(new Date(0))), + // A bare function is a value JSON cannot represent at all. + await catchMessage(echo(() => 1)), + ].join(' | ')) } const result = await runCode(ctx, 'program', { agent }) const text = (result.content[0] as { text: string }).text @@ -2100,13 +2175,13 @@ describe('the run_code dispatch bridge', () => { let nested: JsonValue = 'leaf' for (let index = 0; index < depth; index++) nested = [nested] const value = await request.bindings[0]!.functions.deep_args!({ nested }) - return { logs: [], value } + return printed(value) } const result = await runCode(ctx, 'return tools.deep_args(...)', { agent }) expect(result.isError).toBe(false) - expect(result.isError ? undefined : result.value).toEqual({ logs: [], result: depth }) + expect(result.isError ? undefined : result.value).toEqual({ logs: [String(depth)] }) expect({ observedDepth, observedLeaf }).toEqual({ observedDepth: depth, observedLeaf: 'leaf' }) const dispatch = session.snapshotEvents().find(event => event.type === 'tool/ptc-dispatch') if (dispatch === undefined) throw new Error('expected a durable tool/ptc-dispatch event') @@ -2136,7 +2211,7 @@ describe('the run_code dispatch bridge', () => { })) runtime.behavior = async (request) => { await request.bindings[0]!.functions.mutator!({ list: ['original'] }) - return { logs: [] } + return { output: [] } } const result = await runCode(ctx, 'program', { agent }) expect(result.isError).toBe(false) @@ -2161,38 +2236,38 @@ describe('the run_code dispatch bridge', () => { const functions = request.bindings[0]!.functions expect(Object.getPrototypeOf(functions)).toBeNull() const value = await functions['__proto__']!({}) - return { logs: [], value } + return printed(value) } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) expect(result.content[0]).toEqual({ type: 'text', text: 'proto-tool-ok' }) }) - it('renders every non-string JSON root as pretty JSON while preserving strings raw', async () => { - const { ctx, runtime } = await setup({ mode: 'ptc' }) - runtime.behavior = () => Promise.resolve({ logs: [], value: { n: 42, ok: true } }) + it('renders Python completion values as pretty JSON while preserving strings raw', async () => { + const { ctx, runtime } = await setup({ mode: 'ptc', runtime: { language: 'python' } }) + runtime.behavior = () => Promise.resolve({ output: [], value: { n: 42, ok: true } }) expect((await runCode(ctx, 'object')).content[0]).toEqual({ type: 'text', text: '{\n "n": 42,\n "ok": true\n}' }) - runtime.behavior = () => Promise.resolve({ logs: [], value: {} }) + runtime.behavior = () => Promise.resolve({ output: [], value: {} }) expect((await runCode(ctx, 'empty object')).content[0]).toEqual({ type: 'text', text: '{}' }) const nested = { outer: [{ inner: true }] } - runtime.behavior = () => Promise.resolve({ logs: [], value: nested }) + runtime.behavior = () => Promise.resolve({ output: [], value: nested }) expect((await runCode(ctx, 'nested')).content[0]).toEqual({ type: 'text', text: JSON.stringify(nested, null, 2) }) - runtime.behavior = () => Promise.resolve({ logs: [], value: ['x', 2] }) + runtime.behavior = () => Promise.resolve({ output: [], value: ['x', 2] }) expect((await runCode(ctx, 'array')).content[0]).toEqual({ type: 'text', text: '[\n "x",\n 2\n]' }) - runtime.behavior = () => Promise.resolve({ logs: [], value: [] }) + runtime.behavior = () => Promise.resolve({ output: [], value: [] }) expect((await runCode(ctx, 'empty array')).content[0]).toEqual({ type: 'text', text: '[]' }) - runtime.behavior = () => Promise.resolve({ logs: [], value: null }) + runtime.behavior = () => Promise.resolve({ output: [], value: null }) expect((await runCode(ctx, 'null')).content[0]).toEqual({ type: 'text', text: 'null' }) - runtime.behavior = () => Promise.resolve({ logs: [], value: 'raw' }) + runtime.behavior = () => Promise.resolve({ output: [], value: 'raw' }) expect((await runCode(ctx, 'string')).content[0]).toEqual({ type: 'text', text: 'raw' }) - runtime.behavior = () => Promise.resolve({ logs: [] }) + runtime.behavior = () => Promise.resolve({ output: [] }) const absent = await runCode(ctx, 'undefined') expect(absent.content[0]).toEqual({ type: 'text', text: '(run_code completed with no output)' }) expect(absent.isError ? undefined : absent.value).toEqual({ logs: [] }) }) - it('renders deeply nested JSON without recursive traversal or quadratic indentation', async () => { - const { ctx, runtime } = await setup({ mode: 'ptc' }) + it('renders deeply nested Python completions without recursive traversal or quadratic indentation', async () => { + const { ctx, runtime } = await setup({ mode: 'ptc', runtime: { language: 'python' } }) let value: JsonValue = { emptyArray: [], emptyObject: {}, @@ -2200,7 +2275,7 @@ describe('the run_code dispatch bridge', () => { record: { first: true, second: null }, } for (let depth = 0; depth < 5_000; depth++) value = [value] - runtime.behavior = () => Promise.resolve({ logs: [], value }) + runtime.behavior = () => Promise.resolve({ output: [], value }) const result = await runCode(ctx, 'deep result') @@ -2217,8 +2292,8 @@ describe('the run_code dispatch bridge', () => { const calls = registerEcho(ctx) runtime.behavior = (request) => { // The fake honors the seam contract for an already-aborted signal. - if (request.signal?.aborted) return Promise.resolve({ logs: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } }) - return Promise.resolve({ logs: [], value: 'unreachable' }) + if (request.signal?.aborted) return Promise.resolve({ output: [], error: { kind: 'abort' as const, message: String(request.signal.reason) } }) + return Promise.resolve(printed('unreachable')) } const controller = new AbortController() controller.abort('too-late') @@ -2244,7 +2319,7 @@ describe('the run_code dispatch bridge', () => { controller.abort('cancelled-mid-run') const message = await request.bindings[0]!.functions.echo!({ value: 'x' }) .then(() => 'resolved', (error: unknown) => error instanceof Error ? error.message : String(error)) - return { logs: [], value: message } + return printed(message) } const result = await runCode(ctx, 'program', { signal: controller.signal }) expect(result.isError).toBe(true) @@ -2263,7 +2338,7 @@ describe('the run_code dispatch bridge', () => { const message = `execution canceled; retained variables were ${state}` runtime.behavior = async () => { controller.abort({ kind: 'user' }) - return { logs: [], error: { kind: 'abort', message } } + return { output: [], error: { kind: 'abort', message } } } const result = await runCode(ctx, 'program', { signal: controller.signal }) expect(result.error).toEqual({ @@ -2289,7 +2364,7 @@ describe('the run_code dispatch bridge', () => { expect(request.signal?.reason).toBe(controller.signal.reason) const reason: unknown = request.signal?.reason const message = reason instanceof Error ? reason.message : String(reason) - return { logs: [], error: { kind: 'abort', message } } + return { output: [], error: { kind: 'abort', message } } } const result = await runCode(ctx, 'program', { signal: controller.signal }) @@ -2315,7 +2390,7 @@ describe('the run_code dispatch bridge', () => { const controller = new AbortController() runtime.behavior = async () => { if (cancelled) controller.abort({ kind: 'user' }) - return { logs: ['got this far'], error: failure } + return { output: [{ type: 'text', text: 'got this far' }], error: failure } } const result = await runCode(ctx, 'program', { signal: controller.signal }) @@ -2634,7 +2709,7 @@ describe('host environment reset', () => { void request.bindings[0]!.functions.blocked!({}).catch(() => {}) return program.promise } - const release = vi.spyOn(runtime, 'release').mockImplementation(async () => { program.resolve({ logs: [], error: { kind: 'abort', message: 'environment disposed' } }) }) + const release = vi.spyOn(runtime, 'release').mockImplementation(async () => { program.resolve({ output: [], error: { kind: 'abort', message: 'environment disposed' } }) }) const running = runCode(ctx, 'await tools.blocked({}); while (true) {}', { agent }) await toolStarted.promise let settled = false @@ -2646,7 +2721,7 @@ describe('host environment reset', () => { cleanup.resolve(undefined) await resetting expect((await running).isError).toBe(true) - } finally { cleanup.resolve(undefined); program.resolve({ logs: [] }); await Promise.all([running, resetting]) } + } finally { cleanup.resolve(undefined); program.resolve({ output: [] }); await Promise.all([running, resetting]) } }) it('reports failed cleanup, refuses further code, and allows explicit reset retry', async () => { @@ -2699,20 +2774,32 @@ describe('PTC standing file policy and sandbox outcomes', () => { it('preserves partial enforcement and observed denial in successful output', async () => { const { ctx, runtime } = await setup() try { - runtime.behavior = async () => ({ logs: [], sandbox: { mode: 'read-only', enforcement: 'partial', denied: true } }) + runtime.behavior = async () => ({ output: [], sandbox: { mode: 'read-only', enforcement: 'partial', denied: true } }) const result = await runCode(ctx, 'return 1') expect(result.value).toEqual({ logs: [], sandbox: { mode: 'read-only', enforcement: 'partial', denied: true } }) expect(result.content).toEqual([{ type: 'text', text: 'File sandbox enforcement is partial on this host.\nThe read-only file sandbox denied an operation.' }]) } finally { await ctx.fiber.dispose() } }) + it.each(['line', 'line\n', 'line\n\n'])('keeps written line breaks before sandbox diagnostics: %j', async (log) => { + const { ctx, runtime } = await setup() + try { + runtime.behavior = async () => ({ output: [{ type: 'text', text: log }], + error: { kind: 'exception', message: 'failed' }, sandbox: { mode: 'read-only', denied: false } }) + const result = await runCode(ctx, 'inspect("line"); throw new Error("failed")') + const text = result.content.filter(block => block.type === 'text').map(block => block.text).join('') + const written = log === 'line' ? 'line\n' : log + expect(text).toBe(`Error: code run failed (exception): failed\nCaptured output:\n${written}File sandbox: read-only.`) + } finally { await ctx.fiber.dispose() } + }) + it.each([ { mode: 'danger-full-access' as const, denied: false }, { mode: 'read-only' as const, denied: true, enforcement: 'full' as const }, ])('includes the available sandbox facts with a failed program ($mode)', async (sandbox) => { const { ctx, runtime } = await setup() try { - runtime.behavior = async () => ({ logs: [], error: { kind: 'exception', message: 'failed' }, sandbox }) + runtime.behavior = async () => ({ output: [], error: { kind: 'exception', message: 'failed' }, sandbox }) const result = await runCode(ctx, 'throw new Error("failed")') expect(result.isError).toBe(true) const text = result.content.filter(block => block.type === 'text').map(block => block.text).join('\n') @@ -2895,7 +2982,7 @@ describe('per-program execution controls', () => { let effects = 0 runtime.behavior = () => { effects++ - return Promise.resolve({ logs: ['first effect completed'], + return Promise.resolve({ output: [{ type: 'text', text: 'first effect completed' }], error: { kind: 'exception', message: 'access denied' }, sandbox: { mode: 'read-only', denied: true, enforcement: 'full' } }) } @@ -2927,7 +3014,7 @@ describe('per-program execution controls', () => { expect(ctx.sandboxPolicy.resolve({ session: agent.session }).mode).toBe('read-only') const value = await request.bindings[0]!.functions.echo!({ value: 'nested' }) .then(() => 'unexpected nested grant', () => 'nested approval rejected') - return { logs: [], value } + return printed(value) } const resolver = vi.spyOn(runtime, 'resolve') const result = execute({ sandbox_permissions: 'workspace-write', justification: 'Write generated source', timeoutMs: 1234 }) @@ -3003,7 +3090,7 @@ it.each([ runtime.behavior = async (request) => { entered.resolve(undefined) await release.promise - return { logs: [], value: await request.bindings[0]!.functions.echo!({}) } + return printed(await request.bindings[0]!.functions.echo!({})) } const agent = { ctx, id: SessionId('unloading-ptc'), session: Session.create(SessionId('unloading-ptc')) } as Agent const input = { @@ -3018,7 +3105,7 @@ it.each([ await (unload === 'runtime' ? runtimeProvider : provider).dispose() await expect(ctx.tools.execute(input)).rejects.toThrow('selected tool executor is unavailable') release.resolve(undefined) - expect((await pending).results[0]?.result).toMatchObject({ isError: false, value: { logs: [], result: 'settled' } }) + expect((await pending).results[0]?.result).toMatchObject({ isError: false, value: { logs: ['settled'] } }) if (owned) expect(agent.session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch')) .toMatchObject([{ data: { name: 'echo', isError: false, content: [{ type: 'text', text: 'settled' }] } }]) } finally { diff --git a/packages/core/tool-executor-ptc/tests/run-code.spec.ts b/packages/core/tool-executor-ptc/tests/run-code.spec.ts new file mode 100644 index 0000000000..514113baf3 --- /dev/null +++ b/packages/core/tool-executor-ptc/tests/run-code.spec.ts @@ -0,0 +1,261 @@ +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' +import { brandString } from '@deepseek-ai/dsh-brand' +import { createUserMessage, ToolCallId, type ContentBlock } from '@deepseek-ai/dsh-llm' +import { PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' +import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import SessionProjections from '@deepseek-ai/dsh-session-projection' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import { NativeToolExecutor } from '@deepseek-ai/dsh-tool-executor-native' +import ToolRuntime, { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools' +import ApprovalService, { type ApprovalOutcome } from '@deepseek-ai/dsh-user-approval' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { createRunCodeTool, RunCodeConfig } from '../src/run-code.ts' + +class ControlledRuntime extends PtcRuntime { + readonly language = 'typescript' + readonly isolation = 'fixture' + override get retainsState() { return true } + override get programFormat() { return 'repl' as const } + override get executionInstructions() { return 'Top-level await is supported; the last expression is returned.' } + override get timeout() { return { defaultMs: 120_000, maxMs: 600_000 } } + behavior: (spec: PtcRunSpec) => Promise = async () => ({ output: [] }) + + resolve(request: PtcRunRequest): PtcRunSpec { + return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? this.timeout.defaultMs } + } + + run(spec: PtcRunSpec): Promise { return this.behavior(spec) } +} + +function privateTool(execute = vi.fn(async () => 'private result')) { + return defineTool({ + name: 'cua', description: 'Operate the test computer.', parameters: {}, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + execute, + }) +} + +async function setup(definition: ToolDefinition, limits?: Partial) { + const ctx = new Context() + const runtimeContext = new Context() + const agentContext = new Context() + onTestFinished(async () => { + await ctx.fiber.dispose() + await agentContext.fiber.dispose() + await runtimeContext.fiber.dispose() + }) + provideWorkingDirectoryFixture(ctx) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjections) + ctx.tools.setExecutor(new NativeToolExecutor(ctx)) + await runtimeContext.plugin(ControlledRuntime) + const runtime = runtimeContext.ptcRuntime as ControlledRuntime + const session = ctx.sessions.create(SessionId('private-program')) + session.append('turn/start', { turn: 1 }) + const agent = { ctx: agentContext, id: session.id, session } as Agent + const fiber = await ctx.plugin(Object.assign((owner: Context) => { + owner.tools.register(createRunCodeTool(owner, { + name: 'cua_run_code', description: 'Run computer operations through cua.', + runtime, tools: [definition], + ...limits === undefined ? {} : { limits }, + })) + }, { inject: ['tools'] })) + const execute = async (args: Record = {}, name = 'cua_run_code') => { + const signal = new AbortController().signal + const toolSet = await ctx.tools.resolve({ agent, modelSelection: { provider: 'test', model: 'test' }, signal }) + try { + return await ctx.tools.execute({ + calls: [{ type: 'tool-call', id: ToolCallId('program'), name, arguments: JSON.stringify({ code: 'await cua.inspect()', description: 'Inspect the current computer', ...args }) }], + agent, toolSet, signal, + }) + } finally { toolSet.dispose() } + } + return { ctx, runtime, agent, agentContext, session, fiber, execute } +} + +describe('registered program tool factory', () => { + it('uses the explicit runtime and binds only private definitions under native execution', async () => { + const body = vi.fn(async () => 'private result') + const definition = privateTool(body) + const { ctx, runtime, agent, execute } = await setup(definition) + const unrelated = vi.fn(async () => 'unrelated') + ctx.tools.register({ ...privateTool(unrelated), name: 'other' }) + expect(ctx.get('ptcRuntime')).toBeUndefined() + expect(ctx.tools.get('cua')).toBeUndefined() + expect((await execute({}, 'cua')).results[0]?.result).toMatchObject({ isError: true, error: { info: { code: 'UNKNOWN_TOOL' } } }) + const schema = ctx.tools.schemas().find(tool => tool.name === 'cua_run_code')! + expect(schema.description).toContain('Run computer operations through cua.') + expect(schema.description).toContain(runtime.executionInstructions) + expect(JSON.stringify(schema.parameters)).toContain('Default 120000; capped at 600000') + runtime.behavior = async (request) => { + expect(request.program).toBe('await cua.inspect()') + expect(request.stateOwner).toBe(agent) + expect(Object.keys(request.bindings[0]!.functions)).toEqual(['cua']) + expect(request.discardCompletion).toBe(true) + expect(await request.bindings[0]!.functions.cua!({})).toBe('private result') + return { output: [{ type: 'text', text: 'private result' }] } + } + expect((await execute()).results[0]?.result).toMatchObject({ isError: false, value: { logs: ['private result'] } }) + expect(body).toHaveBeenCalledOnce() + expect(unrelated).not.toHaveBeenCalled() + expect(Object.isFrozen(definition.parameters)).toBe(false) + }) + + it('preserves approval rejection and guard identity for unregistered nested tools', async () => { + const body = vi.fn(async () => 'private result') + const { ctx, runtime, session, execute } = await setup(privateTool(body)) + await ctx.plugin(ApprovalService, { policy: 'ask' }) + let approval: ApprovalOutcome = 'rejected' + let guarded = false + ctx.on('approval/request', () => Promise.resolve(approval)) + ctx.on('tools/pre-execute', (exec, next) => exec.name === 'cua' + ? Promise.resolve({ kind: 'ask', reason: 'Confirm computer operation' }) : next()) + ctx.tools.guard(exec => exec.name === 'cua' && guarded + ? { reason: 'Computer operation blocked', info: { name: 'ComputerGuardError', code: 'COMPUTER_BLOCKED' } } : undefined) + runtime.behavior = async (request) => { + await expect(request.bindings[0]!.functions.cua!({})).rejects.toThrow() + return { output: [] } + } + expect((await execute()).results[0]?.result.isError).toBe(false) + approval = 'allowed-once' + guarded = true + expect((await execute()).results[0]?.result.isError).toBe(false) + expect(body).not.toHaveBeenCalled() + expect(session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch').map(event => event.data.error)) + .toEqual([{ name: 'ApprovalError', code: 'APPROVAL_REJECTED' }, { name: 'ComputerGuardError', code: 'COMPUTER_BLOCKED' }]) + }) + + it('uses its own name for escalation and omits the retained owner', async () => { + const { ctx, runtime, execute } = await setup(privateTool()) + await ctx.plugin(SandboxPolicy, { mode: 'read-only', workspaceRoot: process.cwd() }) + await ctx.plugin(ApprovalService, { policy: 'ask' }) + vi.spyOn(runtime, 'sandboxMode', 'get').mockReturnValue('read-only') + const requested: string[] = [] + ctx.on('approval/request', (request) => { + requested.push(request.toolName) + return Promise.resolve('allowed-once') + }) + runtime.behavior = async (request) => { + expect(request.stateOwner).toBeUndefined() + expect(request.sandboxPolicy?.mode).toBe('workspace-write') + return { output: [], sandbox: { mode: 'workspace-write', denied: true } } + } + const result = (await execute({ sandbox_permissions: 'workspace-write', justification: 'Write computer output' })).results[0]!.result + expect(result.isError).toBe(false) + expect(requested).toEqual(['cua_run_code']) + expect(JSON.stringify(result.content)).toContain('Nested tools retain their own policies and approvals') + }) + + it('records nested results while forwarding images and deferred context from private tools', async () => { + type Attachment = Extract['attachment'] + const image: ContentBlock = { type: 'image', attachment: { + attachmentId: brandString('sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), + mediaType: 'image/png', width: 1, height: 1, bytes: 1, + } } + const definition = defineTool({ + name: 'capture', description: 'Capture the test computer.', parameters: {}, + output: { + schema: { type: 'string' }, render: () => [image], presentationMeta: () => ({ screen: 1 }), + }, + execute: async (_args, exec) => { + exec.deferContext(createUserMessage({ source: { kind: 'ptc-mode' }, content: [{ type: 'text', text: 'capture context' }] })) + exec.concludeTurn() + return 'raw snapshot' + }, + }) + const { ctx, runtime, session, execute } = await setup(definition) + ctx.on('tools/ptc-dispatch-log', async () => [{ type: 'text', text: 'durable screenshot preview' }]) + runtime.behavior = async (request) => { + expect(await request.bindings[0]!.functions.capture!({})).toBe('raw snapshot') + return { output: [{ type: 'text', text: 'inspection complete' }] } + } + const batch = await execute() + expect(batch.results[0]?.result.content).toEqual([{ type: 'text', text: 'inspection complete' }]) + expect(batch.concluded).toBe(true) + expect(batch.additionalContexts.map(context => context.content)).toEqual([[image], [{ type: 'text', text: 'capture context' }]]) + const events = session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch-start' || event.type === 'tool/ptc-dispatch') + expect(events.map(event => event.type)).toEqual(['tool/ptc-dispatch-start', 'tool/ptc-dispatch']) + expect(events[1]?.data).toMatchObject({ + rootCallId: 'program', parentCallId: 'program', subCallId: 'program:ptc:1', name: 'capture', arguments: {}, + isError: false, content: [{ type: 'text', text: 'durable screenshot preview' }], meta: { screen: 1 }, + }) + }) + + it('cancels on owner disposal and awaits nested cleanup before releasing the factory', async () => { + const entered = Promise.withResolvers() + const aborted = Promise.withResolvers() + const cleanup = Promise.withResolvers() + const definition = defineTool({ + name: 'cua', description: 'Wait for computer cleanup.', parameters: {}, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + execute: async (_args, exec) => { + exec.signal.addEventListener('abort', () => { aborted.resolve(undefined) }, { once: true }) + entered.resolve(undefined) + await cleanup.promise + return 'cleaned' + }, + }) + const { ctx, runtime, agent, agentContext, session, fiber, execute } = await setup(definition) + const release = vi.spyOn(runtime, 'release') + runtime.behavior = async (request) => { + void request.bindings[0]!.functions.cua!({}).catch(() => undefined) + await new Promise((resolve) => { + request.signal?.addEventListener('abort', () => { resolve() }, { once: true }) + }) + return { output: [], error: { kind: 'abort', message: 'runtime cancelled' } } + } + const running = execute() + let disposing: Promise | undefined + try { + await entered.promise + let disposed = false + disposing = fiber.dispose().then(() => { disposed = true }) + await aborted.promise + expect(disposed).toBe(false) + expect(session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch')).toHaveLength(0) + cleanup.resolve(undefined) + expect((await running).results[0]?.result).toMatchObject({ isError: true, error: { info: { code: 'CODE_RUN_FAILED' } } }) + await disposing + expect(ctx.tools.get('cua_run_code')).toBeUndefined() + expect(session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch')).toMatchObject([ + { data: { isError: true, error: { name: 'AbortError', code: 'ABORTED' } } }, + ]) + await agentContext.fiber.dispose() + expect(release).toHaveBeenCalledExactlyOnceWith(agent) + } finally { + cleanup.resolve(undefined) + await running + await disposing + } + }) + + it('applies configurable call allowances using the registered tool name', async () => { + const body = vi.fn(async () => 'private result') + const { runtime, session, execute } = await setup(privateTool(body), { maxSubCallsPerMinute: 60, maxParallelSubCalls: 1 }) + runtime.behavior = async (request) => { + await request.bindings[0]!.functions.cua!({}) + await expect(request.bindings[0]!.functions.cua!({})).rejects.toThrow('cua_run_code exceeded its limit of 1 tool calls') + return { output: [], error: { kind: 'abort', message: 'allowance exhausted' } } + } + const result = (await execute({ timeoutMs: 1000 })).results[0]!.result + expect(result).toMatchObject({ isError: true, error: { info: { code: 'CODE_RUN_FAILED' } } }) + expect(JSON.stringify(result.content)).toContain('smaller cua_run_code calls') + expect(body).toHaveBeenCalledOnce() + expect(session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch-start')).toHaveLength(1) + }) + + it('rejects duplicate private bindings and invalid limits before registering effects', async () => { + const definition = privateTool() + const { ctx, runtime } = await setup(definition) + const options = { name: 'duplicate_program', description: 'Duplicate bindings.', runtime, tools: [definition, definition] } + expect(() => createRunCodeTool(ctx, options)).toThrow('duplicate binding cua') + expect(() => createRunCodeTool(ctx, { ...options, tools: [definition], limits: { maxParallelSubCalls: 0 } })).toThrow() + expect(RunCodeConfig({})).toEqual({ maxSubCallsPerMinute: 1024, maxParallelSubCalls: 10 }) + expect(ctx.tools.get('duplicate_program')).toBeUndefined() + }) +}) diff --git a/packages/core/tool-executor-ptc/tests/ts-types.spec.ts b/packages/core/tool-executor-ptc/tests/ts-types.spec.ts index 2ec79e974c..e8c8947c97 100644 --- a/packages/core/tool-executor-ptc/tests/ts-types.spec.ts +++ b/packages/core/tool-executor-ptc/tests/ts-types.spec.ts @@ -137,6 +137,7 @@ describe('renderToolsSdk', () => { expect(text).toContain('declare class ToolCallError extends Error') expect(text).toContain('readonly toolName: ToolName;') expect(text).toContain('declare const tools: {') + expect(text).toContain('readonly attachmentId: string;') expect(text).toContain('type JsonValue = null | boolean | number | string') expect(text.indexOf('bash: {')).toBeGreaterThan(0) expect(text).toContain('"my-mcp.tool":') @@ -152,6 +153,16 @@ describe('renderToolsSdk', () => { expect(text).toContain('lossless JSON') }) + it('declares Image results for read_image and image-or-value results for cua', () => { + const tools: ToolSdkSchema[] = ['read_image', 'cua'].map(name => ({ + name, description: 'Image-producing tool.', parameters: {}, output: { type: 'string' }, + })) + const text = renderToolsSdk(tools) + const outputs = text.slice(text.indexOf('interface ToolOutputMap'), text.indexOf('type ToolName')) + expect(outputs).toContain('read_image: Image;') + expect(outputs).toContain('cua: Image | string;') + }) + it('lists the program before its description', () => { const text = renderToolsSdk([bash]) expect(text).toContain('`code`') @@ -163,14 +174,14 @@ describe('renderToolsSdk', () => { const text = renderToolsSdk([bash]) expect(text).toContain('A declaration does not make its name a directly callable tool') expect(text).toContain('only names supplied as separate tool schemas may be called directly') - expect(text).toContain('`run_code({ code: "return await tools.bash({ description: \'Show current directory\', command: \'pwd\' })", description: "Show current directory" })`') + expect(text).toContain('`run_code({ code: "inspect(await tools.bash({ description: \'Show current directory\', command: \'pwd\' }))", description: "Show current directory" })`') expect(text).toContain('Program-only SDK bindings:') expect(text).not.toContain('The available tools:') }) it('keeps REPL output syntax distinct from function bodies', () => { const text = renderToolsSdk([bash], 'repl') - expect(text).toContain('run_code({ code: "console.log(await tools.bash(') + expect(text).toContain('run_code({ code: "inspect(await tools.bash(') expect(text).not.toContain('return await tools.bash(') expect(text).not.toContain('the body of an async TypeScript function') expect(text).not.toContain('Emit results with `return`') @@ -222,9 +233,10 @@ describe('renderToolsSdk', () => { expect(renderToolsSdk([constrained])).toContain('tools.bash({ command: \'pwd\' })') }) - it('uses a returned result in function-body mode', () => { + it('uses explicit inspection in function-body mode', () => { const text = renderToolsSdk([bash]) - expect(text).toContain('return await tools.bash(') + expect(text).toContain('inspect(await tools.bash(') + expect(text).toContain('- Show selected values and images with `inspect(...values)`; every other intermediate result stays out of the conversation, so extract just what you need.') expect(text).toContain('body of an async TypeScript function') expect(text).not.toContain('TypeScript REPL statements') }) diff --git a/packages/core/tool-executor-ptc/tsdown.config.ts b/packages/core/tool-executor-ptc/tsdown.config.ts new file mode 100644 index 0000000000..8733e57cfb --- /dev/null +++ b/packages/core/tool-executor-ptc/tsdown.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'tsdown' + +export default defineConfig({ + entry: { index: 'lib/types/index.js', 'run-code': 'lib/types/run-code.js' }, + outDir: 'lib', + format: ['esm'], + platform: 'node', + target: 'es2024', + fixedExtension: false, + dts: false, + clean: false, + outputOptions: { chunkFileNames: '_chunks/[name]-[hash].js' }, +}) diff --git a/packages/core/tools/package.json b/packages/core/tools/package.json index dde6ef26a5..5400908b84 100644 --- a/packages/core/tools/package.json +++ b/packages/core/tools/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tools", "description": "Tool registry and execution pipeline for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/credentials/authorization/package.json b/packages/credentials/authorization/package.json index 8a9da04f8f..1d9e87d0be 100644 --- a/packages/credentials/authorization/package.json +++ b/packages/credentials/authorization/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-authorization", "description": "Authorization seam (ctx.authorization): plugin-owned flows that obtain a credential through a conversation with the human", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/credentials/credentials-local/package.json b/packages/credentials/credentials-local/package.json index 2c1f4258b9..c435b250b3 100644 --- a/packages/credentials/credentials-local/package.json +++ b/packages/credentials/credentials-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-credentials-local", "description": "File-backed credentials provider ($DSH_HOME/.env under the live process environment) for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/credentials/credentials/package.json b/packages/credentials/credentials/package.json index 4589152305..bbf70265ee 100644 --- a/packages/credentials/credentials/package.json +++ b/packages/credentials/credentials/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-credentials", "description": "Abstract credential seam (ctx.credentials): settings carry references to secrets, providers own the values", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/credentials/deepseek-account/package.json b/packages/credentials/deepseek-account/package.json index 088b4e8106..d97c62d027 100644 --- a/packages/credentials/deepseek-account/package.json +++ b/packages/credentials/deepseek-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-deepseek-account", "description": "Sign in to DeepSeek and manage account credentials and notifications", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/deliverables/deliverable-file-references/package.json b/packages/deliverables/deliverable-file-references/package.json index c391c2aafc..16ea62e88d 100644 --- a/packages/deliverables/deliverable-file-references/package.json +++ b/packages/deliverables/deliverable-file-references/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-deliverable-file-references", "description": "Shared model guidance for file links and deliverables across DeepSeek Harness hosts", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/deliverables/tool-present/package.json b/packages/deliverables/tool-present/package.json index 241765b9ff..f69a8c46db 100644 --- a/packages/deliverables/tool-present/package.json +++ b/packages/deliverables/tool-present/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-present", "description": "Explicit workspace file delivery declarations for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/deliverables/workspace-changes/package.json b/packages/deliverables/workspace-changes/package.json index f75792f80b..25688bfc8a 100644 --- a/packages/deliverables/workspace-changes/package.json +++ b/packages/deliverables/workspace-changes/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-workspace-changes", "description": "Per-turn workspace file changes recorded from git working-tree snapshots and whole-file captures, with per-file comparisons, for the DeepSeek Harness", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/document/office-kit/package.json b/packages/document/office-kit/package.json index 1349791924..031c28116d 100644 --- a/packages/document/office-kit/package.json +++ b/packages/document/office-kit/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-office-kit", "description": "Shared Office rendering, conversion, and recalculation with bounded queues and caching", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/document/tool-office/package.json b/packages/document/tool-office/package.json index 52aeb942e4..f8928be263 100644 --- a/packages/document/tool-office/package.json +++ b/packages/document/tool-office/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-office", "description": "Model-facing Office tools for rendering, converting, and recalculating documents", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/document/tool-office/tests/activation.spec.ts b/packages/document/tool-office/tests/activation.spec.ts index 916a1fe6e0..71a954ef64 100644 --- a/packages/document/tool-office/tests/activation.spec.ts +++ b/packages/document/tool-office/tests/activation.spec.ts @@ -55,7 +55,7 @@ class SkillRuntime extends PtcRuntime { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } async run(request: PtcRunRequest): Promise { - return { logs: [], value: await request.bindings[0]!.functions.skill!({ name: this.skill }) } + return { output: [], value: await request.bindings[0]!.functions.skill!({ name: this.skill }) } } } diff --git a/packages/document/tool-office/tests/tool-office.spec.ts b/packages/document/tool-office/tests/tool-office.spec.ts index 85d33898ba..c52338b665 100644 --- a/packages/document/tool-office/tests/tool-office.spec.ts +++ b/packages/document/tool-office/tests/tool-office.spec.ts @@ -76,7 +76,7 @@ class CatalogAdapter extends LlmAdapter { class FakeRuntime extends PtcRuntime { readonly language = 'typescript' readonly isolation = 'fake' - behavior: (request: PtcRunRequest) => Promise = () => Promise.resolve({ logs: [] }) + behavior: (request: PtcRunRequest) => Promise = () => Promise.resolve({ output: [] }) resolve(request: PtcRunRequest): PtcRunSpec { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } @@ -648,12 +648,12 @@ describe('arguments and paths', () => { }) describe('PTC dispatch', () => { - it('forwards nested render images and applies execution policy to the nested call', async () => { + it('records nested render images and applies execution policy to the nested call', async () => { const { ctx } = await setup({ ptc: true }) const runtime = ctx.ptcRuntime as FakeRuntime runtime.behavior = async (request) => { - const value = await request.bindings[0]!.functions.office_render!({ input: 'deck.pptx' }) - return { logs: [], value } + await request.bindings[0]!.functions.office_render!({ input: 'deck.pptx' }) + return { output: [] } } const agent = { ...agentOn('vision'), ctx } await loadOffice(ctx, agent) @@ -663,9 +663,15 @@ describe('PTC dispatch', () => { signal, callId: ToolCallId(`run-${++calls}`), name: RUN_CODE_NAME, arguments: args, agent: agent as never, toolSet, }) - const result = await run({ code: 'return await tools.office_render({ input: "deck.pptx" })', description: 'Render' }) + const result = await run({ code: 'await tools.office_render({ input: "deck.pptx" })', description: 'Render' }) expect(result.isError).toBe(false) - expect(result.additionalContexts?.[0]?.content.some(block => block.type === 'image')).toBe(true) + const dispatch = agent.session.snapshotEvents().find(event => event.type === 'tool/ptc-dispatch') + expect(dispatch?.data.content.some(block => block.type === 'image')).toBe(true) + expect(result.content.some(block => block.type === 'image')).toBe(false) + expect(result.additionalContexts).toHaveLength(1) + expect(result.additionalContexts?.[0]).toMatchObject({ + source: { kind: 'ptc-mode' }, content: dispatch?.data.content, + }) const denied: string[] = [] ctx.on('tools/pre-execute', (exec, next) => { @@ -673,7 +679,7 @@ describe('PTC dispatch', () => { denied.push(exec.name) return Promise.resolve({ kind: 'deny' as const, reason: 'office denied by policy' }) }, { prepend: true }) - const refused = await run({ code: 'return await tools.office_render({ input: "deck.pptx" })', description: 'Render' }) + const refused = await run({ code: 'await tools.office_render({ input: "deck.pptx" })', description: 'Render' }) expect(denied).toEqual(['office_render']) expect(text(refused)).toContain('office denied by policy') }) diff --git a/packages/experimental/action-cards/package.json b/packages/experimental/action-cards/package.json index bc9f55715d..cfab384de5 100644 --- a/packages/experimental/action-cards/package.json +++ b/packages/experimental/action-cards/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-action-cards", "description": "Optional action cards below answers: one shared proposal tool, card state, user actions and status notices", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/api-speech-to-text/package.json b/packages/experimental/api-speech-to-text/package.json index dfe124dca3..7c2e0186af 100644 --- a/packages/experimental/api-speech-to-text/package.json +++ b/packages/experimental/api-speech-to-text/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-api-speech-to-text", "description": "Authenticated experimental speech transcription for browser clients", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/auto-review/package.json b/packages/experimental/auto-review/package.json index 93d2e4e982..f816d82969 100644 --- a/packages/experimental/auto-review/package.json +++ b/packages/experimental/auto-review/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-auto-review", "description": "Per-tool LLM authorization review for the DeepSeek Harness Auto permission preset", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "icon": "./icon.svg", "repository": { "type": "git", diff --git a/packages/experimental/badge-skill-bundle/package.json b/packages/experimental/badge-skill-bundle/package.json index 78b7cc2887..7ffd9b7304 100644 --- a/packages/experimental/badge-skill-bundle/package.json +++ b/packages/experimental/badge-skill-bundle/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-badge-skill-bundle", "description": "Let agents add a “powered by dsh” badge to documents, pull requests, and other outputs.", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/browser-use-chrome-devtools-mcp/package.json b/packages/experimental/browser-use-chrome-devtools-mcp/package.json index e0aeb645cb..c3e7ac3d7b 100644 --- a/packages/experimental/browser-use-chrome-devtools-mcp/package.json +++ b/packages/experimental/browser-use-chrome-devtools-mcp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-chrome-devtools-mcp", "description": "Experimental per-Session Chromium browser tools through chrome-devtools-mcp", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/browser-use-playwright-mcp/package.json b/packages/experimental/browser-use-playwright-mcp/package.json index f710257744..156be7b8b2 100644 --- a/packages/experimental/browser-use-playwright-mcp/package.json +++ b/packages/experimental/browser-use-playwright-mcp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-playwright-mcp", "description": "Experimental per-Session Chromium browser tools through @playwright/mcp", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/browser-use-runtime/package.json b/packages/experimental/browser-use-runtime/package.json index 24d0d467ed..40f4a1afa2 100644 --- a/packages/experimental/browser-use-runtime/package.json +++ b/packages/experimental/browser-use-runtime/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-runtime", "description": "Session-owned browser resource lifecycles and MCP integration for experimental providers", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/browser-use-stagehand-native/package.json b/packages/experimental/browser-use-stagehand-native/package.json index 6af18876c5..d801687524 100644 --- a/packages/experimental/browser-use-stagehand-native/package.json +++ b/packages/experimental/browser-use-stagehand-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-stagehand-native", "description": "Experimental Stagehand browser tools with separately configured native models", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/claude-code-mods/package.json b/packages/experimental/claude-code-mods/package.json index c2381389ae..b119c7778e 100644 --- a/packages/experimental/claude-code-mods/package.json +++ b/packages/experimental/claude-code-mods/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-claude-code-mods", "description": "Experimental bridge: load Claude Code mods (hooks modules) and run their hook chains on DeepSeek Harness extension points", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-action-cards/package.json b/packages/experimental/client-ui-action-cards/package.json index db4fe08b24..2db681106f 100644 --- a/packages/experimental/client-ui-action-cards/package.json +++ b/packages/experimental/client-ui-action-cards/package.json @@ -1,5 +1,5 @@ { - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-claude-code-mods/package.json b/packages/experimental/client-ui-claude-code-mods/package.json index a1cf702e44..9121201b9d 100644 --- a/packages/experimental/client-ui-claude-code-mods/package.json +++ b/packages/experimental/client-ui-claude-code-mods/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-claude-code-mods", "description": "Web band above the prompt for Claude Code mods: draws each session's mod tree and sends button presses back to the bridge", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-cot-translation/package.json b/packages/experimental/client-ui-cot-translation/package.json index 9c435f70f6..03916034d0 100644 --- a/packages/experimental/client-ui-cot-translation/package.json +++ b/packages/experimental/client-ui-cot-translation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-cot-translation", "description": "Optional machine translation of expanded reasoning, preserving original Session text", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-creation-recommendations/package.json b/packages/experimental/client-ui-creation-recommendations/package.json index 94a464d9f8..2afbb0cfe7 100644 --- a/packages/experimental/client-ui-creation-recommendations/package.json +++ b/packages/experimental/client-ui-creation-recommendations/package.json @@ -1,5 +1,5 @@ { - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 37b70c60d3..61b61e6dc9 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 6fc86067b4cf949e - zh: 04c9ba17de9839cc + en: c3fa707a638717e4 + zh: dfeba8a57c58a8aa /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 0feae5f8c5ef559f - zh: 5334adff35e3bebd + en: c9541603ea971f46 + zh: 15c41326e3fb29e4 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: bdbae9a42e0b79eb - zh: 0a1ec9f0c56f3ff2 + en: 913b4dd2cc8f2a40 + zh: 2794e247c0063717 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 69a9f9ced6..2d95507268 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -36,12 +36,12 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Code review and changes** — on the right-sidebar start page, opens the same change request tab as the Session header button. - **Header button** — appears when the Session has bound change requests or its directory is inside a Git checkout, and shows or hides the tab. A red dot marks an open change request with failed checks, requested changes, or conflicts. - **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. -- **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which 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 header button's red dot does. The card's header also offers Open in browser, Copy change request link, 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. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, whose count ends in `+` when the provider counted only some threads, and the merge state, or when a merged or closed one ended; and the changed lines, formatted in the selected UI language, whose row opens the changes view. An open draft also offers Ready for review; a change request the host would merge now offers Merge, 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 exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing. +- **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which 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 header button's red dot does. The card's header also offers Open in browser, Copy change request link, 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. 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. 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. An open draft also offers Ready for review; a change request the host would merge now offers Merge, 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 exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing. - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. -- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. 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. 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 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 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. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. +- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. 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. 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 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 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. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. -- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. A change of the file mode alone, such as `chmod +x`, also counts as a new change. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. -- **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers only Add to input, which quotes the whole thread, and View on GitHub. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none. +- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, as a ring filled to the viewed share and a label such as 2 / 3 viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. +- **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers Add to input, which quotes the whole thread, View on GitHub, and the writes the signed-in user may make. Without a pending review, its reply field replies at once, and its menu starts a pending review with the reply; with one, the field adds the reply to it, as GitHub adds every reply of the user to the pending review. Resolve thread and Unresolve thread change its state, and the menu of the user's own comment edits or deletes it after asking, saying when deleting the only comment deletes the thread. A resolved thread stays open while the user writes a reply or an edit in it. A write the code host refuses keeps the text and says why; a write whose outcome is unknown reads the threads again and asks the user to check them before trying again. Every write reads the threads again, since resolving a thread does not change a GitHub pull request's update time. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none. The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. @@ -49,7 +49,7 @@ The diff follows the file tree’s depth-first order: directories before files, `gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCachedReviewBytes`, `reviewRefreshMs`, `maxCommits`, `testPaths`, and `interfacePaths` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). -All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. The GitHub split button starts or adds to a pending review; its menu publishes a single comment immediately. Comments remain beside their code after quoting, queueing, or publishing. Pending comments are edited or removed there. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. Added and deleted files show only their populated line-number column. Pending reviews and comment records are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears its comments, summary, and decision, and reopening starts an empty review. Published GitHub comments and references already added to the main composer are unaffected. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. +All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. Several editors can stay open at once, and choosing the range of an open one focuses it again. In two columns, each comment sits under its own side of the row, so a left and a right comment share that row side by side, each continuing its line’s background. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. Once the review threads are read and the user may review, the GitHub split button starts the user's pending review on GitHub with the comment, or adds the comment to it; the comment then shows as a thread tagged Pending, which only the user sees until the review is submitted. Its menu publishes a single comment immediately, which GitHub refuses while the user has a pending review, so the menu is then absent. Agent references and published comments remain beside their code. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. With a pending review, it submits that review, keeping a submission whose outcome is unknown blocked until the user checks GitHub, as a direct submission is, and Discard review deletes the review and its comments after a confirmation; without one, it publishes the summary as one review. On the user's own pull request, which GitHub lets its author only comment on, Approve and Request changes are unavailable. Added and deleted files show only their populated line-number column. The summary, decision, and records of Agent references and published comments are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears them, and reopening starts an empty summary. The pending review, published GitHub comments, and references already added to the main composer are unaffected. Comment drafts an earlier version kept in this browser stay beside their code tagged Browser draft and can be edited, deleted, or added to the pending review; they keep Submit review disabled while a pending review exists, and without one Submit review publishes them with the summary. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. ----- @@ -72,6 +72,8 @@ Each inspection also decides whether the worktree is missing: the Session's dire `localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, a patch together with its `.gitattributes`, where a failed patch read cancels the attributes read and both reads end before the result, the patch's failure passing on before the attributes failure, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestReview` acts on the same visible bindings, refuses a head other than the latest status's with `forgePanel/stale-head` before reading, and reads the provider's `readReview`, mapping `stale` to `forgePanel/stale-head`, `unsupported` to `forgePanel/review-unsupported`, and other failures to `forgePanel/review-failed`. It keeps one read per change request, keyed by head commit and update time, drops the least recently read once the kept reads exceed `maxCachedReviewBytes` as JSON, and reads again once a kept read is `reviewRefreshMs` old or the reader refreshes the view, since resolving a GitHub thread leaves the update time unchanged. +`changeRequestViewed`, `setFileViewed`, `rerunChecks`, `requestReviews`, `reviewerCandidates`, and `updateBranch` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`. `changeRequestViewed` reads the provider's `viewedFiles` at the head commit of the shown diff and returns null when the provider keeps no viewed marks; a moved head refuses with `forgePanel/stale-head` and another failure with `forgePanel/viewed-failed`. `setFileViewed` saves one file's mark at that head through `setViewed`, and `rerunChecks` and `updateBranch` pass the head commit the card showed; a moved head refuses each of them with `forgePanel/stale-head`, another refusal with `forgePanel/action-failed` and the host's reason, and an outcome the host did not confirm with `forgePanel/action-unknown`. `requestReviews` asks one or more reviewers at once, refusing an empty list or an empty login, and `reviewerCandidates` lists the accounts that match a search, refusing with `forgePanel/reviewers-failed` when the host does not list them. The changes view reads a change request's viewed marks beside its diff, refuses marks read at another head as it refuses such a diff, and lets [`src/client/host-viewed.ts`](src/client/host-viewed.ts) keep each mark the reader sets per change request and head: a read at the same head keeps the marks whose writes are in flight, a mark whose write settled stays until the next read, and a write that settles after a diff at another head loaded changes nothing in it. + `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. @@ -89,6 +91,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/layers.ts`](src/layers.ts) | Review layers from path globs and `linguist-generated` attributes | | [`src/client/mount.ts`](src/client/mount.ts) | Remote mount, slot entries, and action outcome mapping | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | Reusable change request card | +| [`src/client/ChangeRequestOverview.tsx`](src/client/ChangeRequestOverview.tsx) | Checks, review, merge, and linked issue rows with their menus | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | Local changes card | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | Changes view | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | Base branch menu of the Branch scope | @@ -102,6 +105,8 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/client/review-threads.ts`](src/client/review-threads.ts) | Thread places, list filters, hunk excerpts, and thread quotes | | [`src/client/thread-state.ts`](src/client/thread-state.ts) | Thread reads and their places in the shown changes | | [`src/review-cache.ts`](src/review-cache.ts) | Review threads kept in memory | +| [`src/client/host-viewed.ts`](src/client/host-viewed.ts) | Viewed marks the code host keeps, with marks being saved | +| [`src/client/menu-search.ts`](src/client/menu-search.ts) | Keys of the search field at the top of a menu | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | Worktree creation and removed-worktree card | @@ -148,8 +153,8 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. - **Undrawn files** — until the reader scrolls near an expanded file, it holds 22 px per drawn line, which leaves out side-by-side pairing, wrapped lines, unchanged-line rows, and review cards, so the scroll range shifts a little as files draw; its saved review comments also appear only once it draws. - **Find in page over long diffs** — an expanded file draws its lines only once the reader scrolls near it, so the browser's find in page does not match lines of files further down until they are drawn; a page-wide search of the diff needs a find control of the view's own. -- **Viewed files on the code host** — viewed marks of a change request stay in this browser and are not read from or written to GitHub's viewed state (`markFileAsViewed`) until the provider's review operations exist; another browser or device starts without them. -- **Review thread actions** — threads are read-only: replying, resolving, and editing comments, and drafts in GitHub's pending review, are deferred to the provider's review writes. Minimized comments show like others, and avatars load from the code host's image server in the browser. +- **Viewed files on the code host** — GitHub keeps one viewed mark per file and user, not one per commit, so marks in a view of chosen commits stay in this browser, and another browser or device starts without them. A file beyond the provider's `maxViewedFiles` shows no mark from GitHub until it is marked in this view. +- **Review thread writes** — a write through one changes view shows in other open views of the change request at their next status, or after `reviewRefreshMs` for a resolve, which does not change the pull request's update time. GitHub keeps one pending review per user and pull request. A comment draft an earlier version kept in the browser can join the pending review only while its file and lines still match the shown diff; otherwise it can only be edited or deleted. A comment on chosen commits can only be added to the input. Minimized comments show like others, and avatars load from the code host's image server in the browser. - **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. - **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 1419a8ea97..c7f9d4b994 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -36,12 +36,12 @@ kind: "package-reference" - **代码审查和变更**——右侧栏起始页中的入口,与会话标题栏按钮打开同一个变更请求标签页。 - **标题栏按钮**——Session 有已绑定的变更请求、或其目录位于 Git 检出中时出现,用来显示或隐藏标签页。打开状态的变更请求存在检查失败、被要求修改或冲突时,按钮带红点。 - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 -- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`)、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 +- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 -- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 +- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 -- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。只改文件模式(例如 `chmod +x`)也算新改动。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 -- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上只有“添加到输入框”(把整个讨论作为引用插入)和“在 GitHub 中查看”两个操作。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 +- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 +- **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 @@ -49,7 +49,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后 `gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`maxCommits`、`testPaths` 与 `interfacePaths` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 -“全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。GitHub 分段按钮用于开始或加入待提交评审,下拉菜单可以立即发布单条评论。评论在引用、暂存或发布后保留在对应代码旁,暂存评论可在那里编辑或删除。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。新建和删除文件只显示有内容的一侧行号。待提交评审与评论记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空该页签的评论、总结与评审决定,重新打开从空评审开始。已发布到 GitHub 的评论与已加入主输入框的引用不受影响。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 +“全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。可以同时打开多个评论框,再次选中已打开评论框的范围会回到该评论框。两栏时每条评论位于该行自己一侧的下方,左右两侧的评论并排处在同一行,各自延续所在行的底色。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。读到评审讨论且用户可以评审时,GitHub 分段按钮会用这条评论在 GitHub 上开始用户的待提交评审,或把评论加入其中;评论随后显示为带“待提交”标签的讨论,提交评审之前只有用户自己能看到。下拉菜单可以立即发布单条评论;用户有待提交评审时 GitHub 会拒绝单条评论,因此这时没有该菜单。Agent 引用和已发布的评论保留在对应代码旁。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。有待提交评审时提交该评审,结果不明的提交与直接提交一样,在用户到 GitHub 核对之前阻止再次提交;“丢弃评审”在确认后删除该评审及其中的评论;没有待提交评审时,把总结作为一次评审发布。在用户自己的 PR 上,GitHub 只允许作者评论,因此“批准”和“请求更改”不可用。新建和删除文件只显示有内容的一侧行号。总结、评审决定,以及 Agent 引用与已发布评论的记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空它们,重新打开从空总结开始。待提交评审、已发布到 GitHub 的评论与已加入主输入框的引用不受影响。早期版本保存在此浏览器中的评论草稿保留在对应代码旁,带“浏览器草稿”标签,可以编辑、删除或加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”把它们连同总结一起发布。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 ----- @@ -72,6 +72,8 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,补丁与它的 `.gitattributes` 同时读取,补丁读取失败时取消 `.gitattributes` 的读取,两者都结束后才给出结果,补丁的失败优先于 `.gitattributes` 的失败,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。`changeRequestReview` 同样只作用于可见的绑定;head 与最新状态的 head 不同时,读取前就以 `forgePanel/stale-head` 拒绝;随后调用提供方的 `readReview`,把 `stale` 映射为 `forgePanel/stale-head`、`unsupported` 映射为 `forgePanel/review-unsupported`、其余失败映射为 `forgePanel/review-failed`。每个变更请求保留一次读取结果,以 head 提交和更新时间为键;保留的结果按 JSON 计超过 `maxCachedReviewBytes` 时,最久未读的先被丢弃;保留时间达到 `reviewRefreshMs` 后,或读者刷新视图时,重新读取,因为解决 GitHub 讨论不会改变更新时间。 +`changeRequestViewed`、`setFileViewed`、`rerunChecks`、`requestReviews`、`reviewerCandidates` 与 `updateBranch` 只作用于 Session 可见且有提供方服务的绑定,否则以 `forgePanel/not-bound` 拒绝。`changeRequestViewed` 在所示 diff 的 head 提交上读取提供方的 `viewedFiles`,提供方不保存已审阅标记时返回 null;head 已移动时以 `forgePanel/stale-head` 拒绝,其他失败以 `forgePanel/viewed-failed` 拒绝。`setFileViewed` 经 `setViewed` 在该 head 上保存一个文件的标记,`rerunChecks` 与 `updateBranch` 传入卡片显示的 head 提交;head 已移动时它们都以 `forgePanel/stale-head` 拒绝,其他拒绝以 `forgePanel/action-failed` 并附托管平台的原因,托管平台未确认的结果以 `forgePanel/action-unknown` 拒绝。`requestReviews` 一次向一位或多位评审者请求评审,拒绝空列表与空登录名;`reviewerCandidates` 列出与搜索匹配的账号,托管平台未列出时以 `forgePanel/reviewers-failed` 拒绝。变更视图随变更请求的 diff 一起读取其已审阅标记,像拒绝在其他 head 上读取的 diff 一样拒绝这类标记,并由 [`src/client/host-viewed.ts`](src/client/host-viewed.ts) 按变更请求与 head 保存读者设置的每个标记:同一 head 重新读取时保留仍在写入的标记,写入已结束的标记保留到下次读取,另一个 head 的 diff 加载后才结束的写入不会改动它。 + `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。 @@ -89,6 +91,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/layers.ts`](src/layers.ts) | 按路径 glob 与 `linguist-generated` 属性分层 | | [`src/client/mount.ts`](src/client/mount.ts) | Remote 挂载、slot 条目与操作结果映射 | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | 可复用的变更请求卡片 | +| [`src/client/ChangeRequestOverview.tsx`](src/client/ChangeRequestOverview.tsx) | 检查、评审、合并与关联 issue 行及其菜单 | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | 本地变更卡片 | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | “分支”范围的基准分支菜单 | @@ -102,6 +105,8 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/client/review-threads.ts`](src/client/review-threads.ts) | 讨论位置、列表筛选、hunk 摘录与讨论引用 | | [`src/client/thread-state.ts`](src/client/thread-state.ts) | 读取讨论并确定它们在所显示变更中的位置 | | [`src/review-cache.ts`](src/review-cache.ts) | 保存在内存中的评审讨论 | +| [`src/client/host-viewed.ts`](src/client/host-viewed.ts) | 代码托管平台保存的已审阅标记,以及正在保存的标记 | +| [`src/client/menu-search.ts`](src/client/menu-search.ts) | 菜单顶部搜索框的按键处理 | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 | @@ -148,8 +153,8 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 - **尚未绘制的文件**——读者滚动到展开的文件附近之前,它按每个绘制行 22 px 占位,没有计入左右对比的配对、自动换行、未变更行按钮和评审卡片,所以文件绘制时滚动范围会略有变化;它已保存的评审评论也要等它绘制后才显示。 - **长 diff 中的页内查找**——展开的文件要等读者滚动到附近才绘制各行,所以浏览器的页内查找在更靠后的文件绘制之前匹配不到它们的行;要在整个 diff 中查找,需要视图自己的查找控件。 -- **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。 -- **评审讨论的操作**——讨论是只读的:回复、解决、编辑评论,以及 GitHub 待提交评审中的草稿,留待提供方的评审写入能力实现。被折叠隐藏的评论与其他评论显示方式相同;头像由浏览器从代码托管平台的图片服务器加载。 +- **代码托管平台上的已审阅状态**——GitHub 对每个文件和用户只保存一个已审阅标记,不按提交区分,因此所选提交视图中的标记只保存在本浏览器中,换浏览器或设备后没有这些标记。超出提供方 `maxViewedFiles` 的文件在本视图中标记之前不显示 GitHub 上的标记。 +- **评审讨论的写入**——在一个变更视图中的写操作,会在该变更请求的其他已打开视图收到下一次状态时显示;解决讨论不会改变 pull request 的更新时间,要等到 `reviewRefreshMs` 之后才显示。GitHub 每个用户在每个 pull request 上只保留一个待提交评审。早期版本保存在浏览器中的评论草稿,只有其文件和行仍与所显示的 diff 一致时才能加入待提交评审,否则只能编辑或删除。对所选提交的评论只能添加到输入框。被折叠隐藏的评论与其他评论显示方式相同;头像由浏览器从代码托管平台的图片服务器加载。 - **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 - **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/package.json b/packages/experimental/client-ui-forge/package.json index 8dd840d825..755e0192e0 100644 --- a/packages/experimental/client-ui-forge/package.json +++ b/packages/experimental/client-ui-forge/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-forge", "description": "Sidebar panel for a Session's change requests, with a worktree option for new Sessions and its Host Remote", - "version": "0.2.2-rc.1", + "version": "0.2.2-rc.2", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx index 9125fef677..0bcabc3408 100644 --- a/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx +++ b/packages/experimental/client-ui-forge/src/client/BaseMenu.tsx @@ -10,6 +10,7 @@ import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import type { ForgeBaseBranch, ForgeBaseBranches } from '../types.ts' import type { NS } from './locales.ts' +import { searchFieldKeyDown } from './menu-search.ts' import css from './BaseMenu.module.css' /** Milliseconds between the last keystroke of a search and the listing it reads. */ @@ -169,12 +170,7 @@ export function BaseMenu({ chosen, label, missing, visible, list, choose, t }: B } value={query} aria-label={t('diff.base.search')} placeholder={t('diff.base.search')} onChange={(event) => { setQuery(event.target.value) }} - onKeyDown={(event) => { - if (['Home', 'End', 'ArrowLeft', 'ArrowRight'].includes(event.key)) event.stopPropagation() - if (event.key !== 'Enter' || event.nativeEvent.isComposing || first === undefined) return - event.preventDefault() - pick(first.base) - }} /> + onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { pick(first.base) }) }} />
{body}
{t('diff.base.note')}
diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index a5f1abbab2..4e455c1037 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -1,33 +1,36 @@ /** * One change request as a card: its title links to the host, a one-line - * summary shows while collapsed, and while expanded one row per fact (checks, - * review, merge state, and the changed lines, which open its changes) above - * the ready-for-review or merge action. + * summary shows while collapsed, and while expanded one sentence per fact + * (checks, review, merge state, the changed lines, which open its changes, and + * the linked issues) above the ready-for-review or merge action. */ -import { useEffect, useState, type ReactNode } from 'react' +import { useId, useState, type ReactNode } from 'react' import clsx from 'clsx' import { - Button, IconChevronDownOutlineRegular, IconChevronRightOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular, - IconListPenOutlineRegular, IconRightUpOutlineRegular, IconTriangleRightFillRegular, IconUserOutlineRegular, Menu, MenuItemButton, - StateDot, Tooltip, + Button, IconChevronDownOutlineRegular, IconCloseOutlineRegular, IconCopyOutlineRegular, IconListPenOutlineRegular, + IconRightUpOutlineRegular, IconTriangleRightFillRegular, Menu, MenuItemButton, StateDot, Tooltip, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { - ChangeRequestCheck, ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, MergeMethod, MergeRequest, + ChangeRequestSnapshot, CheckState, ChecksRollup, ForgeFailure, MergeMethod, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge/types' import type { ForgePanelChangeRequest } from '../types.ts' -import { formatAgo, formatDuration } from './format.ts' +import { ChecksRow, IssuesRow, MergeRow, ReviewRow, RowParts, ThreadGlyph, type OverviewActions } from './ChangeRequestOverview.tsx' +import { formatAgo } from './format.ts' import { ChangeRequestGlyph, CheckGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' -import { checkCounts, checkDuration, ciSummary, flagOf, numberOf, TONE_LABEL, toneOf } from './status.ts' +import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf } from './status.ts' import css from './ForgeTab.module.css' type Translate = PropsLocale['t'] -/** What a card can do; a surface without a Session binding omits `remove`, `markReady`, `merge`, and `viewChanges`. */ -export interface ChangeRequestActions { +/** + * What a card can do; a surface without a Session binding omits `remove`, `markReady`, `merge`, `viewChanges`, and the + * overview actions. + */ +export interface ChangeRequestActions extends OverviewActions { /** Open a URL outside the app. */ readonly openLink: (url: string) => void /** Copy a URL to the clipboard. */ @@ -87,10 +90,6 @@ const ROLLUP: Record = { failure: 'failure', } -const CHECK_RANK: Record = { - failure: 0, pending: 1, success: 2, neutral: 3, skipped: 3, cancelled: 3, -} - /** The unresolved thread count, with `+` when the provider counted only some threads. */ function threadCount(snapshot: ChangeRequestSnapshot, locale: string): string { const count = snapshot.unresolvedThreads.toLocaleString(locale) @@ -101,17 +100,6 @@ function failureOf(entry: ForgePanelChangeRequest): ForgeFailure | undefined { return entry.update !== null && 'failure' in entry.update ? entry.update.failure : undefined } -/** Failed checks first, then running ones, then the rest, each group in host order. */ -function orderedChecks(checks: readonly ChangeRequestCheck[]): ChangeRequestCheck[] { - return checks.toSorted((left, right) => CHECK_RANK[left.state] - CHECK_RANK[right.state]) -} - -function checkTime(check: ChangeRequestCheck, t: Translate): string { - if (check.state === 'pending') return t(check.startedAt === null ? 'change.check.queued' : 'change.check.running') - const elapsed = checkDuration(check) - return elapsed === undefined ? '' : formatDuration(elapsed, t) -} - function DiffSize({ snapshot, locale }: { readonly snapshot: ChangeRequestSnapshot; readonly locale: string }): ReactNode { return ( @@ -121,7 +109,10 @@ function DiffSize({ snapshot, locale }: { readonly snapshot: ChangeRequestSnapsh ) } -/** The changed lines, as a row that opens the changes view when the provider serves the change request. */ +/** + * The changed lines with the unresolved review thread count, as a row that opens the changes view when the provider + * serves the change request. + */ function ChangesRow({ entry, snapshot, name, actions, locale, t }: { readonly entry: ForgePanelChangeRequest readonly snapshot: ChangeRequestSnapshot @@ -131,14 +122,24 @@ function ChangesRow({ entry, snapshot, name, actions, locale, t }: { readonly t: Translate }): ReactNode { const { viewChanges } = actions + const described = useId() + const threads = snapshot.unresolvedThreads > 0 || snapshot.threadsTruncated ? threadCount(snapshot, locale) : undefined + const threadsText = threads === undefined ? undefined : t('change.threads', { count: threads }) + const trailing = threadsText === undefined ? undefined : ( + + + + ) + const opens = viewChanges !== undefined && entry.ref !== null + // The count shows only a number, so the threads are named in full for assistive technology. const parts = ( <> - - {t('change.row.changes')} - + } + value={} trailing={trailing} opens={opens} /> + {threadsText !== undefined && {threadsText}} ) - if (viewChanges === undefined || entry.ref === null) return
{parts}
+ if (!opens) return
{parts}
return ( ) } @@ -198,105 +199,6 @@ function Target({ snapshot, t }: { readonly snapshot: ChangeRequestSnapshot; rea ) } -type CheckRead = { readonly kind: 'idle' | 'loading' } - | { readonly kind: 'ready'; readonly snapshot: ChangeRequestSnapshot } - | { readonly kind: 'failed'; readonly message: string } - -function ChecksRow({ snapshot, openLink, readChecks, t }: { - readonly snapshot: ChangeRequestSnapshot - readonly openLink: (url: string) => void - readonly readChecks: ChangeRequestActions['readChecks'] - readonly t: Translate -}): ReactNode { - const [open, setOpen] = useState(false) - const [read, setRead] = useState({ kind: 'idle' }) - const [attempt, setAttempt] = useState(0) - const { url, headSha, checksTruncated } = snapshot - useEffect(() => { - if (!open || !checksTruncated || readChecks === undefined) { setRead({ kind: 'idle' }); return } - const controller = new AbortController() - setRead({ kind: 'loading' }) - void (async () => { - try { - const result = await readChecks(url, headSha, controller.signal) - if (!controller.signal.aborted) setRead({ kind: 'ready', snapshot: result }) - } catch (error) { - if (!controller.signal.aborted) setRead({ kind: 'failed', message: error instanceof Error ? error.message : String(error) }) - } - })() - return () => { controller.abort() } - }, [open, url, headSha, checksTruncated, readChecks, attempt]) - const displayed = read.kind === 'ready' && read.snapshot.headSha === headSha ? read.snapshot : snapshot - if (displayed.checks.length === 0 && !displayed.checksTruncated) { - return ( -
- - {t('change.row.checks')} - {t('change.ci.none')} -
- ) - } - const counts = checkCounts(displayed.checks) - const summary = displayed.checksTruncated ? t('change.checks.truncated', { count: displayed.checks.length }) : [ - ...counts.failed > 0 ? [t('change.checks.failed', { count: counts.failed })] : [], - ...counts.running > 0 ? [t('change.checks.running', { count: counts.running })] : [], - ...counts.passed > 0 ? [t('change.checks.passed', { count: counts.passed })] : [], - ...counts.cancelled > 0 ? [t('change.checks.cancelled', { count: counts.cancelled })] : [], - ...counts.other > 0 ? [t('change.checks.other', { count: counts.other })] : [], - ].join(' · ') - const close = (): void => { setOpen(false) } - const footer: MenuEntry[] = displayed.checksTruncated - ? [{ type: 'label', id: 'truncated', text: t('change.checks.truncated', { count: displayed.checks.length }) }] : [] - if (read.kind === 'loading') footer.push({ id: 'loading', label: t('change.checks.loading'), disabled: true, icon: }) - if (read.kind === 'failed') { - footer.push({ type: 'label', id: 'failed', text: t('change.checks.loadFailed', { message: read.message }) }, - { id: 'retry', label: t('change.checks.retry') }) - } - return ( - { setOpen(!open) }}> - - {t('change.row.checks')} - 0 ? 'error' : undefined}> - {summary} - - - - )} - footer={footer} - onSelect={() => { setAttempt(value => value + 1) }} - > - {orderedChecks(displayed.checks).map((check, index) => { - const { url } = check - return ( - } - disabled={url === null} - onSelect={url === null ? close : () => { - close() - openLink(url) - }} - > - - {check.name} - {checkTime(check, t)} - - - ) - })} - - ) -} - /** The merge button and its menu: a title row, one row per method with the chosen one checked, and the confirmation. */ function MergeMenu({ snapshot, name, usual, busy, onMerge, t }: { readonly snapshot: ChangeRequestSnapshot @@ -423,8 +325,8 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: { return (
- - {finished(snapshot, now, t)} + } + value={finished(snapshot, now, t)} tone={snapshot.state} opens={false} />
{changes}
@@ -437,21 +339,15 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: { : snapshot.mergeability === 'conflicting' ? t('change.merge.conflicting', { base: snapshot.baseBranch }) : t('change.merge.unknown') return (
- -
- - {t('change.row.review')} - - {snapshot.unresolvedThreads > 0 || snapshot.threadsTruncated - ? t('change.review.threads', { review, count: threadCount(snapshot, locale) }) : review} - -
-
- - {t('change.row.merge')} - {merge} -
+ + + } + tone={snapshot.mergeability === 'conflicting' ? 'error' : undefined} t={t} /> {changes} +
) } diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css new file mode 100644 index 0000000000..3f0cc3ba36 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.module.css @@ -0,0 +1,196 @@ +/* Overview rows of an expanded change request card and the menus they open. */ + +/* A row that anchors its menu keeps the card's row grid. */ +.rowAnchor { + display: grid; + grid-column: 1 / -1; + grid-template-columns: subgrid; +} + +/* Overlapping reviewer avatars at the end of the review row. */ +.avatars { + display: inline-flex; + align-items: center; +} + +.avatars > .avatar + .avatar { + margin-left: -5px; +} + +.avatars > .avatar { + box-shadow: 0 0 0 1.5px var(--dsw-alias-bg-layer-1); +} + +.moreCount { + margin-left: 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + font-variant-numeric: tabular-nums; +} + +.avatar { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + box-sizing: border-box; + border-radius: 50%; + corner-shape: round; + background: var(--dsw-alias-interactive-bg-active); + color: var(--dsw-alias-label-secondary); + font-size: 10px; + font-weight: 600; + line-height: 1; + object-fit: cover; +} + +/* The update action named at the end of the merge row. */ +.action { + color: var(--dsw-alias-link); + white-space: nowrap; +} + +.menu { + width: min(300px, calc(100vw - 24px)); + max-height: min(420px, calc(100vh - 48px)); +} + +.menuLabel { + padding: 6px 8px 2px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 15px; +} + +.menuStatus { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 6px 8px; + color: var(--dsw-alias-label-secondary); + font-size: 12px; +} + +.check { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + min-width: 0; +} + +.checkTime { + flex: none; + margin-left: auto; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +/* A reviewer is information, not a choice, so it sits in the menu's row geometry without a hover. */ +.reviewer { + display: flex; + align-items: center; + gap: 8px; + min-height: 32px; + padding: 0 8px; + font-size: 12px; +} + +.who { + display: inline-flex; + flex: 1; + align-items: baseline; + gap: 6px; + min-width: 0; + color: var(--dsw-alias-label-primary); +} + +.kind { + flex: none; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + white-space: nowrap; +} + +/* The outcome, then a note when it was given on an older commit, on one line. */ +.outcome { + display: inline-flex; + flex: none; + align-items: baseline; + gap: 4px; + color: var(--dsw-alias-label-secondary); + white-space: nowrap; +} + +.outcome [data-tone='success'] { + color: var(--dsw-alias-state-success-primary); +} + +.outcome [data-tone='error'] { + color: var(--dsw-alias-state-error-primary); +} + +.outcome [data-tone='pending'] { + color: var(--dsw-alias-state-warn-label); +} + +.older { + color: var(--dsw-alias-label-tertiary); + font-size: 11px; +} + +.older::before { + content: '· '; +} + +.menuSearch { + padding: 4px 4px 6px; +} + +.menuRows { + max-height: 280px; + overflow: auto; +} + +.candidate { + display: flex; + align-items: baseline; + gap: 6px; + min-width: 0; +} + +.badge { + flex: none; + padding: 0 5px; + border-radius: var(--dsw-radius-xs); + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-secondary); + font-size: 11px; + line-height: 17px; +} + +/* An issue the change request closes, named by its number; a closed one takes the merged tone. */ +.issue { + border-radius: var(--dsw-radius-xs); + color: var(--dsw-alias-link); + font-variant-numeric: tabular-nums; + text-decoration: none; +} + +.issue[data-state='closed'] { + color: var(--dsw-alias-state-done-primary); +} + +@media (hover: hover) { + .issue:hover { + text-decoration: underline; + text-underline-offset: 2px; + } +} + +.issue:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx new file mode 100644 index 0000000000..4fb047f74d --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx @@ -0,0 +1,620 @@ +/** + * Overview rows of an expanded change request card, each one line: the checks outcome, the review decision with the + * reviewers' avatars, the merge state, and the issues linked to the change request. Details and actions open in a menu + * from the row: the checks grouped by outcome with the rerun of the failed ones, the reviewers with review requests, + * and the branch update. + */ + +import { useEffect, useRef, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { + Button, IconChevronRightOutlineRegular, IconPlusOutlineRegular, IconRefreshOutlineRegular, IconSearchOutlineRegular, + IconUserOutlineRegular, Input, Menu, MenuItemButton, StateDot, Tooltip, + type MenuEntry, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { + BranchUpdateMethod, BranchUpdateRequest, ChangeRequestCheck, ChangeRequestIssue, ChangeRequestReviewer, ChangeRequestSnapshot, + ForgeRerunRequest, ForgeReviewerCandidate, ReviewVerdict, +} from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgePanelChangeRequest } from '../types.ts' +import { formatDuration } from './format.ts' +import { CheckGlyph } from './glyphs.tsx' +import type { ForgePanelKey, NS } from './locales.ts' +import { checkCounts, checkDuration } from './status.ts' +import { searchFieldKeyDown } from './menu-search.ts' +import css from './ForgeTab.module.css' +import overview from './ChangeRequestOverview.module.css' + +type Translate = PropsLocale['t'] + +/** Milliseconds between the last keystroke of a reviewer search and the listing it reads. */ +const SEARCH_DELAY_MS = 150 + +/** Avatars the review row shows before it counts the rest. */ +const AVATARS = 3 + +/** Requests reviews of a change request from more reviewers; settles once the outcome is reported. */ +type RequestReviews = (entry: ForgePanelChangeRequest, reviewers: readonly Pick[]) => Promise + +/** Lists the accounts a review of the change request at `url` can be requested from. */ +type ListCandidates = (url: string, query: string, signal: AbortSignal) => Promise + +/** Overview actions of a card; a surface without a Session binding omits them. */ +export interface OverviewActions { + /** Rerun the failed checks; settles once the outcome is reported. */ + readonly rerunChecks?: ((entry: ForgePanelChangeRequest, request: ForgeRerunRequest) => Promise) | undefined + /** Request reviews from more reviewers; settles once the outcome is reported. */ + readonly requestReviews?: RequestReviews | undefined + /** List accounts a review can be requested from; rejects with the host's reason. */ + readonly reviewerCandidates?: ListCandidates | undefined + /** Bring the base branch's new commits into the head branch; settles once the outcome is reported. */ + readonly updateBranch?: ((entry: ForgePanelChangeRequest, request: BranchUpdateRequest) => Promise) | undefined +} + +/** One action at a time per control: it stays disabled until the previous action settles. */ +function useBusy(): readonly [boolean, (action: () => Promise) => void] { + const [busy, setBusy] = useState(false) + return [busy, (action) => { + setBusy(true) + void action().finally(() => { setBusy(false) }) + }] +} + +/** + * The parts of one fact row: its glyph, its one-line value after the fact's name, which only assistive technology + * reads unless the value names the fact itself, an optional trailing part, and the chevron of a row that opens something. + * @param props - the fact's name for assistive technology, the glyph, the value with its tone, the trailing part, and + * whether the row opens something. + * @returns the row's cells. + */ +export function RowParts({ label, icon, value, tone, trailing, opens }: { + readonly label: string | undefined + readonly icon: ReactNode + readonly value: ReactNode + readonly tone?: string | undefined + readonly trailing?: ReactNode + readonly opens: boolean +}): ReactNode { + return ( + <> + {icon} + + {label !== undefined && {label}} + {value} + + {trailing !== undefined && {trailing}} + {opens && } + + ) +} + +type CheckGroup = 'failed' | 'running' | 'cancelled' | 'passed' | 'other' + +/** Groups that need attention, listed whenever the menu opens. */ +const ATTENTION: readonly CheckGroup[] = ['failed', 'running', 'cancelled'] + +/** Groups the menu lists only on request. */ +const QUIET: readonly CheckGroup[] = ['passed', 'other'] + +const GROUP_LABEL: Record = { + failed: 'checks.group.failed', + running: 'checks.group.running', + cancelled: 'checks.group.cancelled', + passed: 'checks.group.passed', + other: 'checks.group.other', +} + +function groupOf(check: ChangeRequestCheck): CheckGroup { + switch (check.state) { + case 'failure': return 'failed' + case 'pending': return 'running' + case 'success': return 'passed' + case 'cancelled': return 'cancelled' + case 'neutral': + case 'skipped': return 'other' + } +} + +function checkTime(check: ChangeRequestCheck, t: Translate): string { + if (check.state === 'pending') return t(check.startedAt === null ? 'change.check.queued' : 'change.check.running') + const elapsed = checkDuration(check) + return elapsed === undefined ? '' : formatDuration(elapsed, t) +} + +/** The checks outcome in a few words: what needs attention, else that all passed. */ +function checksValue(snapshot: ChangeRequestSnapshot, t: Translate): string { + if (snapshot.checksTruncated) return t('change.checks.truncated', { count: snapshot.checks.length }) + const counts = checkCounts(snapshot.checks) + const parts = [ + ...counts.failed > 0 ? [t('change.checks.failed', { count: counts.failed })] : [], + ...counts.running > 0 ? [t('change.checks.running', { count: counts.running })] : [], + ...counts.cancelled > 0 ? [t('change.checks.cancelled', { count: counts.cancelled })] : [], + ] + return parts.length > 0 ? parts.join(' · ') : t('checks.allPassed', { count: counts.passed + counts.other }) +} + +type CheckRead = { readonly kind: 'idle' | 'loading' } + | { readonly kind: 'ready'; readonly snapshot: ChangeRequestSnapshot } + | { readonly kind: 'failed'; readonly message: string } + +/** Props of the checks row. */ +export interface ChecksRowProps { + readonly entry: ForgePanelChangeRequest + readonly snapshot: ChangeRequestSnapshot + readonly openLink: (url: string) => void + /** Load complete check details independently of polling; cancellation follows the open menu. */ + readonly readChecks: ((url: string, headSha: string, signal: AbortSignal) => Promise) | undefined + readonly rerunChecks: OverviewActions['rerunChecks'] + readonly t: Translate +} + +/** + * Whether a failed check names a rerun that none of the checks sharing it still waits for, as a rerun of checks in + * progress cannot start. + * @param checks - the checks of the head commit. + * @returns whether a rerun of failed checks can start. + */ +function rerunnable(checks: readonly ChangeRequestCheck[]): boolean { + const running = new Set(checks.flatMap(check => check.state === 'pending' && check.rerun !== null ? [check.rerun] : [])) + return checks.some(check => check.state === 'failure' && check.rerun !== null && !running.has(check.rerun)) +} + +/** + * Render the checks outcome as a row whose menu lists the failed, running, and cancelled checks by group, offers to + * rerun the failed ones, and lists the passed and skipped ones on request. A list the poll read only in part is + * completed while the menu is open. + * @param props - the change request, its snapshot, the link and read actions, the rerun action, and copy. + * @returns the row with its menu. + */ +export function ChecksRow({ entry, snapshot, openLink, readChecks, rerunChecks, t }: ChecksRowProps): ReactNode { + const [open, setOpen] = useState(false) + const [quiet, setQuiet] = useState(false) + const [read, setRead] = useState({ kind: 'idle' }) + const [attempt, setAttempt] = useState(0) + const [busy, run] = useBusy() + const { url, headSha, checksTruncated } = snapshot + useEffect(() => { + if (!open || !checksTruncated || readChecks === undefined) { setRead({ kind: 'idle' }); return } + const controller = new AbortController() + setRead({ kind: 'loading' }) + void (async () => { + try { + const result = await readChecks(url, headSha, controller.signal) + if (!controller.signal.aborted) setRead({ kind: 'ready', snapshot: result }) + } catch (error) { + if (!controller.signal.aborted) setRead({ kind: 'failed', message: error instanceof Error ? error.message : String(error) }) + } + })() + return () => { controller.abort() } + }, [open, url, headSha, checksTruncated, readChecks, attempt]) + const displayed = read.kind === 'ready' && read.snapshot.headSha === headSha ? read.snapshot : snapshot + if (displayed.checks.length === 0 && !displayed.checksTruncated) { + return
} value={t('change.ci.none')} opens={false} />
+ } + const counts = checkCounts(displayed.checks) + const rerun = displayed.state === 'open' && displayed.canRerunChecks && rerunnable(displayed.checks) ? rerunChecks : undefined + const groups = (list: readonly CheckGroup[]): { readonly group: CheckGroup; readonly checks: ChangeRequestCheck[] }[] => + list.map(group => ({ group, checks: displayed.checks.filter(check => groupOf(check) === group) })) + .filter(({ checks }) => checks.length > 0) + const quietCount = counts.passed + counts.other + const close = (): void => { + setOpen(false) + setQuiet(false) + } + const rows = (list: readonly CheckGroup[]): ReactNode => groups(list).map(({ group, checks }) => ( +
+
{`${t(GROUP_LABEL[group])} · ${checks.length}`}
+ {checks.map((check, index) => { + const link = check.url + return ( + // The list is replaced as a whole with each snapshot, and check names can repeat. + } disabled={link === null} + onSelect={link === null ? close : () => { + close() + openLink(link) + }}> + + {check.name} + {checkTime(check, t)} + + + ) + })} +
+ )) + const rollup = displayed.checksRollup === 'none' ? 'neutral' : displayed.checksRollup + return ( + { if (open) close(); else setOpen(true) }}> + } value={checksValue(displayed, t)} opens + tone={!displayed.checksTruncated && counts.failed > 0 ? 'error' : undefined} /> + + )}> + {rerun !== undefined && ( + } disabled={busy} onSelect={() => { + close() + run(() => rerun(entry, { headSha })) + }}> + {t('checks.rerunFailed')} + + )} + {rows(ATTENTION)} + {quiet ? rows(QUIET) : quietCount > 0 && ( + 0} + icon={ 0 ? 'success' : 'skipped'} size={14} />} + onSelect={() => { setQuiet(true) }}> + {t('checks.showQuiet', { count: quietCount })} + + )} + {read.kind === 'loading' &&
{t('change.checks.loading')}
} + {read.kind === 'failed' && ( +
+ {t('change.checks.loadFailed', { message: read.message })} + +
+ )} +
+ ) +} + +const VERDICT: Record = { + 'approved': { key: 'reviewers.approved', tone: 'success' }, + 'changes-requested': { key: 'reviewers.changesRequested', tone: 'error' }, + 'commented': { key: 'reviewers.commented', tone: undefined }, + 'dismissed': { key: 'reviewers.dismissed', tone: undefined }, +} + +function Avatar({ url, login, size = 20 }: { readonly url: string | null; readonly login: string; readonly size?: number }): ReactNode { + const [broken, setBroken] = useState(false) + const style = { width: size, height: size } + if (url === null || broken) { + return ( + + ) + } + // Lazy images inside the panel's scroller never load in Chromium, so avatars load eagerly. + return { setBroken(true) }} /> +} + +/** Props of the review row. */ +export interface ReviewRowProps { + readonly entry: ForgePanelChangeRequest + readonly snapshot: ChangeRequestSnapshot + /** The aggregate review outcome. */ + readonly value: string + /** Tone of the aggregate outcome. */ + readonly tone: string | undefined + readonly requestReviews: OverviewActions['requestReviews'] + readonly reviewerCandidates: OverviewActions['reviewerCandidates'] + readonly openLink: (url: string) => void + readonly t: Translate +} + +/** + * Render the review decision as a row with the first reviewers' avatars. Its menu lists each reviewer with their + * latest outcome or that their review is requested, and, when the signed-in user may request reviews, offers to ask a + * reviewer again and to request a review from someone else through a search. + * @param props - the change request, its snapshot, the aggregate outcome, the review request actions, and copy. + * @returns the row with its menu. + */ +export function ReviewRow({ entry, snapshot, value, tone, requestReviews, reviewerCandidates, openLink, t }: ReviewRowProps): ReactNode { + const [open, setOpen] = useState(false) + const [searching, setSearching] = useState(false) + const [busy, run] = useBusy() + const { reviewers } = snapshot + const ask = snapshot.canRequestReviews && reviewerCandidates !== undefined ? requestReviews : undefined + const canRequest = ask !== undefined + const avatars = reviewers.length === 0 ? undefined : ( + + ) + const opens = reviewers.length > 0 || canRequest + const parts = ( + } value={value} tone={tone} trailing={avatars} + opens={opens} /> + ) + if (!opens) return
{parts}
+ const close = (): void => { + setOpen(false) + setSearching(false) + } + const request = ask === undefined ? undefined : (reviewer: Pick): void => { + close() + run(() => ask(entry, [reviewer])) + } + // Asking again suits people who reviewed and are not asked now; bots review on their own triggers. + const again = reviewers.filter(reviewer => reviewer.kind !== 'bot' && !reviewer.requested && reviewer.verdict !== null) + return ( + { if (open) close(); else setOpen(true) }}> + {parts} + + )}> + {searching && request !== undefined && reviewerCandidates !== undefined + ? { request({ kind: 'user', login }) }} t={t} /> + : ( + <> + {reviewers.length === 0 &&
{t('reviewers.none')}
} + {reviewers.map(reviewer => ( + + ))} + {snapshot.reviewersTruncated && ( + { + close() + openLink(snapshot.url) + }}> + {t('reviewers.truncated')} + + )} + {request !== undefined && again.map((reviewer, index) => ( + } + onSelect={() => { request(reviewer) }}> + {t('reviewers.rerequestAria', { login: reviewer.login })} + + ))} + {canRequest && ( + } + onSelect={() => { setSearching(true) }}> + {t('reviewers.requestMore')} + + )} + + )} +
+ ) +} + +/** One reviewer in the review menu: avatar, login, what kind of reviewer, and their latest outcome or pending request. */ +function ReviewerLine({ reviewer, headSha, t }: { + readonly reviewer: ChangeRequestReviewer + readonly headSha: string + readonly t: Translate +}): ReactNode { + const verdict = reviewer.verdict === null ? undefined : VERDICT[reviewer.verdict] + // A shown outcome older than the head; a requested review hides the outcome. + const older = !reviewer.requested && reviewer.verdict !== null && reviewer.reviewedSha !== null + && reviewer.reviewedSha.toLowerCase() !== headSha.toLowerCase() + const kind = reviewer.codeOwner ? t('reviewers.codeOwner') : reviewer.kind === 'team' ? t('reviewers.team') + : reviewer.kind === 'bot' ? t('reviewers.bot') : undefined + return ( +
+ + + {reviewer.login} + {kind !== undefined && {kind}} + + + {reviewer.requested + ? {t('reviewers.pending')} + : verdict !== undefined && {t(verdict.key)}} + {older && {t('reviewers.older')}} + +
+ ) +} + +/** The accounts a reviewer search listed for `query`, or that the listing failed. */ +type Listing = { readonly query: string } & ( + { readonly ok: true; readonly value: readonly ForgeReviewerCandidate[] } | { readonly ok: false }) + +/** The searchable account list of a review request: the host's suggestions first, then accounts matching the search. */ +function ReviewerSearch({ url, list, choose, t }: { + readonly url: string + readonly list: ListCandidates + readonly choose: (login: string) => void + readonly t: Translate +}): ReactNode { + const [query, setQuery] = useState('') + const [attempt, setAttempt] = useState(0) + const [listing, setListing] = useState(null) + const search = useRef(null) + useEffect(() => { + const controller = new AbortController() + const timer = setTimeout(() => { + list(url, query, controller.signal).then( + (value) => { if (!controller.signal.aborted) setListing({ query, ok: true, value }) }, + () => { if (!controller.signal.aborted) setListing({ query, ok: false }) }, + ) + }, query === '' ? 0 : SEARCH_DELAY_MS) + return () => { + clearTimeout(timer) + controller.abort() + } + }, [url, query, attempt, list]) + useEffect(() => { + if (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches) return + const frame = requestAnimationFrame(() => { search.current?.focus() }) + return () => { cancelAnimationFrame(frame) } + }, []) + // A listing of an earlier query is never shown or chosen from, so Enter cannot request a review from an account the + // current query no longer names. + const current = listing !== null && listing.query === query ? listing : null + const candidates = current !== null && current.ok ? current.value : [] + let body: ReactNode + if (current === null) { + body =
{t('reviewers.loading')}
+ } else if (!current.ok) { + body = ( +
+ {t('reviewers.loadFailed')} + +
+ ) + } else if (candidates.length === 0) { + body =
{t('reviewers.empty')}
+ } else { + body = candidates.map(candidate => ( + } + onSelect={() => { choose(candidate.login) }}> + + {candidate.login} + {candidate.name !== null && candidate.name !== candidate.login && {candidate.name}} + {candidate.suggested && {t('reviewers.suggested')}} + + + )) + } + const first = candidates[0] + return ( + <> +
+ } value={query} aria-label={t('reviewers.search')} + placeholder={t('reviewers.search')} onChange={(event) => { setQuery(event.target.value) }} + onKeyDown={(event) => { searchFieldKeyDown(event, first === undefined ? undefined : () => { choose(first.login) }) }} /> +
+
{body}
+ + ) +} + +/** Props of the merge row. */ +export interface MergeRowProps { + readonly entry: ForgePanelChangeRequest + readonly snapshot: ChangeRequestSnapshot + /** Glyph of the row. */ + readonly icon: ReactNode + /** The merge conflict status. */ + readonly value: string + /** Tone of the conflict status. */ + readonly tone: string | undefined + readonly updateBranch: OverviewActions['updateBranch'] + readonly t: Translate +} + +/** + * Render the merge state as a row: the conflict status and whether the head is behind its base. While the signed-in + * user can update the head branch, the row opens the update menu: a title, one row per method, and the confirmation, + * which is refused once the head moved after the menu opened. + * @param props - the change request, its snapshot, the row glyph and status, the update action, and copy. + * @returns the row, with its menu when the branch can be updated. + */ +export function MergeRow({ entry, snapshot, icon, value, tone, updateBranch, t }: MergeRowProps): ReactNode { + const [open, setOpen] = useState(false) + const [confirmedHead, setConfirmedHead] = useState(snapshot.headSha) + const [usual = 'merge'] = snapshot.branchUpdates + const [chosen, setChosen] = useState(usual) + const [busy, run] = useBusy() + const behind = snapshot.branchUpdates.length > 0 + const text = behind ? `${value} · ${t('branch.behind', { base: snapshot.baseBranch })}` : value + if (!behind || updateBranch === undefined) { + return
+ } + const stale = confirmedHead !== snapshot.headSha + const method: BranchUpdateMethod = snapshot.branchUpdates.find(entry => entry === chosen) ?? usual + const base = snapshot.baseBranch + const items: MenuEntry[] = [ + { type: 'label', id: 'title', text: t('branch.updateTitle', { head: snapshot.headBranch, base }) }, + ...snapshot.branchUpdates.map(entry => ({ + id: entry, + label: ( + + {t(`branch.method.${entry}`)} + {t(`branch.note.${entry}`, { base })} + + ), + })), + ] + return ( + { setOpen(false) }} portal align="end" className={overview.rowAnchor} items={items} + selectedId={method} onSelect={setChosen} + anchor={( + + )}> + { + setOpen(false) + run(() => updateBranch(entry, { method, headSha: confirmedHead })) + }}> + {t(stale ? 'branch.changed' : 'branch.confirm')} + + + ) +} + +/** + * A speech bubble, the glyph of review threads. + * @param props - glyph size in pixels. + * @returns the decorative glyph. + */ +export function ThreadGlyph({ size = 14 }: { readonly size?: number }): ReactNode { + return ( + + ) +} + +/** An issue: a ring around a dot. */ +function IssueGlyph(): ReactNode { + return ( + + ) +} + +/** The issue's label: `#n` within the change request's repository, else `owner/name#n`. */ +function issueLabel(issue: ChangeRequestIssue, snapshot: ChangeRequestSnapshot): string { + const { owner, name } = snapshot.ref.repository + const same = issue.repository.owner.toLowerCase() === owner.toLowerCase() + && issue.repository.name.toLowerCase() === name.toLowerCase() + return same ? `#${issue.number}` : `${issue.repository.owner}/${issue.repository.name}#${issue.number}` +} + +/** + * Render the issues linked to the change request, which the host closes once it merges, as one row of links, each + * named by its number with its title in a tooltip, or nothing without one. More issues than the provider read end the + * row with a note. + * @param props - the snapshot, the link action, and copy. + * @returns the row, or null. + */ +export function IssuesRow({ snapshot, openLink, t }: { + readonly snapshot: ChangeRequestSnapshot + readonly openLink: (url: string) => void + readonly t: Translate +}): ReactNode { + if (snapshot.closingIssues.length === 0) return null + const links = snapshot.closingIssues.map((issue, index) => { + const label = issueLabel(issue, snapshot) + return ( + + {index > 0 && t('issues.separator')} + + { + event.preventDefault() + openLink(issue.url) + }}> + {label} + + + + ) + }) + return ( +
+ } opens={false} + value={<>{t('issues.label')}{' '}{links}{snapshot.closingIssuesTruncated && t('issues.more')}} /> +
+ ) +} diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css index 2006c2b546..db93e6decd 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css @@ -14,6 +14,11 @@ .menu { width: min(360px, calc(100vw - 24px)); } .trigger { display: inline-flex; align-items: center; gap: 4px; height: 28px; padding: 0 8px; border: 0; border-radius: var(--dsw-radius-sm); background: transparent; color: var(--dsw-alias-label-primary); font: inherit; white-space: nowrap; cursor: pointer; } .trigger:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; } +/* The label ends in an ellipsis once its toolbar lets the entry shrink. */ +.anchor { min-width: 0; max-width: 100%; } +.trigger { min-width: 0; max-width: 100%; } +.triggerLabel { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.triggerChevron { flex: none; } @media (hover: hover) { .row:hover, .trigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); } } @media (pointer: coarse) { .row { min-height: 44px; } .search input { font-size: 16px; } } diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx index eb24d62b51..73edf2f7aa 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx @@ -133,9 +133,12 @@ export function ChangedFiles(props: ChangedFilesProps): ReactNode { */ export function ChangedFilesMenu({ visible, ...props }: ChangedFilesProps & { readonly visible: boolean }): ReactNode { const [open, setOpen] = useState(false) - return { setOpen(false) }} + return { setOpen(false) }} anchor={}> + onClick={() => { setOpen(value => !value) }}> + {props.t('diff.allFiles', { count: props.files.length })} + + }> { setOpen(false); props.jump(path) }} /> } diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index 9183d560e4..6b71b2428c 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -125,10 +125,10 @@ border-inline-end: 0; } +/* One line of controls, never wrapped; the fold rules after `.tool` move controls into the More menu as it narrows. */ .toolbarMain { display: flex; flex: 1; - flex-wrap: wrap; align-items: center; gap: 0 4px; box-sizing: border-box; @@ -155,30 +155,12 @@ flex: 1; } -.progressSlot { +.progressSlot, +.foldTests, +.filesSlot { display: inline-flex; -} - -/* Breaks the toolbar's review controls onto a second row where one row is too narrow for them. */ -.rowBreak { - display: none; -} - -@container forge-changes (max-width: 640px) { - .reviewRow { - order: 2; - } - - .rowBreak { - display: block; - flex-basis: 100%; - order: 1; - height: 4px; - } - - .progressSlot { - margin-left: auto; - } + flex: none; + min-width: 0; } .select { @@ -293,6 +275,36 @@ transform: rotate(90deg); } +/* `observeToolbarFold` sets `data-fold` on the toolbar row to the shallowest level whose items fit on one line: level 1 + folds the line totals, expansion, side by side, and wrapping into the More menu; level 2 the test switch, with the + progress label shortened to the bare count beside its ring; level 3 refresh. */ +.more { + display: none; +} + +.toolbarMain:is([data-fold='1'], [data-fold='2'], [data-fold='3']) .foldViews, +.toolbarMain:is([data-fold='2'], [data-fold='3']) .foldTests, +.toolbarMain[data-fold='3'] .foldRefresh { + display: none; +} + +/* With every control folded, the file list entry shortens its label before the row overflows. */ +.toolbarMain[data-fold='3'] .filesSlot { + flex-shrink: 1; +} + +.toolbarMain:is([data-fold='1'], [data-fold='2'], [data-fold='3']) .more { + display: inline-flex; +} + +.toolbarMain:is([data-fold='2'], [data-fold='3']) .progressSlot [data-forge-progress='full'] { + display: none; +} + +.toolbarMain:is([data-fold='2'], [data-fold='3']) .progressSlot [data-forge-progress='compact'] { + display: inline-flex; +} + /* A menu row with a path that shortens and its counts. */ .menuRow { display: flex; @@ -528,6 +540,13 @@ } } +/* While its write is in flight or the host's marks could not be read, the mark keeps its place and shows it cannot change. */ +.viewed[data-disabled], +.viewed[data-disabled] input { + color: var(--dsw-alias-label-tertiary); + cursor: default; +} + .viewed:has(input:focus-visible) { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: -1px; @@ -679,6 +698,36 @@ background: var(--forge-diff-empty); } +/* Comments under a side-by-side row: one cell per column, each continuing its line's gutter and background, with the + comments aligned to the code text. Either side holds its own comments, so both sides can show one at once. */ +.notes { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + white-space: normal; +} + +.noteCell { + display: grid; + grid-template-columns: var(--forge-number-width, 3.5em) minmax(0, 1fr); + min-width: 0; +} + +.noteCell + .noteCell { + border-left: 0.5px solid var(--dsw-alias-border-l3); +} + +.noteStack { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; + padding: 8px 12px 10px calc(1.4em + 6px); +} + +.noteStack:empty { + padding: 0; +} + /* Collapsed unchanged lines; the row expands them. */ /* Collapsed unchanged lines, a collapsed large file, and a file whose lines cannot be drawn share one strip; only the first two open on a click. */ @@ -860,7 +909,8 @@ .code[data-split][data-native-side="L"] [data-diff-side="R"] *, .code[data-split][data-native-side="R"] [data-diff-side="L"], .code[data-split][data-native-side="R"] [data-diff-side="L"] * { user-select: none; } -.reviewSubmit { flex: none; white-space: nowrap; } +/* A header button keeps its label on one line; the menus and the title before it shorten instead. */ +.headerAction { flex: none; white-space: nowrap; } .code[data-single-side] .line { grid-template-columns: var(--forge-number-width) 1.4em minmax(0, 1fr); } .code[data-single-side]:not([data-wrap]) .line { grid-template-columns: var(--forge-number-width) 1.4em max-content; } diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 18142cf969..9fe4e1831d 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -25,13 +25,15 @@ import { import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, } from '../types.ts' import type { - ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeThreadId, + ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeReviewWrite, ForgeReviewWriteResult, + ForgeThreadId, ForgeViewedFiles, ForgeViewedRequest, } from '@deepseek-ai/dsh-experimental-forge/types' import { sameReviewSource, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' @@ -44,6 +46,7 @@ import type { ChangesLens, createChangesStore } from './changes-store.ts' import { CommitMenu } from './CommitMenu.tsx' import { HideTestsSwitch, LensControl, LensMenu, LENSES, ViewedProgress } from './ReviewControls.tsx' import { viewedStateOf, type ViewedFiles, type ViewedMarks } from './viewed-files.ts' +import { hostViewedOf, useHostViewed, type HostViewed } from './host-viewed.ts' import { Counts, DiffFile, type DiffFileAction, type DiffFileHandlers } from './DiffFile.tsx' import { SectionReach } from './section-reach.ts' import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx' @@ -53,7 +56,9 @@ import { drawnLines, matchesHunks, textLines } from './diff-rows.ts' import { ChangeRequestGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' import { RefreshGlyph } from './RefreshGlyph.tsx' -import type { FileThreads, ThreadActions, ThreadFocus } from './ReviewThreads.tsx' +import { ViewOptionsMenu } from './ViewOptionsMenu.tsx' +import { observeToolbarFold } from './toolbar-fold.ts' +import type { FileThreads, ThreadActions, ThreadFocus, ThreadWrite } from './ReviewThreads.tsx' import { inFileOrder, type ThreadFilter } from './review-threads.ts' import { usePlacedThreads, useThreadRead, type PlacedThread } from './thread-state.ts' import { ThreadList } from './ThreadList.tsx' @@ -98,14 +103,23 @@ export interface ChangesTabInjected { ) => Promise> /** List the commits of a change request, or null when its provider does not read commits; `signal` aborts the read. */ readonly changeRequestCommits: (url: string, signal: AbortSignal) => Promise> - /** The Session's viewed marks, kept in the browser. */ + /** The Session's viewed marks, kept in the browser for local changes, chosen commits, and hosts that keep none. */ readonly viewedFiles: ViewedFiles + /** + * Read the signed-in user's viewed marks on a change request's files at `headSha`, or null when its provider keeps + * none; `signal` aborts the read. + */ + readonly changeRequestViewed: (url: string, headSha: string, signal: AbortSignal) => Promise> + /** Set or clear the signed-in user's viewed mark on one file of a change request. */ + readonly setFileViewed: (url: string, request: ForgeViewedRequest) => Promise> /** Read one file of a change request at a commit. */ readonly changeRequestText: (url: string, commit: string, path: string) => Promise> /** Read the review threads of a change request at the head of its latest status; `signal` aborts the read. */ readonly changeRequestReview: ( url: string, headSha: string, fresh: boolean, signal: AbortSignal, ) => Promise> + /** Write to the review threads or the pending review of a change request; never retries a write. */ + readonly changeRequestReviewWrite: (url: string, write: ForgeReviewWrite) => Promise> /** Quote a whole review thread of the change request at `url` in the main input without submitting it. */ readonly addThreadToInput: (thread: ForgeReviewThread, url: string, range: string | null) => boolean /** Open a URL outside the app. */ @@ -150,8 +164,16 @@ type ChangesData = readonly localAhead: number | null /** Web page of each file at the head. */ readonly fileUrls: Readonly> + /** The code host's viewed marks of the whole change request, or null when the browser keeps the marks. */ + readonly viewed: HostViewed | null } +/** Why the code host did not take a review write, and whether it may have applied it. */ +interface WriteRefusal { + readonly message: string + readonly unknown: boolean +} + /** Unchanged lines read for one loaded diff: each file's new side and its expanded gaps. */ interface Expansion { readonly data: ChangesData | null @@ -208,11 +230,23 @@ function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: T return key === undefined || base === null ? undefined : t(key, { base: base.name }) } +/** + * Read the changes a view shows. The whole change request also reads the host's viewed marks at the head of the latest + * status, beside the diff; marks read at another head refuse the read as the diff refuses a moved head. + * @param source - local changes or a change request. + * @param scope - local scope to read. + * @param commits - chosen commits of a change request, or null for all of it. + * @param head - head commit of the change request's latest status, or null. + * @param reads - the Remote reads. + * @param signal - cancellation of the reads. + * @returns the changes, or why they could not be read. + */ async function readChanges( source: ChangesSource, scope: ForgeLocalScope, commits: ForgeCommitRange | null, - reads: Pick, + head: string | null, + reads: Pick, signal: AbortSignal, ): Promise> { if (source.kind === 'local') { @@ -221,10 +255,15 @@ async function readChanges( const { files, base, omitted } = result.value return { ok: true, value: { kind: 'local', files, scope, base, omitted } } } - const result = await reads.changeRequestDiff(source.url, commits, signal) + const [result, marks] = await Promise.all([ + reads.changeRequestDiff(source.url, commits, signal), + commits === null && head !== null && head !== '' ? reads.changeRequestViewed(source.url, head, signal) : Promise.resolve(null), + ]) if (!result.ok) return result + if (marks !== null && !marks.ok && marks.error.code === 'forgePanel/stale-head') return marks const { files, headSha, localAhead, fileUrls } = result.value - return { ok: true, value: { kind: 'change', files, url: source.url, headSha, commits, localAhead, fileUrls } } + const viewed = hostViewedOf(marks, headSha) + return { ok: true, value: { kind: 'change', files, url: source.url, headSha, commits, localAhead, fileUrls, viewed } } } /** The ref that identifies a comparison: the chosen base branch, or null for the automatic fork point and other scopes. */ @@ -320,7 +359,7 @@ function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDis {number !== null && {t('change.number', { number })}} {commitMenu} - @@ -371,7 +410,7 @@ function LocalHeader({ state, scope, base, missing, visible, diffBases, choose, } {(scope === 'branch' || creatable) && {scope === 'branch' && commitMenu} - {creatable && } + {creatable && } } ) @@ -434,7 +473,7 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { return

{path}

{state.threads.map(thread => )} + actions={actions} locked={state.locked} outdated t={t} />)}
} @@ -445,7 +484,7 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { */ export function ChangesTab({ useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, - changeRequestText, changeRequestCommits, changeRequestReview, viewedFiles, + changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, changeRequestViewed, setFileViewed, openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() @@ -494,6 +533,47 @@ export function ChangesTab({ setReviewBusy(false) } } + // Every write that may have changed the threads reads them again; writes run one at a time, so a write that starts a + // pending review settles before the next write looks for one. + const [reviewRevision, setReviewRevision] = useState(0) + const writing = useRef>(Promise.resolve()) + /** + * Send one write after the earlier ones. + * @returns undefined once the host took it, else its message and whether its outcome is unknown. + */ + const sendWrite = (url: string, write: ForgeReviewWrite): Promise => { + const run = async (): Promise => { + const response = await changeRequestReviewWrite(url, write) + if (!response.ok) { + if (response.error.code === 'forgePanel/not-bound') { + return { message: t('thread.writeFailed', { message: response.error.message }), unknown: false } + } + setReviewRevision(value => value + 1) + return { message: t('thread.writeUnknown'), unknown: true } + } + const result = response.value + if (result.ok) { + setReviewRevision(value => value + 1) + return undefined + } + switch (result.code) { + case 'unsupported': return { message: t('thread.writeUnsupported'), unknown: false } + case 'failed': + setReviewRevision(value => value + 1) + return { message: t('thread.writeFailed', { message: result.message }), unknown: false } + case 'stale': return { message: t('thread.writeStale'), unknown: false } + case 'unknown': + setReviewRevision(value => value + 1) + return { message: t('thread.writeUnknown'), unknown: true } + /* v8 ignore next -- closed ForgeReviewWriteResult code union exhaustiveness guard */ + default: return assertNever(result.code, 'ForgeReviewWriteResult.code') + } + } + const next = writing.current.then(run, run) + writing.current = next + return next + } + const writeReview = async (url: string, write: ForgeReviewWrite): Promise => (await sendWrite(url, write))?.message const choices = useStore(store => store.byTab[tab.id]) const [wanted, setWanted] = useState(null) const [treeState, setTreeState] = useState({ query: '', collapsed: {}, selected: null }) @@ -564,30 +644,32 @@ export function ChangesTab({ if (!tab.visible || read === null || read === finished || waiting) return const controller = new AbortController() const readAt = latestStatusAt.current - void readChanges(source, localScope, changeCommits, { localDiff, changeRequestDiff }, controller.signal).then((result) => { - if (controller.signal.aborted) return - if (!result.ok && result.error.code === 'forgePanel/stale-head') { - setRefused({ read, statusAt: readAt }) - setFailure(null) - return - } - setFinished(read) - if (result.ok) { - setLoaded({ key: dataKey, data: result.value }) - setFailure(null) - } else { - setFailure({ key: dataKey, code: result.error.code }) - } - }) + void readChanges(source, localScope, changeCommits, head, { localDiff, changeRequestDiff, changeRequestViewed }, controller.signal) + .then((result) => { + if (controller.signal.aborted) return + if (!result.ok && result.error.code === 'forgePanel/stale-head') { + setRefused({ read, statusAt: readAt }) + setFailure(null) + return + } + setFinished(read) + if (result.ok) { + setLoaded({ key: dataKey, data: result.value }) + setFailure(null) + } else { + setFailure({ key: dataKey, code: result.error.code }) + } + }) return () => { controller.abort() } - }, [tab.visible, read, refused, waiting, source, localScope, changeCommits, dataKey, localDiff, changeRequestDiff]) + }, [tab.visible, read, refused, waiting, source, localScope, changeCommits, head, dataKey, localDiff, changeRequestDiff, + changeRequestViewed]) const data = loaded !== null && loaded.key === dataKey ? loaded.data : null // Threads show only while they were read at the head of the latest status and, for the whole change request, at // the head the shown diff was read at, so their positions number the shown files. const prHead = entry?.snapshot?.headSha ?? null const prAuthor = entry?.snapshot?.author ?? null const threadRead = useThreadRead({ visible: tab.visible, url: source.kind === 'change' ? source.url : null, head: prHead, - updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, read: changeRequestReview }) + updatedAt: entry?.snapshot?.updatedAt ?? null, statusAt, attempt, revision: reviewRevision, read: changeRequestReview }) const review = data?.kind === 'change' && threadRead.review !== null && threadRead.review.headSha === prHead && (data.commits !== null || data.headSha === prHead) ? threadRead.review : null const placed = usePlacedThreads(review, data?.kind === 'change' ? { head: prHead ?? '', end: data.headSha, commits: data.commits } : null) @@ -605,7 +687,15 @@ export function ChangesTab({ allFiles.filter(file => shownBy(file, item, hideTests)).length])) as Record, [allFiles, hideTests]) const shownSource = useMemo(() => data === null ? null : reviewSourceOf(data), [data]) const viewedKey = shownSource === null ? '' : viewedSourceOf(shownSource) - const marks = useSyncExternalStore(viewedFiles.subscribe, () => viewedFiles.marksOf(viewedKey)) + const localMarks = useSyncExternalStore(viewedFiles.subscribe, () => viewedFiles.marksOf(viewedKey)) + const hostOwner = useMemo(() => data?.kind === 'change' && data.viewed !== null + ? { url: data.url, headSha: data.headSha, files: data.files, viewed: data.viewed } : null, [data]) + const host = useHostViewed(hostOwner, setFileViewed, (failure) => { + if (failure.kind === 'stale') report('viewed.syncStale') + else if (failure.kind === 'unknown') report('viewed.syncUnknown', { message: failure.message }) + else report('viewed.syncFailed', { message: failure.message }) + }) + const marks = host?.marks ?? localMarks // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again. const rereading = read !== null && finished !== read && data !== null const failed = failure !== null && failure.key === dataKey ? failure.code : null @@ -622,6 +712,13 @@ export function ChangesTab({ const isExpanded = (file: ForgeDiffFile): boolean => chosen[file.path] ?? expandedByDefault(file) const sections = useRef(new Map()) const scrollport = useRef(null) + const toolbarRow = useRef(null) + useLayoutEffect(() => { + const row = toolbarRow.current + /* v8 ignore next -- the toolbar row renders in every state of the view */ + if (row === null) return + return observeToolbarFold(row) + }, []) const reach = useMemo(() => new SectionReach(), []) const attachScrollport = useCallback((element: HTMLDivElement | null) => { scrollport.current = element @@ -711,16 +808,68 @@ export function ChangesTab({ return list } - // A review addresses the head commit, so it is submitted from the view of the whole change request. + // A review addresses the head commit, so it is submitted from the view of the whole change request. A pending review on + // the code host is submitted or discarded there; without one, the summary and any comment drafts kept in the browser + // are published as one review. + const pendingReview = review?.pendingReview ?? null + // Logins compare without case, as GitHub's do. + const ownChangeRequest = review?.viewer != null && prAuthor !== null && review.viewer.toLowerCase() === prAuthor.toLowerCase() + const finishWrite = async (send: () => Promise, done: ForgePanelKey): Promise => { + if (reviewRunning.current) return + reviewRunning.current = true + setReviewBusy(true) + setReviewError(null) + try { + const failure = await send() + if (failure !== undefined) { + setReviewError(failure) + return + } + report(done) + setReviewOpen(false) + } finally { + reviewRunning.current = false + setReviewBusy(false) + } + } const reviewForm = tab.visible && data !== null && reviewOpen && data.kind === 'change' && data.commits === null && { setReviewOpen(false) }} + url={data.url} headSha={data.headSha} pending={pendingReview} own={ownChangeRequest} busy={reviewBusy} error={reviewError} + close={() => { setReviewOpen(false) }} check={() => { openLink(data.url) }} reconcile={() => { queue.finish(false); setReviewError(null) }} submit={() => { const latest = queue.getSnapshot() - void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event, - body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url)) + if (pendingReview === null) { + void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event, + body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url)) + return + } + // The submission is kept as the write to reconcile until the host answers, so an unknown outcome blocks another + // submission, which would otherwise publish a second review once the pending review no longer reads. + void finishWrite(async () => { + if (!queue.begin({ kind: 'review', headSha: data.headSha, event: latest.event, body: latest.body, comments: [] })) { + return t('review.saveFailed') + } + const refusal = await sendWrite(data.url, { kind: 'submit-pending', headSha: data.headSha, review: pendingReview.id, + event: latest.event, body: latest.body }) + if (refusal === undefined) { + if (!queue.finish(true)) report('review.saveFailed') + return undefined + } + if (!refusal.unknown) queue.finish(false) + return refusal.message + }, 'review.submitted') + }} + discard={pendingReview === null ? undefined : () => { + void finishWrite(() => writeReview(data.url, { kind: 'discard-pending', headSha: data.headSha, review: pendingReview.id }), 'review.discarded') }} t={t} /> + /** Add a comment to the pending review on the code host at the head the comment was selected on. */ + const addPending = (selection: ReviewSelection): Promise => { + if (selection.source.kind !== 'change') return Promise.resolve(t('review.stale')) + const { path, side, startLine, endLine, body } = selection.comment + return writeReview(selection.source.url, { kind: 'add-pending', headSha: selection.source.headSha, comment: { path, side, startLine, endLine, body } }) + } + const recordActions: ReviewActions = { source: shownSource ?? (source.kind === 'local' ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope), commits: commitsOf(localScope) } @@ -742,6 +891,11 @@ export function ChangesTab({ readText: (commit, path) => changeRequestText(url, commit, path), inputFailed: () => { live.current.report('thread.inputFailed') }, focused: focus, + writes: { + write: (write: ThreadWrite) => live.current.writeReview(url, { ...write, headSha: review.headSha }), + reviewStarted: review.pendingReview !== null, + canReview: review.viewerCanReview, + }, }, [review, url, prAuthor, addThreadToInput, openLink, changeRequestText, focus]) const fileThreads = useMemo(() => new Map(threadActions === null ? [] : [...placed.files].map(([path, group]) => [path, { ...group, actions: threadActions }])), [placed.files, threadActions]) @@ -819,7 +973,9 @@ export function ChangesTab({ } /** Mark a file viewed and collapse it, keeping its header in view, or clear its mark and expand it. */ const markViewed = (owner: ChangesData, file: ForgeDiffFile, viewed: boolean): void => { - if (!viewedFiles.mark(viewedKey, owner.files, file.path, viewed)) { + if (host !== null) { + if (!host.mark(file.path, viewed)) return + } else if (!viewedFiles.mark(viewedKey, owner.files, file.path, viewed)) { report('viewed.saveFailed') return } @@ -853,8 +1009,11 @@ export function ChangesTab({ // during render rather than in an effect because the file menus read their actions while this same render draws them; // an effect would hand them the previous diff's links. A render React discards leaves values derived from the same // props and state, which the retried render assigns again. - const live = useRef({ data, expandedByDefault, expand, markViewed, fileActions, publishReview, report, nextThread, t }) - live.current = { data, expandedByDefault, expand, markViewed, fileActions, publishReview, report, nextThread, t } + const callbacks = { + data, expandedByDefault, expand, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, t, + } + const live = useRef(callbacks) + live.current = callbacks const handlers = useMemo((): DiffFileHandlers => ({ toggle: (file) => { const byDefault = live.current.expandedByDefault(file) @@ -883,24 +1042,28 @@ export function ChangesTab({ nextThread: (path) => { live.current.nextThread(path) }, reach, }), [reach]) - const reviewStarted = reviewState.comments.length > 0 + const reviewStarted = pendingReview !== null const publishingBlocked = reviewState.uncertain !== null - // Comments on a commit range or on local changes go to the input only; a whole change request also takes GitHub comments. - const publishable = data?.kind === 'change' && data.commits === null + // Comments on a commit range or on local changes go to the input only; a whole change request also takes GitHub comments: + // into its pending review once the threads say the user may review, and on their own while the user has no pending + // review, since GitHub refuses a single comment beside one. + const whole = data?.kind === 'change' && data.commits === null + const queueable = whole && review?.viewerCanReview === true + const single = whole && pendingReview === null const fileReview = useMemo((): ReviewActions | undefined => shownSource === null ? undefined : { source: shownSource, addToInput: addReviewToInput, records: queue, openLink, reviewStarted, onQuoted: (selection) => { if (!queue.recordAgent(selection)) live.current.report('review.saveFailed') }, publishingBlocked, - ...publishable ? { - queue: selection => queue.add(selection), - publish: selection => selection.source.kind === 'change' + ...queueable ? { queue: (selection: ReviewSelection) => live.current.addPending(selection) } : {}, + ...single ? { + publish: (selection: ReviewSelection) => selection.source.kind === 'change' ? live.current.publishReview(selection.source.url, { kind: 'comment', headSha: selection.source.headSha, comment: selection.comment }, url => queue.published(selection, url)) : Promise.resolve(live.current.t('review.stale')), } : {}, - }, [shownSource, addReviewToInput, queue, openLink, reviewStarted, publishingBlocked, publishable]) + }, [shownSource, addReviewToInput, queue, openLink, reviewStarted, publishingBlocked, queueable, single]) let body: ReactNode if (data === null) { @@ -960,6 +1123,9 @@ export function ChangesTab({ threads={fileThreads.get(path)} drawNow={wanted !== null && wanted.center !== null && wanted.path === path} viewed={viewedStateOf(marks, path, file.digest)} + viewedNote={host === null ? t('viewed.hint') : host.unavailable ? t('viewed.unavailable') + : host.saving(path) ? t('viewed.saving') : t('viewed.hintHost')} + viewedDisabled={host !== null && (host.unavailable || host.saving(path))} handlers={handlers} t={t} /> @@ -979,6 +1145,10 @@ export function ChangesTab({ // The toolbar collapses every file while any is expanded, as the files on screen show, and expands every file otherwise. const anyExpanded = files.some(isExpanded) const expansionLabel = t(anyExpanded ? 'diff.collapseAll' : 'diff.expandAll') + const toggleExpansion = (): void => { setChosen(Object.fromEntries(files.map(file => [file.path, !anyExpanded]))) } + const toggleSplit = (): void => { actions.toggledSplit(tab.id) } + const toggleWrap = (): void => { actions.toggledWrap(tab.id) } + const toggleTests = (): void => { actions.toggledTests(tab.id) } const treeAction = t(treePosition === 'left' ? 'diff.moveFileTreeRight' : treePosition === 'right' ? 'diff.hideFileTree' : 'diff.showFileTreeLeft') let additions = 0 let deletions = 0 @@ -1000,7 +1170,8 @@ export function ChangesTab({ ? { actions.based(tab.id, next) }} commitMenu={commitMenu} createChangeRequest={createChangeRequest} t={t} /> - : { setReviewOpen(true) }} t={t} />} {!reviewOpen && reviewState.error !== null && {t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}} {!reviewOpen && reviewState.uncertain !== null && !reviewBusy && source.kind === 'change' &&
@@ -1013,16 +1184,16 @@ export function ChangesTab({
{/* Above the file tree, the lens spans the tree's width; elsewhere a menu in the toolbar takes its place. */} {treeShown &&
} -
+
{tab.visible && source.kind === 'local' && { actions.scoped(tab.id, next) }} t={t} />} - {tab.visible && } + {tab.visible && } {tab.visible && allFiles.length > 0 && ( - + )} - {allFiles.length > 0 && -
{data !== null && failed !== null && ( @@ -1082,6 +1257,11 @@ export function ChangesTab({ {t('diff.stale', { count: data.localAhead })} )} {data?.kind === 'local' && data.omitted > 0 && {t('diff.omitted', { count: data.omitted })}} + {data?.kind === 'change' && data.viewed?.kind === 'failed' && ( + {t('retry')}}> + {t('viewed.readFailed', { message: data.viewed.message })} + + )} {data?.kind === 'change' && threadRead.failure !== null && ( {t('retry')}}> {t('thread.loadFailed', { message: threadRead.failure })} diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index e07bb2f722..fc25c20ebc 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -95,6 +95,10 @@ export interface DiffFileProps { readonly tooltip: string /** Whether the reader marked this change viewed, or marked an earlier change of the file. */ readonly viewed: ViewedState + /** Tooltip of the viewed mark: where marks are kept, or why the mark cannot change now. */ + readonly viewedNote: string + /** Whether the mark cannot change now, while its write is in flight or the host's marks could not be read. */ + readonly viewedDisabled: boolean /** Review threads of the file from the code host, or undefined while none are read; the view keeps their identity. */ readonly threads?: FileThreads | undefined /** Whether the section draws its lines at once, as the target of a thread jump, whose card must exist to be centered. */ @@ -161,6 +165,21 @@ function Code({ text, spans, old, next }: { } /** Whether a side-by-side row repeats an unchanged line or shows a change. */ +/** Whether two comments cover the same lines of the same side. */ +function sameRange(a: ReviewSelection['comment'], b: ReviewSelection['comment']): boolean { + return a.side === b.side && a.startLine === b.startLine && a.endLine === b.endLine +} + +/** Whether a selection covers one line of a side. */ +function covers(item: ReviewSelection, side: 'L' | 'R', line: number): boolean { + return item.comment.side === side && line >= item.comment.startLine && line <= item.comment.endLine +} + +/** The editor key of a range, such as `R3-4`. */ +function rangeKey(item: ReviewSelection): string { + return `${item.comment.side}${item.comment.startLine}-${item.comment.endLine}` +} + function pairKind(pair: SplitRow): 'context' | 'change' { return pair.left !== null && pair.left.kind === 'context' ? 'context' : 'change' } @@ -176,33 +195,53 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme const style: CSSProperties & { '--forge-number-width': string } = { '--forge-number-width': `calc(${Math.max(2, String(maximum).length)}ch + 12px)` } const highlighter = useCodeHighlighter(languageForPath(file.path)) const [selection, setSelection] = useState(null) + // Mirrors `selection` for the release of a hover-plus drag, whose listener outlives the render that chose the range. + const chosen = useRef(null) + const select = (next: ReviewSelection | null): void => { + chosen.current = next + setSelection(next) + } + // Comments being written, in the order they opened; each keeps the range it opened with while new ranges are chosen. + const [editors, setEditors] = useState([]) const root = useRef(null) const origin = useRef<{ side: 'L' | 'R'; line: number } | null>(null) // `add` is a gutter drag that began on a row's hover plus and opens the editor when the pointer is released. const dragging = useRef<'gutter' | 'add' | 'text' | null>(null) const [selecting, setSelecting] = useState(false) - const [editing, setEditing] = useState(false) const [nativeSide, setNativeSide] = useState<'L' | 'R' | null>(null) const nativeSelection = useCallback((): void => { - if (editing || nativeSide === null || root.current === null || review === undefined) return + if (nativeSide === null || root.current === null || review === undefined) return const selected = readCodeSelection(root.current, nativeSide) if (selected === undefined) { + chosen.current = null setSelection(null) setNativeSide(null) return } const comment = selectReviewLines(file, selected.side, selected.from, selected.to) - setSelection(previous => comment === undefined ? null - : previous?.comment.side === comment.side && previous.comment.startLine === comment.startLine - && previous.comment.endLine === comment.endLine - ? previous : { source: review.source, comment }) - }, [editing, nativeSide, review, file]) + const previous = chosen.current + const next = comment === undefined ? null + : previous !== null && sameRange(previous.comment, comment) ? previous : { source: review.source, comment } + chosen.current = next + setSelection(next) + }, [nativeSide, review, file]) useEffect(() => { - if (nativeSide === null || editing) return + if (nativeSide === null) return const changed = (): void => { if (dragging.current === null) nativeSelection() } document.addEventListener('selectionchange', changed) return () => { document.removeEventListener('selectionchange', changed) } - }, [nativeSide, editing, nativeSelection]) + }, [nativeSide, nativeSelection]) + /** Open an editor for a range, or focus the one already open for it, and clear the selection for the next range. */ + const compose = (target: ReviewSelection): void => { + const open = root.current?.querySelector(`[data-forge-comment="${rangeKey(target)}"] textarea`) ?? null + if (open !== null) open.focus() + else setEditors(list => [...list, target]) + const native = window.getSelection() + if (root.current?.contains(native?.anchorNode ?? null) === true) native?.removeAllRanges() + select(null) + setNativeSide(null) + origin.current = null + } useEffect(() => { if (nativeSide === null) return const copy = (event: ClipboardEvent): void => { @@ -220,10 +259,10 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme if (!selecting) return const finish = (event: PointerEvent): void => { if (dragging.current === 'text') nativeSelection() - const compose = dragging.current === 'add' && event.type === 'pointerup' + const release = dragging.current === 'add' && event.type === 'pointerup' ? chosen.current : null dragging.current = null setSelecting(false) - if (compose) setEditing(true) + if (release !== null) compose(release) } window.addEventListener('pointerup', finish) window.addEventListener('pointercancel', finish) @@ -237,12 +276,13 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme : { ...segment, old: sideSpans(segment.rows, 'old', highlighter), new: sideSpans(segment.rows, 'new', highlighter) }), [file, lines, open, highlighter]) // Returns whether the range was accepted; a range across hunks or outside them keeps the previous selection. const choose = (side: 'L' | 'R', line: number, extend: boolean): boolean => { - if (review === undefined || editing) return false + /* v8 ignore next -- the line buttons and hover pluses that choose a range draw only with review actions */ + if (review === undefined) return false const from = extend && origin.current?.side === side ? origin.current.line : line const comment = selectReviewLines(file, side, from, line) if (comment === undefined) return false if (!extend || origin.current?.side !== side) origin.current = { side, line } - setSelection({ source: review.source, comment }) + select({ source: review.source, comment }) return true } // A drag that began on a hover plus extends through every row with a line on its starting side, wherever the pointer crosses that row. @@ -252,8 +292,10 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme const line = from.side === 'L' ? old : next if (line !== null) choose(from.side, line, true) } - const selected = (side: 'L' | 'R', line: number | null): boolean => line !== null && selection !== null - && selection.comment.side === side && line >= selection.comment.startLine && line <= selection.comment.endLine + const selected = (side: 'L' | 'R', line: number | null): boolean => line !== null && selection !== null && covers(selection, side, line) + // The browser paints a native text range itself; a gutter range and every open editor's range take the highlight. + const marked = (side: 'L' | 'R', line: number | null): boolean => line !== null + && ((selected(side, line) && nativeSide === null) || editors.some(item => covers(item, side, line))) // `hover` adds the mouse shortcut: a plus shown while a hovering pointer is over this side of the row. const number = (side: 'L' | 'R', line: number | null, hover: boolean): ReactNode => { if (line === null || review === undefined || !file.hunks.some((hunk) => { @@ -262,13 +304,14 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme })) { return {line ?? ''} } - const plus = !selecting && !editing && selection?.comment.side === side && selection.comment.endLine === line + const plus = !selecting && selection !== null && selection.comment.side === side && selection.comment.endLine === line + ? selection : null return { if (dragging.current === 'gutter' && origin.current?.side === side && event.buttons === 1) choose(side, line, true) }}> - {plus && ( + {plus !== null && ( )} {/* Keyboard and assistive technology reach the same editor through the line button and the labeled plus above. */} - {hover && !plus && !editing && ( + {hover && plus === null && (
) - if (!inserted && endsAt(pair.left?.no ?? null, pair.right?.no ?? null)) { - rows.push(editor) - inserted = true - } - appendComments(pair.left?.no ?? null, pair.right?.no ?? null) - appendThreads(pair.left?.no ?? null, pair.right?.no ?? null) + notes(`notes-${at}-${index}`, pair) } } else { for (const [index, row] of segment.rows.entries()) { // Both numbers place their plus in the sign column, so a row showing the labeled plus offers no hover plus. - const labeled = !selecting && !editing && endsAt(row.old, row.new) - rows.push(
{ extendAdd(event.buttons, row.old, row.new) }}> {singleSide !== 'R' && number('L', row.old, row.kind === 'del' && !labeled)}{singleSide !== 'L' && number('R', row.new, row.kind !== 'del' && !labeled)}{SIGN[row.kind]}
) - if (!inserted && endsAt(row.old, row.new)) { - rows.push(editor) - inserted = true - } - appendComments(row.old, row.new) - appendThreads(row.old, row.new) + rows.push(...commentsAt('L', row.old), ...commentsAt('R', row.new)) } } } - if (review !== undefined) for (const thread of remaining) { - rows.push() + if (review !== undefined) { + // An editor whose last line no longer draws, after a refresh or a narrower choice of commits, follows the lines. + for (const item of unplacedEditors) rows.push(editorOf(item, review)) + for (const thread of remaining) { + rows.push() + } } - for (const item of unplaced) rows.push(threadCard(item, false)) - if (!inserted) rows.push(editor) + for (const item of unplaced) rows.push(threadCard(item)) return
{ setNativeSide(side) - if (editing) return - setSelection(null) + select(null) setSelecting(true) }) }}>{rows}
@@ -425,7 +475,7 @@ function Content(props: DiffFileProps): ReactNode { const { file, large, revealed, handlers, review, threads, t } = props const comments = useFileReview(review, file.path) const records = review === undefined ? null : comments.threads.map(thread => ) + actions={review} locked={comments.locked} outdated={!reviewMatches(thread.selection, review.source, file)} t={t} />) const lineThreads = threads?.lines.map(item => ) if (file.binary) return <>

{t('diff.binary')}

{records}{lineThreads} @@ -504,7 +554,7 @@ function FileMenu({ name, file, handlers, t }: { * @returns the file section. */ function DiffFileSection(props: DiffFileProps): ReactNode { - const { file, expanded, large, revealed, badge, tooltip, viewed, threads, handlers, t } = props + const { file, expanded, large, revealed, badge, tooltip, viewed, viewedNote, viewedDisabled, threads, handlers, t } = props const name = file.path.slice(file.path.lastIndexOf('/') + 1) const element = useRef(null) const [reached, setReached] = useState(false) @@ -555,8 +605,8 @@ function DiffFileSection(props: DiffFileProps): ReactNode { {badge !== '' && {badge}} {!file.binary && } - diff --git a/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css b/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css index 168caafc17..3ce29555e6 100644 --- a/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ForgeTab.module.css @@ -395,13 +395,14 @@ line-height: 18px; } -/* Expanded facts, one row each: an icon under the glyph, the label, the value, - and a chevron on a row that opens something. */ +/* 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. */ .rows { + /* Contains the visually hidden row labels, so they never extend a scroll area outside the panel. */ + position: relative; display: grid; - /* Edge tracks include each row's padding; labels retain their Chinese width and grow for longer translations. */ - grid-template-columns: 24px minmax(32px, max-content) minmax(0, 1fr) 22px; - gap: 2px 10px; + 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); } @@ -411,12 +412,12 @@ grid-column: 1 / -1; grid-template-columns: subgrid; align-items: center; - column-gap: 10px; + column-gap: 8px; box-sizing: border-box; width: 100%; - min-height: 34px; + min-height: 32px; margin: 0; - padding: 0 10px 0 8px; + padding: 0 8px; border: 0; border-radius: var(--dsw-radius-sm); background: transparent; @@ -429,6 +430,10 @@ grid-column: 2 / 4; } +.row:disabled { + cursor: default; +} + .rowButton { cursor: pointer; } @@ -445,23 +450,33 @@ .rowIcon { display: inline-flex; + grid-column: 1; + justify-content: center; color: var(--dsw-alias-label-tertiary); } -.rowLabel { - color: var(--dsw-alias-label-secondary); -} - .rowChevron { + grid-column: 4; color: var(--dsw-alias-label-tertiary); } .rowValue { display: inline-flex; + grid-column: 2; align-items: center; gap: 6px; min-width: 0; - overflow-wrap: anywhere; +} + +/* Trailing detail of a row, such as the reviewers' avatars or the unresolved thread count. */ +.rowTrailing { + display: inline-flex; + grid-column: 3; + align-items: center; + gap: 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + font-variant-numeric: tabular-nums; } .rowValue[data-tone='error'] { @@ -592,3 +607,21 @@ text-overflow: ellipsis; white-space: nowrap; } + +/* The unresolved review thread count at the end of the changes row. */ +.threads { + display: inline-flex; + align-items: center; + gap: 3px; + color: var(--dsw-alias-label-secondary); +} + +/* The name of a fact row, read by assistive technology before its value. */ +.visuallyHidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} diff --git a/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx b/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx index a919d92f23..20eec63c19 100644 --- a/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ForgeTab.tsx @@ -43,6 +43,14 @@ export interface ForgeTabInjected { readonly merge: (entry: ForgePanelChangeRequest, request: MergeRequest) => Promise /** Read the complete checks of an opened change request. */ readonly readChecks: NonNullable + /** Rerun the failed checks or one check; settles once the outcome is reported. */ + readonly rerunChecks: NonNullable + /** Request reviews from more reviewers; settles once the outcome is reported. */ + readonly requestReviews: NonNullable + /** List accounts a review can be requested from. */ + readonly reviewerCandidates: NonNullable + /** Bring the base branch's new commits into the head branch; settles once the outcome is reported. */ + readonly updateBranch: NonNullable /** Check the removed worktree of the Session out again, reporting the outcome. */ readonly restore: () => void /** Open a URL outside the app. */ @@ -158,7 +166,7 @@ function SignIn({ state, copyText, t }: { */ export function ForgeTab({ useTabInfo, sessionId, usePanel, useHost, useLocale, reconnect, refresh, remove, markReady, merge, readChecks, restore, - openLink, copyText, copyPath, + rerunChecks, requestReviews, reviewerCandidates, updateBranch, openLink, copyText, copyPath, reportVisible, createChangeRequest, t, }: ForgeTabProps): ReactNode { const snapshot = usePanel(current => current) @@ -190,6 +198,7 @@ export function ForgeTab({ } const actions: ChangeRequestActions = { openLink, copyLink: copyText, retry: startRefresh, remove, markReady, merge, readChecks, + rerunChecks, requestReviews, reviewerCandidates, updateBranch, viewChanges: (entry) => { viewChanges({ kind: 'change', url: entry.url }) }, } const local = state.local !== null && state.local.files.length > 0 ? state.local : null diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css b/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css index 5ce683c482..d79ac0b0e2 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css @@ -2,7 +2,8 @@ .root, .thread { box-sizing: border-box; width: calc(100% - 20px); max-width: 680px; margin: 10px; padding: 12px; border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-md); background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); font: var(--dsw-font-xs-13); font-family: Inter, var(--dsw-font-family); white-space: normal; } .root { background: var(--dsw-alias-bg-layer-2); border-radius: var(--dsw-radius-lg); } .root:focus-within { border-color: var(--dsw-alias-border-l4); } -.root[data-split][data-side="R"], .thread[data-split][data-side="R"] { margin-inline-start: clamp(10px, calc(100% - 700px), calc(50% + 10px)); } +/* Side by side, a comment fills its side's cell under the code instead of the row's width. */ +[data-forge-comments] > .root, [data-forge-comments] > .thread { width: auto; max-width: none; margin: 0; } .title { margin-bottom: 12px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; } /* Fixed-size textarea layout stays local during typing; native resizing can still change its outer height. */ .input { display: block; box-sizing: border-box; width: 100%; height: 88px; min-height: 88px; contain: strict; padding: 10px 12px; resize: vertical; border: 0.5px solid var(--dsw-alias-border-l4); border-radius: var(--dsw-radius-md); outline: none; background: var(--dsw-alias-bg-layer-3); color: var(--dsw-alias-label-primary); font: inherit; } diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx index 94407dfee8..694dc51bea 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx @@ -15,7 +15,7 @@ export interface ReviewActions { readonly source: ReviewSource /** Browser records shared by the changes tab. */ readonly records?: ReviewQueue - /** Whether another comment already started a pending review. */ + /** Whether the signed-in user has a pending review on the code host that the next comment joins. */ readonly reviewStarted?: boolean /** Open the confirmed publication URL. */ readonly openLink?: (url: string) => void @@ -27,26 +27,32 @@ export interface ReviewActions { readonly onQuoted?: (selection: ReviewSelection) => void /** Publish one comment; an error string preserves the editor. */ readonly publish?: (selection: ReviewSelection) => Promise - /** Keep one comment for the final review; false preserves the editor. */ - readonly queue?: (selection: ReviewSelection) => boolean + /** Add one comment to the pending review on the code host, starting one when needed; an error string preserves the editor. */ + readonly queue?: (selection: ReviewSelection) => Promise } -function GitHubAction({ disabled, busy, started, queue, publish, t }: PropsLocale & { +/** + * Render a primary action with an optional second action in its menu. + * @param props - the main action, the optional menu action, the menu's name, and availability. + * @returns the split button. + */ +export function SplitAction({ disabled, label, run, menuLabel, menu, other }: { readonly disabled: boolean - readonly busy: boolean - readonly started: boolean - readonly queue: () => void - readonly publish: (() => void) | undefined + readonly label: string + readonly run: () => void + /** Accessible name of the menu button. */ + readonly menuLabel: string + /** Label of the action in the menu, or undefined without one. */ + readonly other: string | undefined + readonly menu: () => void }): ReactNode { const [open, setOpen] = useState(false) return
- - {publish !== undefined && { setOpen(false) }} + + {other !== undefined && { setOpen(false) }} anchor={}> - { setOpen(false); publish() }}>{t('review.publish')} + aria-label={menuLabel} onClick={() => { setOpen(value => !value) }}>}> + { setOpen(false); menu() }}>{other} }
} @@ -56,9 +62,8 @@ function GitHubAction({ disabled, busy, started, queue, publish, t }: PropsLocal * @param props - frozen selection, actions, cancellation, and localized copy. * @returns the inline comment form. */ -export function ReviewComposer({ selection, actions, close, visible = true, split = false, t }: PropsLocale & { +export function ReviewComposer({ selection, actions, close, visible = true, t }: PropsLocale & { readonly visible?: boolean - readonly split?: boolean readonly selection: ReviewSelection readonly actions: ReviewActions readonly close: () => void @@ -73,13 +78,14 @@ export function ReviewComposer({ selection, actions, close, visible = true, spli useEffect(() => { input.current?.focus() }, []) const comment = (): ReviewSelection => ({ ...selection, comment: { ...selection.comment, body: body.current } }) const range = reviewRange(selection.comment) - const publish = async (): Promise => { - if (running.current || actions.publish === undefined) return + /** Send the comment to the code host, closing the form once it is taken and keeping its text otherwise. */ + const send = async (destination: ((selection: ReviewSelection) => Promise) | undefined): Promise => { + if (running.current || destination === undefined) return running.current = true setBusy(true) setError(null) try { - const failure = await actions.publish(comment()) + const failure = await destination(comment()) if (failure === undefined) close() else setError(failure) } catch (_error) { @@ -90,7 +96,8 @@ export function ReviewComposer({ selection, actions, close, visible = true, spli } } return ( -
+
{t('review.range', { range })}