From 3a04f62e4ee13258988aa9bf33299389b34b1f80 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:25:44 +0800 Subject: [PATCH 01/54] =?UTF-8?q?=E6=8E=A5=E5=85=A5pi=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E7=9A=84=E5=9B=BE=E7=89=87=E5=A4=A7=E5=B0=8F=E4=B8=8A=E9=99=90?= =?UTF-8?q?=E5=92=8C=E5=8D=95=E8=BE=B9=E4=B8=8A=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/config-catalog.md | 9 ++-- docs/config-catalog.zh.md | 9 ++-- .../pi-image-resize-defaults/guide.i18n.yaml | 16 +++++++ .../pi-image-resize-defaults/guide.md | 19 ++++++++ .../pi-image-resize-defaults/guide.zh.md | 19 ++++++++ .../attachment/attachment/README.i18n.yaml | 4 +- packages/attachment/attachment/README.md | 2 +- packages/attachment/attachment/README.zh.md | 2 +- .../attachment/src/request-projection.ts | 8 +++- .../tests/request-projection.spec.ts | 16 +++++++ packages/llm/llm-pi-ai/README.i18n.yaml | 4 +- packages/llm/llm-pi-ai/README.md | 8 +++- packages/llm/llm-pi-ai/README.zh.md | 8 +++- packages/llm/llm-pi-ai/src/adapter.ts | 10 ++--- packages/llm/llm-pi-ai/src/config.ts | 21 +++++---- packages/llm/llm-pi-ai/src/context.ts | 9 +++- packages/llm/llm-pi-ai/src/image-policy.ts | 29 ++++++++++++ packages/llm/llm-pi-ai/tests/adapter.spec.ts | 31 +++++++++++++ packages/llm/llm-pi-ai/tests/config.spec.ts | 20 +++++++++ .../llm-pi-ai/tests/fixtures/image-limits.ts | 32 +++++++++++++ .../llm/llm-pi-ai/tests/image-policy.spec.ts | 42 ++++++++++++++++++ .../pi-ai-image-limits/runtime.cordis.yml | 17 +++++++ .../pi-ai-image-limits/session.v4.jsonl | 22 +++++++++ .../session/pi-ai-image-limits/snapshot.yml | 8 ++++ .../pi-ai-image-limits/workspace/tall.png | Bin 0 -> 19941 bytes 25 files changed, 331 insertions(+), 34 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md create mode 100644 packages/llm/llm-pi-ai/src/image-policy.ts create mode 100644 packages/llm/llm-pi-ai/tests/fixtures/image-limits.ts create mode 100644 packages/llm/llm-pi-ai/tests/image-policy.spec.ts create mode 100644 snapshots/session/pi-ai-image-limits/runtime.cordis.yml create mode 100644 snapshots/session/pi-ai-image-limits/session.v4.jsonl create mode 100644 snapshots/session/pi-ai-image-limits/snapshot.yml create mode 100644 snapshots/session/pi-ai-image-limits/workspace/tall.png diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 28aadbd195..93d9736f16 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2147,7 +2147,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:251`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:252`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2257,9 +2257,12 @@ export interface PiAiProviderProfile { imageOffloadCountQuantum?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number + /** Maximum width and height for each request image; omission uses the selected pi-ai model's resize limits. */ + requestImageMaxDimension?: number /** - * Raw encoded-byte target for each deterministic inline request version; - * the smallest quality-ladder output is used when no quality fits. + * Raw encoded-byte target overriding the selected model's base64 byte budget; + * omission uses that budget converted to raw bytes, or 1 MiB without catalog metadata. + * The smallest quality-ladder output is used when no quality fits. */ requestImageMaxBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 1e54fadf61..4d6205a0c5 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2149,7 +2149,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:251`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:252`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2259,9 +2259,12 @@ export interface PiAiProviderProfile { imageOffloadCountQuantum?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number + /** Maximum width and height for each request image; omission uses the selected pi-ai model's resize limits. */ + requestImageMaxDimension?: number /** - * Raw encoded-byte target for each deterministic inline request version; - * the smallest quality-ladder output is used when no quality fits. + * Raw encoded-byte target overriding the selected model's base64 byte budget; + * omission uses that budget converted to raw bytes, or 1 MiB without catalog metadata. + * The smallest quality-ladder output is used when no quality fits. */ requestImageMaxBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml new file mode 100644 index 0000000000..2bc13efd1e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/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.4/pi-image-resize-defaults/guide.md +/: + en: d33a8682a54c4897 + zh: de9a68ccc5347c5d +/pi-ai-image-resize-defaults: + en: de949ea90a970dc4 + zh: bc79f0d1bef40861 +/pi-ai-image-resize-defaults/change: + en: bd83d50b52b9c6c3 + zh: 8e634018bf440a9e +/pi-ai-image-resize-defaults/migration: + en: d77384609b1c5aa6 + zh: 06be2b4496cfa037 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md new file mode 100644 index 0000000000..ceef66be1e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "pi-ai request images inherit catalog dimensions and byte budgets unless their route explicitly overrides them." +--- +# pi-ai image resize defaults + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-llm-pi-ai` applies the selected model's `inputLimits.images.resize` width, height, and byte budgets to request images. Previously, request projection used only the total-pixel budget and a fixed 1 MiB raw encoded-byte target. Catalog byte budgets count base64 payload and are converted to raw bytes. Images already stored in a Session receive the new request projection without rewriting their attachments. + +The route's `requestImageMaxBytes` remains a raw encoded-byte override. The new `requestImageMaxDimension` overrides both catalog dimensions. Models without resize metadata retain the existing defaults. Both request serialization and screenshot coordinate targets use these resolved limits. + +## Migration + +1. Leave both overrides unset to follow the installed pi-ai catalog. Review long-image resolution and request sizes after upgrading pi-ai. +2. If a gateway needs different dimensions, set `requestImageMaxDimension` in its `providers.` configuration. Set `requestImageMaxBytes: 1048576` to preserve the previous raw byte target. Choose values the gateway accepts; these overrides can raise or lower the catalog values. +3. Verify the model-facing image descriptor's request dimensions and, for screenshots, the coordinate target. Neither width nor height may exceed the configured dimension. The byte setting remains an encoding target; the smallest quality-ladder result can exceed it. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md new file mode 100644 index 0000000000..5ba14c34aa --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "pi-ai 请求图片继承目录中的尺寸和字节预算,路由显式配置优先。" +--- +# pi-ai 图片缩放默认值 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-llm-pi-ai` 将所选模型的 `inputLimits.images.resize` 宽度、高度和字节预算应用于请求图片。此前,请求投影只使用总像素预算和固定的 1 MiB 原始编码字节目标。目录字节预算按 base64 载荷计算,使用时换算为原始字节。Session 中已保存的图片也会使用新的请求投影,存储附件保持不变。 + +路由的 `requestImageMaxBytes` 仍用于覆盖原始编码字节目标。新增的 `requestImageMaxDimension` 同时覆盖目录中的宽度和高度限制。没有缩放元数据的模型保留现有默认值。请求序列化和截图坐标目标使用同一组解析后的限制。 + +## 迁移 + +1. 不配置这两个覆盖字段,即可跟随已安装的 pi-ai 目录。升级 pi-ai 后,检查长图分辨率和请求大小。 +2. 网关需要不同尺寸时,在其 `providers.` 配置中设置 `requestImageMaxDimension`。设置 `requestImageMaxBytes: 1048576` 可保留原来的原始字节目标。配置值须符合网关要求,这些覆盖值可以调高或调低目录值。 +3. 检查模型侧图片描述中的请求尺寸;截图还需检查坐标目标。宽度和高度均不得超过配置的尺寸。字节配置仍是编码目标,质量阶梯中的最小结果可能超过它。 diff --git a/packages/attachment/attachment/README.i18n.yaml b/packages/attachment/attachment/README.i18n.yaml index 44c9125f4f..6b51f9ea66 100644 --- a/packages/attachment/attachment/README.i18n.yaml +++ b/packages/attachment/attachment/README.i18n.yaml @@ -39,8 +39,8 @@ en: bc4586bb4ce74464 zh: 5ffd0a0e7261bc24 /deepseek-ai-dsh-attachment/understand-the-implementation/service-operations: - en: b94d13fe133d8ce6 - zh: dd4064d20d510afc + en: d6363ab6ffcef365 + zh: ac1068ba4aa6a618 /deepseek-ai-dsh-attachment/understand-the-implementation/source-map: en: 4fb4c96184c38169 zh: 015b06e4bfff4fcd diff --git a/packages/attachment/attachment/README.md b/packages/attachment/attachment/README.md index 075094dcc8..40be9b99f5 100644 --- a/packages/attachment/attachment/README.md +++ b/packages/attachment/attachment/README.md @@ -72,7 +72,7 @@ This section explains the design decisions behind the seam and the service opera ### Service operations -The service family runs one admission-and-storage flow: every entry point enforces source batch limits and canonical base64, prepares provider-independent normalized attachments before publishing any member, and commits them durably in input order without partial results. Host prompt consumers pass ordered text, encoded images, and already resolved file and image references to `ctx.attachments.admitPromptContent()`; the method persists the encoded images, passes references unchanged, and counts every image toward the per-message image count and aggregate byte limits, a stored image by the bytes of the upload that stored it. Encoded protocol adapters call `ctx.attachments.admitEncodedFile()`, which checks canonical base64 before delegating to `saveFile`; adapters recognize attachment failures through `ctx.attachments.isAttachmentError()`. Generic-file callers choose `saveFile` for existing bytes or `saveFileStream` for a bounded asynchronous byte source; both return the same durable reference, while `readFileStream` verifies its digest and length during a bounded read. `readImageRequest` derives deterministic route-sized variants whose identity includes the attachment id, transform version, target dimensions, byte target, and encoder settings. The pure `requestImageDimensions` and `longEdgeDimensions` exports compute aspect-preserving dimensions from a total-pixel budget or an exact long edge, so routes and request pricing share one geometry. `imageHostPath` exposes an implementation-owned host location only to trusted same-process consumers that need execution-world mapping. Callers compose ordered batches while the implementation owns compression concurrency, caching, and singleflight. Reads, streamed writes, and projections preserve caller cancellation. Failures carry stable machine-readable codes, and the caller-correctable admission subset is recognizable at runtime so each protocol adapter maps its own vocabulary; the exact per-operation contracts live in [`src/index.ts`](src/index.ts) and [`src/error.ts`](src/error.ts). +The service family runs one admission-and-storage flow: every entry point enforces source batch limits and canonical base64, prepares provider-independent normalized attachments before publishing any member, and commits them durably in input order without partial results. Host prompt consumers pass ordered text, encoded images, and already resolved file and image references to `ctx.attachments.admitPromptContent()`; the method persists the encoded images, passes references unchanged, and counts every image toward the per-message image count and aggregate byte limits, a stored image by the bytes of the upload that stored it. Encoded protocol adapters call `ctx.attachments.admitEncodedFile()`, which checks canonical base64 before delegating to `saveFile`; adapters recognize attachment failures through `ctx.attachments.isAttachmentError()`. Generic-file callers choose `saveFile` for existing bytes or `saveFileStream` for a bounded asynchronous byte source; both return the same durable reference, while `readFileStream` verifies its digest and length during a bounded read. `readImageRequest` derives deterministic route-sized variants whose identity includes the attachment id, transform version, target dimensions, byte target, and encoder settings. The pure `requestImageDimensions` and `longEdgeDimensions` exports compute aspect-preserving dimensions from a total-pixel budget with optional width/height limits or an exact long edge, so routes and request pricing share one geometry. `imageHostPath` exposes an implementation-owned host location only to trusted same-process consumers that need execution-world mapping. Callers compose ordered batches while the implementation owns compression concurrency, caching, and singleflight. Reads, streamed writes, and projections preserve caller cancellation. Failures carry stable machine-readable codes, and the caller-correctable admission subset is recognizable at runtime so each protocol adapter maps its own vocabulary; the exact per-operation contracts live in [`src/index.ts`](src/index.ts) and [`src/error.ts`](src/error.ts). ### Source map diff --git a/packages/attachment/attachment/README.zh.md b/packages/attachment/attachment/README.zh.md index 400cc79c1e..0a3bc83731 100644 --- a/packages/attachment/attachment/README.zh.md +++ b/packages/attachment/attachment/README.zh.md @@ -72,7 +72,7 @@ kind: "package-reference" ### 服务操作 -服务族运行同一条准入与存储流程:每个入口都强制执行源批次限制与规范 base64,在发布任何成员前准备提供方无关的规范化附件,再按输入顺序持久提交而不产生部分结果。Host 提示词消费方把有序文本、编码图片和已经解析的文件与图片引用交给 `ctx.attachments.admitPromptContent()`;该方法持久化编码图片,让引用原样通过,并把每张图片计入单条消息的图片数量与总字节上限,已存储的图片按存储它的那次上传的字节数计入。编码协议适配器调用 `ctx.attachments.admitEncodedFile()`,由该方法检查规范 base64 后委托给 `saveFile`;适配器通过 `ctx.attachments.isAttachmentError()` 识别附件错误。通用文件调用方可以用 `saveFile` 提交已有字节,或用 `saveFileStream` 提交有界异步字节源;两者返回相同的持久引用,`readFileStream` 则在有界读取过程中校验摘要与长度。`readImageRequest` 派生确定性的路由尺寸变体,其身份包含附件 id、变换版本、目标尺寸、字节目标及编码参数。纯函数导出 `requestImageDimensions` 与 `longEdgeDimensions` 按总像素预算或精确长边计算保持宽高比的尺寸,使路由与请求定价共享同一套几何计算。`imageHostPath` 只向需要把该位置映射到执行环境的受信任同进程消费方暴露实现拥有的宿主位置。调用方组合有序批次,而实现负责管理压缩并发、缓存与 singleflight。读取、流式写入和投影保留调用方的取消语义。失败带有稳定且机器可读的错误码,运行时即可识别可由调用方修正的准入子集,让每个协议适配器映射自己的词汇;各操作的确切约定见 [`src/index.ts`](src/index.ts) 与 [`src/error.ts`](src/error.ts)。 +服务族运行同一条准入与存储流程:每个入口都强制执行源批次限制与规范 base64,在发布任何成员前准备提供方无关的规范化附件,再按输入顺序持久提交而不产生部分结果。Host 提示词消费方把有序文本、编码图片和已经解析的文件与图片引用交给 `ctx.attachments.admitPromptContent()`;该方法持久化编码图片,让引用原样通过,并把每张图片计入单条消息的图片数量与总字节上限,已存储的图片按存储它的那次上传的字节数计入。编码协议适配器调用 `ctx.attachments.admitEncodedFile()`,由该方法检查规范 base64 后委托给 `saveFile`;适配器通过 `ctx.attachments.isAttachmentError()` 识别附件错误。通用文件调用方可以用 `saveFile` 提交已有字节,或用 `saveFileStream` 提交有界异步字节源;两者返回相同的持久引用,`readFileStream` 则在有界读取过程中校验摘要与长度。`readImageRequest` 派生确定性的路由尺寸变体,其身份包含附件 id、变换版本、目标尺寸、字节目标及编码参数。纯函数导出 `requestImageDimensions` 与 `longEdgeDimensions` 按总像素预算及可选宽高限制,或精确长边计算保持宽高比的尺寸,使路由与请求定价共享同一套几何计算。`imageHostPath` 只向需要把该位置映射到执行环境的受信任同进程消费方暴露实现拥有的宿主位置。调用方组合有序批次,而实现负责管理压缩并发、缓存与 singleflight。读取、流式写入和投影保留调用方的取消语义。失败带有稳定且机器可读的错误码,运行时即可识别可由调用方修正的准入子集,让每个协议适配器映射自己的词汇;各操作的确切约定见 [`src/index.ts`](src/index.ts) 与 [`src/error.ts`](src/error.ts)。 ### 源码地图 diff --git a/packages/attachment/attachment/src/request-projection.ts b/packages/attachment/attachment/src/request-projection.ts index 4e809a3632..5c1d15169a 100644 --- a/packages/attachment/attachment/src/request-projection.ts +++ b/packages/attachment/attachment/src/request-projection.ts @@ -10,18 +10,22 @@ export interface ProjectedDimensions { } /** - * Compute aspect-preserving integer dimensions within a hard total-pixel budget. + * Compute aspect-preserving integer dimensions within total-pixel, width, and height limits. * @param width - positive source width. * @param height - positive source height. * @param maxPixels - positive width-times-height cap. + * @param maxWidth - optional maximum width in pixels. + * @param maxHeight - optional maximum height in pixels. * @returns inward-rounded dimensions; small images are not enlarged. */ export function requestImageDimensions( width: number, height: number, maxPixels: number, + maxWidth = Infinity, + maxHeight = Infinity, ): ProjectedDimensions { - const scale = Math.min(1, Math.sqrt(maxPixels / (width * height))) + const scale = Math.min(1, Math.sqrt(maxPixels / (width * height)), maxWidth / width, maxHeight / height) if (scale === 1) return { width, height } if (width >= height) { let projectedWidth = Math.max(1, Math.floor(width * scale)) diff --git a/packages/attachment/attachment/tests/request-projection.spec.ts b/packages/attachment/attachment/tests/request-projection.spec.ts index 2db1578863..edd58c0539 100644 --- a/packages/attachment/attachment/tests/request-projection.spec.ts +++ b/packages/attachment/attachment/tests/request-projection.spec.ts @@ -23,6 +23,22 @@ describe('request image dimensions', () => { expect(projected.width * projected.height).toBeLessThanOrEqual(640_000) }) + it.each([ + [1146, 3657, 4194304, 2000, 2000, 627, 2000], + [3657, 1146, 4194304, 2000, 2000, 2000, 627], + [4000, 800, 4194304, 3000, 300, 1500, 300], + [800, 4000, 4194304, 300, 3000, 300, 1500], + [4000, 4000, 1000000, 2000, 2000, 1000, 1000], + [320, 240, 4194304, 2000, 2000, 320, 240], + [1, 8192, 4194304, 2000, 2000, 1, 2000], + ])('fits %sx%s within %s pixels and %sx%s', (width, height, pixels, maxWidth, maxHeight, expectedWidth, expectedHeight) => { + const projected = requestImageDimensions(width, height, pixels, maxWidth, maxHeight) + expect(projected).toEqual({ width: expectedWidth, height: expectedHeight }) + expect(projected.width * projected.height).toBeLessThanOrEqual(pixels) + expect(projected.width).toBeLessThanOrEqual(maxWidth) + expect(projected.height).toBeLessThanOrEqual(maxHeight) + }) + it('rounds a portrait inward when integer aspect rounding crosses the pixel cap', () => { expect(requestImageDimensions(2, 4, 5)).toEqual({ width: 1, height: 2 }) }) diff --git a/packages/llm/llm-pi-ai/README.i18n.yaml b/packages/llm/llm-pi-ai/README.i18n.yaml index fd6a360e8b..10587dc71c 100644 --- a/packages/llm/llm-pi-ai/README.i18n.yaml +++ b/packages/llm/llm-pi-ai/README.i18n.yaml @@ -21,8 +21,8 @@ en: f3b761c7c7ecb82f zh: e10d999aa348ef86 /deepseek-ai-dsh-llm-pi-ai/use-this-package/configure-provider-routes: - en: 12d3d1506c72ac8b - zh: d966efb555110713 + en: 7562a7074d15bcaa + zh: 0f0337d6ab8778b8 /deepseek-ai-dsh-llm-pi-ai/use-this-package/sign-in-to-a-provider: en: c36f66438638ae08 zh: 066a2fc4cb97c86f diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index 2bba84d774..ecc3a84888 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -46,7 +46,8 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie baseURL: https://proxy.example.com:8443 reasoning: high requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default - requestImageMaxBytes: 1048576 # raw bytes before base64 expansion + requestImageMaxDimension: 3000 # override catalog width and height limits + requestImageMaxBytes: 1048576 # override raw bytes before base64 expansion maxRequestImageBytes: 20971520 # accumulated base64 payload maxRequestImages: 50 # retained image occurrences imageOffloadCountQuantum: 10 # oldest images offloaded per count overflow @@ -86,12 +87,15 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie | `defaultContextWindow` | `1,000,000` | Capacity fallback for undescribed models | | `defaultMaxTokens` | `128,000` | Output-cap fallback for undescribed models | | `requestImagePixelBudget` | `4,194,304` | Total-pixel budget for each deterministic request image | -| `requestImageMaxBytes` | `1 MiB` | Encoded-byte target for each request image before base64 expansion | +| `requestImageMaxDimension` | catalog width/height limits | Maximum width and height for each request image; an explicit value overrides both catalog limits | +| `requestImageMaxBytes` | catalog base64 budget converted to raw bytes; otherwise `1 MiB` | Encoded-byte target before base64 expansion; an explicit value overrides the catalog budget | | `maxRequestImageBytes` | `20 MiB` | Aggregate base64 image-payload bound; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED` | | `maxRequestImages` | `50` | Retained request-image count bound; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED`. The default follows Azure OpenAI's 50-image limit; raise it on routes whose provider accepts more images | | `imageOffloadCountQuantum` | `10`, capped at `maxRequestImages` | Oldest images offloaded per count overflow | | `retryPolicy` | normal, 5 retries | Provider-owned retry policy executed by `dsh-llm-retry` | +Request images inherit `inputLimits.images.resize.maxWidth`, `maxHeight`, and `maxBytes` from the selected pi-ai catalog model. The catalog byte budget counts base64 payload, so its raw target is `3 × floor(maxBytes / 4)`. Route overrides take precedence, including on custom gateways. Missing catalog dimensions leave that axis uncapped by the route; missing bytes retain the 1 MiB target. Total pixels remain governed by `requestImagePixelBudget`. These limits apply to retained history images on every request and to screenshot coordinate targets; stored attachments are unchanged. The encoding quality ladder can still exceed the byte target when no quality fits. Request counts, aggregate payload bounds, and encoding quality remain governed by DSH's existing policies. + The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-llm-pi-ai) is the exhaustive source for every accepted field and its JSDoc. ### Sign in to a provider diff --git a/packages/llm/llm-pi-ai/README.zh.md b/packages/llm/llm-pi-ai/README.zh.md index 9a964b8681..bf163b9d64 100644 --- a/packages/llm/llm-pi-ai/README.zh.md +++ b/packages/llm/llm-pi-ai/README.zh.md @@ -46,7 +46,8 @@ kind: "package-reference" baseURL: https://proxy.example.com:8443 reasoning: high requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default - requestImageMaxBytes: 1048576 # raw bytes before base64 expansion + requestImageMaxDimension: 3000 # override catalog width and height limits + requestImageMaxBytes: 1048576 # override raw bytes before base64 expansion maxRequestImageBytes: 20971520 # accumulated base64 payload maxRequestImages: 50 # retained image occurrences imageOffloadCountQuantum: 10 # oldest images offloaded per count overflow @@ -86,12 +87,15 @@ kind: "package-reference" | `defaultContextWindow` | `1,000,000` | 未描述模型的容量回退 | | `defaultMaxTokens` | `128,000` | 未描述模型的输出上限回退 | | `requestImagePixelBudget` | `4,194,304` | 每张确定性请求图片的总像素预算 | -| `requestImageMaxBytes` | `1 MiB` | 每张请求图片在 base64 扩展前的编码字节目标 | +| `requestImageMaxDimension` | 目录中的宽高限制 | 每张请求图片的最大宽度和高度;显式配置会覆盖目录中的两个限制 | +| `requestImageMaxBytes` | 目录的 base64 预算换算为原始字节;否则为 `1 MiB` | base64 扩展前的编码字节目标;显式配置会覆盖目录预算 | | `maxRequestImageBytes` | `20 MiB` | base64 图片载荷总上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败 | | `maxRequestImages` | `50` | 保留请求图片数量上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败。默认值取 Azure OpenAI 的 50 张上限;提供方接受更多图片的路由应调高 | | `imageOffloadCountQuantum` | `10`,不超过 `maxRequestImages` | 每次数量超限时省略的最老图片数 | | `retryPolicy` | normal,5 次重试 | 由 `dsh-llm-retry` 执行的提供方自有重试策略 | +请求图片继承所选 pi-ai 目录模型的 `inputLimits.images.resize.maxWidth`、`maxHeight` 和 `maxBytes`。目录字节预算按 base64 载荷计算,因此原始字节目标为 `3 × floor(maxBytes / 4)`。路由显式配置优先,自定义网关也可使用。目录缺少某个尺寸时,路由不限制该轴;缺少字节预算时,保留 1 MiB 目标。总像素仍由 `requestImagePixelBudget` 控制。这些限制每次请求都会应用于保留的历史图片和截图坐标目标,已存附件保持不变。编码质量阶梯中没有结果满足字节目标时,结果仍可能超过目标。请求图片数量、总载荷限制和编码质量继续使用 DSH 的现有策略。 + 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-llm-pi-ai)是每个受支持字段及其 JSDoc 的穷尽式真源。 ### 登录提供方 diff --git a/packages/llm/llm-pi-ai/src/adapter.ts b/packages/llm/llm-pi-ai/src/adapter.ts index 89b9edff2c..e456b89db9 100644 --- a/packages/llm/llm-pi-ai/src/adapter.ts +++ b/packages/llm/llm-pi-ai/src/adapter.ts @@ -60,6 +60,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import { idleWatchdog, timeoutOf } from '@deepseek-ai/dsh-timeout' import type { ResolvedPiAiProviderProfile } from './config.ts' import { requestImageTarget, toPiContext } from './context.ts' +import { resolveImageRequestBudget } from './image-policy.ts' import { conversationUpdates, createModels, getSupportedThinkingLevels } from './models.ts' import { toStreamChunks } from './stream.ts' import { bindThinkingToPrefix } from './prefix-binding.ts' @@ -288,9 +289,9 @@ export class PiAiAdapter extends LlmAdapter { override imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef) { const snapshot = this.current() - this.modelOf(snapshot, provider, model) + const selected = this.modelOf(snapshot, provider, model) const profile = this.profileOf(snapshot, provider) - return requestImageTarget(image, { maxPixels: profile.requestImagePixelBudget, maxBytes: profile.requestImageMaxBytes }) + return requestImageTarget(image, resolveImageRequestBudget(selected, profile)) } /** @@ -462,10 +463,7 @@ export class PiAiAdapter extends LlmAdapter { maxRequestImageBytes: profile.maxRequestImageBytes, maxRequestImages: profile.maxRequestImages, imageOffloadCountQuantum: profile.imageOffloadCountQuantum, - requestImagePolicy: { - maxPixels: profile.requestImagePixelBudget, - maxBytes: profile.requestImageMaxBytes, - }, + requestImagePolicy: resolveImageRequestBudget(model, profile), }, onReplayDegrade, updates.systemPromptUpdate === 'in-history', prefixDigests) const manualThinking = model.reasoning && reasoning !== undefined && reasoning !== 'off' && (model as Model<'anthropic-messages'>).compat?.forceAdaptiveThinking !== true diff --git a/packages/llm/llm-pi-ai/src/config.ts b/packages/llm/llm-pi-ai/src/config.ts index 9de6c4416e..bc09cf6a7b 100644 --- a/packages/llm/llm-pi-ai/src/config.ts +++ b/packages/llm/llm-pi-ai/src/config.ts @@ -198,9 +198,12 @@ export interface PiAiProviderProfile { imageOffloadCountQuantum?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number + /** Maximum width and height for each request image; omission uses the selected pi-ai model's resize limits. */ + requestImageMaxDimension?: number /** - * Raw encoded-byte target for each deterministic inline request version; - * the smallest quality-ladder output is used when no quality fits. + * Raw encoded-byte target overriding the selected model's base64 byte budget; + * omission uses that budget converted to raw bytes, or 1 MiB without catalog metadata. + * The smallest quality-ladder output is used when no quality fits. */ requestImageMaxBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ @@ -226,8 +229,6 @@ export interface ResolvedPiAiProviderProfile imageOffloadCountQuantum: number /** Positive total-pixel request-version budget after defaulting. */ requestImagePixelBudget: number - /** Positive raw request-version byte target after defaulting; the smallest quality-ladder output is used when no quality fits. */ - requestImageMaxBytes: number /** Immutable retry policy captured with this provider route. */ retryPolicy: ResolvedRetryPolicy /** @@ -375,7 +376,8 @@ const profile = z.object({ maxRequestImages: z.number().step(1).min(1).default(DEFAULT_MAX_REQUEST_IMAGES), imageOffloadCountQuantum: z.number().step(1).min(1), requestImagePixelBudget: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET), - requestImageMaxBytes: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_MAX_BYTES), + requestImageMaxDimension: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), + requestImageMaxBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), retryPolicy: RetryPolicySchema, }) @@ -481,9 +483,11 @@ export function resolveProfiles( if (!Number.isSafeInteger(requestImagePixelBudget) || requestImagePixelBudget <= 0) { throw new Error(`llm-pi-ai: provider "${provider}" requestImagePixelBudget must be a positive safe integer`) } - const requestImageMaxBytes = source.requestImageMaxBytes ?? DEFAULT_REQUEST_IMAGE_MAX_BYTES - if (!Number.isSafeInteger(requestImageMaxBytes) || requestImageMaxBytes <= 0) { - throw new Error(`llm-pi-ai: provider "${provider}" requestImageMaxBytes must be a positive safe integer`) + for (const field of ['requestImageMaxDimension', 'requestImageMaxBytes'] as const) { + const value = source[field] + if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) { + throw new Error(`llm-pi-ai: provider "${provider}" ${field} must be a positive safe integer`) + } } // Detached from the configuration object because pi-ai types `Model.input` // mutable. The schema's explicit default covers an absent key, so an empty @@ -537,7 +541,6 @@ export function resolveProfiles( maxRequestImages, imageOffloadCountQuantum, requestImagePixelBudget, - requestImageMaxBytes, retryPolicy: resolveRetryPolicy(retryPolicy, `llm-pi-ai: provider "${provider}" retryPolicy`), ...rest.headers === undefined ? {} : { headers: { ...rest.headers } }, ...rest.thinkingBudgets === undefined ? {} : { thinkingBudgets: { ...rest.thinkingBudgets } }, diff --git a/packages/llm/llm-pi-ai/src/context.ts b/packages/llm/llm-pi-ai/src/context.ts index fa8b833d43..5d6deb8bb0 100644 --- a/packages/llm/llm-pi-ai/src/context.ts +++ b/packages/llm/llm-pi-ai/src/context.ts @@ -284,6 +284,10 @@ export interface PiImageRequestContext { export interface PiImageRequestBudget { /** Total-pixel budget; larger sources are downscaled proportionally. */ maxPixels: number + /** Maximum width inherited from the model or explicitly overridden by the route. */ + maxWidth?: number + /** Maximum height inherited from the model or explicitly overridden by the route. */ + maxHeight?: number /** Encoded-byte target for one request image. */ maxBytes: number } @@ -295,7 +299,10 @@ export interface PiImageRequestBudget { * @returns dimensions and byte target shared by serialization and screenshot coordinate mapping. */ export function requestImageTarget(ref: ImageAttachmentRef, budget: PiImageRequestBudget): ImageRequestTarget { - return { ...requestImageDimensions(ref.width, ref.height, budget.maxPixels), maxBytes: budget.maxBytes } + return { + ...requestImageDimensions(ref.width, ref.height, budget.maxPixels, budget.maxWidth, budget.maxHeight), + maxBytes: budget.maxBytes, + } } /** diff --git a/packages/llm/llm-pi-ai/src/image-policy.ts b/packages/llm/llm-pi-ai/src/image-policy.ts new file mode 100644 index 0000000000..6d7fef8146 --- /dev/null +++ b/packages/llm/llm-pi-ai/src/image-policy.ts @@ -0,0 +1,29 @@ +/** Resolve pi-ai image resize metadata and route-owned overrides. */ + +import type { Api, Model } from '@earendil-works/pi-ai' +import { DEFAULT_REQUEST_IMAGE_MAX_BYTES } from './config.ts' +import type { ResolvedPiAiProviderProfile } from './config.ts' +import type { PiImageRequestBudget } from './context.ts' + +/** + * Resolve one model's image dimensions and raw encoded-byte target. + * @param model - selected pi-ai catalog model. + * @param profile - validated route with optional overrides. + * @returns resize limits shared by request serialization and screenshot coordinates. + */ +export function resolveImageRequestBudget( + model: Pick, 'inputLimits'>, + profile: Pick, +): PiImageRequestBudget { + const resize = model.inputLimits?.images?.resize + const maxWidth = profile.requestImageMaxDimension ?? resize?.maxWidth + const maxHeight = profile.requestImageMaxDimension ?? resize?.maxHeight + // Each four base64 characters carry at most three raw bytes, including padding. + const catalogBytes = resize?.maxBytes === undefined ? undefined : Math.floor(resize.maxBytes / 4) * 3 + return { + maxPixels: profile.requestImagePixelBudget, + maxBytes: profile.requestImageMaxBytes ?? catalogBytes ?? DEFAULT_REQUEST_IMAGE_MAX_BYTES, + ...maxWidth === undefined ? {} : { maxWidth }, + ...maxHeight === undefined ? {} : { maxHeight }, + } +} diff --git a/packages/llm/llm-pi-ai/tests/adapter.spec.ts b/packages/llm/llm-pi-ai/tests/adapter.spec.ts index b0785b5f3e..816c4a0190 100644 --- a/packages/llm/llm-pi-ai/tests/adapter.spec.ts +++ b/packages/llm/llm-pi-ai/tests/adapter.spec.ts @@ -1260,3 +1260,34 @@ it('resolves the exact pi-ai image budget for screenshot coordinates', () => { .toEqual({ width: 100, height: 100, maxBytes: 50_000 }) expect(() => adapter.imageRequestTarget('missing', 'deepseek-flash', IMAGE_REF)).toThrow('does not own provider') }) + + +it.each([ + [{}, { width: 627, height: 2000, maxBytes: 3_538_944 }], + [{ requestImageMaxDimension: 3000, requestImageMaxBytes: 500_000 }, { width: 940, height: 3000, maxBytes: 500_000 }], +])('uses the same catalog and override image target for coordinates and the wire request: %j', async (overrides, expected) => { + const server = await mockServer([{ events: anthropicTextEvents }]) + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(RequestImageStore) + const store = ctx.attachments + const read = vi.spyOn(store, 'readImageRequest').mockImplementation(async (ref, target) => ({ + variantId: brandString(`sha256:${'c'.repeat(64)}`), attachment: ref, + data: Uint8Array.of(1), mediaType: ref.mediaType, bytes: 1, + width: target.width, height: target.height, depth: 'uchar', space: 'srgb', hasAlpha: false, + })) + const adapter = new PiAiAdapter({ + profiles: () => resolveProfiles({ anthropic: { apiKeyEnv: 'PI_TEST_KEY', baseURL: server.url, ...overrides } }), + resolveApiKey: () => Promise.resolve('test-key'), resolveAttachments: () => store, auth: memoryAuth(), + }) + const ref = { ...IMAGE_REF, width: 1146, height: 3657 } + expect(adapter.imageRequestTarget('anthropic', 'claude-sonnet-4-5', ref)).toEqual(expected) + const prepared = await adapter.prepareCall('anthropic', 'claude-sonnet-4-5') + const messages = Array.from({ length: 22 }, () => createUserMessage({ content: [{ type: 'image', attachment: ref }], source: { kind: 'user' } })) + const chunks = await Array.fromAsync(prepared.stream({ provider: 'anthropic', model: 'claude-sonnet-4-5', messages })) + expect(chunks.at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'stop' } }) + expect(read).toHaveBeenCalledTimes(1) + expect(read.mock.calls[0]?.[1]).toEqual(expected) + expect(JSON.stringify(server.requests[0])).toContain(`${expected.width}x${expected.height}`) + expect(ref).toMatchObject({ width: 1146, height: 3657 }) +}) diff --git a/packages/llm/llm-pi-ai/tests/config.spec.ts b/packages/llm/llm-pi-ai/tests/config.spec.ts index fe667fe58d..839816d5e4 100644 --- a/packages/llm/llm-pi-ai/tests/config.spec.ts +++ b/packages/llm/llm-pi-ai/tests/config.spec.ts @@ -86,9 +86,29 @@ describe('modality schema boundary', () => { }) describe('request image policy bounds', () => { + it('preserves omitted catalog defaults and explicit route overrides through the schema', () => { + const omitted = routeWith({})() as Options + const profile = resolveProfiles(omitted.providers).get('acme-gateway')! + expect(profile.requestImageMaxDimension).toBeUndefined() + expect(profile.requestImageMaxBytes).toBeUndefined() + const explicit = routeWith({ requestImageMaxDimension: 3000, requestImageMaxBytes: 2000000 })() as Options + expect(resolveProfiles(explicit.providers).get('acme-gateway')).toMatchObject({ + requestImageMaxDimension: 3000, requestImageMaxBytes: 2000000, + }) + }) + + it.each(['requestImageMaxDimension', 'requestImageMaxBytes'])('rejects invalid %s at the configuration parser', (field) => { + for (const value of [0, -1, 1.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) { + expect(routeWith({ [field]: value })).toThrow() + } + }) + it.each([ ['requestImagePixelBudget', 0, /requestImagePixelBudget must be a positive safe integer/], ['requestImagePixelBudget', Number.MAX_SAFE_INTEGER + 1, /requestImagePixelBudget must be a positive safe integer/], + ['requestImageMaxDimension', 0, /requestImageMaxDimension must be a positive safe integer/], + ['requestImageMaxDimension', 1.5, /requestImageMaxDimension must be a positive safe integer/], + ['requestImageMaxDimension', Number.MAX_SAFE_INTEGER + 1, /requestImageMaxDimension must be a positive safe integer/], ['requestImageMaxBytes', 0, /requestImageMaxBytes must be a positive safe integer/], ['requestImageMaxBytes', 1.5, /requestImageMaxBytes must be a positive safe integer/], ] as const)('rejects %s=%s at service resolution', (field, value, message) => { diff --git a/packages/llm/llm-pi-ai/tests/fixtures/image-limits.ts b/packages/llm/llm-pi-ai/tests/fixtures/image-limits.ts new file mode 100644 index 0000000000..5f55dc3af0 --- /dev/null +++ b/packages/llm/llm-pi-ai/tests/fixtures/image-limits.ts @@ -0,0 +1,32 @@ +/** Recorded-session probe of catalog and locally overridden request images. */ + +import { readFile } from 'node:fs/promises' +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-attachment' +import type {} from '@deepseek-ai/dsh-llm' +import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' + +export const name = 'snapshot-pi-image-limits' +export const inject = ['tools', 'llm', 'attachments'] + +/** + * Expose encoded request dimensions through the real attachment provider. + * @param ctx - Loader context containing both configured pi routes. + */ +export function apply(ctx: Context): void { + ctx.effect(() => ctx.tools.register(defineContentToolFixture({ + name: 'snapshot_image_limits', + description: 'Report the source and request image sizes for the catalog and overridden routes.', + parameters: {}, + async execute() { + const source = await ctx.attachments.saveImage({ data: await readFile('tall.png'), mediaType: 'image/png' }) + const results = [] + for (const [provider, model] of [['anthropic', 'claude-sonnet-4-5'], ['image-override', 'vision']] as const) { + const target = ctx.llm.imageRequestTarget(provider, model, source) + const encoded = await ctx.attachments.readImageRequest(source, target) + results.push({ provider, target, encoded: { width: encoded.width, height: encoded.height } }) + } + return [{ type: 'text', text: JSON.stringify({ source: { width: source.width, height: source.height }, results }) }] + }, + }))) +} diff --git a/packages/llm/llm-pi-ai/tests/image-policy.spec.ts b/packages/llm/llm-pi-ai/tests/image-policy.spec.ts new file mode 100644 index 0000000000..df7312ecd1 --- /dev/null +++ b/packages/llm/llm-pi-ai/tests/image-policy.spec.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest' +import { resolveImageRequestBudget } from '../src/image-policy.ts' + +const profile = { requestImagePixelBudget: 2048 * 2048 } + +describe('pi-ai image resize policy', () => { + it('inherits independent dimensions and converts base64 bytes without exceeding the catalog budget', () => { + const policy = resolveImageRequestBudget({ inputLimits: { images: { resize: { + maxWidth: 2000, maxHeight: 3000, maxBytes: 4_718_592, + } } } }, profile) + expect(policy).toEqual({ maxPixels: 4_194_304, maxWidth: 2000, maxHeight: 3000, maxBytes: 3_538_944 }) + }) + + it.each([4, 5, 6, 7, 8, 101])('reserves base64 padding within a %s-byte budget', (maxBytes) => { + const policy = resolveImageRequestBudget({ inputLimits: { images: { resize: { maxBytes } } } }, profile) + expect(Buffer.alloc(policy.maxBytes).toString('base64').length).toBeLessThanOrEqual(maxBytes) + expect(Buffer.alloc(policy.maxBytes + 1).toString('base64').length).toBeGreaterThan(maxBytes) + }) + + it('lets explicit route values raise or lower both catalog dimensions and raw byte targets', () => { + const model = { inputLimits: { images: { resize: { maxWidth: 2000, maxHeight: 2000, maxBytes: 400 } } } } + for (const requestImageMaxDimension of [1000, 3000]) { + for (const requestImageMaxBytes of [100, 500]) { + expect(resolveImageRequestBudget(model, { ...profile, requestImageMaxDimension, requestImageMaxBytes })) + .toEqual({ + maxPixels: 4_194_304, maxWidth: requestImageMaxDimension, maxHeight: requestImageMaxDimension, maxBytes: requestImageMaxBytes, + }) + } + } + }) + + it.each([{}, { inputLimits: {} }, { inputLimits: { images: {} } }])('keeps existing defaults without catalog resize metadata: %j', (model) => { + expect(resolveImageRequestBudget(model, profile)).toEqual({ maxPixels: 4_194_304, maxBytes: 1_048_576 }) + }) + + it('inherits each omitted field independently', () => { + expect(resolveImageRequestBudget({ inputLimits: { images: { resize: { maxHeight: 1500 } } } }, profile)) + .toEqual({ maxPixels: 4_194_304, maxHeight: 1500, maxBytes: 1_048_576 }) + expect(resolveImageRequestBudget({}, { ...profile, requestImageMaxDimension: 3000, requestImageMaxBytes: 500_000 })) + .toEqual({ maxPixels: 4_194_304, maxWidth: 3000, maxHeight: 3000, maxBytes: 500_000 }) + }) +}) diff --git a/snapshots/session/pi-ai-image-limits/runtime.cordis.yml b/snapshots/session/pi-ai-image-limits/runtime.cordis.yml new file mode 100644 index 0000000000..e0004f361a --- /dev/null +++ b/snapshots/session/pi-ai-image-limits/runtime.cordis.yml @@ -0,0 +1,17 @@ +- id: llm-pi-ai + config: + providers: + anthropic: + apiKeyEnv: ANTHROPIC_API_KEY + image-override: + api: anthropic-messages + baseURL: https://image-override.invalid + requestImageMaxDimension: 3000 + requestImageMaxBytes: 1048576 + models: + - id: vision + input: [text, image] + +- insert: + - id: pi-image-limits-probe + name: '../../../packages/llm/llm-pi-ai/tests/fixtures/image-limits.ts' diff --git a/snapshots/session/pi-ai-image-limits/session.v4.jsonl b/snapshots/session/pi-ai-image-limits/session.v4.jsonl new file mode 100644 index 0000000000..d9846b413d --- /dev/null +++ b/snapshots/session/pi-ai-image-limits/session.v4.jsonl @@ -0,0 +1,22 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1783352044766,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"danger-full-access"}} +{"type":"sandbox/mode","data":{"mode":"danger-full-access"}} +{"type":"approval/policy","data":{"policy":"never"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Call snapshot_image_limits, then reply with the single word DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Call snapshot_image_limits, then reply with the single word DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} +{"type":"session/title","data":{"title":"Call snapshot_image_limits, then reply with","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_image_limits","name":"snapshot_image_limits","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_image_limits","name":"snapshot_image_limits","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_image_limits","name":"snapshot_image_limits","arguments":"{}"}} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_image_limits"},"toolCallId":"call_image_limits","content":[{"type":"text","text":"{\"source\":{\"width\":1146,\"height\":3657},\"results\":[{\"provider\":\"anthropic\",\"target\":{\"width\":627,\"height\":2000,\"maxBytes\":3538944},\"encoded\":{\"width\":627,\"height\":2000}},{\"provider\":\"image-override\",\"target\":{\"width\":940,\"height\":3000,\"maxBytes\":1048576},\"encoded\":{\"width\":940,\"height\":3000}}]}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"step/start","data":{"turn":1,"step":2}} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/pi-ai-image-limits/snapshot.yml b/snapshots/session/pi-ai-image-limits/snapshot.yml new file mode 100644 index 0000000000..a03bd41f0a --- /dev/null +++ b/snapshots/session/pi-ai-image-limits/snapshot.yml @@ -0,0 +1,8 @@ +version: 1 +scenario: pi-ai-image-limits +profile: headless +composition: default +recording: authored +header: + class: pi-ai-image-limits + pin: true diff --git a/snapshots/session/pi-ai-image-limits/workspace/tall.png b/snapshots/session/pi-ai-image-limits/workspace/tall.png new file mode 100644 index 0000000000000000000000000000000000000000..4d60d69a10cb812276c17dacb353aa1a6be229a1 GIT binary patch literal 19941 zcmeI(KPZG@0LSqkopbMgGHGbZXg4) zDbd|xGnhDoB#WF)ELZZpqg7e-UEZGe?R}R|&-1?DdU`j;5<@|Mt6x&kiN_`+PgV*! zzFKo-ulG13jUG9%fyu?)x4Usm(Qv8%`Qoc^J!P#&>zmTW)RI@qRc_zS1G(<|E^}Oc zFynZcAr4Fe76Wer-iUk-_$<-{v=L!Q6;s7jF;z?zQ^iyOcnp*Dh^c_ zM$95t&*4gCzuca*Bj5V(>*Jf*^&iR0pE~Lyo0e2=OUm{Y;J~QXsiU0x#Abe#yYPoIOY&WRk^)cJ=Y3($!A%Oq_2q1s}0tg_0 z00IagfB*srAbY@dzx!; N7m72Oh@IH!{5PI^k0}5E literal 0 HcmV?d00001 From 5e462070ea76df5aa19ce5b57deb29cdc8da778f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:28:22 +0800 Subject: [PATCH 02/54] =?UTF-8?q?=E9=AA=8C=E8=AF=81=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=E5=AD=97=E8=8A=82=E9=A2=84=E7=AE=97=E4=B8=8E=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=BF=AB=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/llm/llm-pi-ai/tests/adapter.spec.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/llm/llm-pi-ai/tests/adapter.spec.ts b/packages/llm/llm-pi-ai/tests/adapter.spec.ts index 816c4a0190..0f2c0c3d8a 100644 --- a/packages/llm/llm-pi-ai/tests/adapter.spec.ts +++ b/packages/llm/llm-pi-ai/tests/adapter.spec.ts @@ -389,7 +389,7 @@ describe('PiAiAdapter provider routing', () => { expect(readImageRequest).toHaveBeenCalledWith(ref, { width: 1, height: 1, - maxBytes: 1024 * 1024, + maxBytes: 3_538_944, }, expect.any(AbortSignal)) expect(JSON.stringify(server.requests[0])).toContain(MODEL_IMAGE_PATH) expect(server.paths).toEqual(['/v1/responses']) @@ -1276,13 +1276,18 @@ it.each([ data: Uint8Array.of(1), mediaType: ref.mediaType, bytes: 1, width: target.width, height: target.height, depth: 'uchar', space: 'srgb', hasAlpha: false, })) + let providers: Record = { + anthropic: { apiKeyEnv: 'PI_TEST_KEY', baseURL: server.url, ...overrides }, + } const adapter = new PiAiAdapter({ - profiles: () => resolveProfiles({ anthropic: { apiKeyEnv: 'PI_TEST_KEY', baseURL: server.url, ...overrides } }), + profiles: () => resolveProfiles(providers), resolveApiKey: () => Promise.resolve('test-key'), resolveAttachments: () => store, auth: memoryAuth(), }) const ref = { ...IMAGE_REF, width: 1146, height: 3657 } expect(adapter.imageRequestTarget('anthropic', 'claude-sonnet-4-5', ref)).toEqual(expected) const prepared = await adapter.prepareCall('anthropic', 'claude-sonnet-4-5') + providers = { anthropic: { ...providers['anthropic'], requestImageMaxDimension: 777, requestImageMaxBytes: 333 } } + expect(adapter.imageRequestTarget('anthropic', 'claude-sonnet-4-5', ref)).toMatchObject({ height: 777, maxBytes: 333 }) const messages = Array.from({ length: 22 }, () => createUserMessage({ content: [{ type: 'image', attachment: ref }], source: { kind: 'user' } })) const chunks = await Array.fromAsync(prepared.stream({ provider: 'anthropic', model: 'claude-sonnet-4-5', messages })) expect(chunks.at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'stop' } }) From 3e9f9b308dcd1c0b067e6d6ead69e3b135c426be Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:29:27 +0800 Subject: [PATCH 03/54] =?UTF-8?q?=E4=BD=BF=E7=94=A8=E4=BB=93=E5=BA=93?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E7=9A=84=E5=BC=82=E6=AD=A5=E8=BF=AD=E4=BB=A3?= =?UTF-8?q?=E6=94=B6=E9=9B=86=E6=B5=8B=E8=AF=95=E5=93=8D=E5=BA=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/llm/llm-pi-ai/tests/adapter.spec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/llm/llm-pi-ai/tests/adapter.spec.ts b/packages/llm/llm-pi-ai/tests/adapter.spec.ts index 0f2c0c3d8a..3c8ed928b0 100644 --- a/packages/llm/llm-pi-ai/tests/adapter.spec.ts +++ b/packages/llm/llm-pi-ai/tests/adapter.spec.ts @@ -1289,7 +1289,8 @@ it.each([ providers = { anthropic: { ...providers['anthropic'], requestImageMaxDimension: 777, requestImageMaxBytes: 333 } } expect(adapter.imageRequestTarget('anthropic', 'claude-sonnet-4-5', ref)).toMatchObject({ height: 777, maxBytes: 333 }) const messages = Array.from({ length: 22 }, () => createUserMessage({ content: [{ type: 'image', attachment: ref }], source: { kind: 'user' } })) - const chunks = await Array.fromAsync(prepared.stream({ provider: 'anthropic', model: 'claude-sonnet-4-5', messages })) + const chunks: unknown[] = [] + for await (const chunk of prepared.stream({ provider: 'anthropic', model: 'claude-sonnet-4-5', messages })) chunks.push(chunk) expect(chunks.at(-1)).toMatchObject({ type: 'finish', reason: { kind: 'stop' } }) expect(read).toHaveBeenCalledTimes(1) expect(read.mock.calls[0]?.[1]).toEqual(expected) From ffe6e45c42c97c5d9dc94fa0a26e1dbf4d2b0cc5 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 15:30:26 +0800 Subject: [PATCH 04/54] =?UTF-8?q?=E8=AE=B0=E5=BD=95=E7=9C=9F=E5=AE=9E?= =?UTF-8?q?=E5=9B=BE=E7=89=87=E7=BC=96=E7=A0=81=E5=B0=BA=E5=AF=B8=E7=9A=84?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E5=9B=9E=E6=94=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pi-ai-image-limits/session.v4.jsonl | 2 +- .../session/pi-ai-image-limits/snapshot.yml | 1 + .../tool-schemas.expected.json | 630 ++++++++++++++++++ 3 files changed, 632 insertions(+), 1 deletion(-) create mode 100644 snapshots/session/pi-ai-image-limits/tool-schemas.expected.json diff --git a/snapshots/session/pi-ai-image-limits/session.v4.jsonl b/snapshots/session/pi-ai-image-limits/session.v4.jsonl index d9846b413d..b77670a242 100644 --- a/snapshots/session/pi-ai-image-limits/session.v4.jsonl +++ b/snapshots/session/pi-ai-image-limits/session.v4.jsonl @@ -11,7 +11,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} -{"type":"session/title","data":{"title":"Call snapshot_image_limits, then reply with","messageSeqs":[8],"source":{"kind":"fallback"}}} +{"type":"session/title","data":{"title":"Call snapshot_image_limits, then reply w","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_image_limits","name":"snapshot_image_limits","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_image_limits","name":"snapshot_image_limits","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_image_limits","name":"snapshot_image_limits","arguments":"{}"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_image_limits"},"toolCallId":"call_image_limits","content":[{"type":"text","text":"{\"source\":{\"width\":1146,\"height\":3657},\"results\":[{\"provider\":\"anthropic\",\"target\":{\"width\":627,\"height\":2000,\"maxBytes\":3538944},\"encoded\":{\"width\":627,\"height\":2000}},{\"provider\":\"image-override\",\"target\":{\"width\":940,\"height\":3000,\"maxBytes\":1048576},\"encoded\":{\"width\":940,\"height\":3000}}]}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} diff --git a/snapshots/session/pi-ai-image-limits/snapshot.yml b/snapshots/session/pi-ai-image-limits/snapshot.yml index a03bd41f0a..39adb02445 100644 --- a/snapshots/session/pi-ai-image-limits/snapshot.yml +++ b/snapshots/session/pi-ai-image-limits/snapshot.yml @@ -6,3 +6,4 @@ recording: authored header: class: pi-ai-image-limits pin: true + systemPromptSource: text-turn diff --git a/snapshots/session/pi-ai-image-limits/tool-schemas.expected.json b/snapshots/session/pi-ai-image-limits/tool-schemas.expected.json new file mode 100644 index 0000000000..38a3c9cc25 --- /dev/null +++ b/snapshots/session/pi-ai-image-limits/tool-schemas.expected.json @@ -0,0 +1,630 @@ +{ + "initial": [ + { + "name": "apply_patch", + "description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.", + "parameters": { + "type": "object", + "properties": { + "input": { + "type": "string", + "description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "input" + ] + } + }, + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell; pass `workdir` instead of using `cd`. Managed `$DSH_*` variables expose current harness environment facts. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Provide `description` before `command` in the arguments. Before any delete or move, verify that the resolved absolute target path is the intended one; never run it against a computed path you have not checked. An unset variable expands to an empty string, so guard variables in such paths with `${VAR:?}`. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]`, a policy denial: do not retry another way.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap; on expiry the command moves to the background as a job instead of being killed." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact command the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "description", + "command" + ] + } + }, + { + "name": "create_goal", + "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend. Provide `file_path` before `old_string` and `new_string` in the arguments." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current session goal, including the id and revision that update_goal requires.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns up to 250 matches; a larger result reports where the complete match list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "job_kill", + "description": "Request cancellation of a running background job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job: output since the previous read for stream jobs, or the result of a finished final-output job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job finishes or the timeout expires; a timed-out wait leaves the job running. Defaults to false." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds with wait: true. Defaults to and is capped by configuration." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Large images are downscaled automatically; do not install image libraries or create thumbnails to inspect an image.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation.", + "parameters": { + "type": "object", + "properties": { + "agent": { + "type": "string", + "description": "The name of another agent in your subagent tree, as shown by list_agents." + }, + "message": { + "type": "string", + "description": "The message to deliver to the agent." + } + }, + "required": [ + "agent", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for a skill. Call it before acting on a task that names or clearly matches a skill in the session skill catalog.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "snapshot_image_limits", + "description": "Report the source and request image sizes for the catalog and overridden routes.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a task list to plan multi-step work and show progress; skip it for trivial single-step tasks. Add one todo per concrete step before you start. While work remains, keep the todos being worked on `in_progress`, several only when work runs in parallel. Mark each todo `completed` as soon as it is done.", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the current goal.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit, pause, and resume require a direct top-level human request. complete and blocked are also allowed during an automatic continuation of this goal; blocked is rejected before the configured minimum round count.", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Required only with action blocked: the concrete condition that persisted across rounds and blocks progress." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "wait_agent", + "description": "Wait for input at your next step, including agent messages, completion notifications, and user steering. Returns immediately if new input is pending. `timedOut: false` means new input is pending. Pending input is delivered to the model after code execution finishes.", + "parameters": { + "type": "object", + "properties": { + "timeout_ms": { + "type": "integer", + "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." + } + } + } + }, + { + "name": "web_fetch", + "description": "Fetch the content of a specific HTTP(S) URL and return it decoded to text.", + "parameters": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The HTTP(S) URL to fetch." + } + }, + "required": [ + "url" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "1–10 search queries; their results are merged.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. A stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) end the whole script instead of producing `null`. The script has no filesystem, network, timer, or Node.js APIs; the agents do the work.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain JavaScript body, not TypeScript and without an `export const meta` statement; top-level await is allowed. End with `return `; the JSON-serializable value is this tool's result." + }, + "meta": { + "type": "object", + "description": "The workflow identity as plain JSON, not code.", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background job: return a job id immediately instead of waiting; the return value arrives with the completion notice." + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend. Provide `file_path` before `content` in the arguments." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [] +} From 4c2b8fe3a38635c474bc7b26e3d6990e0227dd30 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 16:03:51 +0800 Subject: [PATCH 05/54] =?UTF-8?q?=E8=AF=B4=E6=98=8E=E5=8D=95=E5=9B=BE?= =?UTF-8?q?=E9=A2=84=E7=AE=97=E4=B8=8E=E5=9B=BE=E7=89=87=E8=81=9A=E5=90=88?= =?UTF-8?q?=E4=B8=8A=E9=99=90=E7=9A=84=E4=BA=A4=E4=BA=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- .../pi-image-resize-defaults/guide.i18n.yaml | 4 ++-- .../v0.2.2-rc.4/pi-image-resize-defaults/guide.md | 2 ++ .../v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md | 2 ++ packages/llm/llm-pi-ai/README.i18n.yaml | 4 ++-- packages/llm/llm-pi-ai/README.md | 2 ++ packages/llm/llm-pi-ai/README.zh.md | 2 ++ packages/llm/llm-pi-ai/src/config.ts | 11 ++++------- 9 files changed, 18 insertions(+), 13 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 93d9736f16..e8a487e083 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2147,7 +2147,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:252`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:249`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 4d6205a0c5..2c45496d33 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2149,7 +2149,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:252`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:249`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml index 2bc13efd1e..fb9a16c19d 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml @@ -9,8 +9,8 @@ en: de949ea90a970dc4 zh: bc79f0d1bef40861 /pi-ai-image-resize-defaults/change: - en: bd83d50b52b9c6c3 - zh: 8e634018bf440a9e + en: 904cf562c1617774 + zh: 3c9cba949e792a1b /pi-ai-image-resize-defaults/migration: en: d77384609b1c5aa6 zh: 06be2b4496cfa037 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md index ceef66be1e..94ed5e1af0 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md @@ -12,6 +12,8 @@ English | [中文](guide.zh.md) The route's `requestImageMaxBytes` remains a raw encoded-byte override. The new `requestImageMaxDimension` overrides both catalog dimensions. Models without resize metadata retain the existing defaults. Both request serialization and screenshot coordinate targets use these resolved limits. +The aggregate `maxRequestImageBytes` budget stays at 20 MiB. Larger encoded images can cause earlier history-image offloading and reduce prefix-cache reuse; see the [retained-image example](../../../../packages/llm/llm-pi-ai/README.md#model-experience). The per-image byte target can be lowered independently of the aggregate budget. + ## Migration 1. Leave both overrides unset to follow the installed pi-ai catalog. Review long-image resolution and request sizes after upgrading pi-ai. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md index 5ba14c34aa..9a8ccb0271 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md @@ -12,6 +12,8 @@ description: "pi-ai 请求图片继承目录中的尺寸和字节预算,路由 路由的 `requestImageMaxBytes` 仍用于覆盖原始编码字节目标。新增的 `requestImageMaxDimension` 同时覆盖目录中的宽度和高度限制。没有缩放元数据的模型保留现有默认值。请求序列化和截图坐标目标使用同一组解析后的限制。 +总预算 `maxRequestImageBytes` 仍为 20 MiB。编码后的图片变大时,历史图片可能更早被省略,前缀缓存的复用范围也会减小,详见[图片保留数量示例](../../../../packages/llm/llm-pi-ai/README.zh.md#model-experience)。单图字节目标可以独立于总预算调低。 + ## 迁移 1. 不配置这两个覆盖字段,即可跟随已安装的 pi-ai 目录。升级 pi-ai 后,检查长图分辨率和请求大小。 diff --git a/packages/llm/llm-pi-ai/README.i18n.yaml b/packages/llm/llm-pi-ai/README.i18n.yaml index 10587dc71c..6909c3196b 100644 --- a/packages/llm/llm-pi-ai/README.i18n.yaml +++ b/packages/llm/llm-pi-ai/README.i18n.yaml @@ -72,8 +72,8 @@ en: e7348db3f7115960 zh: 5fd5fb09d7d09982 /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/what-the-model-sees: - en: f618a730aaa904ce - zh: 0b77a5b799b049e3 + en: b47db2f50b2b0e7f + zh: bf8dfe6628c2b85f /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/token-effect: en: 820221e8ae37aa61 zh: 7e6ff4db10067fc0 diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index ecc3a84888..2bb79dd29c 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -229,6 +229,8 @@ Read these pages when the package-level contract is not enough. They move from t The selected catalog model receives system-message text, conversation history, tools, and supported sampling fields. The adapter preserves later system messages in history order when the catalog model declares `supportsMidConvoSystemMessages`. Otherwise, it converts each non-empty later system message to a user message wrapped in `` before passing it to pi-ai. The wrapper does not grant system-role priority. One-shot `GenerateOptions.system` precedes the initial history prompt. Repeated system messages remain repeated; empty system messages are skipped without discarding earlier text. Tool-update capabilities select the shared historical declaration projection; pi-ai receives initially active tools and grouped developer updates carrying additions and supported removals. When every projected declaration of an Anthropic request with tool updates is deferred, the initially active tools are one placeholder, `DeferredToolPlaceholder`, whose description tells the model never to call it; a call reaches the ordinary unknown-tool result. Anthropic receives later tool definitions inline in the update message. Replay preserves tool-call namespaces for dynamically loaded Responses tools. Each retained image is preceded by text naming its complete attachment id and actual request dimensions. When the current execution filesystem maps the attachment provider's host object, the text also carries a read-only normalized-object path and warns that normalization or request projection may have resized or re-encoded the upload. Each occurrence selected by a logged image-offload decision keeps its own identity and currently resolved access in replacement text, and its normalized attachment is not read or transformed. When the retained occurrences still exceed the route's `maxRequestImages`, or their exact base64 payload exceeds its `maxRequestImageBytes`, the call fails with `IMAGE_OFFLOAD_REQUIRED` so `dsh-compaction-image-offload` records the selected occurrences in an `image/offload` event and retries the step. Provider-native replay metadata is restored only when the adapter validates it for the historical content. On Anthropic Messages routes, a replayed response whose request prefix changed since generation, for example through compaction, loses its thinking blocks; its text and tool calls remain. `imageRequestTarget(provider, model, image)` exposes the same request-image dimensions and byte target to screenshot consumers; adapters without image resizing preserve the normalized source. +The aggregate image budget remains 20 MiB when a catalog supplies a larger per-image target. For images whose actual base64 payload is 4.5 MiB each, four total 18 MiB and fit; five total 22.5 MiB and trigger image offloading. Smaller encoded images allow more retained occurrences, subject to `maxRequestImages`. A larger per-image target can therefore cause earlier offloading and end prefix reuse at the first replaced image. Lower `requestImageMaxBytes` to ask the encoder for smaller outputs, or raise `maxRequestImageBytes` only when the gateway has room for the larger payload plus other request content. + #### Token effect Provider tokenization governs exact input. Retained images add the stable attachment and coordinate descriptor; the offload placeholder replaces an omitted image's visual tokens. Replay metadata may let a native API reuse provider-side state. diff --git a/packages/llm/llm-pi-ai/README.zh.md b/packages/llm/llm-pi-ai/README.zh.md index bf163b9d64..167b2078f5 100644 --- a/packages/llm/llm-pi-ai/README.zh.md +++ b/packages/llm/llm-pi-ai/README.zh.md @@ -229,6 +229,8 @@ Anthropic 可以将每个已签名 thinking 块绑定到生成它时的请求前 所选目录模型会收到系统消息文本、对话历史、工具以及支持的采样字段。目录模型声明 `supportsMidConvoSystemMessages` 时,适配器按历史顺序保留后续系统消息。否则,适配器在传给 pi-ai 之前,将每条非空的后续系统消息转换为以 `` 包裹的用户消息。包裹文本不会赋予系统角色优先级。单次调用的 `GenerateOptions.system` 放在初始历史提示词之前。重复的系统消息仍会重复发送;空系统消息会被跳过,不会丢弃之前的文本。工具更新能力选择共享的历史声明投影;pi-ai 接收初始可用工具,以及按开发者消息分组的新增和受支持的移除更新。当包含工具更新的 Anthropic 请求中所有投影后的声明均为延迟加载时,初始可用工具为一个占位工具 `DeferredToolPlaceholder`,其描述要求模型永不调用它;若被调用,会得到普通的未知工具结果。Anthropic 在更新消息中以内联方式接收后续工具定义。回放会保留工具调用命名空间,以支持动态加载的 Responses 工具。每张保留图片前都会有文本,注明其完整附件 id 与实际请求尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,该文本还会携带只读规范化对象路径,并警告规范化或请求投影可能缩放或重新编码上传内容。日志中的图片省略决策选中的每个出现位置都会在替换文本中保留自己的身份与当前已解析访问方式,其规范化附件不会读取或变换。当保留的出现位置数量仍超过路由的 `maxRequestImages`,或其精确 base64 载荷超过 `maxRequestImageBytes` 时,调用以 `IMAGE_OFFLOAD_REQUIRED` 失败,由 `dsh-compaction-image-offload` 用 `image/offload` 事件记录所选位置并重试步骤。提供方原生回放元数据只在适配器针对历史内容校验通过后恢复。在 Anthropic Messages 路由上,如果回放响应的请求前缀自生成后发生变化(例如经过压缩),该响应会丢失 thinking 块;其文本和工具调用保留。 `imageRequestTarget(provider, model, image)` 向截图调用方提供与模型请求一致的图片尺寸和字节目标;不缩放图片的适配器保留归一化后的原图。 +目录提供更大的单图目标时,图片总预算仍为 20 MiB。若每张图的实际 base64 载荷均为 4.5 MiB,4 张共 18 MiB 可以保留,5 张共 22.5 MiB 会触发图片省略。编码后更小的图片可以保留更多,但仍受 `maxRequestImages` 限制。因此,较大的单图目标可能使图片更早被省略,并从第一张被替换的图片处终止前缀复用。可以调低 `requestImageMaxBytes`,让编码器尝试更小的输出;只有网关能容纳更大图片载荷及请求中的其他内容时,才调高 `maxRequestImageBytes`。 + #### Token 影响 提供方分词决定精确输入。保留图片会添加稳定的附件与坐标描述符;卸载占位符会替代省略图片的视觉 token。回放元数据可能让原生 API 复用提供方侧状态。 diff --git a/packages/llm/llm-pi-ai/src/config.ts b/packages/llm/llm-pi-ai/src/config.ts index bc09cf6a7b..81b21d3526 100644 --- a/packages/llm/llm-pi-ai/src/config.ts +++ b/packages/llm/llm-pi-ai/src/config.ts @@ -47,13 +47,10 @@ import { buildProvider, supportedProtocols } from './provider.ts' export const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000 /** - * Default request-level bound on base64-encoded image payload. Every image in - * history is re-encoded into every request body, so an unbounded conversation - * eventually exceeds a provider or gateway request-size cap and the session - * can never complete another request. The 20MiB default admits fifteen 1MiB - * request versions after base64 expansion and reserves request capacity for - * system prompts, history, tools, and JSON. - * Deployments behind stricter gateways lower it per route. + * Default cap on aggregate base64 image payload, excluding text, tools, and + * JSON overhead. Retained image count depends on actual encoded sizes; + * per-image catalog targets do not raise this cap. Deployments keep it below + * the gateway's complete request-size limit to leave room for other content. */ export const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024 /** From 53d8be7367ae223f56d46954888350d3ab89811a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 16:06:48 +0800 Subject: [PATCH 06/54] =?UTF-8?q?=E6=8C=89=E6=A8=A1=E5=9E=8B=E4=BD=93?= =?UTF-8?q?=E9=AA=8C=E5=AD=97=E6=AE=B5=E7=BB=84=E7=BB=87=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E9=A2=84=E7=AE=97=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/llm/llm-pi-ai/README.i18n.yaml | 12 ++++++------ packages/llm/llm-pi-ai/README.md | 8 ++++---- packages/llm/llm-pi-ai/README.zh.md | 8 ++++---- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/packages/llm/llm-pi-ai/README.i18n.yaml b/packages/llm/llm-pi-ai/README.i18n.yaml index 6909c3196b..f357c55522 100644 --- a/packages/llm/llm-pi-ai/README.i18n.yaml +++ b/packages/llm/llm-pi-ai/README.i18n.yaml @@ -21,8 +21,8 @@ en: f3b761c7c7ecb82f zh: e10d999aa348ef86 /deepseek-ai-dsh-llm-pi-ai/use-this-package/configure-provider-routes: - en: 7562a7074d15bcaa - zh: 0f0337d6ab8778b8 + en: 9e30fcea0804ba7f + zh: d6db5d4e7e2c4cfc /deepseek-ai-dsh-llm-pi-ai/use-this-package/sign-in-to-a-provider: en: c36f66438638ae08 zh: 066a2fc4cb97c86f @@ -72,14 +72,14 @@ en: e7348db3f7115960 zh: 5fd5fb09d7d09982 /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/what-the-model-sees: - en: b47db2f50b2b0e7f - zh: bf8dfe6628c2b85f + en: f553e097cdbb3b3d + zh: 33b579f312aad4fa /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/token-effect: en: 820221e8ae37aa61 zh: 7e6ff4db10067fc0 /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/kv-cache-effect: - en: 6613d52e459d86da - zh: 7d0627e7ff8299e8 + en: 79acfd5cccec0fc5 + zh: d09370981bffc6a1 /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-response: en: 802d7ff60a1d03ff zh: c41c56e28f3e8680 diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index 2bb79dd29c..9523627617 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -96,6 +96,8 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie Request images inherit `inputLimits.images.resize.maxWidth`, `maxHeight`, and `maxBytes` from the selected pi-ai catalog model. The catalog byte budget counts base64 payload, so its raw target is `3 × floor(maxBytes / 4)`. Route overrides take precedence, including on custom gateways. Missing catalog dimensions leave that axis uncapped by the route; missing bytes retain the 1 MiB target. Total pixels remain governed by `requestImagePixelBudget`. These limits apply to retained history images on every request and to screenshot coordinate targets; stored attachments are unchanged. The encoding quality ladder can still exceed the byte target when no quality fits. Request counts, aggregate payload bounds, and encoding quality remain governed by DSH's existing policies. +Lower `requestImageMaxBytes` to ask the encoder for smaller outputs, or raise `maxRequestImageBytes` only when the gateway has room for the larger payload plus other request content. + The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-llm-pi-ai) is the exhaustive source for every accepted field and its JSDoc. ### Sign in to a provider @@ -227,9 +229,7 @@ Read these pages when the package-level contract is not enough. They move from t #### What the model sees -The selected catalog model receives system-message text, conversation history, tools, and supported sampling fields. The adapter preserves later system messages in history order when the catalog model declares `supportsMidConvoSystemMessages`. Otherwise, it converts each non-empty later system message to a user message wrapped in `` before passing it to pi-ai. The wrapper does not grant system-role priority. One-shot `GenerateOptions.system` precedes the initial history prompt. Repeated system messages remain repeated; empty system messages are skipped without discarding earlier text. Tool-update capabilities select the shared historical declaration projection; pi-ai receives initially active tools and grouped developer updates carrying additions and supported removals. When every projected declaration of an Anthropic request with tool updates is deferred, the initially active tools are one placeholder, `DeferredToolPlaceholder`, whose description tells the model never to call it; a call reaches the ordinary unknown-tool result. Anthropic receives later tool definitions inline in the update message. Replay preserves tool-call namespaces for dynamically loaded Responses tools. Each retained image is preceded by text naming its complete attachment id and actual request dimensions. When the current execution filesystem maps the attachment provider's host object, the text also carries a read-only normalized-object path and warns that normalization or request projection may have resized or re-encoded the upload. Each occurrence selected by a logged image-offload decision keeps its own identity and currently resolved access in replacement text, and its normalized attachment is not read or transformed. When the retained occurrences still exceed the route's `maxRequestImages`, or their exact base64 payload exceeds its `maxRequestImageBytes`, the call fails with `IMAGE_OFFLOAD_REQUIRED` so `dsh-compaction-image-offload` records the selected occurrences in an `image/offload` event and retries the step. Provider-native replay metadata is restored only when the adapter validates it for the historical content. On Anthropic Messages routes, a replayed response whose request prefix changed since generation, for example through compaction, loses its thinking blocks; its text and tool calls remain. `imageRequestTarget(provider, model, image)` exposes the same request-image dimensions and byte target to screenshot consumers; adapters without image resizing preserve the normalized source. - -The aggregate image budget remains 20 MiB when a catalog supplies a larger per-image target. For images whose actual base64 payload is 4.5 MiB each, four total 18 MiB and fit; five total 22.5 MiB and trigger image offloading. Smaller encoded images allow more retained occurrences, subject to `maxRequestImages`. A larger per-image target can therefore cause earlier offloading and end prefix reuse at the first replaced image. Lower `requestImageMaxBytes` to ask the encoder for smaller outputs, or raise `maxRequestImageBytes` only when the gateway has room for the larger payload plus other request content. +The selected catalog model receives system-message text, conversation history, tools, and supported sampling fields. The adapter preserves later system messages in history order when the catalog model declares `supportsMidConvoSystemMessages`. Otherwise, it converts each non-empty later system message to a user message wrapped in `` before passing it to pi-ai. The wrapper does not grant system-role priority. One-shot `GenerateOptions.system` precedes the initial history prompt. Repeated system messages remain repeated; empty system messages are skipped without discarding earlier text. Tool-update capabilities select the shared historical declaration projection; pi-ai receives initially active tools and grouped developer updates carrying additions and supported removals. When every projected declaration of an Anthropic request with tool updates is deferred, the initially active tools are one placeholder, `DeferredToolPlaceholder`, whose description tells the model never to call it; a call reaches the ordinary unknown-tool result. Anthropic receives later tool definitions inline in the update message. Replay preserves tool-call namespaces for dynamically loaded Responses tools. Each retained image is preceded by text naming its complete attachment id and actual request dimensions. When the current execution filesystem maps the attachment provider's host object, the text also carries a read-only normalized-object path and warns that normalization or request projection may have resized or re-encoded the upload. Each occurrence selected by a logged image-offload decision keeps its own identity and currently resolved access in replacement text, and its normalized attachment is not read or transformed. When the retained occurrences still exceed the route's `maxRequestImages`, or their exact base64 payload exceeds its `maxRequestImageBytes`, the call fails with `IMAGE_OFFLOAD_REQUIRED` so `dsh-compaction-image-offload` records the selected occurrences in an `image/offload` event and retries the step. The default 20 MiB aggregate budget holds four images of 4.5 MiB actual base64 payload each (18 MiB), while a fifth exceeds it (22.5 MiB). Smaller encodings can retain more images, subject to the count limit. Provider-native replay metadata is restored only when the adapter validates it for the historical content. On Anthropic Messages routes, a replayed response whose request prefix changed since generation, for example through compaction, loses its thinking blocks; its text and tool calls remain. `imageRequestTarget(provider, model, image)` exposes the same request-image dimensions and byte target to screenshot consumers; adapters without image resizing preserve the normalized source. #### Token effect @@ -237,7 +237,7 @@ Provider tokenization governs exact input. Retained images add the stable attach #### KV Cache effect -Later system messages supplied to the adapter stay out of the initial prompt, preserving the preceding request prefix. This does not change the agent loop’s prompt admission, which consolidates updates on routes without native system-update support. Conversion preserves logical request order, while image handles and offload placeholders add model-visible text. A changed execution-world path rewrites a historical handle and can prevent reuse from that image even when attachment identity and request bytes stay stable. Changing adapter instance, provider, model, or another upstream token has the same suffix effect. Omitting stale Anthropic thinking follows a prefix change that already ended reuse at the changed message. The first request that omits thinking recorded without a digest ends reuse at the first such message once. An offload decision turns an earlier image into placeholder text, so reuse ends at that message; the omission never reverts, so the prefix stays stable until the next decision. A count overflow offloads `imageOffloadCountQuantum` images at once, so a saturated route ends reuse at the oldest retained image once per that many new images. +Later system messages supplied to the adapter stay out of the initial prompt, preserving the preceding request prefix. This does not change the agent loop’s prompt admission, which consolidates updates on routes without native system-update support. Conversion preserves logical request order, while image handles and offload placeholders add model-visible text. A changed execution-world path rewrites a historical handle and can prevent reuse from that image even when attachment identity and request bytes stay stable. Changing adapter instance, provider, model, or another upstream token has the same suffix effect. Omitting stale Anthropic thinking follows a prefix change that already ended reuse at the changed message. The first request that omits thinking recorded without a digest ends reuse at the first such message once. An offload decision turns an earlier image into placeholder text, so reuse ends at that message; the omission never reverts, so the prefix stays stable until the next decision. Larger per-image byte targets can reach the unchanged aggregate budget sooner and cause earlier offloading. A count overflow offloads `imageOffloadCountQuantum` images at once, so a saturated route ends reuse at the oldest retained image once per that many new images. ### Provider response diff --git a/packages/llm/llm-pi-ai/README.zh.md b/packages/llm/llm-pi-ai/README.zh.md index 167b2078f5..1024d419ba 100644 --- a/packages/llm/llm-pi-ai/README.zh.md +++ b/packages/llm/llm-pi-ai/README.zh.md @@ -96,6 +96,8 @@ kind: "package-reference" 请求图片继承所选 pi-ai 目录模型的 `inputLimits.images.resize.maxWidth`、`maxHeight` 和 `maxBytes`。目录字节预算按 base64 载荷计算,因此原始字节目标为 `3 × floor(maxBytes / 4)`。路由显式配置优先,自定义网关也可使用。目录缺少某个尺寸时,路由不限制该轴;缺少字节预算时,保留 1 MiB 目标。总像素仍由 `requestImagePixelBudget` 控制。这些限制每次请求都会应用于保留的历史图片和截图坐标目标,已存附件保持不变。编码质量阶梯中没有结果满足字节目标时,结果仍可能超过目标。请求图片数量、总载荷限制和编码质量继续使用 DSH 的现有策略。 +可以调低 `requestImageMaxBytes`,让编码器尝试更小的输出;只有网关能容纳更大图片载荷及请求中的其他内容时,才调高 `maxRequestImageBytes`。 + 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-llm-pi-ai)是每个受支持字段及其 JSDoc 的穷尽式真源。 ### 登录提供方 @@ -227,9 +229,7 @@ Anthropic 可以将每个已签名 thinking 块绑定到生成它时的请求前 #### 模型看到什么 -所选目录模型会收到系统消息文本、对话历史、工具以及支持的采样字段。目录模型声明 `supportsMidConvoSystemMessages` 时,适配器按历史顺序保留后续系统消息。否则,适配器在传给 pi-ai 之前,将每条非空的后续系统消息转换为以 `` 包裹的用户消息。包裹文本不会赋予系统角色优先级。单次调用的 `GenerateOptions.system` 放在初始历史提示词之前。重复的系统消息仍会重复发送;空系统消息会被跳过,不会丢弃之前的文本。工具更新能力选择共享的历史声明投影;pi-ai 接收初始可用工具,以及按开发者消息分组的新增和受支持的移除更新。当包含工具更新的 Anthropic 请求中所有投影后的声明均为延迟加载时,初始可用工具为一个占位工具 `DeferredToolPlaceholder`,其描述要求模型永不调用它;若被调用,会得到普通的未知工具结果。Anthropic 在更新消息中以内联方式接收后续工具定义。回放会保留工具调用命名空间,以支持动态加载的 Responses 工具。每张保留图片前都会有文本,注明其完整附件 id 与实际请求尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,该文本还会携带只读规范化对象路径,并警告规范化或请求投影可能缩放或重新编码上传内容。日志中的图片省略决策选中的每个出现位置都会在替换文本中保留自己的身份与当前已解析访问方式,其规范化附件不会读取或变换。当保留的出现位置数量仍超过路由的 `maxRequestImages`,或其精确 base64 载荷超过 `maxRequestImageBytes` 时,调用以 `IMAGE_OFFLOAD_REQUIRED` 失败,由 `dsh-compaction-image-offload` 用 `image/offload` 事件记录所选位置并重试步骤。提供方原生回放元数据只在适配器针对历史内容校验通过后恢复。在 Anthropic Messages 路由上,如果回放响应的请求前缀自生成后发生变化(例如经过压缩),该响应会丢失 thinking 块;其文本和工具调用保留。 `imageRequestTarget(provider, model, image)` 向截图调用方提供与模型请求一致的图片尺寸和字节目标;不缩放图片的适配器保留归一化后的原图。 - -目录提供更大的单图目标时,图片总预算仍为 20 MiB。若每张图的实际 base64 载荷均为 4.5 MiB,4 张共 18 MiB 可以保留,5 张共 22.5 MiB 会触发图片省略。编码后更小的图片可以保留更多,但仍受 `maxRequestImages` 限制。因此,较大的单图目标可能使图片更早被省略,并从第一张被替换的图片处终止前缀复用。可以调低 `requestImageMaxBytes`,让编码器尝试更小的输出;只有网关能容纳更大图片载荷及请求中的其他内容时,才调高 `maxRequestImageBytes`。 +所选目录模型会收到系统消息文本、对话历史、工具以及支持的采样字段。目录模型声明 `supportsMidConvoSystemMessages` 时,适配器按历史顺序保留后续系统消息。否则,适配器在传给 pi-ai 之前,将每条非空的后续系统消息转换为以 `` 包裹的用户消息。包裹文本不会赋予系统角色优先级。单次调用的 `GenerateOptions.system` 放在初始历史提示词之前。重复的系统消息仍会重复发送;空系统消息会被跳过,不会丢弃之前的文本。工具更新能力选择共享的历史声明投影;pi-ai 接收初始可用工具,以及按开发者消息分组的新增和受支持的移除更新。当包含工具更新的 Anthropic 请求中所有投影后的声明均为延迟加载时,初始可用工具为一个占位工具 `DeferredToolPlaceholder`,其描述要求模型永不调用它;若被调用,会得到普通的未知工具结果。Anthropic 在更新消息中以内联方式接收后续工具定义。回放会保留工具调用命名空间,以支持动态加载的 Responses 工具。每张保留图片前都会有文本,注明其完整附件 id 与实际请求尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,该文本还会携带只读规范化对象路径,并警告规范化或请求投影可能缩放或重新编码上传内容。日志中的图片省略决策选中的每个出现位置都会在替换文本中保留自己的身份与当前已解析访问方式,其规范化附件不会读取或变换。当保留的出现位置数量仍超过路由的 `maxRequestImages`,或其精确 base64 载荷超过 `maxRequestImageBytes` 时,调用以 `IMAGE_OFFLOAD_REQUIRED` 失败,由 `dsh-compaction-image-offload` 用 `image/offload` 事件记录所选位置并重试步骤。默认 20 MiB 总预算可以容纳实际 base64 载荷各为 4.5 MiB 的 4 张图片,共 18 MiB;第 5 张会使载荷达到 22.5 MiB,超过预算。编码后更小的图片可以保留更多,但仍受数量上限限制。提供方原生回放元数据只在适配器针对历史内容校验通过后恢复。在 Anthropic Messages 路由上,如果回放响应的请求前缀自生成后发生变化(例如经过压缩),该响应会丢失 thinking 块;其文本和工具调用保留。 `imageRequestTarget(provider, model, image)` 向截图调用方提供与模型请求一致的图片尺寸和字节目标;不缩放图片的适配器保留归一化后的原图。 #### Token 影响 @@ -237,7 +237,7 @@ Anthropic 可以将每个已签名 thinking 块绑定到生成它时的请求前 #### KV Cache 影响 -传给适配器的后续系统消息不会进入初始提示词,从而保留此前的请求前缀。这不改变 Agent loop 的提示词纳入行为;它仍在不支持原生系统更新的路由上合并更新。转换保持逻辑请求顺序,图片句柄与卸载占位符则会添加模型可见文本。即使附件身份与请求字节保持稳定,执行世界路径变化也会改写历史句柄,并可能从该图片起阻止复用。更换适配器实例、提供方、模型或其他上游 token 具有相同的后缀影响。省略过期的 Anthropic thinking 发生在前缀变化之后,而该变化已在变化的消息处结束复用。第一个省略无摘要记录的 thinking 的请求会在第一条此类消息处结束复用,且仅发生一次。一次省略决策会把较早图片换成占位文本,因此复用在该消息处结束;省略永不回退,在下一次决策前前缀保持稳定。数量超限时一次省略 `imageOffloadCountQuantum` 张图片,因此饱和路由每新增这么多张图片才让复用在最老的保留图片处结束一次。 +传给适配器的后续系统消息不会进入初始提示词,从而保留此前的请求前缀。这不改变 Agent loop 的提示词纳入行为;它仍在不支持原生系统更新的路由上合并更新。转换保持逻辑请求顺序,图片句柄与卸载占位符则会添加模型可见文本。即使附件身份与请求字节保持稳定,执行世界路径变化也会改写历史句柄,并可能从该图片起阻止复用。更换适配器实例、提供方、模型或其他上游 token 具有相同的后缀影响。省略过期的 Anthropic thinking 发生在前缀变化之后,而该变化已在变化的消息处结束复用。第一个省略无摘要记录的 thinking 的请求会在第一条此类消息处结束复用,且仅发生一次。一次省略决策会把较早图片换成占位文本,因此复用在该消息处结束;省略永不回退,在下一次决策前前缀保持稳定。数量超限时一次省略 `imageOffloadCountQuantum` 张图片,因此饱和路由每新增这么多张图片才让复用在最老的保留图片处结束一次。 较大的单图字节目标可能更早耗尽不变的总预算,使图片更早被省略。 ### 提供方响应 From 22ff91a32b80441e3ea6ad6d4c034295a7d2a81e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:13:21 +0800 Subject: [PATCH 07/54] =?UTF-8?q?=E5=8C=BA=E5=88=86=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E7=A1=AC=E4=B8=8A=E9=99=90=E4=B8=8E=E5=8E=8B=E7=BC=A9=E7=9B=AE?= =?UTF-8?q?=E6=A0=87=E5=B9=B6=E6=89=A7=E8=A1=8C=E8=B6=85=E9=99=90=E7=BC=A9?= =?UTF-8?q?=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/config-catalog.md | 18 +- docs/config-catalog.zh.md | 18 +- docs/subsystems/attachment.md | 14 +- docs/subsystems/attachment.zh.md | 14 +- docs/subsystems/llm-streaming.md | 6 +- docs/subsystems/llm-streaming.zh.md | 6 +- .../pi-image-resize-defaults/guide.i18n.yaml | 22 +- .../pi-image-resize-defaults/guide.md | 17 +- .../pi-image-resize-defaults/guide.zh.md | 17 +- .../attachment-local/README.i18n.yaml | 11 +- .../attachment/attachment-local/README.md | 8 +- .../attachment/attachment-local/README.zh.md | 8 +- .../attachment-local/src/encoding.ts | 8 +- .../attachment/attachment-local/src/index.ts | 24 +- .../attachment-local/src/request-image.ts | 71 ++++-- .../attachment-local/tests/index.spec.ts | 15 +- .../tests/request-image-verification.spec.ts | 4 +- .../tests/request-image.spec.ts | 212 +++++++++++++++--- .../attachment/attachment/README.i18n.yaml | 4 +- packages/attachment/attachment/README.md | 4 +- packages/attachment/attachment/README.zh.md | 4 +- packages/attachment/attachment/src/error.ts | 1 + packages/attachment/attachment/src/index.ts | 4 +- packages/attachment/attachment/src/types.ts | 10 +- .../attachment/attachment/tests/index.spec.ts | 6 +- .../tests/provider-lifecycle.spec.ts | 26 ++- .../cua-mcp/tests/projection.spec.ts | 2 +- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/config.ts | 4 +- .../experimental/cua/src/tool-registration.ts | 5 +- .../extensions/tool-cordis/src/api-catalog.ts | 8 +- packages/fs/tool-fs/src/read-image.ts | 1 + packages/fs/tool-fs/tests/read-image.spec.ts | 2 +- .../llm-deepseek-account/tests/config.spec.ts | 4 +- packages/llm/llm-deepseek/README.i18n.yaml | 8 +- packages/llm/llm-deepseek/README.md | 4 +- packages/llm/llm-deepseek/README.zh.md | 4 +- packages/llm/llm-deepseek/src/config.ts | 19 +- packages/llm/llm-deepseek/src/defaults.ts | 2 + packages/llm/llm-deepseek/src/file-store.ts | 4 +- packages/llm/llm-deepseek/src/index.ts | 4 +- .../llm/llm-deepseek/src/listed-catalog.ts | 2 +- .../llm/llm-deepseek/src/request-pricing.ts | 9 +- packages/llm/llm-deepseek/src/types.ts | 2 +- .../llm-deepseek/tests/listed-catalog.spec.ts | 16 +- .../tests/request-pricing.spec.ts | 6 +- .../llm/llm-deepseek/tests/runtime.spec.ts | 34 +-- packages/llm/llm-pi-ai/README.i18n.yaml | 12 +- packages/llm/llm-pi-ai/README.md | 14 +- packages/llm/llm-pi-ai/README.zh.md | 14 +- packages/llm/llm-pi-ai/src/config.ts | 37 ++- packages/llm/llm-pi-ai/src/context.ts | 9 +- packages/llm/llm-pi-ai/src/image-policy.ts | 13 +- packages/llm/llm-pi-ai/tests/adapter.spec.ts | 20 +- packages/llm/llm-pi-ai/tests/config.spec.ts | 46 +++- packages/llm/llm-pi-ai/tests/convert.spec.ts | 2 +- .../llm-pi-ai/tests/fixtures/image-limits.ts | 15 +- .../llm/llm-pi-ai/tests/image-policy.spec.ts | 60 +++-- packages/llm/llm/README.i18n.yaml | 4 +- packages/llm/llm/README.md | 2 +- packages/llm/llm/README.zh.md | 2 +- packages/llm/llm/src/index.ts | 8 +- packages/llm/llm/tests/service.spec.ts | 10 +- .../pi-ai-image-limits/runtime.cordis.yml | 2 +- 66 files changed, 683 insertions(+), 287 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 86417a2f8a..8ab3092a4b 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -401,7 +401,7 @@ export interface SearchLimits { ## `@deepseek-ai/dsh-attachment-local` -- `source`: [`packages/attachment/attachment-local/src/index.ts:65`](../packages/attachment/attachment-local/src/index.ts) +- `source`: [`packages/attachment/attachment-local/src/index.ts:70`](../packages/attachment/attachment-local/src/index.ts) ```ts config-catalog /** Local attachment backend configuration. */ @@ -429,6 +429,10 @@ export interface Config { normalizedImageMaxBytes?: number /** Maximum simultaneous normalization or request-image transformations in this service instance. */ imageCompressionConcurrency?: number + /** Minimum long-edge shrink divisor after a request image exceeds its hard byte limit; must be greater than one. Default: 1.1. */ + requestImageMinShrinkFactor?: number + /** Fraction of the hard byte limit used to estimate the next request-image size; in (0, 1]. Default: 0.95. */ + requestImageByteHeadroom?: number } ``` @@ -2166,7 +2170,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:249`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:255`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2274,16 +2278,18 @@ export interface PiAiProviderProfile { * steps rewrite the request prefix less often. */ imageOffloadCountQuantum?: number + /** Fixed divisor of maxRequestImageBytes when allocating hard per-image budgets; independent of current image count. Default: 20. */ + requestImageBudgetCount?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number /** Maximum width and height for each request image; omission uses the selected pi-ai model's resize limits. */ requestImageMaxDimension?: number /** - * Raw encoded-byte target overriding the selected model's base64 byte budget; - * omission uses that budget converted to raw bytes, or 1 MiB without catalog metadata. - * The smallest quality-ladder output is used when no quality fits. + * Hard per-image encoded-byte cap overriding the selected model's base64 budget. + * The effective cap is the smaller of this value and the route's equal share of maxRequestImageBytes. + * Omission uses the catalog budget converted to raw bytes, or 1 MiB without catalog metadata. */ - requestImageMaxBytes?: number + maxImageBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ retryPolicy?: RetryPolicyConfig } diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 2821869a4d..568225835a 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -403,7 +403,7 @@ export interface SearchLimits { ## `@deepseek-ai/dsh-attachment-local` -- `source`: [`packages/attachment/attachment-local/src/index.ts:65`](../packages/attachment/attachment-local/src/index.ts) +- `source`: [`packages/attachment/attachment-local/src/index.ts:70`](../packages/attachment/attachment-local/src/index.ts) ```ts config-catalog /** Local attachment backend configuration. */ @@ -431,6 +431,10 @@ export interface Config { normalizedImageMaxBytes?: number /** Maximum simultaneous normalization or request-image transformations in this service instance. */ imageCompressionConcurrency?: number + /** Minimum long-edge shrink divisor after a request image exceeds its hard byte limit; must be greater than one. Default: 1.1. */ + requestImageMinShrinkFactor?: number + /** Fraction of the hard byte limit used to estimate the next request-image size; in (0, 1]. Default: 0.95. */ + requestImageByteHeadroom?: number } ``` @@ -2168,7 +2172,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:249`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:255`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2276,16 +2280,18 @@ export interface PiAiProviderProfile { * steps rewrite the request prefix less often. */ imageOffloadCountQuantum?: number + /** Fixed divisor of maxRequestImageBytes when allocating hard per-image budgets; independent of current image count. Default: 20. */ + requestImageBudgetCount?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number /** Maximum width and height for each request image; omission uses the selected pi-ai model's resize limits. */ requestImageMaxDimension?: number /** - * Raw encoded-byte target overriding the selected model's base64 byte budget; - * omission uses that budget converted to raw bytes, or 1 MiB without catalog metadata. - * The smallest quality-ladder output is used when no quality fits. + * Hard per-image encoded-byte cap overriding the selected model's base64 budget. + * The effective cap is the smaller of this value and the route's equal share of maxRequestImageBytes. + * Omission uses the catalog budget converted to raw bytes, or 1 MiB without catalog metadata. */ - requestImageMaxBytes?: number + maxImageBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ retryPolicy?: RetryPolicyConfig } diff --git a/docs/subsystems/attachment.md b/docs/subsystems/attachment.md index bccf3c33a3..75d8bbf887 100644 --- a/docs/subsystems/attachment.md +++ b/docs/subsystems/attachment.md @@ -134,12 +134,14 @@ interface StoredImageAttachment { ```ts type-equiv /** Deterministic request-image target selected by one exact model route for one attachment. */ interface ImageRequestTarget { - /** Target width in pixels; a target above the source keeps the source width. */ + /** Maximum request width in pixels; byte-limit enforcement can produce a smaller image. */ width: number - /** Target height in pixels; a target above the source keeps the source height. */ + /** Maximum request height in pixels; byte-limit enforcement can produce a smaller image. */ height: number - /** Encoded-byte target before base64 expansion or Files API upload; the smallest quality-ladder output is kept when no quality fits. */ - maxBytes: number + /** Hard encoded-byte limit before base64 expansion or Files API upload; successful results never exceed it. */ + maxImageBytes: number + /** Preferred encoded-byte target, no greater than maxImageBytes; exceeding only this target does not reduce resolution. */ + imageTargetBytes: number } ``` @@ -299,9 +301,9 @@ fileHostPath(ref: FileAttachmentRef): string | undefined /** * Generate or read one deterministic model-request version from the stored normalized image. * @param ref - durable provider-independent normalized attachment reference. - * @param target - route-chosen dimensions and byte target; an unmet byte target yields the smallest ladder output. + * @param target - route-chosen maximum dimensions, hard byte limit, and preferred byte target. * @param signal - optional cancellation. - * @returns request bytes and the cache/upload identity covering every transform input. + * @returns request bytes within the hard limit, actual encoded dimensions, and a cache/upload identity covering every transform input. */ readImageRequest( ref: ImageAttachmentRef, target: ImageRequestTarget, signal?: AbortSignal, ): Promise ``` diff --git a/docs/subsystems/attachment.zh.md b/docs/subsystems/attachment.zh.md index c917947b73..ef6c0192cb 100644 --- a/docs/subsystems/attachment.zh.md +++ b/docs/subsystems/attachment.zh.md @@ -134,12 +134,14 @@ interface StoredImageAttachment { ```ts type-equiv /** Deterministic request-image target selected by one exact model route for one attachment. */ interface ImageRequestTarget { - /** Target width in pixels; a target above the source keeps the source width. */ + /** Maximum request width in pixels; byte-limit enforcement can produce a smaller image. */ width: number - /** Target height in pixels; a target above the source keeps the source height. */ + /** Maximum request height in pixels; byte-limit enforcement can produce a smaller image. */ height: number - /** Encoded-byte target before base64 expansion or Files API upload; the smallest quality-ladder output is kept when no quality fits. */ - maxBytes: number + /** Hard encoded-byte limit before base64 expansion or Files API upload; successful results never exceed it. */ + maxImageBytes: number + /** Preferred encoded-byte target, no greater than maxImageBytes; exceeding only this target does not reduce resolution. */ + imageTargetBytes: number } ``` @@ -299,9 +301,9 @@ fileHostPath(ref: FileAttachmentRef): string | undefined /** * Generate or read one deterministic model-request version from the stored normalized image. * @param ref - durable provider-independent normalized attachment reference. - * @param target - route-chosen dimensions and byte target; an unmet byte target yields the smallest ladder output. + * @param target - route-chosen maximum dimensions, hard byte limit, and preferred byte target. * @param signal - optional cancellation. - * @returns request bytes and the cache/upload identity covering every transform input. + * @returns request bytes within the hard limit, actual encoded dimensions, and a cache/upload identity covering every transform input. */ readImageRequest( ref: ImageAttachmentRef, target: ImageRequestTarget, signal?: AbortSignal, ): Promise ``` diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 078f4f4700..b783f4427b 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -929,12 +929,12 @@ declare abstract class LlmAdapter { */ imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined; /** - * Resolve the image dimensions and byte target this adapter sends to the model. + * Resolve the maximum image dimensions and byte budgets this adapter uses for the model. * The default preserves normalized images; adapters that resize must override it. * @param _provider - registered provider route. * @param _model - exact model id. * @param image - normalized image whose request projection is being resolved. - * @returns the same target used by request serialization, before provider-internal processing. + * @returns the target used by request serialization; encoded images can be smaller to satisfy the hard byte limit. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; /** @@ -1113,7 +1113,7 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u * @param provider - registered provider route. * @param model - exact model id. * @param image - normalized image reference. - * @returns dimensions and byte target used by the adapter's request serializer. + * @returns maximum dimensions and byte budgets used by the request serializer; readImageRequest returns the actual encoded dimensions. */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index dcebebf666..66ba3b0a92 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -935,12 +935,12 @@ declare abstract class LlmAdapter { */ imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined; /** - * Resolve the image dimensions and byte target this adapter sends to the model. + * Resolve the maximum image dimensions and byte budgets this adapter uses for the model. * The default preserves normalized images; adapters that resize must override it. * @param _provider - registered provider route. * @param _model - exact model id. * @param image - normalized image whose request projection is being resolved. - * @returns the same target used by request serialization, before provider-internal processing. + * @returns the target used by request serialization; encoded images can be smaller to satisfy the hard byte limit. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; /** @@ -1119,7 +1119,7 @@ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | u * @param provider - registered provider route. * @param model - exact model id. * @param image - normalized image reference. - * @returns dimensions and byte target used by the adapter's request serializer. + * @returns maximum dimensions and byte budgets used by the request serializer; readImageRequest returns the actual encoded dimensions. */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml index fb9a16c19d..0d7510d0ca 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md /: - en: d33a8682a54c4897 - zh: de9a68ccc5347c5d -/pi-ai-image-resize-defaults: - en: de949ea90a970dc4 - zh: bc79f0d1bef40861 -/pi-ai-image-resize-defaults/change: - en: 904cf562c1617774 - zh: 3c9cba949e792a1b -/pi-ai-image-resize-defaults/migration: - en: d77384609b1c5aa6 - zh: 06be2b4496cfa037 + en: 8eab7a795974913a + zh: 54b06c3fea95487a +/request-image-byte-limits: + en: dfddf0d405d1e813 + zh: 87f32625f9ddc97c +/request-image-byte-limits/change: + en: f0636ed9e57d5081 + zh: ad5c5584f0e8bfe1 +/request-image-byte-limits/migration: + en: 56bb5f70380e26b8 + zh: c7a62c8709b1bd90 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md index 94ed5e1af0..8cce3d905c 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md @@ -1,21 +1,22 @@ --- kind: upgrade-guide -description: "pi-ai request images inherit catalog dimensions and byte budgets unless their route explicitly overrides them." +description: "Request-image byte limits are enforced after encoding, and DeepSeek's soft target uses imageTargetBytes." --- -# pi-ai image resize defaults +# Request-image byte limits English | [中文](guide.zh.md) ## Change -`@deepseek-ai/dsh-llm-pi-ai` applies the selected model's `inputLimits.images.resize` width, height, and byte budgets to request images. Previously, request projection used only the total-pixel budget and a fixed 1 MiB raw encoded-byte target. Catalog byte budgets count base64 payload and are converted to raw bytes. Images already stored in a Session receive the new request projection without rewriting their attachments. +Model-request images distinguish `maxImageBytes`, a hard encoded-byte limit, from `imageTargetBytes`, a preferred target. The encoder keeps the 85/75/60 quality ladder and reduces dimensions further only when its smallest output exceeds the hard limit. Each reduction starts from the saved source. A limit that cannot fit even a 1×1 image fails with `IMAGE_REQUEST_TOO_LARGE`; oversized bytes are never returned. Stored attachments are unchanged, and request caches regenerate under a new transform version. -The route's `requestImageMaxBytes` remains a raw encoded-byte override. The new `requestImageMaxDimension` overrides both catalog dimensions. Models without resize metadata retain the existing defaults. Both request serialization and screenshot coordinate targets use these resolved limits. +pi exposes only hard limits. `maxImageBytes` replaces `requestImageMaxBytes` and overrides the selected model's per-image byte cap. `requestImageBudgetCount` defaults to 20. The effective hard limit is the smaller of that cap and `3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount))`; the internal soft target equals it. Default allocation is 0.75 MiB per image. Width and height follow catalog limits unless `requestImageMaxDimension` overrides both with the same value; unequal local width/height overrides are not supported. -The aggregate `maxRequestImageBytes` budget stays at 20 MiB. Larger encoded images can cause earlier history-image offloading and reduce prefix-cache reuse; see the [retained-image example](../../../../packages/llm/llm-pi-ai/README.md#model-experience). The per-image byte target can be lowered independently of the aggregate budget. +DeepSeek renames the configurable `imageMaxBytes` soft target to `imageTargetBytes`, retaining its 2 MiB default. Its hard cap is fixed at 32 MiB. CUA's fixed `screenshotTarget.maxBytes` also becomes a hard cap. Request-image targets describe maximum dimensions; actual output can be smaller. Aggregate request limits still apply to actual encoded payloads. ## Migration -1. Leave both overrides unset to follow the installed pi-ai catalog. Review long-image resolution and request sizes after upgrading pi-ai. -2. If a gateway needs different dimensions, set `requestImageMaxDimension` in its `providers.` configuration. Set `requestImageMaxBytes: 1048576` to preserve the previous raw byte target. Choose values the gateway accepts; these overrides can raise or lower the catalog values. -3. Verify the model-facing image descriptor's request dimensions and, for screenshots, the coordinate target. Neither width nor height may exceed the configured dimension. The byte setting remains an encoding target; the smallest quality-ladder result can exceed it. +1. In pi provider profiles, replace `requestImageMaxBytes` with `maxImageBytes` and review its hard-limit meaning. Set `requestImageBudgetCount` to the desired allocation divisor, independently of the retained-count cap. The aggregate base64 budget must allow at least four bytes per share. For 1 MiB allocations, use a sufficient aggregate budget and divisor, such as 32 MiB and 20 shares, plus `maxImageBytes: 1048576`. +2. In DeepSeek `models` and `modelOverrides`, rename `imageMaxBytes` to `imageTargetBytes`. Keep the value at or below 32 MiB. The retired field is rejected with migration guidance. +3. Consumers of `ImageRequestTarget` replace `maxBytes` with `maxImageBytes` and supply `imageTargetBytes` no greater than it. Read the final width and height from `readImageRequest`, including for coordinate mapping. Direct `readRequestImageFile` and `requestImageVariantId` callers must pass resolved resize controls; DeepSeek helper consumers use `resolveRequestImageTargetBytes` and `DEFAULT_REQUEST_IMAGE_TARGET_BYTES`. +4. Attachment-local deployments may tune `requestImageMinShrinkFactor` (default 1.1, greater than one) and `requestImageByteHeadroom` (default 0.95, in `(0, 1]`). Verify actual encoded bytes stay within the hard limit and coordinate mappings match the returned dimensions. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md index 9a8ccb0271..063787e4df 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md @@ -1,21 +1,22 @@ --- kind: upgrade-guide -description: "pi-ai 请求图片继承目录中的尺寸和字节预算,路由显式配置优先。" +description: "请求图片在编码后执行字节硬上限,DeepSeek 的软目标改用 imageTargetBytes。" --- -# pi-ai 图片缩放默认值 +# 请求图片的字节限制 [English](guide.md) | 中文 ## 变更 -`@deepseek-ai/dsh-llm-pi-ai` 将所选模型的 `inputLimits.images.resize` 宽度、高度和字节预算应用于请求图片。此前,请求投影只使用总像素预算和固定的 1 MiB 原始编码字节目标。目录字节预算按 base64 载荷计算,使用时换算为原始字节。Session 中已保存的图片也会使用新的请求投影,存储附件保持不变。 +模型请求图片区分编码字节硬上限 `maxImageBytes` 和软目标 `imageTargetBytes`。编码器保留 85/75/60 质量阶梯,只有最小结果仍超过硬上限时才继续缩小尺寸。每次缩放都从已保存的源图开始。连 1×1 图片也无法满足上限时,以 `IMAGE_REQUEST_TOO_LARGE` 失败,不返回超限字节。存储附件保持不变,请求缓存使用新的变换版本重新生成。 -路由的 `requestImageMaxBytes` 仍用于覆盖原始编码字节目标。新增的 `requestImageMaxDimension` 同时覆盖目录中的宽度和高度限制。没有缩放元数据的模型保留现有默认值。请求序列化和截图坐标目标使用同一组解析后的限制。 +pi 只暴露硬上限。`maxImageBytes` 替代 `requestImageMaxBytes`,用于覆盖所选模型的单图字节上限。`requestImageBudgetCount` 默认为 20。最终硬上限取该单图上限与 `3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount))` 的较小值,内部软目标等于硬上限。默认每张图分得 0.75 MiB。宽高跟随目录限制,或由 `requestImageMaxDimension` 用同一个值覆盖;不支持分别配置不同的本地宽高上限。 -总预算 `maxRequestImageBytes` 仍为 20 MiB。编码后的图片变大时,历史图片可能更早被省略,前缀缓存的复用范围也会减小,详见[图片保留数量示例](../../../../packages/llm/llm-pi-ai/README.zh.md#model-experience)。单图字节目标可以独立于总预算调低。 +DeepSeek 将可配置软目标 `imageMaxBytes` 重命名为 `imageTargetBytes`,默认仍为 2 MiB,硬上限固定为 32 MiB。CUA 的固定截图配置 `screenshotTarget.maxBytes` 也改为硬上限。请求图片目标描述最大尺寸,实际输出可能更小。请求总量限制仍按实际编码载荷执行。 ## 迁移 -1. 不配置这两个覆盖字段,即可跟随已安装的 pi-ai 目录。升级 pi-ai 后,检查长图分辨率和请求大小。 -2. 网关需要不同尺寸时,在其 `providers.` 配置中设置 `requestImageMaxDimension`。设置 `requestImageMaxBytes: 1048576` 可保留原来的原始字节目标。配置值须符合网关要求,这些覆盖值可以调高或调低目录值。 -3. 检查模型侧图片描述中的请求尺寸;截图还需检查坐标目标。宽度和高度均不得超过配置的尺寸。字节配置仍是编码目标,质量阶梯中的最小结果可能超过它。 +1. 在 pi 提供方配置中,将 `requestImageMaxBytes` 改为 `maxImageBytes`,并按硬上限语义检查取值。通过 `requestImageBudgetCount` 配置预算分摊张数,它独立于保留图片数量上限。base64 总预算须为每份预算至少提供 4 个字节。若希望每张分配 1 MiB,应使用足够的总预算及分摊张数,例如 32 MiB、20 份,再设置 `maxImageBytes: 1048576`。 +2. 在 DeepSeek 的 `models` 和 `modelOverrides` 中,将 `imageMaxBytes` 改为 `imageTargetBytes`,值不得超过 32 MiB。旧字段会被拒绝,并提示迁移方式。 +3. `ImageRequestTarget` 调用方将 `maxBytes` 改为 `maxImageBytes`,并提供不大于硬上限的 `imageTargetBytes`。包括坐标换算在内的调用方,都从 `readImageRequest` 获取最终宽高。直接调用 `readRequestImageFile` 和 `requestImageVariantId` 时须传入已解析的缩放参数;DeepSeek 辅助函数调用方改用 `resolveRequestImageTargetBytes` 和 `DEFAULT_REQUEST_IMAGE_TARGET_BYTES`。 +4. 附件本地存储可配置 `requestImageMinShrinkFactor`,默认 1.1,必须大于 1;以及 `requestImageByteHeadroom`,默认 0.95,范围为 `(0, 1]`。检查实际编码字节满足硬上限,坐标映射与返回尺寸一致。 diff --git a/packages/attachment/attachment-local/README.i18n.yaml b/packages/attachment/attachment-local/README.i18n.yaml index 2caf5e3785..241408d0ef 100644 --- a/packages/attachment/attachment-local/README.i18n.yaml +++ b/packages/attachment/attachment-local/README.i18n.yaml @@ -18,14 +18,17 @@ en: 912a19be4b59ff8a zh: 9c14694cf2ebbaf2 /deepseek-ai-dsh-attachment-local/use-this-package/minimal-configuration: - en: 9597c3d9779cb93d - zh: 900baa94138cc7de + en: 407c75c6f2e8834b + zh: 35dbcf0974fa78bb /deepseek-ai-dsh-attachment-local/use-this-package/where-your-images-are-stored-and-how-long-they-last: en: 4ee90b8f74baa38c zh: 9c577709ec55eb82 /deepseek-ai-dsh-attachment-local/use-this-package/what-happens-when-you-attach-an-image: en: 75ba799b1e4edba4 zh: 06c5f76200e8da8a +/deepseek-ai-dsh-attachment-local/use-this-package/request-image-byte-limits: + en: d2ad0b047828baf8 + zh: 9c22a4b87fafdbec /deepseek-ai-dsh-attachment-local/use-this-package/what-can-go-wrong: en: 377696b2dc08b170 zh: 6b831ef31c93f712 @@ -36,8 +39,8 @@ en: dcd9857653645420 zh: a27259a09f17465d /deepseek-ai-dsh-attachment-local/understand-the-implementation/write-and-read-paths: - en: 4cbbe8a1466ed46f - zh: 49d2d118501867d3 + en: 93c691ba1845b5bf + zh: c9902789a6611746 /deepseek-ai-dsh-attachment-local/understand-the-implementation/source-map: en: 05af85aa85934d01 zh: 1c89e80d496dc0a3 diff --git a/packages/attachment/attachment-local/README.md b/packages/attachment/attachment-local/README.md index b27ac0c75a..572e7b3b59 100644 --- a/packages/attachment/attachment-local/README.md +++ b/packages/attachment/attachment-local/README.md @@ -47,6 +47,8 @@ Mount the plugin with no required configuration. The defaults below define what | `normalizedImageMaxDimension` | `8192` | Maximum long edge after applying the total-pixel budget | | `normalizedImageMaxBytes` | `4 MiB` | Encoded-byte target; the smallest quality-ladder output is kept when none fits | | `imageCompressionConcurrency` | `2` | FIFO limit for concurrent normalization and request transforms | +| `requestImageMinShrinkFactor` | `1.1` | Minimum divisor of the request image long edge after a hard-byte overflow; greater than one | +| `requestImageByteHeadroom` | `0.95` | Fraction of the hard byte limit used to estimate the next size; in `(0, 1]` | The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-attachment-local) is the exhaustive source for every accepted field and its JSDoc. @@ -58,6 +60,10 @@ Attached images are kept below `/attachments/v1` on this machine. Stor Attach an image and its source limits, media, dimensions, and pixels are checked before it is normalized and saved. EXIF orientation is applied, metadata and color profiles are removed, transparency is preserved, and the raster is reduced under a total-pixel budget plus a long-edge cap. Alpha images use WebP and opaque images use JPEG on the shared 85/75/60 quality ladder; the smallest output is retained when every candidate exceeds the byte target. An accepted image reappears in history and later turns, including after restart; the selected model route receives a cached request version and, when its filesystem maps the host object, a read-only execution-world path. +### Request-image byte limits + +Model routes supply `maxImageBytes` as a hard encoded-byte limit and `imageTargetBytes` as a preferred target no greater than that limit. The encoder tries qualities 85, 75, and 60 at the requested dimensions. An output above only the preferred target keeps its resolution. If the smallest output still exceeds the hard limit, the long edge is divided by `max(requestImageMinShrinkFactor, sqrt(actualBytes / (requestImageByteHeadroom × maxImageBytes)))`, rounded down, and strictly reduced. Each attempt encodes the saved source at the new dimensions; it does not recompress the previous lossy result. The loop checks cancellation between encodings and fails with `IMAGE_REQUEST_TOO_LARGE` if even a 1×1 image cannot fit. Successful results and cache hits always satisfy the hard limit. Consumers use the returned width and height for coordinates. + ### What can go wrong An image can be refused when you attach it: unsupported format, over the byte, pixel, or per-side dimension limits, or bytes that do not match their declared type. On a later read, an image that was deleted or corrupted on disk fails with a clear error. Each failure carries a stable code so the client and protocol adapters can explain it in their own words. @@ -87,7 +93,7 @@ Image reads receive a complete reference with a canonical `sha256:` ID, derive t Admission accepts up to 20 images and 200 MiB of source bytes per message; one source may use up to 50 MiB, 64 million pixels, and 65,535 pixels per side. It applies orientation, removes metadata and color profiles, and normalizes under a 2048×2048 total-pixel budget, an 8192-pixel long edge, and a 4 MiB encoded-byte target. Extreme aspect ratios therefore retain their short-edge resolution. Clean single-frame 8-bit sRGB/sRGBA PNG, JPEG, or WebP input already within those limits passes through byte-identically; GIF, animation, metadata, orientation, 16-bit PNG, and incompatible color spaces force conversion. -Request versions live below `/cache/attachments/request-images/`, resolved by `dshCachePath`; an explicit `dshHome` setting applies to both cache and durable storage. Clearing this cache between requests preserves durable attachments, and later reads regenerate the variants. `readImageRequest` scales without enlargement to the route-chosen target, resizing by the long edge only so the encoder derives the short edge as the route predicts, then applies a separate encoded-byte target through the same alpha routing and quality ladder. Its cache identity includes the attachment id, transform version, target dimensions, byte target, and fixed encoder settings; cached bytes are header-probed for format, 8-bit sRGB/sRGBA, dimensions, and alpha facts, and a mismatch regenerates the entry. Concurrent callers share one transform and cache write, while cancellation stops shared work only when no waiter remains. `imageHostPath` derives the normalized object's host path, and the mounted filesystem may map that path into its execution world without writing it to durable history. +Request versions live below `/cache/attachments/request-images/`, resolved by `dshCachePath`; an explicit `dshHome` setting applies to both cache and durable storage. Clearing this cache between requests preserves durable attachments, and later reads regenerate the variants. `readImageRequest` scales without enlargement to the route-chosen target, resizing by the long edge only so the encoder derives the short edge as the route predicts, then enforces the route's preferred byte target and hard byte limit through the same alpha routing and quality ladder, reducing resolution further only for a hard-limit overflow. Its cache identity includes the attachment id, transform version, target dimensions, both byte limits, resize controls, and fixed encoder settings; cached bytes are header-probed for format, 8-bit sRGB/sRGBA, dimensions, alpha facts, and the hard byte limit, and a mismatch regenerates the entry. Concurrent callers share one transform and cache write, while cancellation stops shared work only when no waiter remains. `imageHostPath` derives the normalized object's host path, and the mounted filesystem may map that path into its execution world without writing it to durable history. Generic-file bytes have one canonical object at `/attachments/v1/file-objects//`. Each reference path at `/attachments/v1/files///` is a read-only hard link, so different names for equal bytes do not duplicate disk content. `readFileStream` reads the reference path in bounded chunks and verifies the complete digest and recorded byte count before a consumer can finish successfully. A missing, changed, or truncated object fails its consumer instead of producing a complete export with different bytes. diff --git a/packages/attachment/attachment-local/README.zh.md b/packages/attachment/attachment-local/README.zh.md index a0663aaebe..dff6007494 100644 --- a/packages/attachment/attachment-local/README.zh.md +++ b/packages/attachment/attachment-local/README.zh.md @@ -47,6 +47,8 @@ kind: "package-reference" | `normalizedImageMaxDimension` | `8192` | 应用总像素预算后的最大长边 | | `normalizedImageMaxBytes` | `4 MiB` | 编码字节目标;没有候选满足时保留质量阶梯中的最小输出 | | `imageCompressionConcurrency` | `2` | 并发规范化与请求变换的 FIFO 上限 | +| `requestImageMinShrinkFactor` | `1.1` | 请求图片超过硬字节上限后,长边缩小倍数的最小值;必须大于 1 | +| `requestImageByteHeadroom` | `0.95` | 估算下一次尺寸时使用的硬字节上限比例;范围为 `(0, 1]` | 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-attachment-local)完整列出了所有受支持的字段及其 JSDoc。 @@ -58,6 +60,10 @@ kind: "package-reference" 附加图片后,会先检查源图限制、媒体类型、尺寸与像素,再完成规范化并保存。系统应用 EXIF 方向、移除元数据与色彩配置、保留透明度,并按总像素预算与长边上限缩小光栅。带 alpha 的图片使用 WebP,不透明图片使用 JPEG,共享 85/75/60 质量阶梯;全部候选都超过字节目标时保留最小输出。被接受的图片会重新出现在历史和后续轮次中,重启后也不例外;所选模型路由会收到缓存的请求版本,并在其文件系统可映射宿主对象时收到只读执行世界路径。 +### 请求图片的字节限制 + +模型路由提供硬编码字节上限 `maxImageBytes`,以及不大于硬上限的目标 `imageTargetBytes`。编码器先在请求尺寸下尝试 85、75、60 三档质量。仅超过目标值的输出保持分辨率。最小结果仍超过硬上限时,长边除以 `max(requestImageMinShrinkFactor, sqrt(actualBytes / (requestImageByteHeadroom × maxImageBytes)))`,向下取整并确保严格减小。每次都从已保存的源图按新尺寸编码,不重复压缩上一轮有损结果。每轮编码之间检查取消状态;即使 1×1 图片仍无法满足上限时,以 `IMAGE_REQUEST_TOO_LARGE` 失败。成功结果和缓存命中均满足硬上限。调用方使用返回的实际宽高计算坐标。 + ### 可能出什么问题 附加图片时可能被拒绝:格式不受支持、超出字节、像素或单边尺寸限制,或者字节与声明类型不符。之后读取时,磁盘上被删除或损坏的图片会以明确错误失败。每个失败都带有稳定错误码,客户端与协议适配器可以用自己的措辞解释。 @@ -87,7 +93,7 @@ kind: "package-reference" 准入允许每条消息最多 20 张图片与 200 MiB 源字节;单个源图最多 50 MiB、6400 万像素与单边 65,535 像素。系统应用方向、移除元数据与色彩配置,并把规范化结果限制在 2048×2048 总像素预算、8192 像素长边和 4 MiB 编码字节目标内,因此,即使宽高比极端,图片也会保留短边分辨率。已经满足限制的干净、单帧、8-bit sRGB/sRGBA PNG、JPEG 或 WebP 会逐字节直通;GIF、动画、元数据、方向、16-bit PNG 与不兼容色彩空间会触发转换。 -请求版本位于由 `dshCachePath` 解析的 `/cache/attachments/request-images/`;显式 `dshHome` 设置同时适用于缓存与持久存储。在两次请求之间清空此缓存会保留持久附件,后续读取会重新生成请求版本。`readImageRequest` 在不放大的前提下缩放到路由选定的目标尺寸,缩放只按长边给定,短边由编码器按路由预测的方式推出,随后通过相同的 alpha 路由与质量阶梯应用独立编码字节目标。缓存身份包含附件 id、变换版本、目标尺寸、字节目标与固定编码参数;缓存字节会先通过文件头探测格式、8-bit sRGB/sRGBA、尺寸与 alpha 信息,不匹配时重新生成。并发调用方共享一次变换与缓存写入,且只在没有等待方时由取消停止共享工作。`imageHostPath` 派生规范化对象的宿主路径,挂载的文件系统可以把该路径映射进执行世界,而不会写入持久历史。 +请求版本位于 `/cache/attachments/request-images/`,由 `dshCachePath` 解析;显式 `dshHome` 同时用于缓存和持久存储。请求之间清空此缓存不会影响持久附件,后续读取会重新生成变体。`readImageRequest` 按路由目标缩放且不放大,沿长边调整以保持比例,再按相同的透明度分流和质量阶梯处理软目标及硬字节上限,仅在硬上限仍不满足时继续降低分辨率。缓存身份包含附件 id、变换版本、目标尺寸、两项字节限制、缩放参数和固定编码设置。缓存读取检查格式、8 位 sRGB/sRGBA、尺寸、透明度和硬字节上限,不匹配时重新生成。并发调用共享一次变换和缓存写入,仅在所有等待方均离开后取消共享工作。`imageHostPath` 派生规范化对象的宿主路径,文件系统可以将其映射到执行环境,不写入持久历史。 通用文件字节的唯一规范对象位于 `/attachments/v1/file-objects//`。每条引用路径 `/attachments/v1/files///` 都是只读硬链接,所以名称不同但字节相同的文件不会重复占用磁盘。`readFileStream` 以有界分块读取引用路径,并在消费方成功结束前校验完整摘要与记录的字节数。对象缺失、被改写或截断时,消费方会失败,不会得到字节已经变化的完整导出。 diff --git a/packages/attachment/attachment-local/src/encoding.ts b/packages/attachment/attachment-local/src/encoding.ts index 1b16aafb30..2ebbd49659 100644 --- a/packages/attachment/attachment-local/src/encoding.ts +++ b/packages/attachment/attachment-local/src/encoding.ts @@ -50,20 +50,20 @@ export interface ExhaustedEncoding { /** * Execute encoding candidates in preference order and stop after the first fitting output. * @param attempts - lazy encoders ordered from preferred to fallback representation. - * @param maxBytes - positive encoded-byte target. + * @param imageTargetBytes - positive encoded-byte target. * @returns the first fitting candidate, otherwise the smallest completed fallback. */ export async function encodeFirstWithinLimit( attempts: readonly (() => Promise)[], - maxBytes: number, + imageTargetBytes: number, ): Promise> { const [first, ...remaining] = attempts if (first === undefined) throw new Error('image encoding requires at least one candidate') let smallest = await first() - if (smallest.data.byteLength <= maxBytes) return smallest + if (smallest.data.byteLength <= imageTargetBytes) return smallest for (const attempt of remaining) { const candidate = await attempt() - if (candidate.data.byteLength <= maxBytes) return candidate + if (candidate.data.byteLength <= imageTargetBytes) return candidate if (candidate.data.byteLength < smallest.data.byteLength) { smallest = candidate } diff --git a/packages/attachment/attachment-local/src/index.ts b/packages/attachment/attachment-local/src/index.ts index 2965fef0cc..f836ab5297 100644 --- a/packages/attachment/attachment-local/src/index.ts +++ b/packages/attachment/attachment-local/src/index.ts @@ -23,12 +23,14 @@ import { readFileStreamVerbatim, saveFileStreamVerbatim, saveFileVerbatim, storedFilePath, } from './file-store.ts' import { readRequestImageFile, requestImageVariantId } from './request-image.ts' +import type { RequestImageResizePolicy } from './request-image.ts' export { canPassThroughNormalization, normalizeImage } from './normalization.ts' export type { NormalizedImage, NormalizationPolicy } from './normalization.ts' export { commitPreparedImageFile, prepareImageFile, readImageFile, saveImageFile, validateImageFile } from './store.ts' export type { PreparedImageFile } from './store.ts' export { readRequestImageFile, requestImageVariantId } from './request-image.ts' +export type { RequestImageResizePolicy } from './request-image.ts' /** Default maximum encoded bytes for one submitted image; oversized sources are refused, not shrunk. */ export const DEFAULT_MAX_IMAGE_BYTES = 50 * 1024 * 1024 @@ -61,6 +63,9 @@ export const DEFAULT_IMAGE_COMPRESSION_CONCURRENCY = 2 /** Maximum configurable native image transformations per store. */ export const MAX_IMAGE_COMPRESSION_CONCURRENCY = 8 +const DEFAULT_REQUEST_IMAGE_MIN_SHRINK_FACTOR = 1.1 +const DEFAULT_REQUEST_IMAGE_BYTE_HEADROOM = 0.95 + /** Local attachment backend configuration. */ export interface Config { /** Explicit harness home; omitted follows `DSH_HOME`, then `~/.dsh`. */ @@ -86,6 +91,10 @@ export interface Config { normalizedImageMaxBytes?: number /** Maximum simultaneous normalization or request-image transformations in this service instance. */ imageCompressionConcurrency?: number + /** Minimum long-edge shrink divisor after a request image exceeds its hard byte limit; must be greater than one. Default: 1.1. */ + requestImageMinShrinkFactor?: number + /** Fraction of the hard byte limit used to estimate the next request-image size; in (0, 1]. Default: 0.95. */ + requestImageByteHeadroom?: number } function abortReason(signal: AbortSignal): Error { @@ -159,6 +168,8 @@ export class LocalAttachmentStore extends AttachmentStore { normalizedImageMaxPixels: z.number().step(1).min(1).default(DEFAULT_NORMALIZED_IMAGE_MAX_PIXELS), normalizedImageMaxDimension: z.number().step(1).min(1).default(DEFAULT_NORMALIZED_IMAGE_MAX_DIMENSION), normalizedImageMaxBytes: z.number().step(1).min(1).default(DEFAULT_NORMALIZED_IMAGE_MAX_BYTES), + requestImageMinShrinkFactor: z.number().min(1 + Number.EPSILON).max(Number.MAX_VALUE).default(DEFAULT_REQUEST_IMAGE_MIN_SHRINK_FACTOR), + requestImageByteHeadroom: z.number().min(Number.MIN_VALUE).max(1).default(DEFAULT_REQUEST_IMAGE_BYTE_HEADROOM), imageCompressionConcurrency: z.number().step(1).min(1).max(MAX_IMAGE_COMPRESSION_CONCURRENCY) .default(DEFAULT_IMAGE_COMPRESSION_CONCURRENCY), }) @@ -170,6 +181,7 @@ export class LocalAttachmentStore extends AttachmentStore { readonly normalizationPolicy: Readonly /** Resolved instance-level compression limit. */ readonly imageCompressionConcurrency: number + private readonly requestImageResizePolicy: Readonly private readonly cacheRoot: string private readonly compression: CompressionLimiter private readonly requestInflight = new Map>() @@ -192,6 +204,15 @@ export class LocalAttachmentStore extends AttachmentStore { maxDimension: config.normalizedImageMaxDimension ?? DEFAULT_NORMALIZED_IMAGE_MAX_DIMENSION, maxBytes: config.normalizedImageMaxBytes ?? DEFAULT_NORMALIZED_IMAGE_MAX_BYTES, }) + const minShrinkFactor = config.requestImageMinShrinkFactor ?? DEFAULT_REQUEST_IMAGE_MIN_SHRINK_FACTOR + const byteHeadroom = config.requestImageByteHeadroom ?? DEFAULT_REQUEST_IMAGE_BYTE_HEADROOM + if (!Number.isFinite(minShrinkFactor) || minShrinkFactor <= 1) { + throw new Error('attachment-local: requestImageMinShrinkFactor must be a finite number greater than one') + } + if (!Number.isFinite(byteHeadroom) || byteHeadroom <= 0 || byteHeadroom > 1) { + throw new Error('attachment-local: requestImageByteHeadroom must be a finite number in (0, 1]') + } + this.requestImageResizePolicy = Object.freeze({ minShrinkFactor, byteHeadroom }) const compressionConcurrency = config.imageCompressionConcurrency ?? DEFAULT_IMAGE_COMPRESSION_CONCURRENCY if (!Number.isSafeInteger(compressionConcurrency) || compressionConcurrency < 1 @@ -264,7 +285,7 @@ export class LocalAttachmentStore extends AttachmentStore { signal: AbortSignal | undefined, ): Promise { signal?.throwIfAborted() - const variantId = requestImageVariantId(ref, target) + const variantId = requestImageVariantId(ref, target, this.requestImageResizePolicy) const key = String(variantId) let operation = this.requestInflight.get(key) if (operation?.controller.signal.aborted) { @@ -277,6 +298,7 @@ export class LocalAttachmentStore extends AttachmentStore { this.cacheRoot, stored ?? await this.readImage(ref, sharedSignal), target, + this.requestImageResizePolicy, sharedSignal, ) return request diff --git a/packages/attachment/attachment-local/src/request-image.ts b/packages/attachment/attachment-local/src/request-image.ts index a6140963d6..36d2434290 100644 --- a/packages/attachment/attachment-local/src/request-image.ts +++ b/packages/attachment/attachment-local/src/request-image.ts @@ -4,7 +4,7 @@ import { createHash, randomUUID } from 'node:crypto' import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import type { Sharp } from 'sharp' -import { AttachmentError } from '@deepseek-ai/dsh-attachment' +import { AttachmentError, longEdgeDimensions, requestImageDimensions } from '@deepseek-ai/dsh-attachment' import type { ImageVariantId } from '@deepseek-ai/dsh-attachment/types' import { brandString } from '@deepseek-ai/dsh-brand' import type { @@ -25,7 +25,15 @@ import { detectImage, encodedAlphaIsCompatible, probeImage } from './image.ts' import { requireSharp } from './sharp.ts' /** Transform version included in every cache and upload-index identity. */ -export const REQUEST_IMAGE_TRANSFORM_VERSION = 'request-image-v6' +export const REQUEST_IMAGE_TRANSFORM_VERSION = 'request-image-v7' + +/** Resolved encoder controls for deterministic byte-limit enforcement. */ +export interface RequestImageResizePolicy { + /** Minimum divisor of the long edge after an oversized encoding; greater than one. */ + minShrinkFactor: number + /** Fraction of the hard byte limit used to estimate the next size; greater than zero and at most one. */ + byteHeadroom: number +} interface EncodedRequestImage { data: Uint8Array @@ -52,16 +60,22 @@ function checkedInteger(value: number, name: string): number { function validateTarget(target: ImageRequestTarget): void { checkedInteger(target.width, 'Image request width') checkedInteger(target.height, 'Image request height') - checkedInteger(target.maxBytes, 'Image request maxBytes') + checkedInteger(target.maxImageBytes, 'Image request maxImageBytes') + checkedInteger(target.imageTargetBytes, 'Image request imageTargetBytes') + if (target.imageTargetBytes > target.maxImageBytes) { + throw new AttachmentError('Image request imageTargetBytes must not exceed maxImageBytes.', 'INVALID_ATTACHMENT_REF') + } } -function descriptor(attachment: ImageAttachmentRef, target: ImageRequestTarget): string { +function descriptor(attachment: ImageAttachmentRef, target: ImageRequestTarget, policy: RequestImageResizePolicy): string { return JSON.stringify({ transformVersion: REQUEST_IMAGE_TRANSFORM_VERSION, attachmentId: attachment.attachmentId, targetWidth: target.width, targetHeight: target.height, - encodedByteBudget: target.maxBytes, + maxImageBytes: target.maxImageBytes, + imageTargetBytes: target.imageTargetBytes, + resize: { minShrinkFactor: policy.minShrinkFactor, byteHeadroom: policy.byteHeadroom }, encoding: { webpQualities: IMAGE_ENCODING_QUALITIES, webpEffort: WEBP_ENCODING_EFFORT, @@ -75,18 +89,20 @@ function descriptor(attachment: ImageAttachmentRef, target: ImageRequestTarget): /** * Complete deterministic identity for one attachment and route-chosen request target. * @param attachment - provider-independent durable normalized attachment reference. - * @param target - route-chosen dimensions and byte target. + * @param target - route-chosen dimensions, hard byte limit, and preferred byte target. + * @param policy - resolved size-reduction controls. * @returns branded digest over every request transform input. */ export function requestImageVariantId( attachment: ImageAttachmentRef, target: ImageRequestTarget, + policy: RequestImageResizePolicy, ): ImageVariantId { - return brandString(`sha256:${digest(descriptor(attachment, target))}`) + return brandString(`sha256:${digest(descriptor(attachment, target, policy))}`) } /** Resize by the source long edge only, so the encoder derives the short edge as the route predicts. */ -function pipeline(attachment: StoredImageAttachment, target: ImageRequestTarget): Sharp { +function pipeline(attachment: StoredImageAttachment, target: Pick): Sharp { const byWidth = attachment.ref.width >= attachment.ref.height return sourcePipeline(attachment) .resize({ ...byWidth ? { width: target.width } : { height: target.height }, withoutEnlargement: true }) @@ -101,10 +117,12 @@ async function createRequestImage( attachment: StoredImageAttachment, target: ImageRequestTarget, hasAlpha: boolean, + policy: RequestImageResizePolicy, + signal: AbortSignal | undefined, ): Promise { if (target.width >= attachment.ref.width && target.height >= attachment.ref.height - && attachment.data.byteLength <= target.maxBytes) { + && attachment.data.byteLength <= target.imageTargetBytes) { return { data: attachment.data, mediaType: attachment.ref.mediaType, @@ -112,11 +130,27 @@ async function createRequestImage( height: attachment.ref.height, } } - const encodedVersion = await encodeFirstWithinLimit( - encodingLadder(pipeline(attachment, target), hasAlpha), - target.maxBytes, - ) - return isExhaustedEncoding(encodedVersion) ? encodedVersion.smallest : encodedVersion + let dimensions = requestImageDimensions(attachment.ref.width, attachment.ref.height, Infinity, target.width, target.height) + for (;;) { + signal?.throwIfAborted() + const encoded = await encodeFirstWithinLimit( + encodingLadder(pipeline(attachment, dimensions), hasAlpha), + target.imageTargetBytes, + ) + signal?.throwIfAborted() + const candidate = isExhaustedEncoding(encoded) ? encoded.smallest : encoded + if (candidate.data.byteLength <= target.maxImageBytes) return candidate + const longEdge = Math.max(candidate.width, candidate.height) + if (longEdge === 1) { + throw new AttachmentError( + `Image still exceeds the ${target.maxImageBytes}-byte request limit at 1x1 pixels. Increase the image byte limit.`, + 'IMAGE_REQUEST_TOO_LARGE', + ) + } + const divisor = Math.max(policy.minShrinkFactor, Math.sqrt(candidate.data.byteLength / (policy.byteHeadroom * target.maxImageBytes))) + const nextEdge = Math.max(1, Math.min(longEdge - 1, Math.floor(longEdge / divisor))) + dimensions = longEdgeDimensions(attachment.ref.width, attachment.ref.height, nextEdge) + } } function cachePath(root: string, hash: string): string { @@ -131,6 +165,7 @@ async function readCached( ): Promise { try { const data = new Uint8Array(await readFile(path, { signal })) + if (data.byteLength > target.maxImageBytes) return undefined const detected = await probeImage(data) if (detected.depth !== 'uchar' || detected.space !== 'srgb' || detected.width > target.width || detected.height > target.height @@ -174,7 +209,8 @@ async function writeCached(path: string, data: Uint8Array): Promise { * Generate or reuse one request image below the local attachment cache root. * @param root - absolute attachment cache root; variants use its `request-images` child. * @param attachment - verified normalized attachment bytes and reference. - * @param target - exact route-chosen dimensions and byte target; a target above the source keeps the source size. + * @param target - maximum dimensions, hard byte limit, and preferred byte target; small sources are never enlarged. + * @param policy - resolved size-reduction controls. * @param signal - optional cancellation for cache I/O and image transformation. * @returns verified request bytes and deterministic variant identity. */ @@ -182,16 +218,17 @@ export async function readRequestImageFile( root: string, attachment: StoredImageAttachment, target: ImageRequestTarget, + policy: RequestImageResizePolicy, signal?: AbortSignal, ): Promise { signal?.throwIfAborted() validateTarget(target) const source = await probeImage(attachment.data) - const variantId = requestImageVariantId(attachment.ref, target) + const variantId = requestImageVariantId(attachment.ref, target, policy) const hash = String(variantId).slice('sha256:'.length) const path = cachePath(root, hash) const cached = await readCached(path, target, source.hasAlpha, signal) - const created = cached ?? await createRequestImage(attachment, target, source.hasAlpha) + const created = cached ?? await createRequestImage(attachment, target, source.hasAlpha, policy, signal) const version = cached ?? (created.data === attachment.data ? { ...created, hasAlpha: source.hasAlpha } : await verifyRequestImage(created, source.hasAlpha)) diff --git a/packages/attachment/attachment-local/tests/index.spec.ts b/packages/attachment/attachment-local/tests/index.spec.ts index 64c3977c9d..f1c6495d1b 100644 --- a/packages/attachment/attachment-local/tests/index.spec.ts +++ b/packages/attachment/attachment-local/tests/index.spec.ts @@ -66,6 +66,19 @@ describe('local attachment service', () => { } }) + it('validates request-image shrink controls in both schema and programmatic construction', () => { + for (const value of [0, 1, Number.NaN, Infinity]) { + expect(() => LocalAttachmentStore.Config({ requestImageMinShrinkFactor: value })).toThrow() + expect(() => new LocalAttachmentStore(new Context(), { requestImageMinShrinkFactor: value })) + .toThrow(/requestImageMinShrinkFactor/) + } + for (const value of [0, 1.1, Number.NaN, Infinity]) { + expect(() => LocalAttachmentStore.Config({ requestImageByteHeadroom: value })).toThrow() + expect(() => new LocalAttachmentStore(new Context(), { requestImageByteHeadroom: value })) + .toThrow(/requestImageByteHeadroom/) + } + }) + it('saves and reads through the service boundary', async () => { const dshHome = await mkdtemp(join(tmpdir(), 'dsh-attachment-service-')) try { @@ -86,7 +99,7 @@ describe('local attachment service', () => { String(ref.attachmentId).slice('sha256:'.length), )) await expect(readFile(hostPath)).resolves.toEqual(Buffer.from(data)) - const request = await service.readImageRequest(ref, { width: 1, height: 1, maxBytes: 1024 }) + const request = await service.readImageRequest(ref, { width: 1, height: 1, maxImageBytes: 1024, imageTargetBytes: 1024 }) expect(request).not.toHaveProperty('access') const fileData = Uint8Array.of(0, 1, 2, 255) diff --git a/packages/attachment/attachment-local/tests/request-image-verification.spec.ts b/packages/attachment/attachment-local/tests/request-image-verification.spec.ts index 693b36f737..11c1fea1d3 100644 --- a/packages/attachment/attachment-local/tests/request-image-verification.spec.ts +++ b/packages/attachment/attachment-local/tests/request-image-verification.spec.ts @@ -38,7 +38,9 @@ describe('request image verification', () => { const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) control.mismatch = true - await expect(attachments.readImageRequest(attachment, { width: 22, height: 11, maxBytes: 1024 * 1024 })) + await expect(attachments.readImageRequest(attachment, { + width: 22, height: 11, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + })) .rejects.toMatchObject({ code: 'ATTACHMENT_WRITE_FAILED', message: 'Encoded model-request image does not match its verified 8-bit sRGB metadata.', diff --git a/packages/attachment/attachment-local/tests/request-image.spec.ts b/packages/attachment/attachment-local/tests/request-image.spec.ts index bd27d0bf9d..1ebb89154b 100644 --- a/packages/attachment/attachment-local/tests/request-image.spec.ts +++ b/packages/attachment/attachment-local/tests/request-image.spec.ts @@ -4,6 +4,8 @@ import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import sharp from 'sharp' import { afterEach, describe, expect, it, vi } from 'vitest' +import * as encoding from '../src/encoding.ts' +import { readRequestImageFile } from '../src/request-image.ts' import { CompressionLimiter } from '../src/compression-limiter.ts' import LocalAttachmentStore from '../src/index.ts' @@ -25,17 +27,17 @@ async function image(width: number, height: number): Promise { }).png().toBuffer()) } -async function complexOpaqueAlphaImage(width: number, height: number): Promise { +async function complexAlphaImage(width: number, height: number, opaque = true): Promise { const pixels = new Uint8Array(width * height * 4) let state = 0x2545f491 for (let offset = 0; offset < pixels.length; offset += 4) { - for (let channel = 0; channel < 3; channel += 1) { + for (let channel = 0; channel < (opaque ? 3 : 4); channel += 1) { state ^= state << 13 state ^= state >>> 17 state ^= state << 5 pixels[offset + channel] = state & 0xff } - pixels[offset + 3] = 255 + if (opaque) pixels[offset + 3] = 255 } return new Uint8Array(await sharp(pixels, { raw: { width, height, channels: 4 }, @@ -58,7 +60,7 @@ describe('local request-image cache', () => { const stored = await attachments.readImage(attachment) const fileData = Uint8Array.of(0, 1, 2, 255) const file = await attachments.saveFile({ data: fileData, name: 'notes.bin' }) - const policy = { width: 22, height: 11, maxBytes: 4_096 } + const policy = { width: 22, height: 11, maxImageBytes: 4_096, imageTargetBytes: 4_096 } const initial = await attachments.readImageRequest(attachment, policy) const hash = String(initial.variantId).slice('sha256:'.length) const cacheRoot = join(dshHome, 'cache') @@ -86,7 +88,7 @@ describe('local request-image cache', () => { const first = await attachments.saveImage({ data: await image(8, 4), mediaType: 'image/png' }) const second = await attachments.saveImage({ data: await image(4, 8), mediaType: 'image/png' }) const firstStored = await attachments.readImage(first) - const policy = { width: 8, height: 8, maxBytes: 1024 * 1024 } + const policy = { width: 8, height: 8, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024 } const request = await attachments.readImageRequest(first, policy) const batch = await Promise.all([first, second].map( @@ -101,11 +103,11 @@ describe('local request-image cache', () => { const attachments = await store() const attachment = await attachments.saveImage({ data: await image(8, 4), mediaType: 'image/png' }) - await expect(attachments.readImageRequest(attachment, { width: 0, height: 4, maxBytes: 100 })) + await expect(attachments.readImageRequest(attachment, { width: 0, height: 4, maxImageBytes: 100, imageTargetBytes: 100 })) .rejects.toThrow('Image request width must be a positive integer') - await expect(attachments.readImageRequest(attachment, { width: 8, height: 1.5, maxBytes: 100 })) + await expect(attachments.readImageRequest(attachment, { width: 8, height: 1.5, maxImageBytes: 100, imageTargetBytes: 100 })) .rejects.toThrow('Image request height must be a positive integer') - await expect(attachments.readImageRequest(attachment, { width: 8, height: 4, maxBytes: 0 })) + await expect(attachments.readImageRequest(attachment, { width: 8, height: 4, maxImageBytes: 0, imageTargetBytes: 0 })) .rejects.toThrow('Image request maxBytes must be a positive integer') }) @@ -118,13 +120,27 @@ describe('local request-image cache', () => { const wide = await attachments.saveImage({ data: await image(1920, 1080), mediaType: 'image/png' }) const tall = await attachments.saveImage({ data: await image(1080, 1920), mediaType: 'image/png' }) - const squareRequest = await attachments.readImageRequest(square, { width: 1302, height: 1302, maxBytes }) - const smallRequest = await attachments.readImageRequest(small, { width: 800, height: 800, maxBytes }) - const thinRequest = await attachments.readImageRequest(thin, { width: 4096, height: 20, maxBytes }) - const wideRequest = await attachments.readImageRequest(wide, { width: 1708, height: 961, maxBytes }) - const tallRequest = await attachments.readImageRequest(tall, { width: 961, height: 1708, maxBytes }) - const smaller = await attachments.readImageRequest(square, { width: 1024, height: 1024, maxBytes }) - const enlarged = await attachments.readImageRequest(thin, { width: 9000, height: 45, maxBytes }) + const squareRequest = await attachments.readImageRequest(square, { + width: 1302, height: 1302, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const smallRequest = await attachments.readImageRequest(small, { + width: 800, height: 800, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const thinRequest = await attachments.readImageRequest(thin, { + width: 4096, height: 20, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const wideRequest = await attachments.readImageRequest(wide, { + width: 1708, height: 961, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const tallRequest = await attachments.readImageRequest(tall, { + width: 961, height: 1708, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const smaller = await attachments.readImageRequest(square, { + width: 1024, height: 1024, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) + const enlarged = await attachments.readImageRequest(thin, { + width: 9000, height: 45, maxImageBytes: maxBytes, imageTargetBytes: maxBytes, + }) expect(squareRequest).toMatchObject({ width: 1302, height: 1302, mediaType: 'image/jpeg' }) expect(smallRequest).toMatchObject({ width: 800, height: 800, mediaType: 'image/png' }) @@ -141,28 +157,142 @@ describe('local request-image cache', () => { const attachments = await store() const attachment = await attachments.saveImage({ data: await image(1224, 1429), mediaType: 'image/png' }) const request = await attachments.readImageRequest(attachment, { - width: 1187, height: 1386, maxBytes: 2 * 1024 * 1024, + width: 1187, height: 1386, maxImageBytes: 2 * 1024 * 1024, imageTargetBytes: 2 * 1024 * 1024, }) expect(request).toMatchObject({ width: 1187, height: 1386 }) await expect(sharp(request.data).metadata()).resolves.toMatchObject({ width: 1187, height: 1386 }) }) - it('keeps the smallest ladder output when the encoded-byte target is unreachable', async () => { + it('keeps dimensions when only the soft target is unreachable', async () => { const attachments = await store() const attachment = await attachments.saveImage({ data: await image(1, 1), mediaType: 'image/png' }) - const request = await attachments.readImageRequest(attachment, { width: 1, height: 1, maxBytes: 1 }) + const request = await attachments.readImageRequest(attachment, { width: 1, height: 1, maxImageBytes: 1024, imageTargetBytes: 1 }) expect(request.mediaType).toBe('image/jpeg') expect(request.bytes).toBeGreaterThan(1) expect(request).toMatchObject({ width: 1, height: 1 }) }) + it.each([false, true])('shrinks an oversized request until the encoded bytes fit, alpha=%s', async (alpha) => { + const attachments = await store() + let source = await complexAlphaImage(256, 128, false) + if (!alpha) source = new Uint8Array(await sharp(source).removeAlpha().png().toBuffer()) + const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) + const stored = await attachments.readImage(attachment) + const target = { width: 256, height: 128, maxImageBytes: 2048, imageTargetBytes: 2048 } + const request = await attachments.readImageRequest(attachment, target) + expect(request.bytes).toBeLessThanOrEqual(target.maxImageBytes) + expect(request.width).toBeLessThan(256) + expect(request.height).toBeLessThan(128) + await expect(sharp(request.data).metadata()).resolves.toMatchObject({ width: request.width, height: request.height }) + await expect(attachments.readImage(attachment)).resolves.toEqual(stored) + await expect(attachments.readImageRequest(attachment, target)).resolves.toEqual(request) + }) + + it('respects both dimension bounds before enforcing the byte limit', async () => { + const attachments = await store() + const source = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) + const result = await attachments.readImageRequest(source, { width: 64, height: 4, maxImageBytes: 4096, imageTargetBytes: 4096 }) + expect(result).toMatchObject({ width: 8, height: 4 }) + }) + + it('makes the configured minimum shrink step when the encoded image barely exceeds its hard cap', async () => { + const attachments = await store() + const attachment = await attachments.saveImage({ data: await complexAlphaImage(128, 128, false), mediaType: 'image/png' }) + const baseline = await attachments.readImageRequest(attachment, { + width: 128, height: 128, maxImageBytes: 100_000, imageTargetBytes: 1, + }) + const result = await attachments.readImageRequest(attachment, { + width: 128, height: 128, maxImageBytes: baseline.bytes - 1, imageTargetBytes: 1, + }) + expect(result.width).toBeLessThanOrEqual(Math.floor(128 / 1.1)) + expect(result.bytes).toBeLessThan(baseline.bytes) + }) + + it('stops byte-limit resizing when the caller aborts an outstanding encoding', async () => { + const attachments = await store() + const ref = await attachments.saveImage({ data: await complexAlphaImage(128, 128, false), mediaType: 'image/png' }) + const source = await attachments.readImage(ref) + let entered!: () => void + let release!: () => void + const encodingStarted = new Promise((resolve) => { entered = resolve }) + const resumeEncoding = new Promise((resolve) => { release = resolve }) + const actual = encoding.encodeFirstWithinLimit + const encode = vi.spyOn(encoding, 'encodeFirstWithinLimit').mockImplementationOnce(async (attempts, target) => { + entered() + await resumeEncoding + return actual(attempts, target) + }) + const controller = new AbortController() + const reason = new Error('cancel between request-image encodings') + const result = readRequestImageFile(await home(), source, + { width: 128, height: 128, maxImageBytes: 1024, imageTargetBytes: 1024 }, + { minShrinkFactor: 1.1, byteHeadroom: 0.95 }, controller.signal) + .then(value => value, (error: unknown) => error) + try { + await encodingStarted + controller.abort(reason) + release() + expect(await result).toBe(reason) + expect(encode).toHaveBeenCalledTimes(1) + } finally { + release() + await result + encode.mockRestore() + } + }) + + it('rejects an impossible hard limit after reaching one pixel', async () => { + const attachments = await store() + const attachment = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) + await expect(attachments.readImageRequest(attachment, { width: 64, height: 32, maxImageBytes: 1, imageTargetBytes: 1 })) + .rejects.toMatchObject({ code: 'IMAGE_REQUEST_TOO_LARGE', message: expect.stringContaining('1x1 pixels') }) + }) + + it('rejects invalid soft targets and a soft target above the hard limit', async () => { + const attachments = await store() + const attachment = await attachments.saveImage({ data: await image(8, 4), mediaType: 'image/png' }) + for (const imageTargetBytes of [0, 1.5, 101]) { + await expect(attachments.readImageRequest(attachment, { width: 8, height: 4, maxImageBytes: 100, imageTargetBytes })) + .rejects.toMatchObject({ code: 'INVALID_ATTACHMENT_REF' }) + } + }) + + it('rebuilds a cached image whose dimensions fit but whose actual bytes exceed the hard limit', async () => { + const dshHome = await home() + const attachments = new LocalAttachmentStore(new Context(), { dshHome }) + const attachment = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) + const target = { width: 22, height: 11, maxImageBytes: 4096, imageTargetBytes: 4096 } + const initial = await attachments.readImageRequest(attachment, target) + const hash = String(initial.variantId).slice('sha256:'.length) + const path = join(dshHome, 'cache', 'attachments', 'request-images', hash.slice(0, 2), hash) + const oversized = Buffer.concat([initial.data, Buffer.alloc(target.maxImageBytes)]) + await expect(sharp(oversized).metadata()).resolves.toMatchObject({ width: 22, height: 11 }) + await writeFile(path, oversized) + const rebuilt = await attachments.readImageRequest(attachment, target) + expect(rebuilt.bytes).toBeLessThanOrEqual(target.maxImageBytes) + expect(rebuilt.data).toEqual(initial.data) + }) + + it('includes both byte limits and resize controls in the cache identity', async () => { + const dshHome = await home() + const attachments = new LocalAttachmentStore(new Context(), { dshHome }) + const source = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) + const target = { width: 22, height: 11, maxImageBytes: 4096, imageTargetBytes: 1024 } + const original = await attachments.readImageRequest(source, target) + const softer = await attachments.readImageRequest(source, { ...target, imageTargetBytes: 2048 }) + const larger = await attachments.readImageRequest(source, { ...target, maxImageBytes: 8192 }) + const configured = new LocalAttachmentStore(new Context(), { dshHome, requestImageMinShrinkFactor: 1.5, requestImageByteHeadroom: 0.9 }) + const differentResize = await configured.readImageRequest(source, target) + expect(new Set([original, softer, larger, differentResize].map(item => item.variantId)).size).toBe(4) + }) + it('regenerates invalid, oversized, incompatible, or mismatched cached variants', async () => { const dshHome = await home() const attachments = new LocalAttachmentStore(new Context(), { dshHome }) const attachment = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) - const policy = { width: 22, height: 11, maxBytes: 4_096 } + const policy = { width: 22, height: 11, maxImageBytes: 4_096, imageTargetBytes: 4_096 } const initial = await attachments.readImageRequest(attachment, policy) const hash = String(initial.variantId).slice('sha256:'.length) const path = join(dshHome, 'cache', 'attachments', 'request-images', hash.slice(0, 2), hash) @@ -211,10 +341,18 @@ describe('local request-image cache', () => { data: await image(2048, 1024), mediaType: 'image/png', name: 'wide.png', }) - const squareRequest = await attachments.readImageRequest(square, { width: 800, height: 800, maxBytes: 1024 * 1024 }) - const wideRequest = await attachments.readImageRequest(wide, { width: 1130, height: 565, maxBytes: 1024 * 1024 }) - const repeated = await attachments.readImageRequest(wide, { width: 1130, height: 565, maxBytes: 1024 * 1024 }) - const low = await attachments.readImageRequest(wide, { width: 724, height: 362, maxBytes: 1024 * 1024 }) + const squareRequest = await attachments.readImageRequest(square, { + width: 800, height: 800, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) + const wideRequest = await attachments.readImageRequest(wide, { + width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) + const repeated = await attachments.readImageRequest(wide, { + width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) + const low = await attachments.readImageRequest(wide, { + width: 724, height: 362, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) expect(squareRequest).toMatchObject({ width: 800, height: 800 }) expect(wideRequest).toMatchObject({ width: 1130, height: 565 }) @@ -254,8 +392,12 @@ describe('local request-image cache', () => { const photo = await attachments.saveImage({ data: photoSource, mediaType: 'image/png' }) const alpha = await attachments.saveImage({ data: alphaSource, mediaType: 'image/png' }) - const photoRequest = await attachments.readImageRequest(photo, { width: 128, height: 128, maxBytes: 1024 * 1024 }) - const alphaRequest = await attachments.readImageRequest(alpha, { width: 128, height: 128, maxBytes: 4_096 }) + const photoRequest = await attachments.readImageRequest(photo, { + width: 128, height: 128, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) + const alphaRequest = await attachments.readImageRequest(alpha, { + width: 128, height: 128, maxImageBytes: 4_096, imageTargetBytes: 4_096, + }) expect(photoRequest.mediaType).toBe('image/jpeg') expect(alphaRequest.mediaType).toBe('image/webp') @@ -271,7 +413,9 @@ describe('local request-image cache', () => { }).toColourspace('rgb16').png().toBuffer()) const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) - const request = await attachments.readImageRequest(attachment, { width: 22, height: 11, maxBytes: 1024 * 1024 }) + const request = await attachments.readImageRequest(attachment, { + width: 22, height: 11, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) expect(request.bytes).toBeLessThanOrEqual(1024 * 1024) expect(request.width * request.height).toBeLessThanOrEqual(16 * 16) @@ -282,10 +426,12 @@ describe('local request-image cache', () => { it('accepts a resized WebP request version that omits an all-opaque alpha plane', async () => { const attachments = await store() - const source = await complexOpaqueAlphaImage(64, 32) + const source = await complexAlphaImage(64, 32) const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) - const request = await attachments.readImageRequest(attachment, { width: 22, height: 11, maxBytes: 1024 * 1024 }) + const request = await attachments.readImageRequest(attachment, { + width: 22, height: 11, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) expect(request.mediaType).toBe('image/webp') await expect(sharp(request.data).metadata()).resolves.toMatchObject({ hasAlpha: false }) @@ -307,7 +453,9 @@ describe('local request-image cache', () => { }).png().toBuffer()) const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' }) - const request = await attachments.readImageRequest(attachment, { width: 800, height: 800, maxBytes: 1024 * 1024 }) + const request = await attachments.readImageRequest(attachment, { + width: 800, height: 800, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, + }) expect(request).toMatchObject({ width: 800, height: 800 }) expect(request.bytes).toBeLessThanOrEqual(1024 * 1024) @@ -320,7 +468,7 @@ describe('local request-image cache', () => { }) const run = vi.spyOn(CompressionLimiter.prototype, 'run') const controller = new AbortController() - const policy = { width: 1130, height: 565, maxBytes: 1024 * 1024 } + const policy = { width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024 } const cancelled = attachments.readImageRequest(attachment, policy, controller.signal) const completed = attachments.readImageRequest(attachment, policy) @@ -350,7 +498,7 @@ describe('local request-image cache', () => { const controller = new AbortController() const request = attachments.readImageRequest( attachment, - { width: 1130, height: 565, maxBytes: 1024 * 1024 }, + { width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024 }, controller.signal, ) await vi.waitFor(() => { @@ -383,7 +531,7 @@ describe('local request-image cache', () => { return actualRead(ref, signal) }) const controller = new AbortController() - const policy = { width: 1130, height: 565, maxBytes: 1024 * 1024 } + const policy = { width: 1130, height: 565, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024 } const cancelled = attachments.readImageRequest(attachment, policy, controller.signal) await vi.waitFor(() => { expect(calls).toBe(1) diff --git a/packages/attachment/attachment/README.i18n.yaml b/packages/attachment/attachment/README.i18n.yaml index 6b51f9ea66..6499dbb687 100644 --- a/packages/attachment/attachment/README.i18n.yaml +++ b/packages/attachment/attachment/README.i18n.yaml @@ -39,8 +39,8 @@ en: bc4586bb4ce74464 zh: 5ffd0a0e7261bc24 /deepseek-ai-dsh-attachment/understand-the-implementation/service-operations: - en: d6363ab6ffcef365 - zh: ac1068ba4aa6a618 + en: f23e01288c418599 + zh: 9358d6126de1e576 /deepseek-ai-dsh-attachment/understand-the-implementation/source-map: en: 4fb4c96184c38169 zh: 015b06e4bfff4fcd diff --git a/packages/attachment/attachment/README.md b/packages/attachment/attachment/README.md index 40be9b99f5..d25da84710 100644 --- a/packages/attachment/attachment/README.md +++ b/packages/attachment/attachment/README.md @@ -72,7 +72,9 @@ This section explains the design decisions behind the seam and the service opera ### Service operations -The service family runs one admission-and-storage flow: every entry point enforces source batch limits and canonical base64, prepares provider-independent normalized attachments before publishing any member, and commits them durably in input order without partial results. Host prompt consumers pass ordered text, encoded images, and already resolved file and image references to `ctx.attachments.admitPromptContent()`; the method persists the encoded images, passes references unchanged, and counts every image toward the per-message image count and aggregate byte limits, a stored image by the bytes of the upload that stored it. Encoded protocol adapters call `ctx.attachments.admitEncodedFile()`, which checks canonical base64 before delegating to `saveFile`; adapters recognize attachment failures through `ctx.attachments.isAttachmentError()`. Generic-file callers choose `saveFile` for existing bytes or `saveFileStream` for a bounded asynchronous byte source; both return the same durable reference, while `readFileStream` verifies its digest and length during a bounded read. `readImageRequest` derives deterministic route-sized variants whose identity includes the attachment id, transform version, target dimensions, byte target, and encoder settings. The pure `requestImageDimensions` and `longEdgeDimensions` exports compute aspect-preserving dimensions from a total-pixel budget with optional width/height limits or an exact long edge, so routes and request pricing share one geometry. `imageHostPath` exposes an implementation-owned host location only to trusted same-process consumers that need execution-world mapping. Callers compose ordered batches while the implementation owns compression concurrency, caching, and singleflight. Reads, streamed writes, and projections preserve caller cancellation. Failures carry stable machine-readable codes, and the caller-correctable admission subset is recognizable at runtime so each protocol adapter maps its own vocabulary; the exact per-operation contracts live in [`src/index.ts`](src/index.ts) and [`src/error.ts`](src/error.ts). +The service family runs one admission-and-storage flow: every entry point enforces source batch limits and canonical base64, prepares provider-independent normalized attachments before publishing any member, and commits them durably in input order without partial results. Host prompt consumers pass ordered text, encoded images, and already resolved file and image references to `ctx.attachments.admitPromptContent()`; the method persists the encoded images, passes references unchanged, and counts every image toward the per-message image count and aggregate byte limits, a stored image by the bytes of the upload that stored it. Encoded protocol adapters call `ctx.attachments.admitEncodedFile()`, which checks canonical base64 before delegating to `saveFile`; adapters recognize attachment failures through `ctx.attachments.isAttachmentError()`. Generic-file callers choose `saveFile` for existing bytes or `saveFileStream` for a bounded asynchronous byte source; both return the same durable reference, while `readFileStream` verifies its digest and length during a bounded read. `readImageRequest` derives deterministic route-sized variants whose identity includes the attachment id, transform version, maximum dimensions, hard and preferred byte limits, and encoder settings. The pure `requestImageDimensions` and `longEdgeDimensions` exports compute aspect-preserving dimensions from a total-pixel budget with optional width/height limits or an exact long edge, so routes and request pricing share one geometry. `imageHostPath` exposes an implementation-owned host location only to trusted same-process consumers that need execution-world mapping. Callers compose ordered batches while the implementation owns compression concurrency, caching, and singleflight. Reads, streamed writes, and projections preserve caller cancellation. Failures carry stable machine-readable codes, and the caller-correctable admission subset is recognizable at runtime so each protocol adapter maps its own vocabulary; the exact per-operation contracts live in [`src/index.ts`](src/index.ts) and [`src/error.ts`](src/error.ts). + +Successful request-image reads satisfy `ImageRequestTarget.maxImageBytes`. `imageTargetBytes` is a preferred target no greater than the hard limit. Further resizing is allowed only when the encoded image still exceeds the hard limit; callers use the returned dimensions, and an impossible one-pixel limit fails with `IMAGE_REQUEST_TOO_LARGE`. ### Source map diff --git a/packages/attachment/attachment/README.zh.md b/packages/attachment/attachment/README.zh.md index 0a3bc83731..aa5e7a8332 100644 --- a/packages/attachment/attachment/README.zh.md +++ b/packages/attachment/attachment/README.zh.md @@ -72,7 +72,9 @@ kind: "package-reference" ### 服务操作 -服务族运行同一条准入与存储流程:每个入口都强制执行源批次限制与规范 base64,在发布任何成员前准备提供方无关的规范化附件,再按输入顺序持久提交而不产生部分结果。Host 提示词消费方把有序文本、编码图片和已经解析的文件与图片引用交给 `ctx.attachments.admitPromptContent()`;该方法持久化编码图片,让引用原样通过,并把每张图片计入单条消息的图片数量与总字节上限,已存储的图片按存储它的那次上传的字节数计入。编码协议适配器调用 `ctx.attachments.admitEncodedFile()`,由该方法检查规范 base64 后委托给 `saveFile`;适配器通过 `ctx.attachments.isAttachmentError()` 识别附件错误。通用文件调用方可以用 `saveFile` 提交已有字节,或用 `saveFileStream` 提交有界异步字节源;两者返回相同的持久引用,`readFileStream` 则在有界读取过程中校验摘要与长度。`readImageRequest` 派生确定性的路由尺寸变体,其身份包含附件 id、变换版本、目标尺寸、字节目标及编码参数。纯函数导出 `requestImageDimensions` 与 `longEdgeDimensions` 按总像素预算及可选宽高限制,或精确长边计算保持宽高比的尺寸,使路由与请求定价共享同一套几何计算。`imageHostPath` 只向需要把该位置映射到执行环境的受信任同进程消费方暴露实现拥有的宿主位置。调用方组合有序批次,而实现负责管理压缩并发、缓存与 singleflight。读取、流式写入和投影保留调用方的取消语义。失败带有稳定且机器可读的错误码,运行时即可识别可由调用方修正的准入子集,让每个协议适配器映射自己的词汇;各操作的确切约定见 [`src/index.ts`](src/index.ts) 与 [`src/error.ts`](src/error.ts)。 +服务族运行同一条准入与存储流程:每个入口都强制执行源批次限制与规范 base64,在发布任何成员前准备提供方无关的规范化附件,再按输入顺序持久提交而不产生部分结果。Host 提示词消费方把有序文本、编码图片和已经解析的文件与图片引用交给 `ctx.attachments.admitPromptContent()`;该方法持久化编码图片,让引用原样通过,并把每张图片计入单条消息的图片数量与总字节上限,已存储的图片按存储它的那次上传的字节数计入。编码协议适配器调用 `ctx.attachments.admitEncodedFile()`,由该方法检查规范 base64 后委托给 `saveFile`;适配器通过 `ctx.attachments.isAttachmentError()` 识别附件错误。通用文件调用方可以用 `saveFile` 提交已有字节,或用 `saveFileStream` 提交有界异步字节源;两者返回相同的持久引用,`readFileStream` 则在有界读取过程中校验摘要与长度。`readImageRequest` 派生确定性的路由尺寸变体,其身份包含附件 id、变换版本、最大尺寸、硬字节上限、软字节目标及编码参数。纯函数导出 `requestImageDimensions` 与 `longEdgeDimensions` 按总像素预算及可选宽高限制,或精确长边计算保持宽高比的尺寸,使路由与请求定价共享同一套几何计算。`imageHostPath` 只向需要把该位置映射到执行环境的受信任同进程消费方暴露实现拥有的宿主位置。调用方组合有序批次,而实现负责管理压缩并发、缓存与 singleflight。读取、流式写入和投影保留调用方的取消语义。失败带有稳定且机器可读的错误码,运行时即可识别可由调用方修正的准入子集,让每个协议适配器映射自己的词汇;各操作的确切约定见 [`src/index.ts`](src/index.ts) 与 [`src/error.ts`](src/error.ts)。 + +成功的请求图片读取结果满足 `ImageRequestTarget.maxImageBytes`。`imageTargetBytes` 是不大于硬上限的软目标。只有编码结果仍超过硬上限时才继续降低尺寸;调用方使用返回的实际尺寸。连一个像素的图片也无法满足上限时,以 `IMAGE_REQUEST_TOO_LARGE` 失败。 ### 源码地图 diff --git a/packages/attachment/attachment/src/error.ts b/packages/attachment/attachment/src/error.ts index 2a933daa08..0f120bbc56 100644 --- a/packages/attachment/attachment/src/error.ts +++ b/packages/attachment/attachment/src/error.ts @@ -26,6 +26,7 @@ const ATTACHMENT_ERROR_CODES = [ 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', + 'IMAGE_REQUEST_TOO_LARGE', 'ATTACHMENT_FILES_UNSUPPORTED', ] as const diff --git a/packages/attachment/attachment/src/index.ts b/packages/attachment/attachment/src/index.ts index 802df0cb6b..ab91a069d3 100644 --- a/packages/attachment/attachment/src/index.ts +++ b/packages/attachment/attachment/src/index.ts @@ -270,9 +270,9 @@ export abstract class AttachmentStore extends Service { /** * Generate or read one deterministic model-request version from the stored normalized image. * @param ref - durable provider-independent normalized attachment reference. - * @param target - route-chosen dimensions and byte target; an unmet byte target yields the smallest ladder output. + * @param target - route-chosen maximum dimensions, hard byte limit, and preferred byte target. * @param signal - optional cancellation. - * @returns request bytes and the cache/upload identity covering every transform input. + * @returns request bytes within the hard limit, actual encoded dimensions, and a cache/upload identity covering every transform input. */ readImageRequest( ref: ImageAttachmentRef, diff --git a/packages/attachment/attachment/src/types.ts b/packages/attachment/attachment/src/types.ts index f003d65254..eb3fdfb574 100644 --- a/packages/attachment/attachment/src/types.ts +++ b/packages/attachment/attachment/src/types.ts @@ -140,12 +140,14 @@ export interface StoredImageAttachment { /** Deterministic request-image target selected by one exact model route for one attachment. */ export interface ImageRequestTarget { - /** Target width in pixels; a target above the source keeps the source width. */ + /** Maximum request width in pixels; byte-limit enforcement can produce a smaller image. */ width: number - /** Target height in pixels; a target above the source keeps the source height. */ + /** Maximum request height in pixels; byte-limit enforcement can produce a smaller image. */ height: number - /** Encoded-byte target before base64 expansion or Files API upload; the smallest quality-ladder output is kept when no quality fits. */ - maxBytes: number + /** Hard encoded-byte limit before base64 expansion or Files API upload; successful results never exceed it. */ + maxImageBytes: number + /** Preferred encoded-byte target, no greater than maxImageBytes; exceeding only this target does not reduce resolution. */ + imageTargetBytes: number } /** Cached request version derived from one provider-independent normalized attachment. */ diff --git a/packages/attachment/attachment/tests/index.spec.ts b/packages/attachment/attachment/tests/index.spec.ts index e30615e53b..d8daa3d575 100644 --- a/packages/attachment/attachment/tests/index.spec.ts +++ b/packages/attachment/attachment/tests/index.spec.ts @@ -154,12 +154,14 @@ describe('AttachmentStore.readImageRequest', () => { it('reports unsupported request projection while preserving cancellation', async () => { const store = new UnsupportedProjectionStore(new Context()) const ref = await new RecordingStore(new Context()).saveImage(image(1)) - await expect(store.readImageRequest(ref, { width: 1, height: 1, maxBytes: 1 })) + await expect(store.readImageRequest(ref, { width: 1, height: 1, maxImageBytes: 1, imageTargetBytes: 1 })) .rejects.toMatchObject({ code: 'ATTACHMENT_PROJECTION_UNSUPPORTED' }) const controller = new AbortController() const reason = new Error('cancel unsupported projection') controller.abort(reason) - expect(() => store.readImageRequest(ref, { width: 1, height: 1, maxBytes: 1 }, controller.signal)).toThrow(reason) + expect(() => store.readImageRequest(ref, { + width: 1, height: 1, maxImageBytes: 1, imageTargetBytes: 1, + }, controller.signal)).toThrow(reason) }) it('rejects generic-file storage and exposes no provider-owned host path by default', async () => { diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index ab57b77108..57a659e4d6 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -748,12 +748,12 @@ it('preserves screenshot attachments and invalidates pixel coordinates when wind expect(native.request).not.toHaveBeenCalled() }) -it('maps the actual model-request image pixels back to native points without storing the screenshot twice', async () => { +it.each([100_000, 300])('maps final request-image pixels to native points under a %s-byte hard limit', async (maxImageBytes) => { const f = await setup({ provider: 'image-fixture', model: 'vision' }) await selectApplication(f) class ResizingAdapter extends ImageAdapter { override imageRequestTarget(_provider: string, _model: string, _image: ImageAttachmentRef) { - return { width: 10, height: 5, maxBytes: 100_000 } + return { width: 20, height: 10, maxImageBytes, imageTargetBytes: maxImageBytes } } } f.ctx.llm.registerAdapter(['image-fixture'], new ResizingAdapter()) @@ -761,17 +761,29 @@ it('maps the actual model-request image pixels back to native points without sto onTestFinished(async () => { await f.ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) await f.ctx.plugin(LocalAttachmentStore, { dshHome: root }) const save = vi.spyOn(f.ctx.attachments, 'saveImages') - const image = await sharp({ create: { width: 40, height: 20, channels: 3, background: '#4488cc' } }).png().toBuffer() + const pixels = Buffer.alloc(40 * 20 * 3) + let state = 0x2545f491 + for (let index = 0; index < pixels.length; index++) { + state ^= state << 13 + state ^= state >>> 17 + state ^= state << 5 + pixels[index] = state & 255 + } + const image = await sharp(pixels, { raw: { width: 40, height: 20, channels: 3 } }).png().toBuffer() native.request.mockResolvedValue({ ...imageMetadata, bounds: { x: 10, y: 20, width: 400, height: 200 }, pixelWidth: 40, pixelHeight: 20, mimeType: 'image/png', data: image.toString('base64') }) const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: '7' }) expect(result.isError, JSON.stringify(result.content)).toBe(false) - expect(result.value).toMatchObject({ pixelWidth: 10, pixelHeight: 5, coordinateSpace: 'screenshot-pixels' }) - const value = result.value as { data: string } - expect(await sharp(Buffer.from(value.data, 'base64')).metadata()).toMatchObject({ width: 10, height: 5 }) + expect(result.value).toMatchObject({ coordinateSpace: 'screenshot-pixels' }) + const value = result.value as { data: string; pixelWidth: number; pixelHeight: number } + const encoded = Buffer.from(value.data, 'base64') + expect(encoded.byteLength).toBeLessThanOrEqual(maxImageBytes) + expect(await sharp(encoded).metadata()).toMatchObject({ width: value.pixelWidth, height: value.pixelHeight }) + if (maxImageBytes === 300) expect(value.pixelWidth).toBeLessThan(20) + else expect(value).toMatchObject({ pixelWidth: 20, pixelHeight: 10 }) expect(save).toHaveBeenCalledTimes(1) native.request.mockResolvedValue({ dispatched: true }) - expect((await f.execute('click', { appHandle: 'app-one', windowId: '7', x: 5, y: 2.5 })).isError).toBe(false) + expect((await f.execute('click', { appHandle: 'app-one', windowId: '7', x: value.pixelWidth / 2, y: value.pixelHeight / 2 })).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('click', { appHandle: 'app-one', windowId: '7', x: 200, y: 100 }, expect.any(AbortSignal), expect.any(String)) expect((await f.execute('click', { appHandle: 'app-one', windowId: '7', x: 999, y: 999, relative: true })).isError).toBe(false) expect(native.request).toHaveBeenLastCalledWith('click', { appHandle: 'app-one', windowId: '7', x: 399, y: 199 }, expect.any(AbortSignal), expect.any(String)) diff --git a/packages/experimental/cua-mcp/tests/projection.spec.ts b/packages/experimental/cua-mcp/tests/projection.spec.ts index 3afb12b21d..3d79214946 100644 --- a/packages/experimental/cua-mcp/tests/projection.spec.ts +++ b/packages/experimental/cua-mcp/tests/projection.spec.ts @@ -28,7 +28,7 @@ describe('tool result projection', () => { it('delivers the request version the program observed when the provider fixes a target', async () => { const { attachments, readImageRequest, readImage } = store() const signal = new AbortController().signal - const target = { width: 40, height: 20, maxBytes: 1024 } + const target = { width: 40, height: 20, maxImageBytes: 1024, imageTargetBytes: 1024 } const result = await projectToolResult(success, deferred, { attachments, target: () => target }, signal) expect(result).toEqual({ content: [ { type: 'text', text: '{"visits":1}' }, diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 3a4ec748f2..3e37f1e74c 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: a7759cc0ce7f405a - zh: 1c7f6f11751438ec + en: 67ea5d6331db13f3 + zh: 29c924d2d0083f53 /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: 3f638a4a76023fc5 zh: 515aeb5de6ae5b33 diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index a4a08df9e7..e77e4a473e 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -45,7 +45,7 @@ Keyboard methods are available in the scopes a provider declares; the provider o Connect PTC with `connectCua(() => tools.cua)` or supply a custom dispatcher to `createCuaApi(dispatch)`. Observation methods return their results to the program. Call `inspect(await app.getWindows())` to display a result, or pass a filtered value. `window.getScreenshot()` returns an `Image` whose `path` is readable by the program and whose `width` and `height` describe the stored pixels. Use `inspect("before", before, "after", after)` to display selected screenshots. Read the window ID from `window.windowId`. -`tools.cua` screenshot operations return `Image` in TypeScript programs. Host-side canonical screenshot results carry encoded image data and a durable `attachment` reference; the native renderer projects coordinate metadata and the image into model content. Capture requires an attachment store and either a configured `screenshotTarget` or a resolved model route declaring image input. Admission and storage failures reject the call. Failed calls carry structured identity: native and host refusals use `NativeError` with the native or host code, such as `APP_ACCESS_DENIED`, `NATIVE_TIMEOUT`, or `MODEL_DOES_NOT_SUPPORT_IMAGES` for a model without image input, which stays on `NativeError` because it is the package's one error class and its message keeps the `CODE: ` prefix every `NativeError` carries; a missing Agent, attachment store, or model route uses `ToolContextUnavailableError`; arguments the schema cannot check use `ToolArgsError`; native cancellation after the caller cancels records `AbortError` with `ABORTED`. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. +`tools.cua` screenshot operations return `Image` in TypeScript programs. Host-side canonical screenshot results carry encoded image data and a durable `attachment` reference; the native renderer projects coordinate metadata and the image into model content. Capture requires an attachment store and either a configured `screenshotTarget` or a resolved model route declaring image input. Admission and storage failures reject the call. Failed calls carry structured identity: native and host refusals use `NativeError` with the native or host code, such as `APP_ACCESS_DENIED`, `NATIVE_TIMEOUT`, or `MODEL_DOES_NOT_SUPPORT_IMAGES` for a model without image input, which stays on `NativeError` because it is the package's one error class and its message keeps the `CODE: ` prefix every `NativeError` carries; a missing Agent, attachment store, or model route uses `ToolContextUnavailableError`; arguments the schema cannot check use `ToolArgsError`; native cancellation after the caller cancels records `AbortError` with `ABORTED`. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. `screenshotTarget.maxBytes` is a hard encoded-byte cap; further resizing uses the final encoded dimensions for screenshot coordinates. Application consent precedes launch, observation, capture, and input. Session access is stored by conversation and application identity and survives DSH restart and Computer Use disablement. Other conversations require their own consent. Saved grants require a platform-provided reusable application identity. Refusal and revocation close affected Agent connections, so their old objects require fresh selection. No input is replayed after cancellation, timeout, or reconnect. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index fb6e21f8ef..a322c54667 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -45,7 +45,7 @@ kind: "package-reference" 通过 `connectCua(() => tools.cua)` 连接 PTC,或将自定义分派器传给 `createCuaApi(dispatch)`。观察方法返回结果供程序使用。需要展示时,调用 `inspect(await app.getWindows())` 或传入筛选后的值。`window.getScreenshot()` 返回 `Image`,其 `path` 指向程序可读取的附件文件,`width` 和 `height` 是图片的像素尺寸。使用 `inspect("操作前", before, "操作后", after)` 展示选中的截图,从 `window.windowId` 读取窗口 ID。 -`tools.cua` 的截图操作在 TypeScript 程序中返回 `Image`。宿主侧的规范化截图结果包含编码图像数据与持久的 `attachment` 引用;原生渲染器将坐标元数据和图片投影为模型内容。截图前要求附件服务可用,且已配置 `screenshotTarget` 或当前模型路由声明图片输入。图片接入或保存失败会拒绝调用。 失败调用带有结构化标识:原生与 Host 拒绝使用 `NativeError` 及原生或 Host code,例如 `APP_ACCESS_DENIED`、`NATIVE_TIMEOUT`,模型不支持图片输入时为 `MODEL_DOES_NOT_SUPPORT_IMAGES`,它仍属于 `NativeError`,因为这是本包唯一的错误类,其 message 也与所有 `NativeError` 一样带 `CODE: ` 前缀;缺少 Agent、附件服务或模型路由时使用 `ToolContextUnavailableError`;参数 schema 无法检查的参数错误使用 `ToolArgsError`;调用方取消后的原生取消记录为 `AbortError` 与 `ABORTED`。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 +`tools.cua` 的截图操作在 TypeScript 程序中返回 `Image`。宿主侧的规范化截图结果包含编码图像数据与持久的 `attachment` 引用;原生渲染器将坐标元数据和图片投影为模型内容。截图前要求附件服务可用,且已配置 `screenshotTarget` 或当前模型路由声明图片输入。图片接入或保存失败会拒绝调用。 失败调用带有结构化标识:原生与 Host 拒绝使用 `NativeError` 及原生或 Host code,例如 `APP_ACCESS_DENIED`、`NATIVE_TIMEOUT`,模型不支持图片输入时为 `MODEL_DOES_NOT_SUPPORT_IMAGES`,它仍属于 `NativeError`,因为这是本包唯一的错误类,其 message 也与所有 `NativeError` 一样带 `CODE: ` 前缀;缺少 Agent、附件服务或模型路由时使用 `ToolContextUnavailableError`;参数 schema 无法检查的参数错误使用 `ToolArgsError`;调用方取消后的原生取消记录为 `AbortError` 与 `ABORTED`。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 `screenshotTarget.maxBytes` 是编码字节硬上限;继续缩图后,截图坐标使用最终编码尺寸。 应用授权发生在启动、观察、截图和输入之前。会话许可按对话和应用身份持久化,重启 DSH 或关闭 Computer Use 后仍可复用,其他对话需要单独授权。长期许可要求平台提供可复用的应用身份。拒绝或撤销会关闭受影响的 Agent 连接,因此旧对象必须重新选择目标。取消、超时或重新连接后均不重放输入。 diff --git a/packages/experimental/cua/src/config.ts b/packages/experimental/cua/src/config.ts index 1072932ea9..cf8b96a2cb 100644 --- a/packages/experimental/cua/src/config.ts +++ b/packages/experimental/cua/src/config.ts @@ -25,9 +25,9 @@ export const CuaStandaloneRunCodeConfig: Schema', description: 'Generate or read one deterministic model-request version from the stored normalized image.', - parameters: [{ name: 'ref', description: 'durable provider-independent normalized attachment reference.' }, { name: 'target', description: 'route-chosen dimensions and byte target; an unmet byte target yields the smallest ladder output.' }, { name: 'signal', description: 'optional cancellation.' }], - returns: 'request bytes and the cache/upload identity covering every transform input.', + parameters: [{ name: 'ref', description: 'durable provider-independent normalized attachment reference.' }, { name: 'target', description: 'route-chosen maximum dimensions, hard byte limit, and preferred byte target.' }, { name: 'signal', description: 'optional cancellation.' }], + returns: 'request bytes within the hard limit, actual encoded dimensions, and a cache/upload identity covering every transform input.', }, ], }, @@ -2326,7 +2326,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ signature: 'imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget', description: 'Resolve the image projection for an exact registered model route.', parameters: [{ name: 'provider', description: 'registered provider route.' }, { name: 'model', description: 'exact model id.' }, { name: 'image', description: 'normalized image reference.' }], - returns: 'dimensions and byte target used by the adapter\'s request serializer.', + returns: 'maximum dimensions and byte budgets used by the request serializer; readImageRequest returns the actual encoded dimensions.', }, { signature: 'fileRequestText(ref: FileAttachmentRef): string', @@ -7771,7 +7771,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ImageRequestTarget', - declaration: 'export interface ImageRequestTarget {\n width: number;\n height: number;\n maxBytes: number;\n}', + declaration: 'export interface ImageRequestTarget {\n width: number;\n height: number;\n maxImageBytes: number;\n imageTargetBytes: number;\n}', }, { name: 'ImageUploadValue', diff --git a/packages/fs/tool-fs/src/read-image.ts b/packages/fs/tool-fs/src/read-image.ts index 98b7ea1a2c..f5d7d24896 100644 --- a/packages/fs/tool-fs/src/read-image.ts +++ b/packages/fs/tool-fs/src/read-image.ts @@ -266,6 +266,7 @@ function saveFailureDetail(error: AttachmentError, attachments: AttachmentStore, case 'ATTACHMENT_CORRUPT': case 'ATTACHMENT_NOT_FOUND': case 'ATTACHMENT_READ_FAILED': + case 'IMAGE_REQUEST_TOO_LARGE': case 'ATTACHMENT_PROJECTION_UNSUPPORTED': case 'ATTACHMENT_FILES_UNSUPPORTED': return undefined diff --git a/packages/fs/tool-fs/tests/read-image.spec.ts b/packages/fs/tool-fs/tests/read-image.spec.ts index 2142241f99..e0336f1a8c 100644 --- a/packages/fs/tool-fs/tests/read-image.spec.ts +++ b/packages/fs/tool-fs/tests/read-image.spec.ts @@ -765,7 +765,7 @@ describe('image admission failures', () => { it.each([ 'ATTACHMENT_WRITE_FAILED', 'TOO_MANY_IMAGES', 'INVALID_IMAGE_BASE64', 'INVALID_FILE_BASE64', 'INVALID_ATTACHMENT_REF', - 'ATTACHMENT_CORRUPT', 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', + 'IMAGE_REQUEST_TOO_LARGE', 'ATTACHMENT_CORRUPT', 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', 'ATTACHMENT_FILES_UNSUPPORTED', ] as const)('passes AttachmentError %s without a read remedy through unchanged', async (code) => { const result = await failingSave(() => new AttachmentError('Stored attachment failed.', code)) diff --git a/packages/llm/llm-deepseek-account/tests/config.spec.ts b/packages/llm/llm-deepseek-account/tests/config.spec.ts index f6e62893e6..26d594a508 100644 --- a/packages/llm/llm-deepseek-account/tests/config.spec.ts +++ b/packages/llm/llm-deepseek-account/tests/config.spec.ts @@ -17,7 +17,9 @@ it.each([ [{ modelOverrides: { '': {} } }, /modelOverrides keys must be non-empty model ids/], [{ modelOverrides: { 'deepseek-flash': { id: 'other' } } }, /modelOverrides\.deepseek-flash sets "id"/], [{ modelOverrides: { 'deepseek-flash': { contextWindow: 0 } } }, /modelOverrides\.deepseek-flash is invalid: .*contextWindow must be a positive integer/], - [{ modelOverrides: { 'deepseek-flash': { inputModalities: ['text'], imageMaxBytes: 1 } } }, /modelOverrides\.deepseek-flash is invalid: .*cannot declare image request limits/], + [{ modelOverrides: { 'deepseek-flash': { + inputModalities: ['text'], imageTargetBytes: 1, + } } }, /modelOverrides\.deepseek-flash is invalid: .*cannot declare image request limits/], ])('rejects %j', (options, message) => { expect(() => { Reflect.apply(resolveAccountOptions, undefined, [options]) }).toThrow(message) }) diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index c06aafb116..2b03ed3634 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -21,8 +21,8 @@ en: 6850d08bc091ad23 zh: 2906e6cf1dfed6ce /deepseek-ai-dsh-llm-deepseek/use-this-package/minimal-configuration: - en: 027d877820d26c65 - zh: 080705c5c20d1032 + en: 91f433de6cb0939f + zh: aea6b38facebe188 /deepseek-ai-dsh-llm-deepseek/use-this-package/endpoint-and-wire-format: en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc @@ -30,8 +30,8 @@ en: 5f8cda73f2c10260 zh: 2a507d9ee8b9c67a /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: - en: f20f2cfbb38e4ba9 - zh: c527b91c8b747886 + en: baab62ea4b39b382 + zh: d00aca9dde9383bb /deepseek-ai-dsh-llm-deepseek/use-this-package/dynamic-configuration: en: 49290fc5647136b4 zh: 96fa9ce0f9e83c13 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 1fea939f35..3b7020f21b 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -50,7 +50,7 @@ Choose this adapter for DeepSeek's official API or a Messages-compatible gateway filesApiTimeoutMs: 20000 ``` -A request selects the route with `provider: deepseek-official`; the model id passes through to the wire, so new DeepSeek models need no re-registration. Omitted `models` advertises the text- and image-capable `deepseek-flash` alongside the text-only `deepseek-v4-pro`, each with the 1,048,576-token context window the official model listing declares. An explicit list replaces those defaults, and core calls still pass unlisted model ids through as text-only routes. On the official endpoint the API-key route follows the service's model listing while `models` holds those defaults ([listing rules](../llm-deepseek-api-key/README.md#use-this-package)). GUI selection requires a catalog entry; a saved selection can still submit requests after its catalog entry disappears. Clients, including model discovery tools, can read the advisory entries through `ctx.llm.listModels('deepseek-official')`. Image-capable entries may set `imagePixelBudget` to a positive integer or `low`, and may set `imageMaxBytes`. An entry may declare `systemPromptUpdate: in-history` when its endpoint reads the latest `system` message at any position of `messages` as the complete effective system prompt; the adapter reports the mode on the resolved model and the prepared call, and the agent loop then appends a changed prompt after the cached history instead of rewriting the leading system message ([decision rule](../../core/agent-loop/README.md#understand-the-implementation)). The default `deepseek-flash` entry declares this mode; other models require an explicit `models` declaration, and any value other than `in-history` fails at load with `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present`. +A request selects the route with `provider: deepseek-official`; the model id passes through to the wire, so new DeepSeek models need no re-registration. Omitted `models` advertises the text- and image-capable `deepseek-flash` alongside the text-only `deepseek-v4-pro`, each with the 1,048,576-token context window the official model listing declares. An explicit list replaces those defaults, and core calls still pass unlisted model ids through as text-only routes. On the official endpoint the API-key route follows the service's model listing while `models` holds those defaults ([listing rules](../llm-deepseek-api-key/README.md#use-this-package)). GUI selection requires a catalog entry; a saved selection can still submit requests after its catalog entry disappears. Clients, including model discovery tools, can read the advisory entries through `ctx.llm.listModels('deepseek-official')`. Image-capable entries may set `imagePixelBudget` to a positive integer or `low`, and may set `imageTargetBytes`. An entry may declare `systemPromptUpdate: in-history` when its endpoint reads the latest `system` message at any position of `messages` as the complete effective system prompt; the adapter reports the mode on the resolved model and the prepared call, and the agent loop then appends a changed prompt after the cached history instead of rewriting the leading system message ([decision rule](../../core/agent-loop/README.md#understand-the-implementation)). The default `deepseek-flash` entry declares this mode; other models require an explicit `models` declaration, and any value other than `in-history` fails at load with `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present`. | Field | Default | Meaning | |---|---|---| @@ -98,7 +98,7 @@ Provider plugins supply credentials through two adapter hooks. `resolveAuth(conn ### Streaming with thinking and images -An image-capable route chooses each durable reference's request target and resolves it into a deterministic request version. Omitting `imagePixelBudget` sizes the target on the published vision token grid of 14px patches, 3:1 downsampling, and at most 1024 tokens per image, so a square image keeps up to 1302×1302 pixels and a 16:9 image is sent as 1708×961 for the provider's 1708×966 grid; a positive integer replaces the grid with a total-pixel budget, and `low` uses 512×512 total pixels. Every request image is capped at 4096 pixels per side, the provider limit for requests carrying 15 or more images, and `imageMaxBytes` defaults to 2 MiB. Alpha images use WebP effort 0 and opaque images use JPEG on the 85/75/60 quality ladder, keeping the smallest output when every candidate exceeds the target. Every retained image is preceded by text naming its complete attachment id and actual request dimensions. When the current filesystem maps the attachment provider's host object, that text also carries a read-only execution-world path and the extension for a writable copy. Text-only and unlisted routes receive stable attachment placeholders while durable history keeps the image references. +An image-capable route chooses each durable reference's request target and resolves it into a deterministic request version. Omitting `imagePixelBudget` sizes the target on the published vision token grid of 14px patches, 3:1 downsampling, and at most 1024 tokens per image, so a square image keeps up to 1302×1302 pixels and a 16:9 image is sent as 1708×961 for the provider's 1708×966 grid; a positive integer replaces the grid with a total-pixel budget, and `low` uses 512×512 total pixels. Every request image is capped at 4096 pixels per side, the provider limit for requests carrying 15 or more images, and `imageTargetBytes` defaults to 2 MiB. Alpha images use WebP effort 0 and opaque images use JPEG on the 85/75/60 quality ladder, keeping the smallest output when every candidate exceeds the target. Every retained image is preceded by text naming its complete attachment id and actual request dimensions. When the current filesystem maps the attachment provider's host object, that text also carries a read-only execution-world path and the extension for a writable copy. Text-only and unlisted routes receive stable attachment placeholders while durable history keeps the image references. Request images have a fixed 32 MiB hard byte limit; only an output above that limit triggers further resizing. The configurable 2 MiB `imageTargetBytes` remains a soft target. Request descriptors and screenshot coordinates use the actual encoded dimensions; synchronous token estimates use the pre-encoding target. The adapter normally uploads those exact request bytes through `/v1/files` and sends file-id references. Files requests and model requests containing file ids include `anthropic-beta: files-api-2025-04-14`. All requests reject redirects so credentials remain on the configured origin. A failed or timed-out file resolution rebuilds the whole model request with inline base64 under the inline budget; one request never mixes file ids and inline images. Caller cancellation stops the request. diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 64c4ff8bcc..c45213e0c4 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -50,7 +50,7 @@ kind: "package-reference" filesApiTimeoutMs: 20000 ``` -请求用 `provider: deepseek-official` 选择路由;模型 id 原样传到协议,因此新增 DeepSeek 模型无需重新注册。省略 `models` 时公布支持文本和图像的 `deepseek-flash`,以及仅支持文本的 `deepseek-v4-pro`,各自的上下文窗口均为官方模型列表声明的 1,048,576 token。显式列表会替换这些默认值,核心调用中未列出的模型 id 仍作为纯文本路由原样通过。在官方端点上,当 `models` 保持这些默认值时,API key 路由改为使用服务端的模型列表([列表规则](../llm-deepseek-api-key/README.zh.md#use-this-package))。GUI 选择要求模型具有目录条目;条目消失后,已保存的选择仍可提交请求。包括模型发现工具在内的客户端可通过 `ctx.llm.listModels('deepseek-official')` 读取这些建议性条目。支持图片的条目可把 `imagePixelBudget` 设置为正整数或 `low`,也可以设置 `imageMaxBytes`。当端点把 `messages` 中任意位置最新的 `system` 消息读作完整的有效系统提示词时,条目可以声明 `systemPromptUpdate: in-history`;适配器会在已解析模型与已准备调用上报告该模式,agent loop(智能体循环)随后把变化后的提示词追加到已缓存历史之后,而不是改写开头的 system 消息([决策规则](../../core/agent-loop/README.zh.md#understand-the-implementation))。默认的 `deepseek-flash` 条目声明该模式;其他模型需通过 `models` 显式声明,`in-history` 以外的任何值都会在加载时以 `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present` 失败。 +请求用 `provider: deepseek-official` 选择路由;模型 id 原样传到协议,因此新增 DeepSeek 模型无需重新注册。省略 `models` 时公布支持文本和图像的 `deepseek-flash`,以及仅支持文本的 `deepseek-v4-pro`,各自的上下文窗口均为官方模型列表声明的 1,048,576 token。显式列表会替换这些默认值,核心调用中未列出的模型 id 仍作为纯文本路由原样通过。在官方端点上,当 `models` 保持这些默认值时,API key 路由改为使用服务端的模型列表([列表规则](../llm-deepseek-api-key/README.zh.md#use-this-package))。GUI 选择要求模型具有目录条目;条目消失后,已保存的选择仍可提交请求。包括模型发现工具在内的客户端可通过 `ctx.llm.listModels('deepseek-official')` 读取这些建议性条目。支持图片的条目可把 `imagePixelBudget` 设置为正整数或 `low`,也可以设置 `imageTargetBytes`。当端点把 `messages` 中任意位置最新的 `system` 消息读作完整的有效系统提示词时,条目可以声明 `systemPromptUpdate: in-history`;适配器会在已解析模型与已准备调用上报告该模式,agent loop(智能体循环)随后把变化后的提示词追加到已缓存历史之后,而不是改写开头的 system 消息([决策规则](../../core/agent-loop/README.zh.md#understand-the-implementation))。默认的 `deepseek-flash` 条目声明该模式;其他模型需通过 `models` 显式声明,`in-history` 以外的任何值都会在加载时以 `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present` 失败。 | 字段 | 默认值 | 含义 | |---|---|---| @@ -98,7 +98,7 @@ Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 B ### 带 thinking 与图片的流式调用 -支持图片的路由为每个持久引用选定请求目标,再把它解析为确定性请求版本。省略 `imagePixelBudget` 时按官方公布的视觉 token 网格定目标,即 14 px patch、3:1 降采样、单图最多 1024 token,因此正方形图片最多保留 1302×1302 像素,16:9 图片以 1708×961 发送、对应提供方 1708×966 的网格;正整数会用总像素预算取代网格,`low` 使用总计 512×512 像素。每张请求图片单边最多 4096 像素,这是提供方对包含 15 张及以上图片的请求的限制;`imageMaxBytes` 默认为 2 MiB。带 alpha 的图片使用 effort 0 的 WebP,不透明图片使用 JPEG,并采用 85/75/60 质量阶梯;全部候选都超过目标时保留最小输出。每张保留图片前都有文本,注明完整附件 id 与实际请求尺寸。当前文件系统可以映射附件提供方的宿主对象时,该文本还携带只读执行世界路径与可写副本使用的扩展名。纯文本与未列出路由接收稳定附件占位符,而持久历史继续保留图片引用。 +支持图片的路由为每个持久引用选定请求目标,再把它解析为确定性请求版本。省略 `imagePixelBudget` 时按官方公布的视觉 token 网格定目标,即 14 px patch、3:1 降采样、单图最多 1024 token,因此正方形图片最多保留 1302×1302 像素,16:9 图片以 1708×961 发送、对应提供方 1708×966 的网格;正整数会用总像素预算取代网格,`low` 使用总计 512×512 像素。每张请求图片单边最多 4096 像素,这是提供方对包含 15 张及以上图片的请求的限制;`imageTargetBytes` 默认为 2 MiB。带 alpha 的图片使用 effort 0 的 WebP,不透明图片使用 JPEG,并采用 85/75/60 质量阶梯;全部候选都超过目标时保留最小输出。每张保留图片前都有文本,注明完整附件 id 与实际请求尺寸。当前文件系统可以映射附件提供方的宿主对象时,该文本还携带只读执行世界路径与可写副本使用的扩展名。纯文本与未列出路由接收稳定附件占位符,而持久历史继续保留图片引用。 请求图片还有固定的 32 MiB 硬字节上限,只有超过该上限才会继续缩小尺寸。可配置的 2 MiB `imageTargetBytes` 仍是软目标。请求描述和截图坐标使用实际编码尺寸,同步 token 估算使用编码前的目标尺寸。 适配器通常通过 `/v1/files` 上传这些确切请求字节,并发送 file-id 引用。Files 请求与包含 file id 的模型请求均携带 `anthropic-beta: files-api-2025-04-14`。全部请求拒绝重定向,确保凭据仅发送到配置的源。文件解析失败或超时会按内联预算,用内联 base64 重建整份模型请求;一次请求绝不混用 file id 与内联图片。调用方取消会停止请求。 diff --git a/packages/llm/llm-deepseek/src/config.ts b/packages/llm/llm-deepseek/src/config.ts index c88208a5ff..436477c437 100644 --- a/packages/llm/llm-deepseek/src/config.ts +++ b/packages/llm/llm-deepseek/src/config.ts @@ -10,8 +10,8 @@ import type { LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environm import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type { DeepSeekCatalogModel, DeepSeekConnectionOptions } from './types.ts' import { DEFAULT_MODELS } from './models.ts' -import { MAX_FILE_UPLOAD_CONCURRENCY, MAX_FILE_UPLOAD_RETRIES, DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS, DEFAULT_MAX_INLINE_REQUEST_IMAGE_BYTES, DEFAULT_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_INLINE_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM, DEFAULT_FILE_EXPIRY_SECONDS, DEFAULT_FILE_REFRESH_MARGIN_SECONDS, DEFAULT_FILE_QUOTA_CLEANUP_BATCH, DEFAULT_FILES_API_TIMEOUT_MS } from './defaults.ts' -import { DEFAULT_MAX_IMAGES_PER_REQUEST, DEFAULT_MAX_REQUEST_FILES_BYTES, DEFAULT_REQUEST_IMAGE_MAX_BYTES } from './request-pricing.ts' +import { MAX_IMAGE_BYTES, MAX_FILE_UPLOAD_CONCURRENCY, MAX_FILE_UPLOAD_RETRIES, DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS, DEFAULT_MAX_INLINE_REQUEST_IMAGE_BYTES, DEFAULT_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_INLINE_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM, DEFAULT_FILE_EXPIRY_SECONDS, DEFAULT_FILE_REFRESH_MARGIN_SECONDS, DEFAULT_FILE_QUOTA_CLEANUP_BATCH, DEFAULT_FILES_API_TIMEOUT_MS } from './defaults.ts' +import { DEFAULT_MAX_IMAGES_PER_REQUEST, DEFAULT_MAX_REQUEST_FILES_BYTES, DEFAULT_REQUEST_IMAGE_TARGET_BYTES } from './request-pricing.ts' const MODEL_MODALITIES = ['text', 'image'] as const satisfies readonly ModelModality[] @@ -83,7 +83,7 @@ export const catalogModelFields = { contextWindow: z.number().step(1).min(1), maxTokens: z.number().step(1).min(1), imagePixelBudget: z.union([z.number().step(1).min(1), 'low']), - imageMaxBytes: z.number().step(1).min(1), + imageTargetBytes: z.number().step(1).min(1).max(MAX_IMAGE_BYTES), systemPromptUpdate: z.const('in-history'), toolUpdate: z.union(['in-history', 'addition-only'] as const), } @@ -176,7 +176,10 @@ function resolveModels(models: readonly DeepSeekCatalogModel[] | undefined): Dee throw new Error(`llm-deepseek: catalog model "${model.id}" inputModalities must not contain duplicates`) } const hasImage = inputModalities.includes('image') - if (!hasImage && (model.imagePixelBudget !== undefined || model.imageMaxBytes !== undefined)) { + if ('imageMaxBytes' in model) { + throw new Error('llm-deepseek: replace model imageMaxBytes with imageTargetBytes for the encoded-byte target') + } + if (!hasImage && (model.imagePixelBudget !== undefined || model.imageTargetBytes !== undefined)) { throw new Error(`llm-deepseek: text-only catalog model "${model.id}" cannot declare image request limits`) } if (model.imagePixelBudget !== undefined @@ -184,9 +187,9 @@ function resolveModels(models: readonly DeepSeekCatalogModel[] | undefined): Dee && (!Number.isSafeInteger(model.imagePixelBudget) || model.imagePixelBudget <= 0)) { throw new Error(`llm-deepseek: catalog model "${model.id}" imagePixelBudget must be "low" or a positive safe integer`) } - if (model.imageMaxBytes !== undefined - && (!Number.isSafeInteger(model.imageMaxBytes) || model.imageMaxBytes <= 0)) { - throw new Error(`llm-deepseek: catalog model "${model.id}" imageMaxBytes must be a positive safe integer`) + if (model.imageTargetBytes !== undefined + && (!Number.isSafeInteger(model.imageTargetBytes) || model.imageTargetBytes <= 0 || model.imageTargetBytes > MAX_IMAGE_BYTES)) { + throw new Error(`llm-deepseek: catalog model "${model.id}" imageTargetBytes must be a positive safe integer no greater than 32 MiB`) } // Widened: a dynamic config update reaches this check without schema validation. const systemPromptUpdate: string | undefined = model.systemPromptUpdate @@ -211,7 +214,7 @@ function resolveModels(models: readonly DeepSeekCatalogModel[] | undefined): Dee ...hasImage ? { ...model.imagePixelBudget === undefined ? {} : { imagePixelBudget: model.imagePixelBudget }, - imageMaxBytes: model.imageMaxBytes ?? DEFAULT_REQUEST_IMAGE_MAX_BYTES, + imageTargetBytes: model.imageTargetBytes ?? DEFAULT_REQUEST_IMAGE_TARGET_BYTES, } : {}, } diff --git a/packages/llm/llm-deepseek/src/defaults.ts b/packages/llm/llm-deepseek/src/defaults.ts index ad18472b62..731467d052 100644 --- a/packages/llm/llm-deepseek/src/defaults.ts +++ b/packages/llm/llm-deepseek/src/defaults.ts @@ -1,5 +1,7 @@ /** Shared provider limits and Chat Files API defaults. */ +/** Provider hard encoded-byte limit for one request image. */ +export const MAX_IMAGE_BYTES = 32 * 1024 * 1024 /** Default maximum idle interval while an adapter stream read is outstanding. */ export const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 300_000 /** Default combined request/response context capacity. */ diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index 4a3ee7830d..1e98238bc0 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -11,8 +11,8 @@ import { deepSeekFileScope, DeepSeekUploadIndex } from './upload-index.ts' import { serializeAuthHeaders } from './auth-headers.ts' import type { DeepSeekUploadRecord } from './upload-index.ts' -/** Shared Files-store limit for each request image, including file-id references. */ -export const MAX_IMAGE_BYTES = 32 * 1024 * 1024 +import { MAX_IMAGE_BYTES } from './defaults.ts' +export { MAX_IMAGE_BYTES } from './defaults.ts' const OWNED_FILE_PREFIX = 'dsh-' /** Per-image deadline whose expiry during upload starts Files backoff. */ export const FILES_API_TIMEOUT = 'DEEPSEEK_FILES_API_TIMEOUT' diff --git a/packages/llm/llm-deepseek/src/index.ts b/packages/llm/llm-deepseek/src/index.ts index 1c7ab36255..95b148b0f0 100644 --- a/packages/llm/llm-deepseek/src/index.ts +++ b/packages/llm/llm-deepseek/src/index.ts @@ -20,10 +20,10 @@ export { DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET, DEFAULT_MAX_IMAGES_PER_REQUEST, DEFAULT_MAX_REQUEST_FILES_BYTES, - DEFAULT_REQUEST_IMAGE_MAX_BYTES, + DEFAULT_REQUEST_IMAGE_TARGET_BYTES, REQUEST_IMAGE_MAX_DIMENSION, deepSeekImageRequestPricing, - resolveRequestImageMaxBytes, + resolveRequestImageTargetBytes, resolveRequestImageTarget, } from './request-pricing.ts' export { deepSeekImageTokens, deepSeekRequestImageDimensions } from './image-tokens.ts' diff --git a/packages/llm/llm-deepseek/src/listed-catalog.ts b/packages/llm/llm-deepseek/src/listed-catalog.ts index 5dbe68d91f..89c16ab2df 100644 --- a/packages/llm/llm-deepseek/src/listed-catalog.ts +++ b/packages/llm/llm-deepseek/src/listed-catalog.ts @@ -50,7 +50,7 @@ function layered(model: DeepSeekCatalogModel, layer: ModelOverride): DeepSeekCat const merged: DeepSeekCatalogModel = { ...model, ...layer } if (merged.inputModalities?.includes('image') !== true) { if (layer.imagePixelBudget === undefined) delete merged.imagePixelBudget - if (layer.imageMaxBytes === undefined) delete merged.imageMaxBytes + if (layer.imageTargetBytes === undefined) delete merged.imageTargetBytes } return merged } diff --git a/packages/llm/llm-deepseek/src/request-pricing.ts b/packages/llm/llm-deepseek/src/request-pricing.ts index df7416b369..8854a40470 100644 --- a/packages/llm/llm-deepseek/src/request-pricing.ts +++ b/packages/llm/llm-deepseek/src/request-pricing.ts @@ -9,6 +9,7 @@ * @module dsh-llm-deepseek/request-pricing */ +import { MAX_IMAGE_BYTES } from './defaults.ts' import { offloadedImageText, requestImageHandleText, textOnlyImageText } from '@deepseek-ai/dsh-llm' import type { ImageAttachmentAccessResolver, ImageBlock, LlmImageRequestPrice, LlmImageRequestPricing } from '@deepseek-ai/dsh-llm' import { longEdgeDimensions, requestImageDimensions } from '@deepseek-ai/dsh-attachment' @@ -23,7 +24,7 @@ export const DEFAULT_MAX_IMAGES_PER_REQUEST = 600 /** Total-pixel budget matching provider low-detail image input. */ export const DEFAULT_LOW_DETAIL_IMAGE_PIXEL_BUDGET = 512 * 512 /** Encoded-byte target for one deterministic model-request image; the smallest quality-ladder output is used when no quality fits. */ -export const DEFAULT_REQUEST_IMAGE_MAX_BYTES = 2 * 1024 * 1024 +export const DEFAULT_REQUEST_IMAGE_TARGET_BYTES = 2 * 1024 * 1024 /** * Provider per-side limit for a request carrying 15 or more images, applied * to every request image so the image count never changes a projection. @@ -36,8 +37,8 @@ export const REQUEST_IMAGE_MAX_DIMENSION = 4096 * @returns the route's encoded-byte target. * @internal */ -export function resolveRequestImageMaxBytes(model: DeepSeekCatalogModel): number { - return model.imageMaxBytes ?? DEFAULT_REQUEST_IMAGE_MAX_BYTES +export function resolveRequestImageTargetBytes(model: DeepSeekCatalogModel): number { + return model.imageTargetBytes ?? DEFAULT_REQUEST_IMAGE_TARGET_BYTES } /** @@ -61,7 +62,7 @@ export function resolveRequestImageTarget( const capped = Math.max(projected.width, projected.height) > REQUEST_IMAGE_MAX_DIMENSION ? longEdgeDimensions(source.width, source.height, REQUEST_IMAGE_MAX_DIMENSION) : projected - return { ...capped, maxBytes: resolveRequestImageMaxBytes(model) } + return { ...capped, maxImageBytes: MAX_IMAGE_BYTES, imageTargetBytes: resolveRequestImageTargetBytes(model) } } /** diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index 0efced1afe..5dd4fdc3ef 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -29,7 +29,7 @@ export interface DeepSeekCatalogModel { */ imagePixelBudget?: number | 'low' /** Encoded-byte target for one deterministic request preview; the smallest quality-ladder output is used when no quality fits. */ - imageMaxBytes?: number + imageTargetBytes?: number /** * `'in-history'` declares that the endpoint reads the latest `system` * message at any position of the conversation as the complete effective diff --git a/packages/llm/llm-deepseek/tests/listed-catalog.spec.ts b/packages/llm/llm-deepseek/tests/listed-catalog.spec.ts index ec51880cb9..6f8b035999 100644 --- a/packages/llm/llm-deepseek/tests/listed-catalog.spec.ts +++ b/packages/llm/llm-deepseek/tests/listed-catalog.spec.ts @@ -4,7 +4,7 @@ import { resolveAdapterOptions } from '../src/config.ts' import { resolveListedCatalog } from '../src/listed-catalog.ts' import type { ModelOverride } from '../src/listed-catalog.ts' import { parseModelListing } from '../src/listing.ts' -import { DEFAULT_REQUEST_IMAGE_MAX_BYTES } from '../src/request-pricing.ts' +import { DEFAULT_REQUEST_IMAGE_TARGET_BYTES } from '../src/request-pricing.ts' const FLASH = { id: 'deepseek-flash', name: 'DeepSeek-V4.1-Flash', context_window: 1_048_576, max_output_tokens: 393_216, @@ -51,7 +51,7 @@ describe('with a listing', () => { expect(catalog.offered[1]).toEqual({ id: 'deepseek-flash', name: 'DeepSeek-V4.1-Flash', contextWindow: 1_048_576, maxTokens: 256_000, inputModalities: ['text', 'image'], systemPromptUpdate: 'in-history', toolUpdate: 'addition-only', - imageMaxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES, + imageTargetBytes: DEFAULT_REQUEST_IMAGE_TARGET_BYTES, }) expect(catalog.offered[0]).not.toHaveProperty('systemPromptUpdate') expect(catalog.offered[0]?.description).toContain('agentic coding') @@ -102,7 +102,7 @@ describe('with a listing', () => { it('drops inherited image limits from a model the listing makes text-only', () => { const [flash] = resolve([{ ...FLASH, input_modalities: ['text'] }]).offered expect(flash).toMatchObject({ inputModalities: ['text'] }) - expect(flash).not.toHaveProperty('imageMaxBytes') + expect(flash).not.toHaveProperty('imageTargetBytes') }) it.each([ @@ -128,7 +128,7 @@ describe('with a listing', () => { it('serves a vouched unknown model with listed metadata only', () => { const [model] = resolve([{ ...FLASH, id: 'deepseek-v5', ...requires('0.1.0') }]).offered expect(model).not.toHaveProperty('toolUpdate') - expect(model).toMatchObject({ id: 'deepseek-v5', contextWindow: 1_048_576, imageMaxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES }) + expect(model).toMatchObject({ id: 'deepseek-v5', contextWindow: 1_048_576, imageTargetBytes: DEFAULT_REQUEST_IMAGE_TARGET_BYTES }) }) it('reports unreadable requirements and unusable declarations, but not unknown models', () => { @@ -166,14 +166,16 @@ describe('with a listing', () => { const catalog = resolve([FLASH, { ...PRO, id: 'deepseek-v5', ...requires('0.1.0') }], { 'deepseek-flash': { inputModalities: ['text'] }, 'deepseek-v5': { contextWindow: 9 }, }) - expect(catalog.offered[0]).not.toHaveProperty('imageMaxBytes') + expect(catalog.offered[0]).not.toHaveProperty('imageTargetBytes') expect(catalog.offered[1]?.contextWindow).toBe(9) expect(catalog.overrideErrors).toEqual([]) }) - it.each([{ imagePixelBudget: 'low' as const }, { imageMaxBytes: 1 }])('reports an override %j that does not apply and a stale override id', (limits) => { + it.each([{ imagePixelBudget: 'low' as const }, { + imageTargetBytes: 1, + }])('reports an override %j that does not apply and a stale override id', (limits) => { const catalog = resolve([PRO], { 'deepseek-v4-pro': limits, 'retired': { contextWindow: 1 } }) - expect(catalog.offered[0]).not.toHaveProperty('imageMaxBytes') + expect(catalog.offered[0]).not.toHaveProperty('imageTargetBytes') expect(catalog.overrideErrors).toEqual([ expect.stringMatching(/^modelOverrides\.deepseek-v4-pro does not apply \(.*cannot declare image request limits/), 'modelOverrides names "retired", which neither the model listing nor the built-in catalog describes', diff --git a/packages/llm/llm-deepseek/tests/request-pricing.spec.ts b/packages/llm/llm-deepseek/tests/request-pricing.spec.ts index 4a28593520..f56fa456de 100644 --- a/packages/llm/llm-deepseek/tests/request-pricing.spec.ts +++ b/packages/llm/llm-deepseek/tests/request-pricing.spec.ts @@ -138,9 +138,11 @@ describe('DeepSeek request-image pricing', () => { }) it('exposes the same image dimensions and byte budget used by DeepSeek request preparation', () => { - const model = { ...VISION_MODEL, imagePixelBudget: 10_000, imageMaxBytes: 50_000 } + const model = { ...VISION_MODEL, imagePixelBudget: 10_000, imageTargetBytes: 50_000 } const source = ref('screenshot', 1000, 1000, 60_000) const provider = adapter({ models: [model] }) - expect(provider.imageRequestTarget('deepseek', 'vision', source)).toEqual({ width: 100, height: 100, maxBytes: 50_000 }) + expect(provider.imageRequestTarget('deepseek', 'vision', source)).toEqual({ + width: 100, height: 100, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 50_000, + }) expect(() => provider.imageRequestTarget('deepseek', 'missing', source)).toThrow('no declared image projection') }) diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index 61890886bf..e7a93f2a1d 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -175,15 +175,15 @@ describe('request image target', () => { it.each([ [ { id: 'default' }, - { width: 1302, height: 1302, maxBytes: 2 * 1024 * 1024 }, + { width: 1302, height: 1302, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 2 * 1024 * 1024 }, ], [ { id: 'low', imagePixelBudget: 'low' as const }, - { width: 512, height: 512, maxBytes: 2 * 1024 * 1024 }, + { width: 512, height: 512, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 2 * 1024 * 1024 }, ], [ - { id: 'custom', imagePixelBudget: 320_000, imageMaxBytes: 512_000 }, - { width: 565, height: 565, maxBytes: 512_000 }, + { id: 'custom', imagePixelBudget: 320_000, imageTargetBytes: 512_000 }, + { width: 565, height: 565, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 512_000 }, ], ])('resolves route-owned defaults and overrides for %s on a 4096x4096 source', (model, expected) => { expect(resolveRequestImageTarget(model, { width: 4096, height: 4096 })).toEqual(expected) @@ -191,9 +191,9 @@ describe('request image target', () => { it('caps every request image at the provider per-side limit', () => { expect(resolveRequestImageTarget({ id: 'default' }, { width: 8192, height: 78 })) - .toEqual({ width: 4096, height: 39, maxBytes: 2 * 1024 * 1024 }) + .toEqual({ width: 4096, height: 39, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 2 * 1024 * 1024 }) expect(resolveRequestImageTarget({ id: 'custom', imagePixelBudget: 640_000 }, { width: 10_000, height: 100 })) - .toEqual({ width: 4096, height: 41, maxBytes: 2 * 1024 * 1024 }) + .toEqual({ width: 4096, height: 41, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 2 * 1024 * 1024 }) }) it('answers image request pricing from the current connection snapshot', () => { @@ -449,7 +449,7 @@ describe('DeepSeekAdapter against a mock server', () => { bytes: 3, }]) expect(signalSeen[0]).toBeInstanceOf(AbortSignal) - expect(policies).toEqual([{ width: 1, height: 1, maxBytes: 2 * 1024 * 1024 }]) + expect(policies).toEqual([{ width: 1, height: 1, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 2 * 1024 * 1024 }]) }) it('rejects unknown plugin content without preparing nested images', async () => { @@ -707,7 +707,7 @@ describe('DeepSeekAdapter against a mock server', () => { expect(attachmentMocks.readImageRequest).toHaveBeenCalledWith( recent, - { width: 1, height: 1, maxBytes: 2 * 1024 * 1024 }, + { width: 1, height: 1, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 2 * 1024 * 1024 }, expect.any(AbortSignal), ) const body = server.requests[0] as { messages: unknown[] } @@ -734,7 +734,7 @@ describe('DeepSeekAdapter against a mock server', () => { id: 'vision-low', inputModalities: ['text', 'image'], imagePixelBudget: 'low', - imageMaxBytes: 512_000, + imageTargetBytes: 512_000, }, { id: 'vision-custom', @@ -759,13 +759,13 @@ describe('DeepSeekAdapter against a mock server', () => { expect(attachmentMocks.readImageRequest).toHaveBeenNthCalledWith( 1, imageRef, - { width: 1, height: 1, maxBytes: 512_000 }, + { width: 1, height: 1, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 512_000 }, expect.any(AbortSignal), ) expect(attachmentMocks.readImageRequest).toHaveBeenNthCalledWith( 2, imageRef, - { width: 1, height: 1, maxBytes: 2 * 1024 * 1024 }, + { width: 1, height: 1, maxImageBytes: 32 * 1024 * 1024, imageTargetBytes: 2 * 1024 * 1024 }, expect.any(AbortSignal), ) }) @@ -2118,8 +2118,9 @@ describe('plugin registration and config', () => { ['imagePixelBudget', 0, /imagePixelBudget must be "low" or a positive safe integer/], ['imagePixelBudget', Number.MAX_SAFE_INTEGER + 1, /imagePixelBudget must be "low" or a positive safe integer/], ['imagePixelBudget', 'auto', /imagePixelBudget must be "low" or a positive safe integer/], - ['imageMaxBytes', 0, /imageMaxBytes must be a positive safe integer/], - ['imageMaxBytes', 1.5, /imageMaxBytes must be a positive safe integer/], + ['imageTargetBytes', 0, /imageTargetBytes must be a positive safe integer/], + ['imageTargetBytes', 32 * 1024 * 1024 + 1, /imageTargetBytes must be a positive safe integer/], + ['imageTargetBytes', 1.5, /imageTargetBytes must be a positive safe integer/], ] as const)('rejects per-model %s=%s', (field, value, message) => { expect(() => resolveAdapterOptions({ models: [{ id: 'vision', inputModalities: ['image'], [field]: value }], @@ -2442,3 +2443,10 @@ describe('plugin registration and config', () => { expect(ctx.llm.listProviders()).toEqual([]) }) }) + + +it('rejects the retired imageMaxBytes model setting instead of ignoring its soft target', () => { + expect(() => resolveAdapterOptions({ models: [{ + id: 'vision', inputModalities: ['text', 'image'], ...{ imageMaxBytes: 1024 }, + }] })).toThrow(/replace model imageMaxBytes with imageTargetBytes/) +}) diff --git a/packages/llm/llm-pi-ai/README.i18n.yaml b/packages/llm/llm-pi-ai/README.i18n.yaml index f357c55522..531a450326 100644 --- a/packages/llm/llm-pi-ai/README.i18n.yaml +++ b/packages/llm/llm-pi-ai/README.i18n.yaml @@ -21,8 +21,8 @@ en: f3b761c7c7ecb82f zh: e10d999aa348ef86 /deepseek-ai-dsh-llm-pi-ai/use-this-package/configure-provider-routes: - en: 9e30fcea0804ba7f - zh: d6db5d4e7e2c4cfc + en: 90a1571e9de28c7d + zh: 8a2d445ed31f1bd7 /deepseek-ai-dsh-llm-pi-ai/use-this-package/sign-in-to-a-provider: en: c36f66438638ae08 zh: 066a2fc4cb97c86f @@ -72,14 +72,14 @@ en: e7348db3f7115960 zh: 5fd5fb09d7d09982 /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/what-the-model-sees: - en: f553e097cdbb3b3d - zh: 33b579f312aad4fa + en: f1f9af4800b6aaa6 + zh: 3745881f1a9c18a7 /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/token-effect: en: 820221e8ae37aa61 zh: 7e6ff4db10067fc0 /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-request-through-pi-ai/kv-cache-effect: - en: 79acfd5cccec0fc5 - zh: d09370981bffc6a1 + en: c0fd11162e393727 + zh: c4ebcdf7049ae677 /deepseek-ai-dsh-llm-pi-ai/model-experience/provider-response: en: 802d7ff60a1d03ff zh: c41c56e28f3e8680 diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index 9523627617..0bd53c91d1 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -47,7 +47,8 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie reasoning: high requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default requestImageMaxDimension: 3000 # override catalog width and height limits - requestImageMaxBytes: 1048576 # override raw bytes before base64 expansion + maxImageBytes: 1048576 # hard per-image cap before allocation + requestImageBudgetCount: 20 # fixed number of equal budget shares maxRequestImageBytes: 20971520 # accumulated base64 payload maxRequestImages: 50 # retained image occurrences imageOffloadCountQuantum: 10 # oldest images offloaded per count overflow @@ -88,15 +89,16 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie | `defaultMaxTokens` | `128,000` | Output-cap fallback for undescribed models | | `requestImagePixelBudget` | `4,194,304` | Total-pixel budget for each deterministic request image | | `requestImageMaxDimension` | catalog width/height limits | Maximum width and height for each request image; an explicit value overrides both catalog limits | -| `requestImageMaxBytes` | catalog base64 budget converted to raw bytes; otherwise `1 MiB` | Encoded-byte target before base64 expansion; an explicit value overrides the catalog budget | +| `maxImageBytes` | catalog base64 cap converted to raw bytes; otherwise `1 MiB` | Hard per-image cap before allocation; an explicit value overrides the catalog cap | +| `requestImageBudgetCount` | `20` | Fixed divisor of the aggregate image budget; independent of retained image count | | `maxRequestImageBytes` | `20 MiB` | Aggregate base64 image-payload bound; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED` | | `maxRequestImages` | `50` | Retained request-image count bound; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED`. The default follows Azure OpenAI's 50-image limit; raise it on routes whose provider accepts more images | | `imageOffloadCountQuantum` | `10`, capped at `maxRequestImages` | Oldest images offloaded per count overflow | | `retryPolicy` | normal, 5 retries | Provider-owned retry policy executed by `dsh-llm-retry` | -Request images inherit `inputLimits.images.resize.maxWidth`, `maxHeight`, and `maxBytes` from the selected pi-ai catalog model. The catalog byte budget counts base64 payload, so its raw target is `3 × floor(maxBytes / 4)`. Route overrides take precedence, including on custom gateways. Missing catalog dimensions leave that axis uncapped by the route; missing bytes retain the 1 MiB target. Total pixels remain governed by `requestImagePixelBudget`. These limits apply to retained history images on every request and to screenshot coordinate targets; stored attachments are unchanged. The encoding quality ladder can still exceed the byte target when no quality fits. Request counts, aggregate payload bounds, and encoding quality remain governed by DSH's existing policies. +Request images inherit the selected pi-ai model's `inputLimits.images.resize` width, height, and base64-byte cap. `requestImageMaxDimension` overrides both dimensions with one value; it cannot express unequal width and height overrides. `maxImageBytes` overrides the per-image cap in raw encoded bytes. The effective hard limit is `min(3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount)), maxImageBytes or catalog cap or 1 MiB)`, with the catalog cap converted using `3 × floor(catalogBytes / 4)`. Configuration must allow at least four aggregate base64 bytes per budget share. Defaults allocate 0.75 MiB per image, so 20 images at that limit use at most 20 MiB of base64 payload. Budget shares stay fixed as history grows; `maxRequestImages` separately controls retained occurrences. Missing catalog dimensions leave that axis uncapped, while total pixels remain governed by `requestImagePixelBudget`. -Lower `requestImageMaxBytes` to ask the encoder for smaller outputs, or raise `maxRequestImageBytes` only when the gateway has room for the larger payload plus other request content. +pi exposes no separate soft-byte target: the shared encoder's `imageTargetBytes` equals its effective `maxImageBytes`. After the quality ladder, images that still exceed the limit are resized and re-encoded until they fit; an impossible limit fails explicitly. Stored attachments stay unchanged. Image descriptors and screenshot coordinates use the final encoded dimensions. Increase `requestImageBudgetCount` for smaller per-image allocations, or decrease it for larger ones; the aggregate cap still applies to actual payloads. The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-llm-pi-ai) is the exhaustive source for every accepted field and its JSDoc. @@ -229,7 +231,7 @@ Read these pages when the package-level contract is not enough. They move from t #### What the model sees -The selected catalog model receives system-message text, conversation history, tools, and supported sampling fields. The adapter preserves later system messages in history order when the catalog model declares `supportsMidConvoSystemMessages`. Otherwise, it converts each non-empty later system message to a user message wrapped in `` before passing it to pi-ai. The wrapper does not grant system-role priority. One-shot `GenerateOptions.system` precedes the initial history prompt. Repeated system messages remain repeated; empty system messages are skipped without discarding earlier text. Tool-update capabilities select the shared historical declaration projection; pi-ai receives initially active tools and grouped developer updates carrying additions and supported removals. When every projected declaration of an Anthropic request with tool updates is deferred, the initially active tools are one placeholder, `DeferredToolPlaceholder`, whose description tells the model never to call it; a call reaches the ordinary unknown-tool result. Anthropic receives later tool definitions inline in the update message. Replay preserves tool-call namespaces for dynamically loaded Responses tools. Each retained image is preceded by text naming its complete attachment id and actual request dimensions. When the current execution filesystem maps the attachment provider's host object, the text also carries a read-only normalized-object path and warns that normalization or request projection may have resized or re-encoded the upload. Each occurrence selected by a logged image-offload decision keeps its own identity and currently resolved access in replacement text, and its normalized attachment is not read or transformed. When the retained occurrences still exceed the route's `maxRequestImages`, or their exact base64 payload exceeds its `maxRequestImageBytes`, the call fails with `IMAGE_OFFLOAD_REQUIRED` so `dsh-compaction-image-offload` records the selected occurrences in an `image/offload` event and retries the step. The default 20 MiB aggregate budget holds four images of 4.5 MiB actual base64 payload each (18 MiB), while a fifth exceeds it (22.5 MiB). Smaller encodings can retain more images, subject to the count limit. Provider-native replay metadata is restored only when the adapter validates it for the historical content. On Anthropic Messages routes, a replayed response whose request prefix changed since generation, for example through compaction, loses its thinking blocks; its text and tool calls remain. `imageRequestTarget(provider, model, image)` exposes the same request-image dimensions and byte target to screenshot consumers; adapters without image resizing preserve the normalized source. +The selected catalog model receives system-message text, conversation history, tools, and supported sampling fields. The adapter preserves later system messages in history order when the catalog model declares `supportsMidConvoSystemMessages`. Otherwise, it converts each non-empty later system message to a user message wrapped in `` before passing it to pi-ai. The wrapper does not grant system-role priority. One-shot `GenerateOptions.system` precedes the initial history prompt. Repeated system messages remain repeated; empty system messages are skipped without discarding earlier text. Tool-update capabilities select the shared historical declaration projection; pi-ai receives initially active tools and grouped developer updates carrying additions and supported removals. When every projected declaration of an Anthropic request with tool updates is deferred, the initially active tools are one placeholder, `DeferredToolPlaceholder`, whose description tells the model never to call it; a call reaches the ordinary unknown-tool result. Anthropic receives later tool definitions inline in the update message. Replay preserves tool-call namespaces for dynamically loaded Responses tools. Each retained image is preceded by text naming its complete attachment id and actual request dimensions. When the current execution filesystem maps the attachment provider's host object, the text also carries a read-only normalized-object path and warns that normalization or request projection may have resized or re-encoded the upload. Each occurrence selected by a logged image-offload decision keeps its own identity and currently resolved access in replacement text, and its normalized attachment is not read or transformed. When the retained occurrences still exceed the route's `maxRequestImages`, or their exact base64 payload exceeds its `maxRequestImageBytes`, the call fails with `IMAGE_OFFLOAD_REQUIRED` so `dsh-compaction-image-offload` records the selected occurrences in an `image/offload` event and retries the step. The default allocation limits each encoded image to 0.75 MiB, allowing 20 such images within the 20 MiB aggregate base64 budget. Smaller images can retain more occurrences, subject to the count limit. Provider-native replay metadata is restored only when the adapter validates it for the historical content. On Anthropic Messages routes, a replayed response whose request prefix changed since generation, for example through compaction, loses its thinking blocks; its text and tool calls remain. `imageRequestTarget(provider, model, image)` exposes the maximum dimensions and byte limits to screenshot consumers; `readImageRequest` returns the actual encoded dimensions after enforcing the byte limit. #### Token effect @@ -237,7 +239,7 @@ Provider tokenization governs exact input. Retained images add the stable attach #### KV Cache effect -Later system messages supplied to the adapter stay out of the initial prompt, preserving the preceding request prefix. This does not change the agent loop’s prompt admission, which consolidates updates on routes without native system-update support. Conversion preserves logical request order, while image handles and offload placeholders add model-visible text. A changed execution-world path rewrites a historical handle and can prevent reuse from that image even when attachment identity and request bytes stay stable. Changing adapter instance, provider, model, or another upstream token has the same suffix effect. Omitting stale Anthropic thinking follows a prefix change that already ended reuse at the changed message. The first request that omits thinking recorded without a digest ends reuse at the first such message once. An offload decision turns an earlier image into placeholder text, so reuse ends at that message; the omission never reverts, so the prefix stays stable until the next decision. Larger per-image byte targets can reach the unchanged aggregate budget sooner and cause earlier offloading. A count overflow offloads `imageOffloadCountQuantum` images at once, so a saturated route ends reuse at the oldest retained image once per that many new images. +Later system messages supplied to the adapter stay out of the initial prompt, preserving the preceding request prefix. This does not change the agent loop’s prompt admission, which consolidates updates on routes without native system-update support. Conversion preserves logical request order, while image handles and offload placeholders add model-visible text. A changed execution-world path rewrites a historical handle and can prevent reuse from that image even when attachment identity and request bytes stay stable. Changing adapter instance, provider, model, or another upstream token has the same suffix effect. Omitting stale Anthropic thinking follows a prefix change that already ended reuse at the changed message. The first request that omits thinking recorded without a digest ends reuse at the first such message once. An offload decision turns an earlier image into placeholder text, so reuse ends at that message; the omission never reverts, so the prefix stays stable until the next decision. Changing configured byte budgets can resize historical request images and end prefix reuse; merely adding an image does not change the per-image allocation. A count overflow offloads `imageOffloadCountQuantum` images at once, so a saturated route ends reuse at the oldest retained image once per that many new images. ### Provider response diff --git a/packages/llm/llm-pi-ai/README.zh.md b/packages/llm/llm-pi-ai/README.zh.md index 1024d419ba..49e519a0b7 100644 --- a/packages/llm/llm-pi-ai/README.zh.md +++ b/packages/llm/llm-pi-ai/README.zh.md @@ -47,7 +47,8 @@ kind: "package-reference" reasoning: high requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default requestImageMaxDimension: 3000 # override catalog width and height limits - requestImageMaxBytes: 1048576 # override raw bytes before base64 expansion + maxImageBytes: 1048576 # hard per-image cap before allocation + requestImageBudgetCount: 20 # fixed number of equal budget shares maxRequestImageBytes: 20971520 # accumulated base64 payload maxRequestImages: 50 # retained image occurrences imageOffloadCountQuantum: 10 # oldest images offloaded per count overflow @@ -88,15 +89,16 @@ kind: "package-reference" | `defaultMaxTokens` | `128,000` | 未描述模型的输出上限回退 | | `requestImagePixelBudget` | `4,194,304` | 每张确定性请求图片的总像素预算 | | `requestImageMaxDimension` | 目录中的宽高限制 | 每张请求图片的最大宽度和高度;显式配置会覆盖目录中的两个限制 | -| `requestImageMaxBytes` | 目录的 base64 预算换算为原始字节;否则为 `1 MiB` | base64 扩展前的编码字节目标;显式配置会覆盖目录预算 | +| `maxImageBytes` | 目录的 base64 上限换算为原始字节;否则为 `1 MiB` | 分摊前的单图硬上限;显式配置会覆盖目录上限 | +| `requestImageBudgetCount` | `20` | 图片总预算的固定分摊张数,与当前保留图片数量无关 | | `maxRequestImageBytes` | `20 MiB` | base64 图片载荷总上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败 | | `maxRequestImages` | `50` | 保留请求图片数量上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败。默认值取 Azure OpenAI 的 50 张上限;提供方接受更多图片的路由应调高 | | `imageOffloadCountQuantum` | `10`,不超过 `maxRequestImages` | 每次数量超限时省略的最老图片数 | | `retryPolicy` | normal,5 次重试 | 由 `dsh-llm-retry` 执行的提供方自有重试策略 | -请求图片继承所选 pi-ai 目录模型的 `inputLimits.images.resize.maxWidth`、`maxHeight` 和 `maxBytes`。目录字节预算按 base64 载荷计算,因此原始字节目标为 `3 × floor(maxBytes / 4)`。路由显式配置优先,自定义网关也可使用。目录缺少某个尺寸时,路由不限制该轴;缺少字节预算时,保留 1 MiB 目标。总像素仍由 `requestImagePixelBudget` 控制。这些限制每次请求都会应用于保留的历史图片和截图坐标目标,已存附件保持不变。编码质量阶梯中没有结果满足字节目标时,结果仍可能超过目标。请求图片数量、总载荷限制和编码质量继续使用 DSH 的现有策略。 +请求图片继承所选 pi-ai 模型的 `inputLimits.images.resize` 宽度、高度和 base64 字节上限。`requestImageMaxDimension` 用同一个值覆盖宽高,不能分别配置不同的宽度和高度上限。`maxImageBytes` 按原始编码字节覆盖单图上限。最终硬上限为 `min(3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount)), maxImageBytes 或目录上限或 1 MiB)`,其中目录上限通过 `3 × floor(catalogBytes / 4)` 换算。总预算须为每份预算至少提供 4 个 base64 字节。默认每张图分得 0.75 MiB,20 张达到该上限的图片最多占用 20 MiB base64 载荷。历史增长不会改变分摊张数;`maxRequestImages` 单独控制保留图片数量。目录缺少某个尺寸时,路由不限制该轴,总像素仍由 `requestImagePixelBudget` 控制。 -可以调低 `requestImageMaxBytes`,让编码器尝试更小的输出;只有网关能容纳更大图片载荷及请求中的其他内容时,才调高 `maxRequestImageBytes`。 +pi 不暴露单独的软字节目标,共享编码器的 `imageTargetBytes` 等于最终 `maxImageBytes`。质量阶梯结束后仍超限的图片会继续缩小尺寸并重新编码,直到满足上限;无法满足的极小上限会明确报错。存储附件保持不变。图片描述和截图坐标使用最终编码尺寸。调大 `requestImageBudgetCount` 会减小每张图的分配额度,调小则增加额度;总预算仍按实际载荷执行。 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-llm-pi-ai)是每个受支持字段及其 JSDoc 的穷尽式真源。 @@ -229,7 +231,7 @@ Anthropic 可以将每个已签名 thinking 块绑定到生成它时的请求前 #### 模型看到什么 -所选目录模型会收到系统消息文本、对话历史、工具以及支持的采样字段。目录模型声明 `supportsMidConvoSystemMessages` 时,适配器按历史顺序保留后续系统消息。否则,适配器在传给 pi-ai 之前,将每条非空的后续系统消息转换为以 `` 包裹的用户消息。包裹文本不会赋予系统角色优先级。单次调用的 `GenerateOptions.system` 放在初始历史提示词之前。重复的系统消息仍会重复发送;空系统消息会被跳过,不会丢弃之前的文本。工具更新能力选择共享的历史声明投影;pi-ai 接收初始可用工具,以及按开发者消息分组的新增和受支持的移除更新。当包含工具更新的 Anthropic 请求中所有投影后的声明均为延迟加载时,初始可用工具为一个占位工具 `DeferredToolPlaceholder`,其描述要求模型永不调用它;若被调用,会得到普通的未知工具结果。Anthropic 在更新消息中以内联方式接收后续工具定义。回放会保留工具调用命名空间,以支持动态加载的 Responses 工具。每张保留图片前都会有文本,注明其完整附件 id 与实际请求尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,该文本还会携带只读规范化对象路径,并警告规范化或请求投影可能缩放或重新编码上传内容。日志中的图片省略决策选中的每个出现位置都会在替换文本中保留自己的身份与当前已解析访问方式,其规范化附件不会读取或变换。当保留的出现位置数量仍超过路由的 `maxRequestImages`,或其精确 base64 载荷超过 `maxRequestImageBytes` 时,调用以 `IMAGE_OFFLOAD_REQUIRED` 失败,由 `dsh-compaction-image-offload` 用 `image/offload` 事件记录所选位置并重试步骤。默认 20 MiB 总预算可以容纳实际 base64 载荷各为 4.5 MiB 的 4 张图片,共 18 MiB;第 5 张会使载荷达到 22.5 MiB,超过预算。编码后更小的图片可以保留更多,但仍受数量上限限制。提供方原生回放元数据只在适配器针对历史内容校验通过后恢复。在 Anthropic Messages 路由上,如果回放响应的请求前缀自生成后发生变化(例如经过压缩),该响应会丢失 thinking 块;其文本和工具调用保留。 `imageRequestTarget(provider, model, image)` 向截图调用方提供与模型请求一致的图片尺寸和字节目标;不缩放图片的适配器保留归一化后的原图。 +所选目录模型会收到系统消息文本、对话历史、工具以及支持的采样字段。目录模型声明 `supportsMidConvoSystemMessages` 时,适配器按历史顺序保留后续系统消息。否则,适配器在传给 pi-ai 之前,将每条非空的后续系统消息转换为以 `` 包裹的用户消息。包裹文本不会赋予系统角色优先级。单次调用的 `GenerateOptions.system` 放在初始历史提示词之前。重复的系统消息仍会重复发送;空系统消息会被跳过,不会丢弃之前的文本。工具更新能力选择共享的历史声明投影;pi-ai 接收初始可用工具,以及按开发者消息分组的新增和受支持的移除更新。当包含工具更新的 Anthropic 请求中所有投影后的声明均为延迟加载时,初始可用工具为一个占位工具 `DeferredToolPlaceholder`,其描述要求模型永不调用它;若被调用,会得到普通的未知工具结果。Anthropic 在更新消息中以内联方式接收后续工具定义。回放会保留工具调用命名空间,以支持动态加载的 Responses 工具。每张保留图片前都会有文本,注明其完整附件 id 与实际请求尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,该文本还会携带只读规范化对象路径,并警告规范化或请求投影可能缩放或重新编码上传内容。日志中的图片省略决策选中的每个出现位置都会在替换文本中保留自己的身份与当前已解析访问方式,其规范化附件不会读取或变换。当保留的出现位置数量仍超过路由的 `maxRequestImages`,或其精确 base64 载荷超过 `maxRequestImageBytes` 时,调用以 `IMAGE_OFFLOAD_REQUIRED` 失败,由 `dsh-compaction-image-offload` 用 `image/offload` 事件记录所选位置并重试步骤。默认每张编码图片最多为 0.75 MiB,20 张达到上限的图片可以放入 20 MiB base64 总预算。较小的图片可以保留更多,但仍受数量上限限制。提供方原生回放元数据只在适配器针对历史内容校验通过后恢复。在 Anthropic Messages 路由上,如果回放响应的请求前缀自生成后发生变化(例如经过压缩),该响应会丢失 thinking 块;其文本和工具调用保留。 `imageRequestTarget(provider, model, image)` 向截图调用方提供最大尺寸和字节上限;`readImageRequest` 返回执行字节限制后的实际编码尺寸。 #### Token 影响 @@ -237,7 +239,7 @@ Anthropic 可以将每个已签名 thinking 块绑定到生成它时的请求前 #### KV Cache 影响 -传给适配器的后续系统消息不会进入初始提示词,从而保留此前的请求前缀。这不改变 Agent loop 的提示词纳入行为;它仍在不支持原生系统更新的路由上合并更新。转换保持逻辑请求顺序,图片句柄与卸载占位符则会添加模型可见文本。即使附件身份与请求字节保持稳定,执行世界路径变化也会改写历史句柄,并可能从该图片起阻止复用。更换适配器实例、提供方、模型或其他上游 token 具有相同的后缀影响。省略过期的 Anthropic thinking 发生在前缀变化之后,而该变化已在变化的消息处结束复用。第一个省略无摘要记录的 thinking 的请求会在第一条此类消息处结束复用,且仅发生一次。一次省略决策会把较早图片换成占位文本,因此复用在该消息处结束;省略永不回退,在下一次决策前前缀保持稳定。数量超限时一次省略 `imageOffloadCountQuantum` 张图片,因此饱和路由每新增这么多张图片才让复用在最老的保留图片处结束一次。 较大的单图字节目标可能更早耗尽不变的总预算,使图片更早被省略。 +传给适配器的后续系统消息不会进入初始提示词,从而保留此前的请求前缀。这不改变 Agent loop 的提示词纳入行为;它仍在不支持原生系统更新的路由上合并更新。转换保持逻辑请求顺序,图片句柄与卸载占位符则会添加模型可见文本。即使附件身份与请求字节保持稳定,执行世界路径变化也会改写历史句柄,并可能从该图片起阻止复用。更换适配器实例、提供方、模型或其他上游 token 具有相同的后缀影响。省略过期的 Anthropic thinking 发生在前缀变化之后,而该变化已在变化的消息处结束复用。第一个省略无摘要记录的 thinking 的请求会在第一条此类消息处结束复用,且仅发生一次。一次省略决策会把较早图片换成占位文本,因此复用在该消息处结束;省略永不回退,在下一次决策前前缀保持稳定。数量超限时一次省略 `imageOffloadCountQuantum` 张图片,因此饱和路由每新增这么多张图片才让复用在最老的保留图片处结束一次。 修改字节预算配置可能缩放历史请求图片并影响前缀复用;仅新增图片不会改变单图分配额度。 ### 提供方响应 diff --git a/packages/llm/llm-pi-ai/src/config.ts b/packages/llm/llm-pi-ai/src/config.ts index 81b21d3526..de09eca4d6 100644 --- a/packages/llm/llm-pi-ai/src/config.ts +++ b/packages/llm/llm-pi-ai/src/config.ts @@ -66,9 +66,11 @@ export const DEFAULT_MAX_REQUEST_IMAGES = 50 * than once per image. */ export const DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM = 10 +/** Number of equal image allocations used to derive the default hard per-image byte limit. */ +export const DEFAULT_REQUEST_IMAGE_BUDGET_COUNT = 20 /** Default total-pixel budget preserves the complete 2048px normalized attachment. */ export const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048 -/** Default raw encoded-byte target before inline base64 expansion; the smallest quality-ladder output is used when no quality fits. */ +/** Fallback hard per-image byte cap when the catalog declares none, before sharing the aggregate budget. */ export const DEFAULT_REQUEST_IMAGE_MAX_BYTES = 1024 * 1024 /** Context capacity assumed for a model neither configuration nor the catalog sizes. */ @@ -193,16 +195,18 @@ export interface PiAiProviderProfile { * steps rewrite the request prefix less often. */ imageOffloadCountQuantum?: number + /** Fixed divisor of maxRequestImageBytes when allocating hard per-image budgets; independent of current image count. Default: 20. */ + requestImageBudgetCount?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number /** Maximum width and height for each request image; omission uses the selected pi-ai model's resize limits. */ requestImageMaxDimension?: number /** - * Raw encoded-byte target overriding the selected model's base64 byte budget; - * omission uses that budget converted to raw bytes, or 1 MiB without catalog metadata. - * The smallest quality-ladder output is used when no quality fits. + * Hard per-image encoded-byte cap overriding the selected model's base64 budget. + * The effective cap is the smaller of this value and the route's equal share of maxRequestImageBytes. + * Omission uses the catalog budget converted to raw bytes, or 1 MiB without catalog metadata. */ - requestImageMaxBytes?: number + maxImageBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ retryPolicy?: RetryPolicyConfig } @@ -224,6 +228,8 @@ export interface ResolvedPiAiProviderProfile maxRequestImages: number /** Positive count-overflow offload step, at most {@link maxRequestImages}, after defaulting. */ imageOffloadCountQuantum: number + /** Positive fixed divisor of the aggregate image-byte budget after defaulting. */ + requestImageBudgetCount: number /** Positive total-pixel request-version budget after defaulting. */ requestImagePixelBudget: number /** Immutable retry policy captured with this provider route. */ @@ -372,9 +378,10 @@ const profile = z.object({ maxRequestImageBytes: z.number().step(1).min(1).default(DEFAULT_MAX_REQUEST_IMAGE_BYTES), maxRequestImages: z.number().step(1).min(1).default(DEFAULT_MAX_REQUEST_IMAGES), imageOffloadCountQuantum: z.number().step(1).min(1), + requestImageBudgetCount: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_REQUEST_IMAGE_BUDGET_COUNT), requestImagePixelBudget: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET), requestImageMaxDimension: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), - requestImageMaxBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), + maxImageBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), retryPolicy: RetryPolicySchema, }) @@ -448,6 +455,12 @@ export function resolveProfiles( const resolved = new Map() for (const [provider, source] of entries) { rejectRemovedFields(provider, source) + if ('imageTargetBytes' in source) { + throw new Error('llm-pi-ai: imageTargetBytes is not configurable; pi uses its effective maxImageBytes as the target') + } + if ('requestImageMaxBytes' in source) { + throw new Error('llm-pi-ai: replace requestImageMaxBytes with maxImageBytes; the new value is a hard per-image cap') + } if (provider.length === 0) throw new Error('llm-pi-ai: provider names must be non-empty') if (source.baseURL !== undefined && source.baseURL.length === 0) { throw new Error(`llm-pi-ai: provider "${provider}" has an empty baseURL`) @@ -465,9 +478,16 @@ export function resolveProfiles( ) } const maxRequestImageBytes = source.maxRequestImageBytes ?? DEFAULT_MAX_REQUEST_IMAGE_BYTES - if (!Number.isInteger(maxRequestImageBytes) || maxRequestImageBytes <= 0) { + if (!Number.isSafeInteger(maxRequestImageBytes) || maxRequestImageBytes <= 0) { throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImageBytes must be a positive integer`) } + const requestImageBudgetCount = source.requestImageBudgetCount ?? DEFAULT_REQUEST_IMAGE_BUDGET_COUNT + if (!Number.isSafeInteger(requestImageBudgetCount) || requestImageBudgetCount <= 0) { + throw new Error(`llm-pi-ai: provider "${provider}" requestImageBudgetCount must be a positive safe integer`) + } + if (requestImageBudgetCount > Math.floor(maxRequestImageBytes / 4)) { + throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImageBytes must allow four base64 bytes per requestImageBudgetCount`) + } const maxRequestImages = source.maxRequestImages ?? DEFAULT_MAX_REQUEST_IMAGES if (!Number.isSafeInteger(maxRequestImages) || maxRequestImages <= 0) { throw new Error(`llm-pi-ai: provider "${provider}" maxRequestImages must be a positive safe integer`) @@ -480,7 +500,7 @@ export function resolveProfiles( if (!Number.isSafeInteger(requestImagePixelBudget) || requestImagePixelBudget <= 0) { throw new Error(`llm-pi-ai: provider "${provider}" requestImagePixelBudget must be a positive safe integer`) } - for (const field of ['requestImageMaxDimension', 'requestImageMaxBytes'] as const) { + for (const field of ['requestImageMaxDimension', 'maxImageBytes'] as const) { const value = source[field] if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) { throw new Error(`llm-pi-ai: provider "${provider}" ${field} must be a positive safe integer`) @@ -538,6 +558,7 @@ export function resolveProfiles( maxRequestImages, imageOffloadCountQuantum, requestImagePixelBudget, + requestImageBudgetCount, retryPolicy: resolveRetryPolicy(retryPolicy, `llm-pi-ai: provider "${provider}" retryPolicy`), ...rest.headers === undefined ? {} : { headers: { ...rest.headers } }, ...rest.thinkingBudgets === undefined ? {} : { thinkingBudgets: { ...rest.thinkingBudgets } }, diff --git a/packages/llm/llm-pi-ai/src/context.ts b/packages/llm/llm-pi-ai/src/context.ts index 5d6deb8bb0..77e469d8e2 100644 --- a/packages/llm/llm-pi-ai/src/context.ts +++ b/packages/llm/llm-pi-ai/src/context.ts @@ -288,8 +288,8 @@ export interface PiImageRequestBudget { maxWidth?: number /** Maximum height inherited from the model or explicitly overridden by the route. */ maxHeight?: number - /** Encoded-byte target for one request image. */ - maxBytes: number + /** Hard encoded-byte limit for one request image; pi also uses it as the preferred target. */ + maxImageBytes: number } /** @@ -301,7 +301,8 @@ export interface PiImageRequestBudget { export function requestImageTarget(ref: ImageAttachmentRef, budget: PiImageRequestBudget): ImageRequestTarget { return { ...requestImageDimensions(ref.width, ref.height, budget.maxPixels, budget.maxWidth, budget.maxHeight), - maxBytes: budget.maxBytes, + maxImageBytes: budget.maxImageBytes, + imageTargetBytes: budget.maxImageBytes, } } @@ -367,7 +368,7 @@ async function toPiContextWithImages( const { attachments, resolveImageAccess, maxRequestImageBytes, maxRequestImages, imageOffloadCountQuantum } = images const requestImagePolicy = images.requestImagePolicy ?? { maxPixels: DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET, - maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES, + maxImageBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES, } assertSupportedHistory(options.messages) const split = splitSystemPrompt(options) diff --git a/packages/llm/llm-pi-ai/src/image-policy.ts b/packages/llm/llm-pi-ai/src/image-policy.ts index 6d7fef8146..12b910b76a 100644 --- a/packages/llm/llm-pi-ai/src/image-policy.ts +++ b/packages/llm/llm-pi-ai/src/image-policy.ts @@ -1,28 +1,35 @@ /** Resolve pi-ai image resize metadata and route-owned overrides. */ +import { LlmError } from '@deepseek-ai/dsh-llm' import type { Api, Model } from '@earendil-works/pi-ai' import { DEFAULT_REQUEST_IMAGE_MAX_BYTES } from './config.ts' import type { ResolvedPiAiProviderProfile } from './config.ts' import type { PiImageRequestBudget } from './context.ts' /** - * Resolve one model's image dimensions and raw encoded-byte target. + * Resolve one model's image dimensions and hard raw encoded-byte limit. * @param model - selected pi-ai catalog model. * @param profile - validated route with optional overrides. * @returns resize limits shared by request serialization and screenshot coordinates. */ export function resolveImageRequestBudget( model: Pick, 'inputLimits'>, - profile: Pick, + profile: Pick, ): PiImageRequestBudget { const resize = model.inputLimits?.images?.resize const maxWidth = profile.requestImageMaxDimension ?? resize?.maxWidth const maxHeight = profile.requestImageMaxDimension ?? resize?.maxHeight // Each four base64 characters carry at most three raw bytes, including padding. const catalogBytes = resize?.maxBytes === undefined ? undefined : Math.floor(resize.maxBytes / 4) * 3 + const allocatedBytes = Math.floor(profile.maxRequestImageBytes / profile.requestImageBudgetCount / 4) * 3 + const maxImageBytes = Math.min(allocatedBytes, profile.maxImageBytes ?? catalogBytes ?? DEFAULT_REQUEST_IMAGE_MAX_BYTES) + if (maxImageBytes < 1) { + throw new LlmError('pi-ai image byte budget cannot encode a nonempty base64 image; increase the image byte limits.', 'INVALID_CONFIG') + } return { maxPixels: profile.requestImagePixelBudget, - maxBytes: profile.requestImageMaxBytes ?? catalogBytes ?? DEFAULT_REQUEST_IMAGE_MAX_BYTES, + maxImageBytes, ...maxWidth === undefined ? {} : { maxWidth }, ...maxHeight === undefined ? {} : { maxHeight }, } diff --git a/packages/llm/llm-pi-ai/tests/adapter.spec.ts b/packages/llm/llm-pi-ai/tests/adapter.spec.ts index 3c8ed928b0..5ad7e16e97 100644 --- a/packages/llm/llm-pi-ai/tests/adapter.spec.ts +++ b/packages/llm/llm-pi-ai/tests/adapter.spec.ts @@ -389,7 +389,7 @@ describe('PiAiAdapter provider routing', () => { expect(readImageRequest).toHaveBeenCalledWith(ref, { width: 1, height: 1, - maxBytes: 3_538_944, + maxImageBytes: 786_432, imageTargetBytes: 786_432, }, expect.any(AbortSignal)) expect(JSON.stringify(server.requests[0])).toContain(MODEL_IMAGE_PATH) expect(server.paths).toEqual(['/v1/responses']) @@ -1255,16 +1255,20 @@ it.each([ }) it('resolves the exact pi-ai image budget for screenshot coordinates', () => { - const adapter = adapterOf({ deepseek: { apiKeyEnv: 'PI_TEST_KEY', requestImagePixelBudget: 10_000, requestImageMaxBytes: 50_000 } }) + const adapter = adapterOf({ deepseek: { apiKeyEnv: 'PI_TEST_KEY', requestImagePixelBudget: 10_000, maxImageBytes: 50_000 } }) expect(adapter.imageRequestTarget('deepseek', 'deepseek-flash', { ...IMAGE_REF, width: 1000, height: 1000 })) - .toEqual({ width: 100, height: 100, maxBytes: 50_000 }) + .toEqual({ width: 100, height: 100, maxImageBytes: 50_000, imageTargetBytes: 50_000 }) expect(() => adapter.imageRequestTarget('missing', 'deepseek-flash', IMAGE_REF)).toThrow('does not own provider') }) it.each([ - [{}, { width: 627, height: 2000, maxBytes: 3_538_944 }], - [{ requestImageMaxDimension: 3000, requestImageMaxBytes: 500_000 }, { width: 940, height: 3000, maxBytes: 500_000 }], + [{}, { width: 627, height: 2000, maxImageBytes: 786_432, imageTargetBytes: 786_432 }], + [{ + requestImageMaxDimension: 3000, maxImageBytes: 500_000, + }, { + width: 940, height: 3000, maxImageBytes: 500_000, imageTargetBytes: 500_000, + }], ])('uses the same catalog and override image target for coordinates and the wire request: %j', async (overrides, expected) => { const server = await mockServer([{ events: anthropicTextEvents }]) const ctx = new Context() @@ -1286,8 +1290,10 @@ it.each([ const ref = { ...IMAGE_REF, width: 1146, height: 3657 } expect(adapter.imageRequestTarget('anthropic', 'claude-sonnet-4-5', ref)).toEqual(expected) const prepared = await adapter.prepareCall('anthropic', 'claude-sonnet-4-5') - providers = { anthropic: { ...providers['anthropic'], requestImageMaxDimension: 777, requestImageMaxBytes: 333 } } - expect(adapter.imageRequestTarget('anthropic', 'claude-sonnet-4-5', ref)).toMatchObject({ height: 777, maxBytes: 333 }) + providers = { anthropic: { ...providers['anthropic'], requestImageMaxDimension: 777, maxImageBytes: 333 } } + expect(adapter.imageRequestTarget('anthropic', 'claude-sonnet-4-5', ref)).toMatchObject({ + height: 777, maxImageBytes: 333, imageTargetBytes: 333, + }) const messages = Array.from({ length: 22 }, () => createUserMessage({ content: [{ type: 'image', attachment: ref }], source: { kind: 'user' } })) const chunks: unknown[] = [] for await (const chunk of prepared.stream({ provider: 'anthropic', model: 'claude-sonnet-4-5', messages })) chunks.push(chunk) diff --git a/packages/llm/llm-pi-ai/tests/config.spec.ts b/packages/llm/llm-pi-ai/tests/config.spec.ts index 839816d5e4..1753f88e81 100644 --- a/packages/llm/llm-pi-ai/tests/config.spec.ts +++ b/packages/llm/llm-pi-ai/tests/config.spec.ts @@ -90,27 +90,32 @@ describe('request image policy bounds', () => { const omitted = routeWith({})() as Options const profile = resolveProfiles(omitted.providers).get('acme-gateway')! expect(profile.requestImageMaxDimension).toBeUndefined() - expect(profile.requestImageMaxBytes).toBeUndefined() - const explicit = routeWith({ requestImageMaxDimension: 3000, requestImageMaxBytes: 2000000 })() as Options + expect(profile.maxImageBytes).toBeUndefined() + expect(profile.requestImageBudgetCount).toBe(20) + const explicit = routeWith({ requestImageMaxDimension: 3000, maxImageBytes: 2000000 })() as Options expect(resolveProfiles(explicit.providers).get('acme-gateway')).toMatchObject({ - requestImageMaxDimension: 3000, requestImageMaxBytes: 2000000, + requestImageMaxDimension: 3000, maxImageBytes: 2000000, }) }) - it.each(['requestImageMaxDimension', 'requestImageMaxBytes'])('rejects invalid %s at the configuration parser', (field) => { - for (const value of [0, -1, 1.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) { - expect(routeWith({ [field]: value })).toThrow() - } - }) + it.each(['requestImageMaxDimension', 'maxImageBytes', 'requestImageBudgetCount'])( + 'rejects invalid %s at the configuration parser', (field) => { + for (const value of [0, -1, 1.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) { + expect(routeWith({ [field]: value })).toThrow() + } + }, + ) it.each([ + ['requestImageBudgetCount', 0, /requestImageBudgetCount must be a positive safe integer/], + ['requestImageBudgetCount', 1.5, /requestImageBudgetCount must be a positive safe integer/], ['requestImagePixelBudget', 0, /requestImagePixelBudget must be a positive safe integer/], ['requestImagePixelBudget', Number.MAX_SAFE_INTEGER + 1, /requestImagePixelBudget must be a positive safe integer/], ['requestImageMaxDimension', 0, /requestImageMaxDimension must be a positive safe integer/], ['requestImageMaxDimension', 1.5, /requestImageMaxDimension must be a positive safe integer/], ['requestImageMaxDimension', Number.MAX_SAFE_INTEGER + 1, /requestImageMaxDimension must be a positive safe integer/], - ['requestImageMaxBytes', 0, /requestImageMaxBytes must be a positive safe integer/], - ['requestImageMaxBytes', 1.5, /requestImageMaxBytes must be a positive safe integer/], + ['maxImageBytes', 0, /maxImageBytes must be a positive safe integer/], + ['maxImageBytes', 1.5, /maxImageBytes must be a positive safe integer/], ] as const)('rejects %s=%s at service resolution', (field, value, message) => { const programmatic = { providers: { @@ -127,3 +132,24 @@ describe('request image policy bounds', () => { }).toThrow(message) }) }) + + +it('rejects an aggregate budget without room for one base64 group per allocated image', () => { + expect(() => resolveProfiles({ anthropic: { maxRequestImageBytes: 79, requestImageBudgetCount: 20 } })) + .toThrow(/four base64 bytes/) + expect(resolveProfiles({ anthropic: { maxRequestImageBytes: 80, requestImageBudgetCount: 20 } }).get('anthropic')) + .toMatchObject({ maxRequestImageBytes: 80, requestImageBudgetCount: 20 }) + expect(() => resolveProfiles({ anthropic: { maxRequestImageBytes: Number.MAX_SAFE_INTEGER + 1 } })) + .toThrow(/maxRequestImageBytes/) +}) + +it('rejects the retired soft-byte configuration key instead of ignoring it', () => { + expect(() => { assertServiceable(routeWith({ requestImageMaxBytes: 1024 })() as Options) }) + .toThrow(/replace requestImageMaxBytes with maxImageBytes/) +}) + + +it('refuses a separate pi soft target at the configuration boundary', () => { + expect(() => { assertServiceable(routeWith({ imageTargetBytes: 1024 })() as Options) }) + .toThrow(/imageTargetBytes is not configurable/) +}) diff --git a/packages/llm/llm-pi-ai/tests/convert.spec.ts b/packages/llm/llm-pi-ai/tests/convert.spec.ts index 2f1cd59d5a..5520ad9661 100644 --- a/packages/llm/llm-pi-ai/tests/convert.spec.ts +++ b/packages/llm/llm-pi-ai/tests/convert.spec.ts @@ -119,7 +119,7 @@ describe('toPiContext', () => { expect(readImageRequest).toHaveBeenCalledWith( attachment, - { width: 1, height: 1, maxBytes: 1024 * 1024 }, + { width: 1, height: 1, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024 }, undefined, ) expect(context.messages[0]).toEqual({ diff --git a/packages/llm/llm-pi-ai/tests/fixtures/image-limits.ts b/packages/llm/llm-pi-ai/tests/fixtures/image-limits.ts index 5f55dc3af0..c465f2853f 100644 --- a/packages/llm/llm-pi-ai/tests/fixtures/image-limits.ts +++ b/packages/llm/llm-pi-ai/tests/fixtures/image-limits.ts @@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises' import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-attachment' +import { isAttachmentError } from '@deepseek-ai/dsh-attachment' import type {} from '@deepseek-ai/dsh-llm' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' @@ -24,9 +24,18 @@ export function apply(ctx: Context): void { for (const [provider, model] of [['anthropic', 'claude-sonnet-4-5'], ['image-override', 'vision']] as const) { const target = ctx.llm.imageRequestTarget(provider, model, source) const encoded = await ctx.attachments.readImageRequest(source, target) - results.push({ provider, target, encoded: { width: encoded.width, height: encoded.height } }) + results.push({ provider, target, encoded: { + width: encoded.width, height: encoded.height, withinLimit: encoded.bytes <= target.maxImageBytes, + } }) } - return [{ type: 'text', text: JSON.stringify({ source: { width: source.width, height: source.height }, results }) }] + let impossibleBudgetError = '' + try { + await ctx.attachments.readImageRequest(source, { width: 1, height: 1, maxImageBytes: 1, imageTargetBytes: 1 }) + } catch (error) { + if (!isAttachmentError(error) || error.code !== 'IMAGE_REQUEST_TOO_LARGE') throw error + impossibleBudgetError = error.code + } + return [{ type: 'text', text: JSON.stringify({ impossibleBudgetError, source: { width: source.width, height: source.height }, results }) }] }, }))) } diff --git a/packages/llm/llm-pi-ai/tests/image-policy.spec.ts b/packages/llm/llm-pi-ai/tests/image-policy.spec.ts index df7312ecd1..cff0d6d4d9 100644 --- a/packages/llm/llm-pi-ai/tests/image-policy.spec.ts +++ b/packages/llm/llm-pi-ai/tests/image-policy.spec.ts @@ -1,42 +1,60 @@ import { describe, expect, it } from 'vitest' import { resolveImageRequestBudget } from '../src/image-policy.ts' -const profile = { requestImagePixelBudget: 2048 * 2048 } +const profile = { requestImagePixelBudget: 2048 * 2048, maxRequestImageBytes: 20 * 1024 * 1024, requestImageBudgetCount: 20 } +const model = { inputLimits: { images: { resize: { maxWidth: 2000, maxHeight: 3000, maxBytes: 4_718_592 } } } } -describe('pi-ai image resize policy', () => { - it('inherits independent dimensions and converts base64 bytes without exceeding the catalog budget', () => { - const policy = resolveImageRequestBudget({ inputLimits: { images: { resize: { - maxWidth: 2000, maxHeight: 3000, maxBytes: 4_718_592, - } } } }, profile) - expect(policy).toEqual({ maxPixels: 4_194_304, maxWidth: 2000, maxHeight: 3000, maxBytes: 3_538_944 }) +describe('pi-ai hard image budget', () => { + it('allocates 0.75 MiB per image without raising the aggregate budget', () => { + expect(resolveImageRequestBudget(model, profile)) + .toEqual({ maxPixels: 4_194_304, maxWidth: 2000, maxHeight: 3000, maxImageBytes: 786_432 }) }) - it.each([4, 5, 6, 7, 8, 101])('reserves base64 padding within a %s-byte budget', (maxBytes) => { + it.each([4, 5, 6, 7, 8, 101])('honors a smaller catalog cap including base64 padding: %s', (maxBytes) => { const policy = resolveImageRequestBudget({ inputLimits: { images: { resize: { maxBytes } } } }, profile) - expect(Buffer.alloc(policy.maxBytes).toString('base64').length).toBeLessThanOrEqual(maxBytes) - expect(Buffer.alloc(policy.maxBytes + 1).toString('base64').length).toBeGreaterThan(maxBytes) + expect(Buffer.alloc(policy.maxImageBytes).toString('base64').length).toBeLessThanOrEqual(maxBytes) + expect(Buffer.alloc(policy.maxImageBytes + 1).toString('base64').length).toBeGreaterThan(maxBytes) }) - it('lets explicit route values raise or lower both catalog dimensions and raw byte targets', () => { - const model = { inputLimits: { images: { resize: { maxWidth: 2000, maxHeight: 2000, maxBytes: 400 } } } } + it.each([[20_971_520, 20], [83, 20], [101, 7], [400, 1]])('keeps %s base64 bytes sufficient for %s allocations', (bytes, count) => { + const policy = resolveImageRequestBudget({}, { ...profile, maxRequestImageBytes: bytes, requestImageBudgetCount: count }) + const encodedBytes = Buffer.alloc(policy.maxImageBytes).toString('base64').length + expect(encodedBytes * count).toBeLessThanOrEqual(bytes) + expect(Buffer.alloc(policy.maxImageBytes + 1).toString('base64').length * count).toBeGreaterThan(bytes) + }) + + it('lets local caps replace catalog limits while preserving the aggregate allocation', () => { + const smallCatalog = { inputLimits: { images: { resize: { maxWidth: 2000, maxHeight: 2000, maxBytes: 400 } } } } for (const requestImageMaxDimension of [1000, 3000]) { - for (const requestImageMaxBytes of [100, 500]) { - expect(resolveImageRequestBudget(model, { ...profile, requestImageMaxDimension, requestImageMaxBytes })) + for (const maxImageBytes of [100, 500, 2_000_000]) { + expect(resolveImageRequestBudget(smallCatalog, { ...profile, requestImageMaxDimension, maxImageBytes })) .toEqual({ - maxPixels: 4_194_304, maxWidth: requestImageMaxDimension, maxHeight: requestImageMaxDimension, maxBytes: requestImageMaxBytes, + maxPixels: 4_194_304, maxWidth: requestImageMaxDimension, maxHeight: requestImageMaxDimension, + maxImageBytes: Math.min(maxImageBytes, 786_432), }) } } }) - it.each([{}, { inputLimits: {} }, { inputLimits: { images: {} } }])('keeps existing defaults without catalog resize metadata: %j', (model) => { - expect(resolveImageRequestBudget(model, profile)).toEqual({ maxPixels: 4_194_304, maxBytes: 1_048_576 }) + it('changes per-image allocation only when configured budgets change', () => { + expect(resolveImageRequestBudget(model, { ...profile, requestImageBudgetCount: 10 }).maxImageBytes).toBe(1_572_864) + expect(resolveImageRequestBudget(model, { ...profile, maxRequestImageBytes: 40 * 1024 * 1024 }).maxImageBytes).toBe(1_572_864) }) - it('inherits each omitted field independently', () => { + it.each([{}, { inputLimits: {} }, { inputLimits: { images: {} } }])('uses the fallback cap and allocation without catalog metadata: %j', (source) => { + expect(resolveImageRequestBudget(source, profile)).toEqual({ maxPixels: 4_194_304, maxImageBytes: 786_432 }) + expect(resolveImageRequestBudget(source, { ...profile, requestImageBudgetCount: 1 }).maxImageBytes).toBe(1_048_576) + }) + + it('inherits omitted dimensions independently', () => { expect(resolveImageRequestBudget({ inputLimits: { images: { resize: { maxHeight: 1500 } } } }, profile)) - .toEqual({ maxPixels: 4_194_304, maxHeight: 1500, maxBytes: 1_048_576 }) - expect(resolveImageRequestBudget({}, { ...profile, requestImageMaxDimension: 3000, requestImageMaxBytes: 500_000 })) - .toEqual({ maxPixels: 4_194_304, maxWidth: 3000, maxHeight: 3000, maxBytes: 500_000 }) + .toEqual({ maxPixels: 4_194_304, maxHeight: 1500, maxImageBytes: 786_432 }) + expect(resolveImageRequestBudget({}, { ...profile, requestImageMaxDimension: 3000, maxImageBytes: 500_000 })) + .toEqual({ maxPixels: 4_194_304, maxWidth: 3000, maxHeight: 3000, maxImageBytes: 500_000 }) + }) + + it('refuses a catalog byte budget too small for a nonempty base64 image', () => { + expect(() => resolveImageRequestBudget({ inputLimits: { images: { resize: { maxBytes: 3 } } } }, profile)) + .toThrow(/cannot encode a nonempty base64 image/) }) }) diff --git a/packages/llm/llm/README.i18n.yaml b/packages/llm/llm/README.i18n.yaml index 17fca7f409..e609825846 100644 --- a/packages/llm/llm/README.i18n.yaml +++ b/packages/llm/llm/README.i18n.yaml @@ -39,8 +39,8 @@ en: fbdadaf319e03d9c zh: edec7c5ef22b37ac /deepseek-ai-dsh-llm/understand-the-implementation/main-flow: - en: c95d4947745e39bb - zh: ec37b969f27629e2 + en: 753dfd5f60e46ff1 + zh: b27eefa78efe25ff /deepseek-ai-dsh-llm/understand-the-implementation/invariants: en: 0163a050239248e5 zh: 885c95bedcbe2ff4 diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index ddc03932e7..23eb8c52fd 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -129,7 +129,7 @@ The service is built on one separation: **the logical contract is provider-neutr ### Main flow -A request is validated against its exact model's capability — context window, output default, reasoning efforts, input modalities, and `systemPromptUpdate` mode — and any adapter-configured defaults are materialized. The runtime preserves freezing for already-frozen input; hand-built callers own input immutability. `prepareCall()` binds those facts, detached context, and retry policy to the exact adapter generation that performs terminal dispatch, so HMR or dynamic settings cannot combine one generation's image capability with another generation's endpoint. An image-capable adapter projects durable references into route-specific request versions; `resolveImageAttachmentAccess()` separately maps an attachment provider's optional host object into the current tool execution world without changing the request image or its `variantId`. A text-only route receives deterministic per-image placeholders, including tool-role result images, without rewriting append-only session history. Durable `FileBlock` references never reach any adapter: request assembly replaces each one, including tool-role result occurrences, with deterministic handle text naming the file and its saved read-only path, resolved through the mounted attachment and filesystem providers. `ctx.llm.fileRequestText(ref)` exposes that exact synchronous projection to request measurement. An image occurrence derived with `offloaded: true` reaches every route as placeholder text through `projectOffloadedImages()`. An image-capable route whose retained occurrences exceed its `LlmImageRequestBudget` at their exact bytes fails with `IMAGE_OFFLOAD_REQUIRED` naming the additional oldest occurrences (`requiredImageOffload()`), never with an unlogged projection; `dsh-compaction-image-offload` logs the selected occurrences in one `image/offload` event and retries. Adapters that charge visual tokens declare per-route `imageRequestPricing`, which `ctx.llm.imageRequestPricing(provider, model)` resolves synchronously for the token meter. Dispatch goes through the `llm/stream` waterfall, then chunks return as token-level deltas and every adapter outcome reaches the consumer as one terminal `finish` chunk. `imageRequestTarget(provider, model, image)` exposes the same request-image dimensions and byte target to screenshot consumers; adapters without image resizing preserve the normalized source. +A request is validated against its exact model's capability — context window, output default, reasoning efforts, input modalities, and `systemPromptUpdate` mode — and any adapter-configured defaults are materialized. The runtime preserves freezing for already-frozen input; hand-built callers own input immutability. `prepareCall()` binds those facts, detached context, and retry policy to the exact adapter generation that performs terminal dispatch, so HMR or dynamic settings cannot combine one generation's image capability with another generation's endpoint. An image-capable adapter projects durable references into route-specific request versions; `resolveImageAttachmentAccess()` separately maps an attachment provider's optional host object into the current tool execution world without changing the request image or its `variantId`. A text-only route receives deterministic per-image placeholders, including tool-role result images, without rewriting append-only session history. Durable `FileBlock` references never reach any adapter: request assembly replaces each one, including tool-role result occurrences, with deterministic handle text naming the file and its saved read-only path, resolved through the mounted attachment and filesystem providers. `ctx.llm.fileRequestText(ref)` exposes that exact synchronous projection to request measurement. An image occurrence derived with `offloaded: true` reaches every route as placeholder text through `projectOffloadedImages()`. An image-capable route whose retained occurrences exceed its `LlmImageRequestBudget` at their exact bytes fails with `IMAGE_OFFLOAD_REQUIRED` naming the additional oldest occurrences (`requiredImageOffload()`), never with an unlogged projection; `dsh-compaction-image-offload` logs the selected occurrences in one `image/offload` event and retries. Adapters that charge visual tokens declare per-route `imageRequestPricing`, which `ctx.llm.imageRequestPricing(provider, model)` resolves synchronously for the token meter. Dispatch goes through the `llm/stream` waterfall, then chunks return as token-level deltas and every adapter outcome reaches the consumer as one terminal `finish` chunk. `imageRequestTarget(provider, model, image)` exposes maximum dimensions and byte budgets; screenshot consumers use the actual dimensions returned by `readImageRequest` after byte-limit resizing. File detection reads current content, including tool-role result content, on every request without caching message identities or freeze state. The [archived file-scan decision](../../../.agents/notes/archived/simplification/2026-09-07-file-content-scan.md) records the measured traversal cost. diff --git a/packages/llm/llm/README.zh.md b/packages/llm/llm/README.zh.md index 2a1bf8bfbf..5199033c1d 100644 --- a/packages/llm/llm/README.zh.md +++ b/packages/llm/llm/README.zh.md @@ -129,7 +129,7 @@ const configure = (maxTokens: number): ConfigureCall => ### 主流程 -请求会对照其精确模型的能力校验,包括上下文窗口、输出默认值、推理强度、输入模态与 `systemPromptUpdate` 模式,并填入任何适配器配置的默认值。运行时保留已冻结输入的冻结状态;手动构建请求的调用方负责保证输入不可变。`prepareCall()` 把这些事实、分离的上下文与重试策略绑定到执行最终分发的精确适配器代次,因此 HMR(热模块替换)或动态设置无法把一个代次的图片能力与另一代次的端点混用。支持图片的适配器把持久引用投影为路由专用请求版本;`resolveImageAttachmentAccess()` 会单独把附件提供方的可选宿主对象映射进当前工具执行世界,而不改变请求图片或其 `variantId`。纯文本路由接收确定性的逐图片占位符,包括 tool-role 结果图片,而不会改写仅追加会话历史。持久 `FileBlock` 引用永远不会到达任何适配器:请求组装把每个引用(包括 tool-role 结果中的出现)替换为确定性句柄文本,指出文件与其只读保存路径,路径经由挂载的附件与文件系统提供方解析。`ctx.llm.fileRequestText(ref)` 向请求计量公开相同的同步投影。派生后带有 `offloaded: true` 的图片出现位置,经 `projectOffloadedImages()` 以占位文本到达每条路由。支持图片的路由在保留的出现位置按精确字节超过其 `LlmImageRequestBudget` 时,以 `IMAGE_OFFLOAD_REQUIRED` 失败并说明还需省略多少最老的出现位置(`requiredImageOffload()`),绝不发送未记录的投影;`dsh-compaction-image-offload` 用一条 `image/offload` 事件记录所选位置并重试。对视觉 token 收费的适配器声明按路由的 `imageRequestPricing`,`ctx.llm.imageRequestPricing(provider, model)` 为 token meter 同步解析它。分发经过 `llm/stream` waterfall(瀑布式事件),随后分片以 token 级增量返回,每个适配器结果都以唯一一个终止 `finish` 分片到达消费方。 `imageRequestTarget(provider, model, image)` 向截图调用方提供与模型请求一致的图片尺寸和字节目标;不缩放图片的适配器保留归一化后的原图。 +请求会对照其精确模型的能力校验,包括上下文窗口、输出默认值、推理强度、输入模态与 `systemPromptUpdate` 模式,并填入任何适配器配置的默认值。运行时保留已冻结输入的冻结状态;手动构建请求的调用方负责保证输入不可变。`prepareCall()` 把这些事实、分离的上下文与重试策略绑定到执行最终分发的精确适配器代次,因此 HMR(热模块替换)或动态设置无法把一个代次的图片能力与另一代次的端点混用。支持图片的适配器把持久引用投影为路由专用请求版本;`resolveImageAttachmentAccess()` 会单独把附件提供方的可选宿主对象映射进当前工具执行世界,而不改变请求图片或其 `variantId`。纯文本路由接收确定性的逐图片占位符,包括 tool-role 结果图片,而不会改写仅追加会话历史。持久 `FileBlock` 引用永远不会到达任何适配器:请求组装把每个引用(包括 tool-role 结果中的出现)替换为确定性句柄文本,指出文件与其只读保存路径,路径经由挂载的附件与文件系统提供方解析。`ctx.llm.fileRequestText(ref)` 向请求计量公开相同的同步投影。派生后带有 `offloaded: true` 的图片出现位置,经 `projectOffloadedImages()` 以占位文本到达每条路由。支持图片的路由在保留的出现位置按精确字节超过其 `LlmImageRequestBudget` 时,以 `IMAGE_OFFLOAD_REQUIRED` 失败并说明还需省略多少最老的出现位置(`requiredImageOffload()`),绝不发送未记录的投影;`dsh-compaction-image-offload` 用一条 `image/offload` 事件记录所选位置并重试。对视觉 token 收费的适配器声明按路由的 `imageRequestPricing`,`ctx.llm.imageRequestPricing(provider, model)` 为 token meter 同步解析它。分发经过 `llm/stream` waterfall(瀑布式事件),随后分片以 token 级增量返回,每个适配器结果都以唯一一个终止 `finish` 分片到达消费方。 `imageRequestTarget(provider, model, image)` 提供最大尺寸和字节预算;截图调用方使用 `readImageRequest` 执行字节限制后返回的实际尺寸。 文件检测在每次请求时读取当前内容,包括 tool-role 结果内容,不缓存消息身份或冻结状态。[已归档的文件扫描决策](../../../.agents/notes/archived/simplification/2026-09-07-file-content-scan.md)记录了实测遍历成本。 diff --git a/packages/llm/llm/src/index.ts b/packages/llm/llm/src/index.ts index 24b06101b4..06cbfd9552 100644 --- a/packages/llm/llm/src/index.ts +++ b/packages/llm/llm/src/index.ts @@ -220,15 +220,15 @@ export abstract class LlmAdapter { } /** - * Resolve the image dimensions and byte target this adapter sends to the model. + * Resolve the maximum image dimensions and byte budgets this adapter uses for the model. * The default preserves normalized images; adapters that resize must override it. * @param _provider - registered provider route. * @param _model - exact model id. * @param image - normalized image whose request projection is being resolved. - * @returns the same target used by request serialization, before provider-internal processing. + * @returns the target used by request serialization; encoded images can be smaller to satisfy the hard byte limit. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget { - return { width: image.width, height: image.height, maxBytes: image.bytes } + return { width: image.width, height: image.height, maxImageBytes: image.bytes, imageTargetBytes: image.bytes } } /** @@ -669,7 +669,7 @@ export class LlmRuntime extends TypertRemoteService { * @param provider - registered provider route. * @param model - exact model id. * @param image - normalized image reference. - * @returns dimensions and byte target used by the adapter's request serializer. + * @returns maximum dimensions and byte budgets used by the request serializer; readImageRequest returns the actual encoded dimensions. */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget { return this.registration(provider).adapter.imageRequestTarget(provider, model, image) diff --git a/packages/llm/llm/tests/service.spec.ts b/packages/llm/llm/tests/service.spec.ts index 76678c99ab..027180ef6e 100644 --- a/packages/llm/llm/tests/service.spec.ts +++ b/packages/llm/llm/tests/service.spec.ts @@ -1717,12 +1717,16 @@ it('delegates image coordinate projections and preserves images for adapters wit try { const image = { attachmentId: brandString('sha256:' + 'a'.repeat(64)), mediaType: 'image/png' as const, bytes: 200, width: 640, height: 480 } ctx.llm.registerAdapter(['identity'], new ScriptedAdapter([])) - expect(ctx.llm.imageRequestTarget('identity', 'vision', image)).toEqual({ width: 640, height: 480, maxBytes: 200 }) + expect(ctx.llm.imageRequestTarget('identity', 'vision', image)).toEqual({ + width: 640, height: 480, maxImageBytes: 200, imageTargetBytes: 200, + }) class ResizingAdapter extends ScriptedAdapter { - override imageRequestTarget() { return { width: 320, height: 240, maxBytes: 100 } } + override imageRequestTarget() { return { width: 320, height: 240, maxImageBytes: 100, imageTargetBytes: 100 } } } ctx.llm.registerAdapter(['resized'], new ResizingAdapter([])) - expect(ctx.llm.imageRequestTarget('resized', 'vision', image)).toEqual({ width: 320, height: 240, maxBytes: 100 }) + expect(ctx.llm.imageRequestTarget('resized', 'vision', image)).toEqual({ + width: 320, height: 240, maxImageBytes: 100, imageTargetBytes: 100, + }) expect(() => ctx.llm.imageRequestTarget('absent', 'vision', image)).toThrow() } finally { await ctx.fiber.dispose() } }) diff --git a/snapshots/session/pi-ai-image-limits/runtime.cordis.yml b/snapshots/session/pi-ai-image-limits/runtime.cordis.yml index e0004f361a..8b67ac9889 100644 --- a/snapshots/session/pi-ai-image-limits/runtime.cordis.yml +++ b/snapshots/session/pi-ai-image-limits/runtime.cordis.yml @@ -7,7 +7,7 @@ api: anthropic-messages baseURL: https://image-override.invalid requestImageMaxDimension: 3000 - requestImageMaxBytes: 1048576 + maxImageBytes: 4096 models: - id: vision input: [text, image] From 26474179d2b35ab75ab691ffee182252f84a8727 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:17:29 +0800 Subject: [PATCH 08/54] =?UTF-8?q?=E4=BF=9D=E7=95=99=E8=AF=B7=E6=B1=82?= =?UTF-8?q?=E5=9B=BE=E7=89=87=E5=B7=B2=E5=8F=96=E6=95=B4=E7=9A=84=E6=AF=94?= =?UTF-8?q?=E4=BE=8B=E5=B0=BA=E5=AF=B8=E5=B9=B6=E5=8C=BA=E5=88=86=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E8=BD=AF=E7=A1=AC=E9=A2=84=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/attachment/attachment-local/src/request-image.ts | 6 +++++- packages/attachment/attachment-local/tests/index.spec.ts | 8 ++++++-- .../attachment-local/tests/request-image.spec.ts | 4 ++-- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/attachment/attachment-local/src/request-image.ts b/packages/attachment/attachment-local/src/request-image.ts index 36d2434290..c0b0c1110b 100644 --- a/packages/attachment/attachment-local/src/request-image.ts +++ b/packages/attachment/attachment-local/src/request-image.ts @@ -130,7 +130,11 @@ async function createRequestImage( height: attachment.ref.height, } } - let dimensions = requestImageDimensions(attachment.ref.width, attachment.ref.height, Infinity, target.width, target.height) + const source = attachment.ref + let dimensions = longEdgeDimensions(source.width, source.height, source.width >= source.height ? target.width : target.height) + if (dimensions.width > target.width || dimensions.height > target.height) { + dimensions = requestImageDimensions(source.width, source.height, Infinity, target.width, target.height) + } for (;;) { signal?.throwIfAborted() const encoded = await encodeFirstWithinLimit( diff --git a/packages/attachment/attachment-local/tests/index.spec.ts b/packages/attachment/attachment-local/tests/index.spec.ts index f1c6495d1b..4e7f294fe5 100644 --- a/packages/attachment/attachment-local/tests/index.spec.ts +++ b/packages/attachment/attachment-local/tests/index.spec.ts @@ -67,16 +67,20 @@ describe('local attachment service', () => { }) it('validates request-image shrink controls in both schema and programmatic construction', () => { - for (const value of [0, 1, Number.NaN, Infinity]) { + for (const value of [0, 1, Infinity]) { expect(() => LocalAttachmentStore.Config({ requestImageMinShrinkFactor: value })).toThrow() expect(() => new LocalAttachmentStore(new Context(), { requestImageMinShrinkFactor: value })) .toThrow(/requestImageMinShrinkFactor/) } - for (const value of [0, 1.1, Number.NaN, Infinity]) { + for (const value of [0, 1.1, Infinity]) { expect(() => LocalAttachmentStore.Config({ requestImageByteHeadroom: value })).toThrow() expect(() => new LocalAttachmentStore(new Context(), { requestImageByteHeadroom: value })) .toThrow(/requestImageByteHeadroom/) } + expect(() => new LocalAttachmentStore(new Context(), { requestImageMinShrinkFactor: Number.NaN })) + .toThrow(/requestImageMinShrinkFactor/) + expect(() => new LocalAttachmentStore(new Context(), { requestImageByteHeadroom: Number.NaN })) + .toThrow(/requestImageByteHeadroom/) }) it('saves and reads through the service boundary', async () => { diff --git a/packages/attachment/attachment-local/tests/request-image.spec.ts b/packages/attachment/attachment-local/tests/request-image.spec.ts index 1ebb89154b..f6db6cb428 100644 --- a/packages/attachment/attachment-local/tests/request-image.spec.ts +++ b/packages/attachment/attachment-local/tests/request-image.spec.ts @@ -108,7 +108,7 @@ describe('local request-image cache', () => { await expect(attachments.readImageRequest(attachment, { width: 8, height: 1.5, maxImageBytes: 100, imageTargetBytes: 100 })) .rejects.toThrow('Image request height must be a positive integer') await expect(attachments.readImageRequest(attachment, { width: 8, height: 4, maxImageBytes: 0, imageTargetBytes: 0 })) - .rejects.toThrow('Image request maxBytes must be a positive integer') + .rejects.toThrow('Image request maxImageBytes must be a positive integer') }) it('resizes by the long edge to the exact target and keys the cache by target', async () => { @@ -396,7 +396,7 @@ describe('local request-image cache', () => { width: 128, height: 128, maxImageBytes: 1024 * 1024, imageTargetBytes: 1024 * 1024, }) const alphaRequest = await attachments.readImageRequest(alpha, { - width: 128, height: 128, maxImageBytes: 4_096, imageTargetBytes: 4_096, + width: 128, height: 128, maxImageBytes: 64 * 1024, imageTargetBytes: 4_096, }) expect(photoRequest.mediaType).toBe('image/jpeg') From 7ef9ab2932132fe8f580c67c02e0a36f42e969e6 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:21:46 +0800 Subject: [PATCH 09/54] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E8=BE=93=E5=85=A5=E5=BC=80=E5=85=B3=E5=AF=B9=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E8=BD=AF=E7=9B=AE=E6=A0=87=E5=AD=97=E6=AE=B5=E7=9A=84=E6=B8=85?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/user/guide/providers.i18n.yaml | 4 ++-- docs/user/guide/providers.md | 2 +- docs/user/guide/providers.zh.md | 2 +- packages/client/ui-settings-models/README.i18n.yaml | 4 ++-- packages/client/ui-settings-models/README.md | 2 +- packages/client/ui-settings-models/README.zh.md | 2 +- .../client/ui-settings-models/src/client/ModelInputTypes.tsx | 2 +- .../tests/model-input-types.client.spec.tsx | 4 ++-- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index fb0f9c5069..4166236141 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -24,8 +24,8 @@ en: b882ec69a6899d8a zh: 66a1713aca0e6f1c /configure-models/advanced-configuration/image-input: - en: 75350cb615da03a4 - zh: 6f8b3510085e4ac4 + en: f8451240e6a09b95 + zh: 5980a42a1bb4a4dc /configure-models/advanced-configuration/deepseek-account-models: en: fc09d02a89b211a7 zh: e0f23a8912a24178 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 78d7807212..422fda51d3 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -80,7 +80,7 @@ These examples show config fields inside a profile patch. A Cordis config overri Pi-ai's `input` accepts `text` and `image` and applies to that model alone. An explicit nonempty selection takes priority. An omitted or empty `input` inherits the installed catalog's input types, then the route's `defaultInput`, which defaults to `[text]`. The checkboxes display these inherited values without saving an override when you merely open the row. -DeepSeek treats an omitted `inputModalities` as text-only and rejects an empty list. Clearing Image also removes that model's `imagePixelBudget` and `imageMaxBytes`, because DeepSeek rejects image limits on a text-only model. Set those limits again if you later enable images and need custom limits. +DeepSeek treats an omitted `inputModalities` as text-only and rejects an empty list. Clearing Image also removes that model's `imagePixelBudget` and `imageTargetBytes`, because DeepSeek rejects image limits on a text-only model. Set those limits again if you later enable images and need custom limits. To restore inheritance after editing the checkboxes, remove the model's `input` or `inputModalities` field from `cordis.patch.yml`. **Restore defaults** removes the entire model-catalog override, including other model edits, so use it only when you want to restore the whole catalog. diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index 9eeef277b4..f9a377a02b 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -80,7 +80,7 @@ Provider ID 是永久的,因为请求、已保存会话、模型默认值和 Pi-ai 的 `input` 接受 `text` 和 `image`,且只作用于该模型。显式的非空选择优先。省略或为空的 `input` 先继承已安装目录的输入类型,再回退到路由的 `defaultInput`,后者默认为 `[text]`。复选框会显示这些继承值,仅打开模型行不会保存覆盖值。 -DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。取消图片还会移除该模型的 `imagePixelBudget` 和 `imageMaxBytes`,因为 DeepSeek 拒绝纯文本模型上的图片限制。以后重新启用图片且需要自定义限制时,需再次设置这些限制。 +DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。取消图片还会移除该模型的 `imagePixelBudget` 和 `imageTargetBytes`,因为 DeepSeek 拒绝纯文本模型上的图片限制。以后重新启用图片且需要自定义限制时,需再次设置这些限制。 修改复选框后如需恢复继承,可在 `cordis.patch.yml` 中移除模型的 `input` 或 `inputModalities` 字段。**恢复默认模型**会移除整个模型目录覆盖,包括其他模型编辑,因此仅在需要恢复整个目录时使用。 diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index d6a66e45df..11750f9e42 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -21,8 +21,8 @@ en: fa2cefbf8c4fdafe zh: 3a4689591b50f6ea /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: 041857583e079891 - zh: b6cd6dd11609aa28 + en: 96fa6b09906d3b9c + zh: 398cf138fa16adfc /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index 24605451db..d386fe1a32 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -63,7 +63,7 @@ The DeepSeek card edits the `llm-deepseek` endpoint, credentials, retry policy, Drag a model’s reorder handle to change its position within the provider, or focus the handle and use the up and down arrow keys. Apply saves the order; Cancel discards it. Each model keeps its settings, expanded options, and unfinished capacity text when moved. The full-row drag preview and reduced-motion-aware row animations share primitives with workspace reordering; before/after insertion markers follow the same style. Row spacing and the adjoining drop targets share one gap value so the space between rows accepts drops. -Expand **Customized settings → Model options** to edit each model. When the model row is narrow, the main row shows only the model ID; expand the row to view or edit its display name. Wider rows show both fields side by side. Focusing a display name expands its row and keeps it open until explicitly collapsed. Tab reaches the option and delete buttons before the display name at every width. Both provider families share the same row layout, labels, and icons: context window and max output tokens occupy two columns, and **Input types** occupies a separate row with **Text** and **Image** checkboxes. A row without an input declaration displays the installed model’s input types, then the provider default, then Text. Known pi-ai providers load their installed catalog without endpoint I/O; opening a row does not write an override. Explicit input selections take precedence, including text-only overrides of vision models. Checkbox edits save the selected types, with at least one type required. DeepSeek writes `inputModalities`; pi-ai writes `input`. Unchecking Image for DeepSeek also removes `imagePixelBudget` and `imageMaxBytes`, because the adapter rejects those limits without image input. Clearing the input field in `cordis.patch.yml` restores adapter inheritance; **Restore default models** resets the entire catalog override. Declare only input types the upstream model can actually process. +Expand **Customized settings → Model options** to edit each model. When the model row is narrow, the main row shows only the model ID; expand the row to view or edit its display name. Wider rows show both fields side by side. Focusing a display name expands its row and keeps it open until explicitly collapsed. Tab reaches the option and delete buttons before the display name at every width. Both provider families share the same row layout, labels, and icons: context window and max output tokens occupy two columns, and **Input types** occupies a separate row with **Text** and **Image** checkboxes. A row without an input declaration displays the installed model’s input types, then the provider default, then Text. Known pi-ai providers load their installed catalog without endpoint I/O; opening a row does not write an override. Explicit input selections take precedence, including text-only overrides of vision models. Checkbox edits save the selected types, with at least one type required. DeepSeek writes `inputModalities`; pi-ai writes `input`. Unchecking Image for DeepSeek also removes `imagePixelBudget` and `imageTargetBytes`, because the adapter rejects those limits without image input. Clearing the input field in `cordis.patch.yml` restores adapter inheritance; **Restore default models** resets the entire catalog override. Declare only input types the upstream model can actually process. A model row on a hand-declared pi-ai route also edits its **Reasoning levels**, the `reasoningEfforts` the adapter already reads from `cordis.patch.yml`; the **?** beside the label explains the two columns. With the switch off the field is absent, so the model does not reason and the model picker offers no level; a stored `false` is kept until the switch is used. Turning it on always starts from rows for off, low, medium, and high; it does not restore levels removed earlier, and **Cancel** discards the edit instead. Each row pairs a level select — the keys `llm-pi-ai`'s configuration schema accepts in `reasoningEfforts`, read from the namespace schema like the protocol choices and today `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`, each usable once — with the **API value** sent for it, which starts as the level name; a field cleared while typing stores the level name and shows it once the field is left. Off only turns reasoning off, so its value field is disabled; a value already written for it in `cordis.patch.yml` is shown and kept. Changing a row's level resets a value still spelled as the old level; a custom value carries over only between two thinking levels, so changing a row to or from Off resets it. A stored key the schema does not list keeps its row and stays selectable there. Rows can be added and deleted and are saved in row order, while the model picker lists the levels in escalation order. The section refuses what the adapter refuses: no level besides Off — including a `reasoningEfforts:` left without a value, which shows the switch on with no rows — or a value that is missing on a level besides Off or empty on any level. A refused value marks its field invalid, and leaving that field fills in the level name. The rows keep no state of their own, so a model row reused after a deletion, a reset, or a fold shows only its own model. On a Gemini API route the level select offers only `minimal`, `low`, `medium`, and `high`, turning the switch on starts from low, medium, and high, and each value field is disabled and holds the level name, which changing a row's level keeps; the Gemini implementation accepts only those four names as values. A stored level, or a value other than its level name, blocks saving with a message under the rows, in the create card and in the editor alike; the editor checks inherited models as well once the protocol is Gemini. Routes served from the installed catalog and the DeepSeek card keep the adapter's levels and show no reasoning control. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 9af095ccac..a9b49c7b2f 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -63,7 +63,7 @@ API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自 拖动模型的排序手柄可调整它在当前提供商内的位置,也可以聚焦手柄后使用上下方向键。保存会保留顺序,取消会放弃修改。移动时,每个模型的参数、已展开选项和未完成的容量输入都会随模型保留。整行拖拽预览及遵循减少动态效果设置的行动画,与工作区排序共用基础组件;前后插入标记沿用相同样式。行距与相邻拖放区域共用同一个间距值,行间空白也可接收放置。 -展开**自定义设置 → 模型选项**编辑模型。模型行较窄时,主行仅显示模型 ID,展开模型行后可查看或编辑显示名称;宽度充足时,两个输入框并排显示。显示名称获得焦点时会展开该行,并保持展开,直到显式收起。所有宽度下,Tab 都先经过模型选项和删除按钮,再到显示名称。两个提供商家族共用相同的模型行布局、标签和图标:上下文窗口与最大输出 token 数分为两列,**输入类型**独占下一行,提供**文本**和**图片**复选框。未声明输入类型的模型行优先显示已安装模型的输入类型,其次是提供商默认值,最后回退为文本。已知 pi-ai 提供商会加载已安装目录,不向端点发送请求;打开模型行不会写入覆盖值。显式输入选择具有优先权,包括为视觉模型设置的仅文本覆盖。修改复选框会保存所选类型,且至少保留一种。DeepSeek 写入 `inputModalities`,pi-ai 写入 `input`。DeepSeek 取消勾选图片时,还会移除 `imagePixelBudget` 和 `imageMaxBytes`,因为适配器在没有图片输入时拒绝这些限制。在 `cordis.patch.yml` 中清除输入字段可恢复适配器继承;**恢复默认模型**会重置整个模型目录覆盖。仅声明上游模型实际能够处理的输入类型。 +展开**自定义设置 → 模型选项**编辑模型。模型行较窄时,主行仅显示模型 ID,展开模型行后可查看或编辑显示名称;宽度充足时,两个输入框并排显示。显示名称获得焦点时会展开该行,并保持展开,直到显式收起。所有宽度下,Tab 都先经过模型选项和删除按钮,再到显示名称。两个提供商家族共用相同的模型行布局、标签和图标:上下文窗口与最大输出 token 数分为两列,**输入类型**独占下一行,提供**文本**和**图片**复选框。未声明输入类型的模型行优先显示已安装模型的输入类型,其次是提供商默认值,最后回退为文本。已知 pi-ai 提供商会加载已安装目录,不向端点发送请求;打开模型行不会写入覆盖值。显式输入选择具有优先权,包括为视觉模型设置的仅文本覆盖。修改复选框会保存所选类型,且至少保留一种。DeepSeek 写入 `inputModalities`,pi-ai 写入 `input`。DeepSeek 取消勾选图片时,还会移除 `imagePixelBudget` 和 `imageTargetBytes`,因为适配器在没有图片输入时拒绝这些限制。在 `cordis.patch.yml` 中清除输入字段可恢复适配器继承;**恢复默认模型**会重置整个模型目录覆盖。仅声明上游模型实际能够处理的输入类型。 手工声明的 pi-ai 路由上,模型行还会编辑**推理等级**,即适配器本来就从 `cordis.patch.yml` 读取的 `reasoningEfforts`;标签旁的 **?** 说明两列的含义。开关关闭时该字段不存在,模型不推理,模型选择器不提供任何档位;已存储的 `false` 在开关被操作前保持不变。打开开关总是从 off、low、medium 和 high 四行开始,不会恢复之前删掉的档位;要放弃修改请点**取消**。每行把一个档位选择框——可选值是 `llm-pi-ai` 配置 schema 允许作为 `reasoningEfforts` 键的档位,与协议选项一样从命名空间 schema 读取,目前为 `off`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max`,每个档位只能用一次——与发送给它的 **API 参数值**配成一对,参数值初始为档位名;输入时清空的字段会存为档位名,离开字段后显示出来。Off 只表示关闭思考,因此它的参数值输入框是禁用的;`cordis.patch.yml` 中已为它写好的值会显示并保留。修改某行的档位时,仍是旧档位名的参数值会随之重置;自定义值只在两个思考档位之间保留,切到或切离 Off 都会重置。schema 未列出的已存键会保留自己的行,并可在该行中继续选择。行可以增删,并按行的顺序保存,模型选择器则按升级顺序列出档位。本节拒绝适配器会拒绝的配置:没有 Off 以外的档位(包括未写值的 `reasoningEfforts:`,此时开关显示为打开且没有任何行),或者 Off 以外的档位缺少参数值、任意档位的参数值为空字符串。被拒绝的值会把对应输入框标为无效,离开该输入框时会填入档位名。各行不保留自己的状态,因此删除、恢复默认或折叠之后被复用的模型行只显示它自己的模型。在 Gemini API 路由上,档位选择框只提供 `minimal`、`low`、`medium` 和 `high`,打开开关从 low、medium 和 high 三行开始,参数值输入框全部禁用并保持为档位名,修改某行档位时也随之改为新档位名;Gemini 实现只接受这四个名称作为参数值。已存储的超出范围的档位,或与档位名不同的参数值,会在行下方显示提示并阻止保存,新建卡片与编辑器都是如此;协议为 Gemini 时,编辑器也会检查继承的模型。走已安装目录的路由和 DeepSeek 卡片沿用适配器的档位,不显示推理等级控件。 diff --git a/packages/client/ui-settings-models/src/client/ModelInputTypes.tsx b/packages/client/ui-settings-models/src/client/ModelInputTypes.tsx index a92e88ae36..2f9596235f 100644 --- a/packages/client/ui-settings-models/src/client/ModelInputTypes.tsx +++ b/packages/client/ui-settings-models/src/client/ModelInputTypes.tsx @@ -49,7 +49,7 @@ export function ModelInputTypes({ model, field, position, disabled, fallback, t, // DeepSeek rejects image request limits on a text-only model. if (field === 'inputModalities' && !nextSelected.includes('image')) { Reflect.deleteProperty(next, 'imagePixelBudget') - Reflect.deleteProperty(next, 'imageMaxBytes') + Reflect.deleteProperty(next, 'imageTargetBytes') } onChange(next) }} diff --git a/packages/client/ui-settings-models/tests/model-input-types.client.spec.tsx b/packages/client/ui-settings-models/tests/model-input-types.client.spec.tsx index b8a37964e0..d95f43fd90 100644 --- a/packages/client/ui-settings-models/tests/model-input-types.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/model-input-types.client.spec.tsx @@ -45,12 +45,12 @@ describe.each(['inputModalities', 'input'] as const)('%s input types', (field) = it('removes DeepSeek image limits when images are unchecked', () => { const onChange = vi.fn() - const model = { id: 'vision', [field]: ['text', 'image'], description: 'kept', imagePixelBudget: 'low', imageMaxBytes: 12345 } + const model = { id: 'vision', [field]: ['text', 'image'], description: 'kept', imagePixelBudget: 'low', imageTargetBytes: 12345 } render( en[key]} onChange={onChange} />) fireEvent.click(screen.getByRole('checkbox', { name: en.modelInputImage })) expect(onChange).toHaveBeenCalledWith({ id: 'vision', description: 'kept', [field]: ['text'], - ...field === 'input' ? { imagePixelBudget: 'low', imageMaxBytes: 12345 } : {}, + ...field === 'input' ? { imagePixelBudget: 'low', imageTargetBytes: 12345 } : {}, }) expect(model[field]).toEqual(['text', 'image']) }) From 05fc5110001614c329f8137c1e2d676ce86d1a12 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 18:33:27 +0800 Subject: [PATCH 10/54] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E7=A1=AC=E4=B8=8A?= =?UTF-8?q?=E9=99=90=E4=BC=9A=E8=AF=9D=E5=9B=9E=E6=94=BE=E5=B9=B6=E4=BF=AE?= =?UTF-8?q?=E5=A4=8DCI=E6=96=AD=E8=A8=80=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../attachment/attachment-local/tests/request-image.spec.ts | 5 +++-- snapshots/session/pi-ai-image-limits/session.v4.jsonl | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/attachment/attachment-local/tests/request-image.spec.ts b/packages/attachment/attachment-local/tests/request-image.spec.ts index f6db6cb428..45fddbb26d 100644 --- a/packages/attachment/attachment-local/tests/request-image.spec.ts +++ b/packages/attachment/attachment-local/tests/request-image.spec.ts @@ -246,8 +246,9 @@ describe('local request-image cache', () => { it('rejects an impossible hard limit after reaching one pixel', async () => { const attachments = await store() const attachment = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' }) - await expect(attachments.readImageRequest(attachment, { width: 64, height: 32, maxImageBytes: 1, imageTargetBytes: 1 })) - .rejects.toMatchObject({ code: 'IMAGE_REQUEST_TOO_LARGE', message: expect.stringContaining('1x1 pixels') }) + const request = attachments.readImageRequest(attachment, { width: 64, height: 32, maxImageBytes: 1, imageTargetBytes: 1 }) + await expect(request).rejects.toMatchObject({ code: 'IMAGE_REQUEST_TOO_LARGE' }) + await expect(request).rejects.toThrow('1x1 pixels') }) it('rejects invalid soft targets and a soft target above the hard limit', async () => { diff --git a/snapshots/session/pi-ai-image-limits/session.v4.jsonl b/snapshots/session/pi-ai-image-limits/session.v4.jsonl index b77670a242..b558c5d16f 100644 --- a/snapshots/session/pi-ai-image-limits/session.v4.jsonl +++ b/snapshots/session/pi-ai-image-limits/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Call snapshot_image_limits, then reply w","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_image_limits","name":"snapshot_image_limits","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_image_limits","name":"snapshot_image_limits","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_image_limits","name":"snapshot_image_limits","arguments":"{}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_image_limits"},"toolCallId":"call_image_limits","content":[{"type":"text","text":"{\"source\":{\"width\":1146,\"height\":3657},\"results\":[{\"provider\":\"anthropic\",\"target\":{\"width\":627,\"height\":2000,\"maxBytes\":3538944},\"encoded\":{\"width\":627,\"height\":2000}},{\"provider\":\"image-override\",\"target\":{\"width\":940,\"height\":3000,\"maxBytes\":1048576},\"encoded\":{\"width\":940,\"height\":3000}}]}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_image_limits"},"toolCallId":"call_image_limits","content":[{"type":"text","text":"{\"impossibleBudgetError\":\"IMAGE_REQUEST_TOO_LARGE\",\"source\":{\"width\":1146,\"height\":3657},\"results\":[{\"provider\":\"anthropic\",\"target\":{\"width\":627,\"height\":2000,\"maxImageBytes\":786432,\"imageTargetBytes\":786432},\"encoded\":{\"width\":627,\"height\":2000,\"withinLimit\":true}},{\"provider\":\"image-override\",\"target\":{\"width\":940,\"height\":3000,\"maxImageBytes\":4096,\"imageTargetBytes\":4096},\"encoded\":{\"width\":410,\"height\":1308,\"withinLimit\":true}}]}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} From 01d345774229cae12db0a592d0a0002a2bddd211 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 19:06:34 +0800 Subject: [PATCH 11/54] =?UTF-8?q?=E9=9A=8Fmaster=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E5=8D=87=E7=BA=A7=E8=BF=81=E7=A7=BB=E5=9B=BE=E7=89=87=E9=99=90?= =?UTF-8?q?=E5=88=B6=E5=8D=87=E7=BA=A7=E6=8C=87=E5=8D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pi-image-resize-defaults/guide.i18n.yaml | 6 +++--- .../pi-image-resize-defaults/guide.md | 0 .../pi-image-resize-defaults/guide.zh.md | 0 3 files changed, 3 insertions(+), 3 deletions(-) rename docs/upgrade-guide/{v0.2.2-rc.4 => v0.2.2-rc.5}/pi-image-resize-defaults/guide.i18n.yaml (85%) rename docs/upgrade-guide/{v0.2.2-rc.4 => v0.2.2-rc.5}/pi-image-resize-defaults/guide.md (100%) rename docs/upgrade-guide/{v0.2.2-rc.4 => v0.2.2-rc.5}/pi-image-resize-defaults/guide.zh.md (100%) diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml similarity index 85% rename from docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml rename to docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml index 0d7510d0ca..7a0b4a91c3 100644 --- a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml @@ -1,13 +1,13 @@ # 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.4/pi-image-resize-defaults/guide.md +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md /: en: 8eab7a795974913a zh: 54b06c3fea95487a /request-image-byte-limits: - en: dfddf0d405d1e813 - zh: 87f32625f9ddc97c + en: 6bee071887ac3982 + zh: ec0176e47b3e64a1 /request-image-byte-limits/change: en: f0636ed9e57d5081 zh: ad5c5584f0e8bfe1 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.md rename to docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md diff --git a/docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.zh.md similarity index 100% rename from docs/upgrade-guide/v0.2.2-rc.4/pi-image-resize-defaults/guide.zh.md rename to docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.zh.md From ee7813eecc00f3ebd048ebce7ab629d5101a4c71 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 18 Nov 2026 19:25:57 +0800 Subject: [PATCH 12/54] =?UTF-8?q?=E8=AE=A9=E6=8B=96=E6=8B=BD=E6=B5=8F?= =?UTF-8?q?=E8=A7=88=E5=99=A8=E6=B5=8B=E8=AF=95=E7=AD=89=E5=BE=85=E7=A8=B3?= =?UTF-8?q?=E5=AE=9A=E6=8E=A7=E4=BB=B6=E5=B9=B6=E5=91=BD=E4=B8=AD=E5=8F=AF?= =?UTF-8?q?=E8=A7=81=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/web/tests/session-drag-scroll.e2e.ts | 36 ++++++++++++++++++----- apps/web/tests/sidebar-right.e2e.ts | 1 + 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/apps/web/tests/session-drag-scroll.e2e.ts b/apps/web/tests/session-drag-scroll.e2e.ts index 2059d10b16..6ab7de5e95 100644 --- a/apps/web/tests/session-drag-scroll.e2e.ts +++ b/apps/web/tests/session-drag-scroll.e2e.ts @@ -86,13 +86,35 @@ describe('web e2e: session drag scrolling', () => { expect((await scrollTops()).viewport).toBeGreaterThan(0) await rest((await listEdges()).top + 4, async () => (await scrollTops()).list === 0) await rest((await listEdges()).bottom - 4, async () => (await scrollTops()).list > 300) - // Drop onto a row that was out of view when the drag started. - const middle = (await listEdges()).top + 200 - await page.mouse.move(x, middle, { steps: 3 }) - await page.mouse.move(x + 1, middle) - await page.mouse.move(x, middle) - const target = await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)! - .closest('[role="treeitem"]')!.querySelector('[class*="title"]')!.textContent, { x, y: middle }) + // Stop edge scrolling, then use a row centre rather than a fixed offset that can fall in a gap. + const edges = await listEdges() + await page.mouse.move(x, (edges.top + edges.bottom) / 2, { steps: 3 }) + const target = await page.evaluate(() => { + const list = document.querySelector('[data-sidebar-list-area]')! + const viewport = document.querySelector('[data-sidebar-scrollport]')!.getBoundingClientRect() + const bounds = list.getBoundingClientRect() + const visibleTop = Math.max(bounds.top, viewport.top) + const visibleBottom = Math.min(bounds.bottom, viewport.bottom) + const middle = (visibleTop + visibleBottom) / 2 + const candidates = [...list.querySelectorAll('[role="treeitem"]:not([aria-expanded])')].map((row) => { + const box = row.getBoundingClientRect() + return { title: row.querySelector('[class*="title"]')?.textContent ?? '', box, centre: box.top + box.height / 2 } + }).filter(row => row.box.top >= visibleTop && row.box.bottom <= visibleBottom + && /^Conversation (\d{2}|[89])$/.test(row.title)) + .sort((a, b) => Math.abs(a.centre - middle) - Math.abs(b.centre - middle)) + const row = candidates[0] + if (!row) throw new Error('No fully visible destination Session row after autoscroll') + return row.title + }) + const destination = rows.filter({ hasText: target }) + await destination.hover({ trial: true }) + const destinationBox = (await destination.boundingBox())! + const drop = { x: destinationBox.x + 30, y: destinationBox.y + destinationBox.height / 2 } + await page.mouse.move(drop.x, drop.y, { steps: 3 }) + await page.mouse.move(drop.x + 1, drop.y) + await page.mouse.move(drop.x, drop.y) + await expect.poll(() => page.evaluate(({ x, y }) => document.elementFromPoint(x, y) + ?.closest('[role="treeitem"]')?.querySelector('[class*="title"]')?.textContent, drop)).toBe(target) expect(target).toMatch(/^Conversation (\d{2}|[89])$/) await page.mouse.up() const titles = () => rows.locator('[class*="title"]').allTextContents() diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 2928f03842..d67fa228c2 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -164,6 +164,7 @@ async function hitsItself(locator: Locator): Promise { * surface and release over the conversation. */ async function floatByDrag(page: Page, tab: Locator): Promise { + await tab.hover({ trial: true }) const surface = page.locator('[data-dockkit-surface]').first() const box = await surface.boundingBox() if (box === null) throw new Error('surface is not rendered') From 08b7d59ec88ef341ee39e4055126ffc8796d7274 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 10:19:49 +0800 Subject: [PATCH 13/54] =?UTF-8?q?=E6=98=8E=E7=A1=AE=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E7=9B=AE=E6=A0=87=E8=AE=A1=E7=AE=97=E5=87=BD=E6=95=B0=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E7=9A=84=E7=A1=AC=E4=B8=8A=E9=99=90=E4=B8=8E=E8=BD=AF?= =?UTF-8?q?=E7=9B=AE=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/experimental/cua/src/tool-registration.ts | 2 +- packages/llm/llm-deepseek/src/request-pricing.ts | 9 ++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/experimental/cua/src/tool-registration.ts b/packages/experimental/cua/src/tool-registration.ts index 84fe1bd10a..5ab7961065 100644 --- a/packages/experimental/cua/src/tool-registration.ts +++ b/packages/experimental/cua/src/tool-registration.ts @@ -54,7 +54,7 @@ declare module '@deepseek-ai/cordis' { * Project a configured screenshot target onto one stored image. * @param configured - Validated `screenshotTarget`. * @param image - Durable normalized screenshot. - * @returns The request target for that image: the long edge capped at the configured value, the configured byte budget. + * @returns Maximum screenshot dimensions, with the configured byte value as both the hard limit and the soft target. */ export function fixedScreenshotTarget(configured: CuaScreenshotTargetConfig, image: ImageAttachmentRef): ImageRequestTarget { return { diff --git a/packages/llm/llm-deepseek/src/request-pricing.ts b/packages/llm/llm-deepseek/src/request-pricing.ts index 8854a40470..35447b7827 100644 --- a/packages/llm/llm-deepseek/src/request-pricing.ts +++ b/packages/llm/llm-deepseek/src/request-pricing.ts @@ -42,13 +42,12 @@ export function resolveRequestImageTargetBytes(model: DeepSeekCatalogModel): num } /** - * Resolve the deterministic request target one DeepSeek model route chooses - * for one source image: the published token grid unless the model overrides - * it with a pixel budget, then the provider per-side limit, then the route's - * encoded-byte target. Small images are never enlarged. + * Resolve maximum request dimensions from the published token grid or the + * model's pixel budget, capped by the provider per-side limit. Small images + * are never enlarged. Byte limits remain separate from the dimension bounds. * @param model - Advertised model route and its optional image overrides. * @param source - intrinsic dimensions of the normalized attachment. - * @returns Complete request dimensions and encoded-byte target. + * @returns Maximum request dimensions, the fixed provider hard byte limit, and the model's soft encoded-byte target. * @internal */ export function resolveRequestImageTarget( From 8ada27036d0a60df3e1f01fc21da265f9b98cec3 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 19 Nov 2026 10:48:45 +0800 Subject: [PATCH 14/54] fix(test): use lane budget for creation fixture installation --- .../experimental/creation-recommendations/tests/fixture.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/experimental/creation-recommendations/tests/fixture.ts b/packages/experimental/creation-recommendations/tests/fixture.ts index 4b91d84ac4..f2ebd2fa36 100644 --- a/packages/experimental/creation-recommendations/tests/fixture.ts +++ b/packages/experimental/creation-recommendations/tests/fixture.ts @@ -3,7 +3,7 @@ import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' -import { expect, onTestFinished, vi } from 'vitest' +import { expect, onTestFinished, TestRunner, vi } from 'vitest' import { brandString } from '@deepseek-ai/dsh-brand' import type { MessageId } from '@deepseek-ai/dsh-llm' import { appendPluginRecord, type SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' @@ -106,7 +106,8 @@ export async function fixture(initial?: PageCardState) { const spec = await entered.promise await writeBundle(spec.cwd!, current()!.bundleName!) result.resolve({ output: [], stopReason: 'completed', structured: { ready: true } }) - await vi.waitFor(() => { expect(current()?.phase).toBe('installed') }) + // Bundle validation and the profile copy perform real filesystem I/O within the test's lane budget. + await vi.waitFor(() => { expect(current()?.phase).toBe('installed') }, { timeout: TestRunner.getCurrentTest()!.timeout }) return spec } return { ctx, agent, agentHandle, harness, directory, manager, bundles, startActivation, dispose, result, entered, From 19cd62a86b8e4d98aa4e7d6bdd12f6fbffc3b664 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Thu, 19 Nov 2026 17:30:27 +0800 Subject: [PATCH 15/54] feat(ui-settings-models): edit reasoning levels of catalog provider models The Models page showed the per-model reasoning-level control only on hand-declared pi-ai routes. The adapter resolves a model entry's `reasoningEfforts` the same way on catalog routes, so the editor now offers the control on every pi-ai route and checks the declarations before saving. With the switch off the field is absent and a catalog model keeps the installed catalog's levels. --- .../catalog-inputs.expected.md | 4 ++ apps/web/tests/models-settings.e2e.ts | 40 +++++++++++++++++++ docs/user/guide/providers.i18n.yaml | 12 +++--- docs/user/guide/providers.md | 6 +-- docs/user/guide/providers.zh.md | 6 +-- .../ui-settings-models/README.i18n.yaml | 4 +- packages/client/ui-settings-models/README.md | 4 +- .../client/ui-settings-models/README.zh.md | 4 +- .../src/client/ModelListEditor.tsx | 5 +-- .../src/client/ModelReasoningEfforts.tsx | 8 ++-- .../src/client/ProviderEditor.tsx | 10 ++--- .../ui-settings-models/src/client/store.ts | 2 +- .../model-reasoning-efforts.client.spec.tsx | 16 +++++++- .../tests/provider-form.client.spec.tsx | 33 +++++++++++---- packages/llm/llm-pi-ai/README.i18n.yaml | 4 +- packages/llm/llm-pi-ai/README.md | 2 +- packages/llm/llm-pi-ai/README.zh.md | 2 +- 17 files changed, 117 insertions(+), 45 deletions(-) diff --git a/apps/web/tests/expected/models-settings/catalog-inputs.expected.md b/apps/web/tests/expected/models-settings/catalog-inputs.expected.md index a80292169c..2af15efeee 100644 --- a/apps/web/tests/expected/models-settings/catalog-inputs.expected.md +++ b/apps/web/tests/expected/models-settings/catalog-inputs.expected.md @@ -61,6 +61,10 @@ - text: 文本 - checkbox "图片" [checked] - text: 图片 + - group "推理等级 1": + - text: 推理等级 + - button "推理等级说明": "?" + - switch "推理等级 1" - button "添加模型" - button "取消" - button "保存" diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index 3c2b3ff0fc..b6da142437 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -543,6 +543,46 @@ describe('web e2e: Models settings page configures a dormant provider', () => { expect(tripwire.pageErrors).toEqual([]) }, 60_000) + it('replaces an installed catalog model\'s reasoning levels and returns to them when switched off', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-models-catalog-reasoning')) + await scaffold.ctx.settings.mutate('llm-pi-ai', [{ + op: 'set', path: ['providers', 'openai'], value: { models: [{ id: 'gpt-6-astra', name: 'GPT-6 Astra' }] }, + }]) + const dialog = page.getByRole('dialog', { name: '设置' }) + const edit = dialog.getByRole('button', { name: '编辑 openai', exact: true }) + const toggle = dialog.getByRole('switch', { name: '推理等级 1' }) + const efforts = async (): Promise => + (await scaffold.ctx.llm.resolveModelInfo('openai', 'gpt-6-astra')).reasoning?.efforts.map(effort => String(effort.id)) ?? [] + const openModelOptions = async (): Promise => { + await edit.click() + await dialog.getByText('自定义设置').click() + await dialog.getByRole('button', { name: '模型选项 1' }).click() + } + try { + const inherited = await efforts() + expect(inherited).toContain('max') + await openModelOptions() + expect(await toggle.getAttribute('aria-checked')).toBe('false') + await toggle.click() + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await toggle.waitFor({ state: 'detached' }) + expect(await efforts()).toEqual(['off', 'low', 'medium', 'high']) + // The saved notice confirms the browser directory refresh, so the reopened draft holds the stored levels. + await dialog.getByText('已保存 openai。', { exact: true }).waitFor({ timeout: 10_000 }) + + await openModelOptions() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') + await toggle.click() + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await toggle.waitFor({ state: 'detached' }) + expect(await efforts()).toEqual(inherited) + } finally { + await scaffold.ctx.settings.mutate('llm-pi-ai', [{ op: 'unset', path: ['providers', 'openai'] }]) + await edit.waitFor({ state: 'detached' }) + } + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + it('saves model drag order, discards canceled moves, and preserves the other provider', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-models-order')) const dialog = page.getByRole('dialog', { name: '设置' }) diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index fb0f9c5069..0dca689270 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -21,8 +21,8 @@ en: 281b2f40645aa5eb zh: 861bfe9584d9d30f /configure-models/advanced-configuration: - en: b882ec69a6899d8a - zh: 66a1713aca0e6f1c + en: 217be2655684ec9f + zh: 50bb9ce264c545f3 /configure-models/advanced-configuration/image-input: en: 75350cb615da03a4 zh: 6f8b3510085e4ac4 @@ -30,11 +30,11 @@ en: fc09d02a89b211a7 zh: e0f23a8912a24178 /configure-models/advanced-configuration/reasoning-effort: - en: f2ffb493997dcc72 - zh: dee9238f072e53ad + en: f6a2efb22fb32f7a + zh: ff8075497aca7d2a /configure-models/advanced-configuration/request-compatibility: en: 6f52195d1502783e zh: 34dbbeacb541afd4 /configure-models/troubleshooting: - en: af9f866bec7701f0 - zh: 0e4f5e1da975be41 + en: 941e0027d0decaad + zh: 4233dbb97c08d348 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 78d7807212..6ef06e87b4 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -51,7 +51,7 @@ If a saved default names a provider that was deleted, the composer displays **Se The generated [plugin configuration catalog](../../config-catalog.md) lists every supported field and default for every plugin; [`dsh-llm-pi-ai`](../../config-catalog.md#deepseek-aidsh-llm-pi-ai) is the provider section this page configures. The [`dsh-llm-pi-ai`](../../../packages/llm/llm-pi-ai/README.md) and [`dsh-llm-deepseek`](../../../packages/llm/llm-deepseek/README.md) references own direct `cordis.patch.yml` configuration, catalog resolution, reasoning controls, credentials, and adapter errors. ::: tip Additional settings -The Models page exposes the API key, display name, base URL, API protocol, and each model's id, display name, context window, max output tokens, and input types, plus the reasoning levels of a model on a custom model API provider. Configure the reasoning levels of a built-in provider's models, request-compatibility switches, headers, timeouts, and retry policy in `$DSH_HOME/profiles//cordis.patch.yml`, the same document the page writes. Edit it directly, or, when the browser runs on the same machine as the server, open it with **Open configuration file** in the Settings header; the adapters re-read it on the next request, so nothing needs a restart. The subsections below cover the fields most gateways need. +The Models page exposes the API key, display name, base URL, API protocol, and each model's id, display name, context window, max output tokens, and input types, plus the reasoning levels of a model on a built-in or custom model API provider. Configure request-compatibility switches, headers, timeouts, and retry policy in `$DSH_HOME/profiles//cordis.patch.yml`, the same document the page writes. Edit it directly, or, when the browser runs on the same machine as the server, open it with **Open configuration file** in the Settings header; the adapters re-read it on the next request, so nothing needs a restart. The subsections below cover the fields most gateways need. For the standard Web UI launch with `dsh web`, `` is `web`, so the path is `$DSH_HOME/profiles/web/cordis.patch.yml`. If you launch a custom profile, use the name selected at startup instead. ::: @@ -135,7 +135,7 @@ A model that needs a newer DeepSeek Harness fails with `CLIENT_UPGRADE_REQUIRED` The model picker offers an **Effort** menu for a model that declares reasoning levels. A built-in provider's models inherit their levels from the installed catalog, and DeepSeek's models keep the adapter's levels. A model you enter by hand declares none until you add them, so until then the Effort entry does not appear in the menu and the endpoint's own default decides whether the model thinks. -On a custom model API provider, declare the levels in **Settings → Models**: edit the provider, open **Customized settings**, expand the model's **Model options**, and turn on **Reasoning levels**. The rows start with off, low, medium, and high. Each row pairs a level with the **API value** sent for it, which defaults to the level name; change it only where the model provider's API documentation spells the level differently. Add or delete rows to match what the endpoint supports, keep at least one level besides off, and save. Turning the switch off removes the declaration. +On a built-in or custom model API provider, declare the levels in **Settings → Models**: edit the provider, open **Customized settings**, expand the model's **Model options**, and turn on **Reasoning levels**. The rows start with off, low, medium, and high. Each row pairs a level with the **API value** sent for it, which defaults to the level name; change it only where the model provider's API documentation spells the level differently. Add or delete rows to match what the endpoint supports, keep at least one level besides off, and save. Levels declared for a built-in provider's model replace the ones it inherits. Turning the switch off removes the declaration, and a built-in provider's model then inherits its levels again. The page writes `reasoningEfforts` in `$DSH_HOME/profiles//cordis.patch.yml`, where you can also declare the levels directly: @@ -224,7 +224,7 @@ Every switch, its accepted values, and the protocols that take it are listed und - **Fetching available models reports neither a `data` array nor a `models` object** — The endpoint's listing is in a format discovery does not read. Enter the models by hand. - **The gateway refuses every request although the key and URL are right** — Its request shape differs from OpenAI's. Start with `compat.supportsDeveloperRole: false` and `compat.maxTokensField: max_tokens` on the route. - **Only reasoning models fail** — pi-ai sends their system prompt as the `developer` role, which the gateway rejects. Set `compat.supportsDeveloperRole: false`. -- **The Effort menu does not appear for a model you entered by hand** — It declares no levels. On a custom model API provider, turn on **Reasoning levels** in the model's **Model options**; elsewhere, add `reasoningEfforts` to the model in `cordis.patch.yml`. +- **The Effort menu does not appear for a model you entered by hand** — It declares no levels. Turn on **Reasoning levels** in the model's **Model options**, or add `reasoningEfforts` to the model in `cordis.patch.yml`. - **`off` does not stop a DeepSeek model from thinking** — An empty `off` sends no reasoning field at all, and an endpoint that thinks by default keeps thinking. Set `compat.thinkingFormat: deepseek` on the model or the route. - **A compat switch is refused as having no value** — A key written with nothing after the colon. Give it a value, or remove the key to keep the installed catalog's. - **An image is refused before sending** — The model declares no image modality. Give a custom provider's model `input: [text, image]`; on DeepSeek's own route, select an image-capable entry from the configured catalog (`deepseek-flash` by default) and confirm that your gateway serves that model with image input. diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index 9eeef277b4..7e3e602e73 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -51,7 +51,7 @@ Provider ID 是永久的,因为请求、已保存会话、模型默认值和 自动生成的[插件配置目录](../../config-catalog.zh.md)列出每个插件的所有受支持字段与默认值;[`dsh-llm-pi-ai`](../../config-catalog.zh.md#deepseek-aidsh-llm-pi-ai) 就是本页所配置的那个提供商段落。[`dsh-llm-pi-ai`](../../../packages/llm/llm-pi-ai/README.zh.md) 和 [`dsh-llm-deepseek`](../../../packages/llm/llm-deepseek/README.zh.md) 参考文档负责直接 `cordis.patch.yml` 配置、目录解析、推理控制、凭据与适配器错误。 ::: tip 其他设置 -模型页提供 API 密钥、显示名称、API 地址、API 协议,以及每个模型的 ID、显示名称、上下文窗口、最大输出 token 数和输入类型;自定义模型 API 提供商的模型还可以在这里设置推理等级。内置提供商模型的推理等级、请求兼容性开关、请求头、超时和重试策略在 `$DSH_HOME/profiles//cordis.patch.yml` 中设置,也就是模型页写入的同一份文档。可以直接编辑它;浏览器与服务器在同一台机器时,也可以点击设置页顶部的**打开配置文件**打开它。适配器会在下一次请求时重新读取,无需重启任何东西。下面各小节介绍多数网关会用到的字段。 +模型页提供 API 密钥、显示名称、API 地址、API 协议,以及每个模型的 ID、显示名称、上下文窗口、最大输出 token 数和输入类型;内置提供商和自定义模型 API 提供商的模型还可以在这里设置推理等级。请求兼容性开关、请求头、超时和重试策略在 `$DSH_HOME/profiles//cordis.patch.yml` 中设置,也就是模型页写入的同一份文档。可以直接编辑它;浏览器与服务器在同一台机器时,也可以点击设置页顶部的**打开配置文件**打开它。适配器会在下一次请求时重新读取,无需重启任何东西。下面各小节介绍多数网关会用到的字段。 按常规方式通过 `dsh web` 启动 Web UI 时,`` 就是 `web`,完整路径为 `$DSH_HOME/profiles/web/cordis.patch.yml`。如果使用自定义 profile,请替换为启动时指定的名称。 ::: @@ -135,7 +135,7 @@ DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。 对于声明了推理等级的模型,模型选择器会提供**推理等级**菜单。内置提供商的模型从已安装目录继承其等级,DeepSeek 的模型沿用适配器提供的等级。手动录入的模型在添加等级之前不声明任何等级,因此模型菜单里不会出现推理等级项,由端点自身的默认值决定模型是否思考。 -自定义模型 API 提供商可以在**设置 → 模型**中声明等级:编辑该提供商,打开**自定义设置**,展开该模型的**模型选项**,然后打开**推理等级**。默认带有 off、low、medium、high 四行。每行把一个档位与发送给它的 **API 参数值**配成一对,参数值默认与档位名相同;只有模型提供商的 API 文档写法不同时才需要修改。按端点支持的档位增删行,至少保留一个 off 以外的档位,然后保存。关闭开关会删除该声明。 +内置提供商和自定义模型 API 提供商都可以在**设置 → 模型**中声明等级:编辑该提供商,打开**自定义设置**,展开该模型的**模型选项**,然后打开**推理等级**。默认带有 off、low、medium、high 四行。每行把一个档位与发送给它的 **API 参数值**配成一对,参数值默认与档位名相同;只有模型提供商的 API 文档写法不同时才需要修改。按端点支持的档位增删行,至少保留一个 off 以外的档位,然后保存。为内置提供商的模型声明的等级会取代它继承的等级。关闭开关会删除该声明,内置提供商的模型随即重新继承其等级。 模型页会把 `reasoningEfforts` 写入 `$DSH_HOME/profiles//cordis.patch.yml`,也可以直接在其中声明等级: @@ -224,7 +224,7 @@ DeepSeek 将省略的 `inputModalities` 视为纯文本,并拒绝空列表。 - **获取可用模型提示既没有 `data` 数组也没有 `models` 对象**:端点返回的列表格式不在探测的读取范围内。请手动输入模型。 - **密钥与地址都正确,网关却拒绝每一个请求**:它的请求形状与 OpenAI 不同。先在路由上设 `compat.supportsDeveloperRole: false` 与 `compat.maxTokensField: max_tokens`。 - **只有推理模型失败**:pi-ai 把它们的系统提示词以 `developer` 角色发出,而网关拒绝该角色。设 `compat.supportsDeveloperRole: false`。 -- **手动录入的模型没有推理等级菜单**:该模型没有声明任何等级。如果是自定义模型 API 提供商,在该模型的**模型选项**中打开**推理等级**;其他提供商在 `cordis.patch.yml` 中给该模型加上 `reasoningEfforts`。 +- **手动录入的模型没有推理等级菜单**:该模型没有声明任何等级。在该模型的**模型选项**中打开**推理等级**,或在 `cordis.patch.yml` 中给该模型加上 `reasoningEfforts`。 - **`off` 无法让 DeepSeek 模型停止思考**:留空的 `off` 不发送任何推理字段,默认思考的端点就继续思考。请在模型或路由上设置 `compat.thinkingFormat: deepseek`。 - **某个 compat 开关因没有值而被拒绝**:冒号后什么都没写。给它一个值,或删掉该键以沿用已安装 catalog 的值。 - **图片在发送前被拒绝**:该模型未声明图片模态。请给自定义提供商的模型加上 `input: [text, image]`;在 DeepSeek 自身的路由上,请从配置的目录中选择支持图片的条目(默认为 `deepseek-flash`),并确认网关提供该模型且支持图片输入。 diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index d6a66e45df..1f1f1aa549 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -21,8 +21,8 @@ en: fa2cefbf8c4fdafe zh: 3a4689591b50f6ea /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: 041857583e079891 - zh: b6cd6dd11609aa28 + en: 23bcea3d60051515 + zh: 07b26ca9de990c5e /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index 24605451db..3d7abcd6c7 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -55,7 +55,7 @@ Leaving the saved mask untouched preserves existing authentication. A saved cred An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. -The collapsed 自定义设置 fold carries the curated extras: `baseURL` for both families (the placeholder shows the endpoint the profile resolves to, the public endpoint for deepseek, else the `defaultBaseURL` the configurable-provider directory reports for a pi-ai catalog route), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Profile `headers` remain deployment configuration in `cordis.patch.yml` or Cordis config and have no Models-page editor. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. There is no provider-scoped reasoning-effort field: effort is a per-model capability, so a provider-scoped control could only be set to a value some models reject. Each model row edits `id`, optional display `name`, optional `contextWindow`/`maxTokens`, input types, and, on a hand-declared pi-ai route, reasoning levels; unrelated model fields survive edits. +The collapsed 自定义设置 fold carries the curated extras: `baseURL` for both families (the placeholder shows the endpoint the profile resolves to, the public endpoint for deepseek, else the `defaultBaseURL` the configurable-provider directory reports for a pi-ai catalog route), each adapter's model catalog, and the **display name** and **API protocol** of a pi-ai route the adapter does not ship. Profile `headers` remain deployment configuration in `cordis.patch.yml` or Cordis config and have no Models-page editor. The Provider ID stays fixed: it is the settings key, the name every other namespace and every logged session references, and the stem of a credential reference the page cannot read back to move. There is no provider-scoped reasoning-effort field: effort is a per-model capability, so a provider-scoped control could only be set to a value some models reject. Each model row edits `id`, optional display `name`, optional `contextWindow`/`maxTokens`, input types, and, on a pi-ai route, reasoning levels; unrelated model fields survive edits. The same fold edits the provider's `retryPolicy` for both families. **Retry policy** defaults to the inherited policy and names its mode; choosing **Transient errors** or **All errors** writes a user-layer policy. Transient mode edits the maximum retry count and the retried error codes, ticked from the choices the `retryableCodes` schema publishes, shown in words (for example **Rate limited** for `RATE_LIMIT`), plus any inherited or stored code outside them, shown verbatim. A third-party code is typed into **Custom error code** and added with **Add** or Enter, which never submits the card: surrounding whitespace is trimmed, case is kept, an empty entry is ignored, and a code already listed is selected instead of duplicated. An added code is selected in the draft only, stays listed after it is unchecked during the same edit, and appears again on reopening once saved; the last ticked code cannot be cleared, and ticking exactly the inherited codes keeps the field inherited; both modes edit the initial delay, maximum delay, and jitter ratio under a **Backoff** fold, which starts open only when the stored policy customizes backoff. Each empty field shows and keeps the inherited value, read from the composition layer, then the schema default. Apply is disabled while a field holds a value the adapter refuses, such as a fractional retry count, a delay that is not positive, or a jitter ratio above 1. The refusal appears below the fields, or above the card actions while the fold is closed. A stored policy without a mode shows the inherited mode, or the schema's first mode when none is inherited, and Apply saves that mode. Switching modes keeps only the fields the new mode declares. Clearing a field unsets it, so the inherited value applies again; choosing the default again removes the user-layer policy. @@ -65,7 +65,7 @@ Drag a model’s reorder handle to change its position within the provider, or f Expand **Customized settings → Model options** to edit each model. When the model row is narrow, the main row shows only the model ID; expand the row to view or edit its display name. Wider rows show both fields side by side. Focusing a display name expands its row and keeps it open until explicitly collapsed. Tab reaches the option and delete buttons before the display name at every width. Both provider families share the same row layout, labels, and icons: context window and max output tokens occupy two columns, and **Input types** occupies a separate row with **Text** and **Image** checkboxes. A row without an input declaration displays the installed model’s input types, then the provider default, then Text. Known pi-ai providers load their installed catalog without endpoint I/O; opening a row does not write an override. Explicit input selections take precedence, including text-only overrides of vision models. Checkbox edits save the selected types, with at least one type required. DeepSeek writes `inputModalities`; pi-ai writes `input`. Unchecking Image for DeepSeek also removes `imagePixelBudget` and `imageMaxBytes`, because the adapter rejects those limits without image input. Clearing the input field in `cordis.patch.yml` restores adapter inheritance; **Restore default models** resets the entire catalog override. Declare only input types the upstream model can actually process. -A model row on a hand-declared pi-ai route also edits its **Reasoning levels**, the `reasoningEfforts` the adapter already reads from `cordis.patch.yml`; the **?** beside the label explains the two columns. With the switch off the field is absent, so the model does not reason and the model picker offers no level; a stored `false` is kept until the switch is used. Turning it on always starts from rows for off, low, medium, and high; it does not restore levels removed earlier, and **Cancel** discards the edit instead. Each row pairs a level select — the keys `llm-pi-ai`'s configuration schema accepts in `reasoningEfforts`, read from the namespace schema like the protocol choices and today `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`, each usable once — with the **API value** sent for it, which starts as the level name; a field cleared while typing stores the level name and shows it once the field is left. Off only turns reasoning off, so its value field is disabled; a value already written for it in `cordis.patch.yml` is shown and kept. Changing a row's level resets a value still spelled as the old level; a custom value carries over only between two thinking levels, so changing a row to or from Off resets it. A stored key the schema does not list keeps its row and stays selectable there. Rows can be added and deleted and are saved in row order, while the model picker lists the levels in escalation order. The section refuses what the adapter refuses: no level besides Off — including a `reasoningEfforts:` left without a value, which shows the switch on with no rows — or a value that is missing on a level besides Off or empty on any level. A refused value marks its field invalid, and leaving that field fills in the level name. The rows keep no state of their own, so a model row reused after a deletion, a reset, or a fold shows only its own model. On a Gemini API route the level select offers only `minimal`, `low`, `medium`, and `high`, turning the switch on starts from low, medium, and high, and each value field is disabled and holds the level name, which changing a row's level keeps; the Gemini implementation accepts only those four names as values. A stored level, or a value other than its level name, blocks saving with a message under the rows, in the create card and in the editor alike; the editor checks inherited models as well once the protocol is Gemini. Routes served from the installed catalog and the DeepSeek card keep the adapter's levels and show no reasoning control. +A model row on a pi-ai route, catalog or hand-declared, also edits its **Reasoning levels**, the `reasoningEfforts` the adapter already reads from `cordis.patch.yml`; the **?** beside the label explains the two columns. With the switch off the field is absent: a model the installed catalog describes keeps the catalog's levels, and any other model does not reason and the model picker offers it no level; a stored `false` is kept until the switch is used. Turning it on always starts from rows for off, low, medium, and high; it does not restore levels removed earlier, and **Cancel** discards the edit instead. Each row pairs a level select — the keys `llm-pi-ai`'s configuration schema accepts in `reasoningEfforts`, read from the namespace schema like the protocol choices and today `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`, each usable once — with the **API value** sent for it, which starts as the level name; a field cleared while typing stores the level name and shows it once the field is left. Off only turns reasoning off, so its value field is disabled; a value already written for it in `cordis.patch.yml` is shown and kept. Changing a row's level resets a value still spelled as the old level; a custom value carries over only between two thinking levels, so changing a row to or from Off resets it. A stored key the schema does not list keeps its row and stays selectable there. Rows can be added and deleted and are saved in row order, while the model picker lists the levels in escalation order. The section refuses what the adapter refuses: no level besides Off — including a `reasoningEfforts:` left without a value, which shows the switch on with no rows — or a value that is missing on a level besides Off or empty on any level. A refused value marks its field invalid, and leaving that field fills in the level name. The rows keep no state of their own, so a model row reused after a deletion, a reset, or a fold shows only its own model. On a route whose `api` names the Gemini API the level select offers only `minimal`, `low`, `medium`, and `high`, turning the switch on starts from low, medium, and high, and each value field is disabled and holds the level name, which changing a row's level keeps; the Gemini implementation accepts only those four names as values. A stored level, or a value other than its level name, blocks saving with a message under the rows, in the create card and in the editor alike; the editor checks inherited models as well once the protocol is Gemini. A catalog route normally stores no `api`; its rows then offer every level with an editable value, whichever protocol its models speak. The DeepSeek card keeps the adapter's levels and shows no reasoning control. Empty pi-ai capacity fields display `1M` for the context window and `128K` for maximum output tokens. These hints use decimal K/M units; leaving the fields empty preserves adapter inheritance. Provider-level defaults can differ from the hints. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 9af095ccac..98654858fe 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -55,7 +55,7 @@ API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自 目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。 -收起的「自定义设置」折叠区承载精选的额外字段:两个家族都有 `baseURL`(占位符显示 profile 解析出的端点,deepseek 即公共端点;没有时显示可配置提供商目录为 pi-ai 内置路由报告的 `defaultBaseURL`)、各适配器自己的模型目录,以及适配器未提供的 pi-ai 路由的**显示名称**与 **API 协议**。Profile `headers` 仍是 `cordis.patch.yml` 或 Cordis 配置中的部署配置,Models 页面不提供编辑器。Provider ID 保持固定:它是 settings 的键、其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。这里没有提供商级的推理等级字段:它是按模型的能力,提供商级的控件只可能被设成某些模型会拒绝的值。每个模型行可编辑 `id`、可选显示 `name`、可选 `contextWindow`/`maxTokens`、输入类型,以及手工声明的 pi-ai 路由上的推理等级;无关的模型字段在编辑后仍会保留。 +收起的「自定义设置」折叠区承载精选的额外字段:两个家族都有 `baseURL`(占位符显示 profile 解析出的端点,deepseek 即公共端点;没有时显示可配置提供商目录为 pi-ai 内置路由报告的 `defaultBaseURL`)、各适配器自己的模型目录,以及适配器未提供的 pi-ai 路由的**显示名称**与 **API 协议**。Profile `headers` 仍是 `cordis.patch.yml` 或 Cordis 配置中的部署配置,Models 页面不提供编辑器。Provider ID 保持固定:它是 settings 的键、其他每个 namespace 与每一条已记录会话引用的名字,也是页面读不回、因而搬不走的凭据引用词干。这里没有提供商级的推理等级字段:它是按模型的能力,提供商级的控件只可能被设成某些模型会拒绝的值。每个模型行可编辑 `id`、可选显示 `name`、可选 `contextWindow`/`maxTokens`、输入类型,以及 pi-ai 路由上的推理等级;无关的模型字段在编辑后仍会保留。 同一折叠区还为两个家族编辑提供商的 `retryPolicy`。**重试策略**默认沿用继承的策略并显示其模式;选择**仅临时错误**或**所有错误**会写入用户层策略。临时错误模式编辑最大重试次数和要重试的错误码,错误码从 `retryableCodes` schema 发布的选项中勾选,选项以文字显示(例如 `RATE_LIMIT` 显示为**请求限流**),选项之外继承或已存储的错误码也会列出并原样显示。第三方错误码可在**自定义错误码**中输入,点击**添加**或按 Enter 加入,Enter 不会提交卡片:首尾空白会去除,大小写保留,空输入被忽略,已列出的错误码只会被勾选而不会重复添加。添加的错误码只在草稿中被勾选,本次编辑中取消勾选后仍保留在列表里,保存后重新打开会再次显示;最后一个勾选项不能取消,勾选的错误码与继承值完全相同时字段保持继承;两种模式都在**退避**折叠区中编辑初始延迟、最大延迟和抖动比例,只有已存储策略自定义了退避时该折叠区才默认展开。每个空字段显示并保留继承值,先取组合层的值,再取 schema 默认值。字段中有适配器会拒绝的值时,应用按钮不可用,例如小数重试次数、非正延迟或大于 1 的抖动比例。拒绝原因显示在字段下方;折叠区收起时显示在卡片操作按钮上方。未设置模式的已存储策略显示继承的模式,没有可继承的模式时显示 schema 中的第一个模式,应用时会保存该模式。切换模式时只保留新模式声明的字段。清空字段会取消该字段的设置,从而重新使用继承值;重新选择默认会移除用户层策略。 @@ -65,7 +65,7 @@ API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自 展开**自定义设置 → 模型选项**编辑模型。模型行较窄时,主行仅显示模型 ID,展开模型行后可查看或编辑显示名称;宽度充足时,两个输入框并排显示。显示名称获得焦点时会展开该行,并保持展开,直到显式收起。所有宽度下,Tab 都先经过模型选项和删除按钮,再到显示名称。两个提供商家族共用相同的模型行布局、标签和图标:上下文窗口与最大输出 token 数分为两列,**输入类型**独占下一行,提供**文本**和**图片**复选框。未声明输入类型的模型行优先显示已安装模型的输入类型,其次是提供商默认值,最后回退为文本。已知 pi-ai 提供商会加载已安装目录,不向端点发送请求;打开模型行不会写入覆盖值。显式输入选择具有优先权,包括为视觉模型设置的仅文本覆盖。修改复选框会保存所选类型,且至少保留一种。DeepSeek 写入 `inputModalities`,pi-ai 写入 `input`。DeepSeek 取消勾选图片时,还会移除 `imagePixelBudget` 和 `imageMaxBytes`,因为适配器在没有图片输入时拒绝这些限制。在 `cordis.patch.yml` 中清除输入字段可恢复适配器继承;**恢复默认模型**会重置整个模型目录覆盖。仅声明上游模型实际能够处理的输入类型。 -手工声明的 pi-ai 路由上,模型行还会编辑**推理等级**,即适配器本来就从 `cordis.patch.yml` 读取的 `reasoningEfforts`;标签旁的 **?** 说明两列的含义。开关关闭时该字段不存在,模型不推理,模型选择器不提供任何档位;已存储的 `false` 在开关被操作前保持不变。打开开关总是从 off、low、medium 和 high 四行开始,不会恢复之前删掉的档位;要放弃修改请点**取消**。每行把一个档位选择框——可选值是 `llm-pi-ai` 配置 schema 允许作为 `reasoningEfforts` 键的档位,与协议选项一样从命名空间 schema 读取,目前为 `off`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max`,每个档位只能用一次——与发送给它的 **API 参数值**配成一对,参数值初始为档位名;输入时清空的字段会存为档位名,离开字段后显示出来。Off 只表示关闭思考,因此它的参数值输入框是禁用的;`cordis.patch.yml` 中已为它写好的值会显示并保留。修改某行的档位时,仍是旧档位名的参数值会随之重置;自定义值只在两个思考档位之间保留,切到或切离 Off 都会重置。schema 未列出的已存键会保留自己的行,并可在该行中继续选择。行可以增删,并按行的顺序保存,模型选择器则按升级顺序列出档位。本节拒绝适配器会拒绝的配置:没有 Off 以外的档位(包括未写值的 `reasoningEfforts:`,此时开关显示为打开且没有任何行),或者 Off 以外的档位缺少参数值、任意档位的参数值为空字符串。被拒绝的值会把对应输入框标为无效,离开该输入框时会填入档位名。各行不保留自己的状态,因此删除、恢复默认或折叠之后被复用的模型行只显示它自己的模型。在 Gemini API 路由上,档位选择框只提供 `minimal`、`low`、`medium` 和 `high`,打开开关从 low、medium 和 high 三行开始,参数值输入框全部禁用并保持为档位名,修改某行档位时也随之改为新档位名;Gemini 实现只接受这四个名称作为参数值。已存储的超出范围的档位,或与档位名不同的参数值,会在行下方显示提示并阻止保存,新建卡片与编辑器都是如此;协议为 Gemini 时,编辑器也会检查继承的模型。走已安装目录的路由和 DeepSeek 卡片沿用适配器的档位,不显示推理等级控件。 +pi-ai 路由上,无论走已安装目录还是手工声明,模型行还会编辑**推理等级**,即适配器本来就从 `cordis.patch.yml` 读取的 `reasoningEfforts`;标签旁的 **?** 说明两列的含义。开关关闭时该字段不存在:已安装目录中有的模型沿用目录的档位,其他模型不推理,模型选择器不为它提供任何档位;已存储的 `false` 在开关被操作前保持不变。打开开关总是从 off、low、medium 和 high 四行开始,不会恢复之前删掉的档位;要放弃修改请点**取消**。每行把一个档位选择框——可选值是 `llm-pi-ai` 配置 schema 允许作为 `reasoningEfforts` 键的档位,与协议选项一样从命名空间 schema 读取,目前为 `off`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max`,每个档位只能用一次——与发送给它的 **API 参数值**配成一对,参数值初始为档位名;输入时清空的字段会存为档位名,离开字段后显示出来。Off 只表示关闭思考,因此它的参数值输入框是禁用的;`cordis.patch.yml` 中已为它写好的值会显示并保留。修改某行的档位时,仍是旧档位名的参数值会随之重置;自定义值只在两个思考档位之间保留,切到或切离 Off 都会重置。schema 未列出的已存键会保留自己的行,并可在该行中继续选择。行可以增删,并按行的顺序保存,模型选择器则按升级顺序列出档位。本节拒绝适配器会拒绝的配置:没有 Off 以外的档位(包括未写值的 `reasoningEfforts:`,此时开关显示为打开且没有任何行),或者 Off 以外的档位缺少参数值、任意档位的参数值为空字符串。被拒绝的值会把对应输入框标为无效,离开该输入框时会填入档位名。各行不保留自己的状态,因此删除、恢复默认或折叠之后被复用的模型行只显示它自己的模型。在 `api` 为 Gemini API 的路由上,档位选择框只提供 `minimal`、`low`、`medium` 和 `high`,打开开关从 low、medium 和 high 三行开始,参数值输入框全部禁用并保持为档位名,修改某行档位时也随之改为新档位名;Gemini 实现只接受这四个名称作为参数值。已存储的超出范围的档位,或与档位名不同的参数值,会在行下方显示提示并阻止保存,新建卡片与编辑器都是如此;协议为 Gemini 时,编辑器也会检查继承的模型。走已安装目录的路由通常不存储 `api`;此时无论其模型使用哪种协议,各行都提供全部档位且参数值可编辑。DeepSeek 卡片沿用适配器的档位,不显示推理等级控件。 pi-ai 容量字段为空时,上下文窗口显示 `1M`,最大输出 token 数显示 `128K`。这些提示使用十进制 K/M 单位;保留空值会继续继承适配器配置。提供方级默认值可能与提示不同。 diff --git a/packages/client/ui-settings-models/src/client/ModelListEditor.tsx b/packages/client/ui-settings-models/src/client/ModelListEditor.tsx index 7e7f2c1907..a7fedc6ff4 100644 --- a/packages/client/ui-settings-models/src/client/ModelListEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ModelListEditor.tsx @@ -75,9 +75,8 @@ export interface ModelListEditorProps { /** Installed provider whose catalog supplies defaults without endpoint I/O. */ catalogProvider?: string | undefined /** - * Reasoning levels a hand-declared route's rows may declare in - * `reasoningEfforts`, in escalation order; absent or empty shows no - * reasoning control, leaving a catalog model's levels to the catalog. + * Reasoning levels the rows may declare in `reasoningEfforts`, in + * escalation order; absent or empty shows no reasoning control. */ reasoningLevels?: readonly string[] | undefined /** Whether the route's protocol accepts only {@link reasoningLevels}, each sent under its own name. */ diff --git a/packages/client/ui-settings-models/src/client/ModelReasoningEfforts.tsx b/packages/client/ui-settings-models/src/client/ModelReasoningEfforts.tsx index f798097710..6db89af722 100644 --- a/packages/client/ui-settings-models/src/client/ModelReasoningEfforts.tsx +++ b/packages/client/ui-settings-models/src/client/ModelReasoningEfforts.tsx @@ -1,4 +1,4 @@ -/** Reasoning-level declarations for a model on a hand-declared pi-ai route. */ +/** Reasoning-level declarations for a model on a pi-ai route. */ import { useState } from 'react' import type { ReactNode } from 'react' @@ -52,7 +52,7 @@ function readEfforts(model: DeepSeekModelDraft): Entries | undefined { function withEfforts(model: DeepSeekModelDraft, entries: Entries | undefined): DeepSeekModelDraft { const next = { ...model } if (entries === undefined) { - // Absent is how a hand-declared model says it does not reason. + // Absent keeps the installed catalog's levels; a model the catalog does not describe then does not reason. Reflect.deleteProperty(next, 'reasoningEfforts') return next } @@ -81,7 +81,7 @@ function outsideLevels(only: readonly string[], level: string, wire: unknown): b } /** - * Mirror the pi-ai refusals of a hand-declared `reasoningEfforts`, so a card + * Mirror the pi-ai refusals of a model's `reasoningEfforts`, so a card * names the row instead of failing at the write. * @param value - drafted `models` value, or `undefined` while inherited. * @param only - the levels the route's protocol accepts, each sent under its @@ -120,7 +120,7 @@ interface ModelReasoningEffortsProps { } /** - * Edit the `reasoningEfforts` a hand-declared pi-ai model offers: a switch, + * Edit the `reasoningEfforts` a pi-ai model offers: a switch, * then one row per level pairing the level with the value sent for it. Every * row is read from the model, so a reused instance shows its new model. * @param props - model declaration and row replacement action. diff --git a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx index 6dc2fb3b63..e8f6eb73a9 100644 --- a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx @@ -250,12 +250,12 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { // The model list is validated by the same per-row checker for both families, // so a bad row is named by its position rather than by a blanket message. - // Only a hand-declared pi-ai route's rows edit reasoning levels — the one - // model list with no installed catalog behind it — so only there are the - // levels read and the declarations checked. + // Every pi-ai route's rows edit reasoning levels, catalog and hand-declared + // alike: the adapter resolves a row's `reasoningEfforts` the same way on + // both, so the levels are read and the declarations checked for both. const schemaReasoningLevels = useMemo( - () => layout === 'pi-ai' && props.declared === true ? reasoningLevelChoices(namespace, schema) : [], - [layout, props.declared, namespace, schema], + () => layout === 'pi-ai' ? reasoningLevelChoices(namespace, schema) : [], + [layout, namespace, schema], ) // What the form currently shows, which is what an interrogation must ask and // what decides the protocol's own constraints: an edited-but-unsaved protocol. diff --git a/packages/client/ui-settings-models/src/client/store.ts b/packages/client/ui-settings-models/src/client/store.ts index 0877cd7da2..b1d5909a6e 100644 --- a/packages/client/ui-settings-models/src/client/store.ts +++ b/packages/client/ui-settings-models/src/client/store.ts @@ -147,7 +147,7 @@ export function protocolChoices( } /** - * The reasoning levels a hand-declared route's models may declare, read out of + * The reasoning levels a pi-ai route's models may declare, read out of * the owning namespace's own schema for the same reason as * {@link protocolChoices}: the levels the page offers and the keys the * adapter accepts in `reasoningEfforts` come from the same `Config`. diff --git a/packages/client/ui-settings-models/tests/model-reasoning-efforts.client.spec.tsx b/packages/client/ui-settings-models/tests/model-reasoning-efforts.client.spec.tsx index a7a84026b4..9089c70f67 100644 --- a/packages/client/ui-settings-models/tests/model-reasoning-efforts.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/model-reasoning-efforts.client.spec.tsx @@ -1,5 +1,5 @@ // @vitest-environment jsdom -/** Reasoning levels of hand-declared pi-ai models: echo, level rows, API values, refusals, and placement. */ +/** Reasoning levels of pi-ai models: echo, level rows, API values, refusals, and placement. */ import { useState } from 'react' import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -325,10 +325,22 @@ describe('reasoning levels in the model list', () => { expect(writes.at(-1)).toEqual([{ id: 'b', reasoningEfforts: DEFAULTS }]) }) + it('edits a catalog route row', () => { + const writes: DeepSeekModelDraft[][] = [] + render( { writes.push(next) }} catalogProvider="openai" reasoningLevels={LEVELS} + probe={{ settingsNs: 'llm-pi-ai', provider: 'openai' }} + operations={operations} disabled={false} t={t} onBusyChange={() => {}} + />) + fireEvent.click(screen.getByRole('button', { name: `${en.modelAdvanced} 1` })) + fireEvent.click(toggle()) + expect(writes.at(-1)).toEqual([{ id: 'gpt-5', reasoningEfforts: DEFAULTS }]) + }) + it.each([ ['without a level list', undefined], ['with an empty level list', []], - ])('shows no reasoning control %s, leaving catalog rows to the installed catalog', (_label, reasoningLevels) => { + ])('shows no reasoning control %s', (_label, reasoningLevels) => { render( { .toContainEqual({ op: 'unset', path: ['providers', 'openai', 'models'] }) }) + it('declares reasoning levels on a catalog route model and stores them in its models list', async () => { + const { mutate } = await mountSection({ + providers: { openai: { apiKeyEnv: 'OPENAI_API_KEY', models: [{ id: 'gpt-5', name: 'GPT-5' }] } }, + }) + openEditor('openai') + expandModel(1) + // Switched off, the field is absent and the model keeps the installed catalog's levels. + const toggle = screen.getByRole('switch', { name: `${en.modelReasoning} 1` }) + expect(toggle.getAttribute('aria-checked')).toBe('false') + + fireEvent.click(toggle) + fireEvent.click(screen.getByText(en.apply)) + await waitFor(() => { expect(mutate).toHaveBeenCalledTimes(1) }) + expect(firstMutate(mutate).ops).toEqual([{ + op: 'set', path: ['providers', 'openai', 'models'], + value: [{ id: 'gpt-5', name: 'GPT-5', reasoningEfforts: { off: null, low: 'low', medium: 'medium', high: 'high' } }], + }]) + }) }) describe('capacity spellings', () => { @@ -1228,11 +1246,11 @@ describe('hand-declared providers', () => { }) it.each([ - ['blocks a hand-declared route', true], - ['leaves a catalog route to the adapter', false], - ])('%s whose stored reasoning levels the adapter refuses', async (_label, declared) => { - // Only a hand-declared route's rows edit reasoning levels, so only there - // can the card name the row and offer the switch that repairs it. + ['a hand-declared route', true], + ['a catalog route', false], + ])('blocks %s whose stored reasoning levels the adapter refuses', async (_label, declared) => { + // The adapter refuses the same declarations on both kinds of route, and + // both edit them, so the card names the row and offers the switch that repairs it. await mountSection({ providers: { 'acme-gateway': { @@ -1244,9 +1262,8 @@ describe('hand-declared providers', () => { }) openEditor('acme-gateway') - const refusal = `${en.model} 1: ${en.modelReasoningNeedsLevel}` - expect(screen.queryByText(refusal) !== null).toBe(declared) - expect(buttonNamed(en.apply).disabled).toBe(declared) + expect(screen.getByText(`${en.model} 1: ${en.modelReasoningNeedsLevel}`)).toBeTruthy() + expect(buttonNamed(en.apply).disabled).toBe(true) }) it('retries only the key after the profile landed, and reports the provider on cancel', async () => { diff --git a/packages/llm/llm-pi-ai/README.i18n.yaml b/packages/llm/llm-pi-ai/README.i18n.yaml index fd6a360e8b..e5ec3b67eb 100644 --- a/packages/llm/llm-pi-ai/README.i18n.yaml +++ b/packages/llm/llm-pi-ai/README.i18n.yaml @@ -93,8 +93,8 @@ en: b6bd570c0159ba08 zh: 7d2d91eea6a8d830 /deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work: - en: fdbe8ce850250b66 - zh: d8b9a06a996850c1 + en: ca569aca42ffe0bc + zh: 2d5e30f0b422166b /deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work/dev-note: en: 3678dd0f6642c2a5 zh: 75cbdd064cc64282 diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index 2bba84d774..a1be5040ea 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -267,7 +267,7 @@ These limits define where the adapter stops and future work begins. They are cur - **Uncataloged models need an unambiguous protocol** — catalog routes preserve each model's protocol, including both Azure APIs under `azure`. A model absent from a mixed-protocol catalog needs an explicit route-level `api`, which overrides every model on the route and must be one of the supported custom protocols. For Azure deployment names, keep the catalog model ID and set `AZURE_OPENAI_DEPLOYMENT_NAME_MAP`. - **A modality declaration is not verified** — a model declaring `image` its gateway does not serve is refused by the provider after prompt admission. The durable image remains in history and the same misdeclared model can fail again; switching to a text-only model remains possible because the shared LLM runtime projects image references into stable text for that request. - **An unauthenticated route depends on its protocol** — a route naming no credential resolves as configured-but-keyless, but pi-ai's OpenAI-compatible implementation still requires an API key or an `Authorization` header, so a keyless local server needs a placeholder credential referenced by `apiKeyEnv` or an `Authorization` entry in `headers`. pi-ai's Gemini implementation refuses a request without an API key, so a `google-generative-ai` route always needs `apiKeyEnv`, whose value it sends as `x-goog-api-key`. -- **Gemini accepts four reasoning levels** — on `google-generative-ai`, pi-ai's Gemini implementation sends only `minimal`, `low`, `medium`, or `high`, compared without case, and fails a request whose `reasoningEfforts` value names anything else; the [Models page](../../client/ui-settings-models/README.md) offers only these levels for such a route. A request without a level, including `off`, sends pi-ai's disabled-thinking configuration, which models that cannot disable thinking, such as Gemini 2.5 Pro, may reject. +- **Gemini accepts four reasoning levels** — on `google-generative-ai`, pi-ai's Gemini implementation sends only `minimal`, `low`, `medium`, or `high`, compared without case, and fails a request whose `reasoningEfforts` value names anything else; the [Models page](../../client/ui-settings-models/README.md) offers only these levels for a route whose `api` names this protocol. A request without a level, including `off`, sends pi-ai's disabled-thinking configuration, which models that cannot disable thinking, such as Gemini 2.5 Pro, may reject. - **`GenerateOptions.stop` is unsupported** — pi-ai's common stream options cannot guarantee stop-sequence behavior across providers. - **Conversation update support comes only from the installed pi-ai catalog** — native system and tool updates require the catalog model’s mid-conversation compat flags, which profiles cannot set. Hand-declared routes and unflagged models receive later system text as user-role reminders and the complete current tool list at the start of each request. - **Images are accepted only in user and tool-result messages** — images in system, developer, or assistant history fail with `UNSUPPORTED_CONTENT` on both conversion paths. diff --git a/packages/llm/llm-pi-ai/README.zh.md b/packages/llm/llm-pi-ai/README.zh.md index 9a964b8681..c0b0699a45 100644 --- a/packages/llm/llm-pi-ai/README.zh.md +++ b/packages/llm/llm-pi-ai/README.zh.md @@ -267,7 +267,7 @@ pi-ai 事件变成 harness 的推理、文本、工具调用、用量与 finish - **目录外模型需要明确的协议**——目录路由保留每个模型的协议,包括 `azure` 下的两种 Azure API。混合协议目录中不存在的模型需要显式设置路由级 `api`;该设置覆盖路由上的所有模型,且必须属于受支持的自定义协议。Azure 部署名称应通过 `AZURE_OPENAI_DEPLOYMENT_NAME_MAP` 设置,模型 ID 保持为目录中的 ID。 - **模态声明不受校验**——声明 `image` 而其网关不支持的模型会在提示词准入后被提供方拒绝。持久图片仍留在历史中,同一误声明模型可能再次失败;切换到纯文本模型仍然可行,因为共享 LLM 运行时会针对该请求把图片引用投影为稳定文本。 - **未认证路由取决于其协议**——不点名凭据的路由解析为已配置但无密钥,但 pi-ai 的 OpenAI 兼容实现仍要求 API 密钥或 `Authorization` 标头,因此无密钥本地服务器需要由 `apiKeyEnv` 引用或 `headers` 中的 `Authorization` 条目提供的占位凭据。pi-ai 的 Gemini 实现会拒绝没有 API 密钥的请求,因此 `google-generative-ai` 路由始终需要 `apiKeyEnv`,其值以 `x-goog-api-key` 发送。 -- **Gemini 只接受四个推理等级**——在 `google-generative-ai` 上,pi-ai 的 Gemini 实现只发送 `minimal`、`low`、`medium` 或 `high`(不区分大小写),`reasoningEfforts` 的值为其他名称时请求失败;[模型页](../../client/ui-settings-models/README.zh.md)只为此类路由提供这些档位。不带等级的请求(包括 `off`)会发送 pi-ai 的关闭思考配置,无法关闭思考的模型(例如 Gemini 2.5 Pro)可能拒绝该请求。 +- **Gemini 只接受四个推理等级**——在 `google-generative-ai` 上,pi-ai 的 Gemini 实现只发送 `minimal`、`low`、`medium` 或 `high`(不区分大小写),`reasoningEfforts` 的值为其他名称时请求失败;[模型页](../../client/ui-settings-models/README.zh.md)只为 `api` 指定该协议的路由提供这些档位。不带等级的请求(包括 `off`)会发送 pi-ai 的关闭思考配置,无法关闭思考的模型(例如 Gemini 2.5 Pro)可能拒绝该请求。 - **不支持 `GenerateOptions.stop`**——pi-ai 的通用流式选项无法跨提供方保证停止序列行为。 - **对话更新支持只来自已安装的 pi-ai 目录**——原生系统与工具更新需要目录模型的对话中 compat 标志,profile 不能设置这些标志。手工声明的路由与未标记的模型会以用户角色提醒接收后续系统文本,并在每次请求开头接收完整的当前工具列表。 - **图片只在 user 与工具结果消息中被接受**——system、developer 或 assistant 历史中的图片在两条转换路径上都会以 `UNSUPPORTED_CONTENT` 失败。 From 00b1ac207d6dff938845458ee7a8aa638d5ac762 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 19 Nov 2026 18:39:52 +0800 Subject: [PATCH 16/54] fix(sdk): disable the workflow tool in the PTC executor overlay The PTC overlay now disables the workflow-ptc engine and tool-workflow rows, as the Desktop ptc agent preset does: run_code already orchestrates tool calls in code, so SDK and headless PTC runs no longer list workflow, its prompt section, or its run_code binding. Native execution keeps the workflow tool. --- apps/cli/config/examples/ptc.yml | 8 +++++ apps/cli/reference/README.i18n.yaml | 4 +-- apps/cli/reference/README.md | 2 +- apps/cli/reference/README.zh.md | 2 +- .../tests/profiles/sdk/keyless-smoke.e2e.ts | 2 ++ .../guide.i18n.yaml | 16 ++++++++++ .../ptc-overlay-workflow-removed/guide.md | 30 +++++++++++++++++++ .../ptc-overlay-workflow-removed/guide.zh.md | 30 +++++++++++++++++++ packages/bundle/sdk-app/README.i18n.yaml | 4 +-- packages/bundle/sdk-app/README.md | 2 +- packages/bundle/sdk-app/README.zh.md | 2 +- 11 files changed, 94 insertions(+), 8 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.zh.md diff --git a/apps/cli/config/examples/ptc.yml b/apps/cli/config/examples/ptc.yml index 65905eacdd..8adf9b17f1 100644 --- a/apps/cli/config/examples/ptc.yml +++ b/apps/cli/config/examples/ptc.yml @@ -8,3 +8,11 @@ - id: tool-fs config: applyPatch: false + +# run_code already orchestrates tool calls in code, so PTC mode omits the +# separate workflow tool and its engine, as the Web ptc preset does. +- id: workflow-ptc + disabled: true + +- id: tool-workflow + disabled: true diff --git a/apps/cli/reference/README.i18n.yaml b/apps/cli/reference/README.i18n.yaml index 84a966f601..5cae7ff164 100644 --- a/apps/cli/reference/README.i18n.yaml +++ b/apps/cli/reference/README.i18n.yaml @@ -21,8 +21,8 @@ en: 8d2cfff9bab7327f zh: 21515ab6e6798504 /dsh-cli-behavior-reference/web-profile: - en: b9bf517793555b80 - zh: 3dd96ecaaa6faea3 + en: ed6e1eea01293b53 + zh: 43d9380872a93161 /dsh-cli-behavior-reference/shared-deployment-behavior: en: f02219118dcec531 zh: fe2977628d7340da diff --git a/apps/cli/reference/README.md b/apps/cli/reference/README.md index 49d3c5a78d..77c9231420 100644 --- a/apps/cli/reference/README.md +++ b/apps/cli/reference/README.md @@ -132,7 +132,7 @@ The base-backed modes treat the invoking directory as the default workspace root New sessions in base-backed profiles default to the `workspace-write` permission preset. Bash and filesystem mutations are restricted to the session workspace and platform temporary roots; reads and network access are not confined, while process visibility depends on the selected sandbox backend — bwrap runs commands in a private PID namespace that hides host processes, and Landlock and Seatbelt leave host process visibility unchanged. `DSH_PERMISSION_MODE` changes the process fallback. Stored General-settings permissions affect later Web sessions, not an already-open one. The standalone `sdk-minimal` tree instead pins `danger-full-access` and mounts no approval or permission-settings service. -Web, headless, and SDK inherit native tool execution from the base bundle; use a [PTC overlay](../config/examples/ptc.yml) to select PTC. The shipped `minimal` agent preset keeps that deployment presentation, fixes the complete system prompt to `You are a helpful software engineer assistant.`, and provides the platform-selected persistent shell and `read_image`. It supports automatic context compaction and the human `/compact` command. Select 极简模式 when creating a Web session; the shared browser, workspace, persistence, sandbox, and permission host remains in place. +Web, headless, and SDK inherit native tool execution from the base bundle; use a [PTC overlay](../config/examples/ptc.yml) to select PTC, which also disables the `workflow` tool and its engine as the Web `ptc` preset does. The shipped `minimal` agent preset keeps that deployment presentation, fixes the complete system prompt to `You are a helpful software engineer assistant.`, and provides the platform-selected persistent shell and `read_image`. It supports automatic context compaction and the human `/compact` command. Select 极简模式 when creating a Web session; the shared browser, workspace, persistence, sandbox, and permission host remains in place. ## Shared deployment behavior diff --git a/apps/cli/reference/README.zh.md b/apps/cli/reference/README.zh.md index e58ddef171..0a7a4f054d 100644 --- a/apps/cli/reference/README.zh.md +++ b/apps/cli/reference/README.zh.md @@ -132,7 +132,7 @@ dsh web --help 基于 base 的 profile 中,新会话默认使用 `workspace-write` 权限预设。Bash 和文件系统修改仅限于会话 workspace 与平台临时根目录;读取和网络访问不受限制,进程可见性则取决于所选沙箱后端——bwrap 在私有 PID 命名空间中运行命令并隐藏宿主进程,Landlock 与 Seatbelt 保持宿主进程可见性不变。`DSH_PERMISSION_MODE` 更改进程后备值。General settings 中存储的权限影响后续 Web 会话,不改变已打开的会话。独立的 `sdk-minimal` 配置树则固定为 `danger-full-access`,且不挂载 approval 或权限 settings 服务。 -Web、headless 与 SDK 继承 base bundle 的原生工具执行;使用 [PTC overlay](../config/examples/ptc.yml) 可选择 PTC。随附的 `minimal` agent preset 会保留该部署的呈现方式,将完整系统提示词固定为 `You are a helpful software engineer assistant.`,并提供按平台选择的持久 shell 和 `read_image`。它支持自动上下文压缩和用户 `/compact` 命令。创建 Web 会话时请选择极简模式;共享的浏览器、workspace、持久化、沙箱与权限宿主保持不变。 +Web、headless 与 SDK 继承 base bundle 的原生工具执行;使用 [PTC overlay](../config/examples/ptc.yml) 可选择 PTC,它还会像 Web 的 `ptc` preset 一样禁用 `workflow` 工具及其引擎。随附的 `minimal` agent preset 会保留该部署的呈现方式,将完整系统提示词固定为 `You are a helpful software engineer assistant.`,并提供按平台选择的持久 shell 和 `read_image`。它支持自动上下文压缩和用户 `/compact` 命令。创建 Web 会话时请选择极简模式;共享的浏览器、workspace、持久化、沙箱与权限宿主保持不变。 ## 共享部署行为 diff --git a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts index 6ac211dbfc..22a78c6a93 100644 --- a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts +++ b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts @@ -201,7 +201,9 @@ describe('Python SDK dsh profile keyless smoke', () => { expect(toolNames).toEqual(['run_code']) for (const tool of expectedTools) expect(requestText.includes(`${tool}:`), tool).toBe(true) expect(requestText.includes('apply_patch:')).toBe(false) + expect(requestText.includes('workflow:')).toBe(false) } else { + expect(toolNames).toContain('workflow') expect(toolNames).toEqual(expect.arrayContaining(expectedTools)) expect(toolNames.includes('apply_patch')).toBe(patchEnabled) expect(toolNames.includes('str_replace_editor')).toBe(editorEnabled) diff --git a/docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.i18n.yaml new file mode 100644 index 0000000000..cede622429 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/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.5/ptc-overlay-workflow-removed/guide.md +/: + en: 32cd596f33cbe3fe + zh: c6304ea503609c57 +/ptc-overlay-removes-the-workflow-tool: + en: 389c0090be88abcc + zh: 1f5498b7911d5d7b +/ptc-overlay-removes-the-workflow-tool/change: + en: dd25e801f0366a18 + zh: 2a37aec73190bf73 +/ptc-overlay-removes-the-workflow-tool/migration: + en: ef99a22e80844e1c + zh: cd3ad5ebeb7b9e7a diff --git a/docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.md new file mode 100644 index 0000000000..319f8ccc03 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.md @@ -0,0 +1,30 @@ +--- +kind: upgrade-guide +description: "The PTC executor overlay no longer exposes the workflow tool or loads its workflow engine." +--- + +# PTC overlay removes the workflow tool + +English | [中文](guide.zh.md) + +## Change + +In earlier releases, [`apps/cli/config/examples/ptc.yml`](../../../../apps/cli/config/examples/ptc.yml) only switched tool execution to PTC, so a headless or SDK run with this overlay still listed the `workflow` tool, its `tool:workflow` system prompt section, and its `run_code` binding. The overlay now also disables the `workflow-ptc` engine and `tool-workflow` rows, as the Web `ptc` agent preset does: `run_code` orchestrates tool calls in code, and the model no longer sees or can call `workflow`. Native execution, which is the default without the overlay, keeps the workflow tool. + +This affects TypeScript and Python SDK applications and headless runs that pass the overlay, and any prompt, evaluation, or recorded transcript that expects `workflow` in PTC mode. + +## Migration + +1. To keep the workflow tool in PTC mode, apply one more patch after the overlay that turns both rows back on: + + ```yaml + - id: workflow-ptc + disabled: false + + - id: tool-workflow + disabled: false + ``` + + Pass it through `--patch` after `ptc.yml`, or after the overlay in the TypeScript or Python SDK `patches` option. +2. Otherwise, move orchestration that called `workflow` into `run_code` programs or `subagent` calls. +3. Confirm with a PTC run: without the extra patch the first model request has no `tool:workflow` section and its `run_code` bindings declare no `workflow` function; with the patch both return. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.zh.md new file mode 100644 index 0000000000..a75b634da9 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/ptc-overlay-workflow-removed/guide.zh.md @@ -0,0 +1,30 @@ +--- +kind: upgrade-guide +description: "PTC 执行器 overlay 不再提供 workflow 工具,也不再加载 workflow 引擎。" +--- + +# PTC overlay 移除 workflow 工具 + +[English](guide.md) | 中文 + +## 变更 + +在此前的版本中,[`apps/cli/config/examples/ptc.yml`](../../../../apps/cli/config/examples/ptc.yml) 只把工具执行切换为 PTC,因此带该 overlay 的 headless 或 SDK 运行仍会列出 `workflow` 工具、其 `tool:workflow` 系统提示词段落以及对应的 `run_code` 绑定。现在该 overlay 还会禁用 `workflow-ptc` 引擎行和 `tool-workflow` 行,与 Web 的 `ptc` agent preset 相同:`run_code` 用代码编排工具调用,模型不再看到也无法调用 `workflow`。不带该 overlay 时默认的原生执行仍保留 workflow 工具。 + +受影响的是传入该 overlay 的 TypeScript 与 Python SDK 应用和 headless 运行,以及在 PTC 模式下预期存在 `workflow` 的提示词、评测或录制的会话记录。 + +## 迁移 + +1. 若要在 PTC 模式下保留 workflow 工具,在该 overlay 之后再应用一个重新启用这两行的 patch: + + ```yaml + - id: workflow-ptc + disabled: false + + - id: tool-workflow + disabled: false + ``` + + 通过 `--patch` 在 `ptc.yml` 之后传入,或在 TypeScript、Python SDK 的 `patches` 选项中放在该 overlay 之后。 +2. 否则,把原先调用 `workflow` 的编排改为 `run_code` 程序或 `subagent` 调用。 +3. 用一次 PTC 运行确认:不带额外 patch 时,第一个模型请求中没有 `tool:workflow` 段落,其 `run_code` 绑定也不声明 `workflow` 函数;带上该 patch 后两者都会恢复。 diff --git a/packages/bundle/sdk-app/README.i18n.yaml b/packages/bundle/sdk-app/README.i18n.yaml index d808749914..42d8c7178d 100644 --- a/packages/bundle/sdk-app/README.i18n.yaml +++ b/packages/bundle/sdk-app/README.i18n.yaml @@ -15,8 +15,8 @@ en: 4e53164159b5ce41 zh: 89582dc0294d0776 /deepseek-ai-dsh-sdk-app/use-this-package: - en: 544309ea0bdf6d79 - zh: 67f1f40c075d38b2 + en: dd70f84fe0084e30 + zh: 365e705ac368eaa2 /deepseek-ai-dsh-sdk-app/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 diff --git a/packages/bundle/sdk-app/README.md b/packages/bundle/sdk-app/README.md index 3101c4fbac..af65c51213 100644 --- a/packages/bundle/sdk-app/README.md +++ b/packages/bundle/sdk-app/README.md @@ -23,7 +23,7 @@ The SDK stdio application as a `dsh` profile bundle over [`dsh-base`](../base/RE ## Use this package -The `sdk` profile includes native desktop tools and model context. Native tool execution is the default. For PTC, pass the [executor overlay](../../../apps/cli/config/examples/ptc.yml) through `--patch` or the `patches` option in the TypeScript or Python SDK. `DSH_TOOLS_MODE` is ignored. +The `sdk` profile includes native desktop tools and model context. Native tool execution is the default. For PTC, pass the [executor overlay](../../../apps/cli/config/examples/ptc.yml) through `--patch` or the `patches` option in the TypeScript or Python SDK; like the Web `ptc` preset, it also disables the `workflow` tool and its engine. `DSH_TOOLS_MODE` is ignored. The startup provider binds stdin EOF to the launcher's bounded successful shutdown. SDK protocol `shutdown`, SIGINT, and SIGTERM retain their owning server or launcher paths; disposal drains the root profile tree and persistence. Stdout is reserved for newline-delimited JSON-RPC frames. The bundle disables model-generated session titles because the SDK exposes no title surface; deterministic fallback titles remain durable without an auxiliary model request. The inherited projection cache checkpoints SDK-created sessions for later consumers; its durability barrier flushes each covered log prefix before publishing the cache row and may split otherwise coalesced JSONL runs. A deployment selects a different complete composition through profile bundles and patch files, not another app bin. diff --git a/packages/bundle/sdk-app/README.zh.md b/packages/bundle/sdk-app/README.zh.md index a24c4f4358..37997aa29a 100644 --- a/packages/bundle/sdk-app/README.zh.md +++ b/packages/bundle/sdk-app/README.zh.md @@ -23,7 +23,7 @@ kind: "package-bundle" ## 使用本包 -`sdk` profile 包含原生桌面工具和模型上下文。默认使用原生工具执行。需要 PTC 时,通过 `--patch` 或 TypeScript、Python SDK 的 `patches` 选项传入[执行器 overlay](../../../apps/cli/config/examples/ptc.yml)。`DSH_TOOLS_MODE` 不生效。 +`sdk` profile 包含原生桌面工具和模型上下文。默认使用原生工具执行。需要 PTC 时,通过 `--patch` 或 TypeScript、Python SDK 的 `patches` 选项传入[执行器 overlay](../../../apps/cli/config/examples/ptc.yml);与 Web 的 `ptc` preset 相同,它还会禁用 `workflow` 工具及其引擎。`DSH_TOOLS_MODE` 不生效。 启动提供方把 stdin EOF 接到启动器的有界成功关闭流程。SDK 协议 `shutdown`、SIGINT 与 SIGTERM 继续使用各自所属的 server 或启动器路径;dispose(资源释放)会排空根 profile 配置树与持久化。stdout 专用于按换行分隔的 JSON-RPC 帧。SDK 不提供 title 表层,因此本组合包禁用模型生成的会话标题;确定性的 fallback title 仍会持久化,但不发起辅助模型请求。继承的投影缓存会为 SDK 创建的会话写入检查点,供后续消费方使用;其持久性屏障会在发布缓存行前 flush 所覆盖的日志前缀,因此可能拆分原本会合并的 JSONL 行。部署通过 profile 组合包与 patch 文件选择另一套完整组合,而不是使用另一个应用 bin。 From 3b663197a825bacc20b4c7f617e7fa577d77ad6f Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 19 Nov 2026 18:40:12 +0800 Subject: [PATCH 17/54] feat(preset): enable plugin management in the Desktop PTC preset The Desktop ptc preset now enables plugin_manager under the same condition as the standard preset: only when the Host provides an editable profile. PTC sessions then manage plugins through run_code bindings, as SDK PTC sessions already do, and the preset guide no longer says plugin management is off. --- apps/cli/tests/web-agent-presets.e2e.ts | 3 +++ packages/boot/plugin-manager/README.i18n.yaml | 4 ++-- packages/boot/plugin-manager/README.md | 2 +- packages/boot/plugin-manager/README.zh.md | 2 +- packages/bundle/web-app/README.i18n.yaml | 4 ++-- packages/bundle/web-app/README.md | 2 +- packages/bundle/web-app/README.zh.md | 2 +- packages/bundle/web-app/presets/ptc.patch.yml | 2 +- .../src/client/guide-locales.ts | 16 +++++++------- .../system-prompt.expected.md | 22 +++++++++++++++++++ .../system-prompt.expected.md | 22 +++++++++++++++++++ .../web/ptc-round/system-prompt.expected.md | 22 +++++++++++++++++++ 12 files changed, 86 insertions(+), 17 deletions(-) diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index ce69dc6d27..d20e00f90d 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -723,6 +723,9 @@ describe('the shipped Web composition', () => { const sdk = assembly.sections.find(section => section.name === 'tools:sdk')?.text ?? '' expect(sdk).not.toContain('str_replace_editor') expect(sdk).toContain('web_search') + // Like `standard`, PTC manages plugins when the Host provides an editable profile. + expect(toolNames(ctx, coded.agent)).toContain('plugin_manager') + expect(sdk).toContain('plugin_manager') // The presentation is this agent's alone: the deployment default is // native, and the session composed from `standard` still sees it. diff --git a/packages/boot/plugin-manager/README.i18n.yaml b/packages/boot/plugin-manager/README.i18n.yaml index 3aaf2eab14..b1769306fa 100644 --- a/packages/boot/plugin-manager/README.i18n.yaml +++ b/packages/boot/plugin-manager/README.i18n.yaml @@ -15,8 +15,8 @@ en: 87679c51aa3693f5 zh: 11684a48a5806afb /deepseek-ai-dsh-plugin-manager/use-this-package: - en: ff51b012b845dd8a - zh: 1c6131057ff98844 + en: ab504ec577c22c52 + zh: 2651009eb331ba71 /deepseek-ai-dsh-plugin-manager/use-this-package/version-compatibility-and-exemptions: en: 483285658e267dd5 zh: 846bec2daac59a96 diff --git a/packages/boot/plugin-manager/README.md b/packages/boot/plugin-manager/README.md index a010e6d6d5..5eb21327c5 100644 --- a/packages/boot/plugin-manager/README.md +++ b/packages/boot/plugin-manager/README.md @@ -28,7 +28,7 @@ Manage the current profile's plugins without editing configuration by hand. Enab ## Use this package -Base-backed profiles provide the manager. In Web, the sidebar's **Plugins** page ([ui-plugin-manager](../../client/ui-plugin-manager/README.md)) manages the profile's bundles and their uniquely addressable rows. Agent-preset rows remain read-only. The `plugin_manager` tool exposes the same operations and is enabled in the Standard and Creator presets. Other Web presets keep it disabled by default. The full SDK profile enables it at profile scope in native/PTC mode; without HMR, saved changes return `restart-required` with `no-hmr` and apply after the runtime restarts. Every tool action requires `danger-full-access` or approval for that call. Under lower sandbox modes, `ask` requests approval; `never`, rejection, cancellation, or an unavailable approval channel prevents execution. An approval leaves the session permission mode unchanged. Profile changes persist across sessions, and installed Host code executes in-process outside the workspace sandbox. Dependency build-script approval remains separate. +Base-backed profiles provide the manager. In Web, the sidebar's **Plugins** page ([ui-plugin-manager](../../client/ui-plugin-manager/README.md)) manages the profile's bundles and their uniquely addressable rows. Agent-preset rows remain read-only. The `plugin_manager` tool exposes the same operations and is enabled in the Standard, PTC, and Creator presets. Other Web presets keep it disabled by default. The full SDK profile enables it at profile scope in native/PTC mode; without HMR, saved changes return `restart-required` with `no-hmr` and apply after the runtime restarts. Every tool action requires `danger-full-access` or approval for that call. Under lower sandbox modes, `ask` requests approval; `never`, rejection, cancellation, or an unavailable approval channel prevents execution. An approval leaves the session permission mode unchanged. Profile changes persist across sessions, and installed Host code executes in-process outside the workspace sandbox. Dependency build-script approval remains separate. For a deployment without agent presets other than the full SDK profile, enable the tool in the profile patch. Package installation/removal requires pnpm on `PATH` or an explicit `pnpmCommand`; a launcher-provided package manager takes precedence. Preset-backed sessions use their preset’s `tool-plugin-manager` entry. diff --git a/packages/boot/plugin-manager/README.zh.md b/packages/boot/plugin-manager/README.zh.md index 8bcea7e870..e47b13bb51 100644 --- a/packages/boot/plugin-manager/README.zh.md +++ b/packages/boot/plugin-manager/README.zh.md @@ -28,7 +28,7 @@ kind: "package-reference" ## 使用本包 -基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在标准和 Creator 预设中启用。其他 Web 预设仍默认禁用。完整 SDK profile 在 profile 作用域为 native/PTC 模式启用此工具;没有 HMR 时,保存的变更返回 `restart-required` 和 `no-hmr`,在运行时重启后应用。每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。 +基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在标准、PTC 和 Creator 预设中启用。其他 Web 预设仍默认禁用。完整 SDK profile 在 profile 作用域为 native/PTC 模式启用此工具;没有 HMR 时,保存的变更返回 `restart-required` 和 `no-hmr`,在运行时重启后应用。每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。 除完整 SDK profile 外,未使用 Agent 预设的部署在 profile patch 中启用工具;安装/移除包要求 PATH 中有 pnpm,或显式配置 `pnpmCommand`,启动器提供的包管理器优先;使用预设的会话由其预设中的 `tool-plugin-manager` 条目控制。 diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index b41e243063..218704f3db 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -30,8 +30,8 @@ en: df205a26b6d49168 zh: e46ed7cf9e06248a /deepseek-ai-dsh-web-app/use-this-package/per-session-agent-setup: - en: 1e33a677bcad2e4e - zh: 7a69b71a6b98c432 + en: 99557925a59aee67 + zh: e2160750bd65505a /deepseek-ai-dsh-web-app/understand-the-implementation: en: 567cf3afa68e6b68 zh: f065cdb56c28d4e6 diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index 68072d35bf..0dcb540a64 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -94,7 +94,7 @@ When you launch `dsh --profile web` over SSH, the URL line still prints but the ### Per-session agent setup -Each browser session selects a shipped preset (`standard` by default). The Agent presets settings page changes the default and edits preset child plugins; saves persist in `$DSH_HOME/profiles/web/cordis.patch.yml`. Standard and Creator enable the plugin-management tool only when the Host provides an editable profile. +Each browser session selects a shipped preset (`standard` by default). The Agent presets settings page changes the default and edits preset child plugins; saves persist in `$DSH_HOME/profiles/web/cordis.patch.yml`. Standard, PTC, and Creator enable the plugin-management tool only when the Host provides an editable profile. Both modes expose read-only runtime inspection through `cordis_inspect`; see [its context effects](../../extensions/tool-cordis/README.md#model-experience). Standard, PTC, and Creator include the `dsh-doc` skill for questions about DSH and requested plugin or preset work. It guides the agent to the installed version's documentation and source. See [Model Experience](#model-experience) for loading and context effects. diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index fb737d61ab..3346c21a94 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -94,7 +94,7 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public- ### 按会话的 agent 设置 -每个浏览器会话选择一个随发行版交付的 preset(默认 `standard`)。Agent 预设设置页可更改默认项并编辑预设的子插件;保存结果持久化到 `$DSH_HOME/profiles/web/cordis.patch.yml`。只有 Host 提供可编辑的 profile 时,标准模式和 Creator 才会启用插件管理工具。 +每个浏览器会话选择一个随发行版交付的 preset(默认 `standard`)。Agent 预设设置页可更改默认项并编辑预设的子插件;保存结果持久化到 `$DSH_HOME/profiles/web/cordis.patch.yml`。只有 Host 提供可编辑的 profile 时,标准模式、PTC 模式和 Creator 才会启用插件管理工具。 两种模式均通过 `cordis_inspect` 提供只读运行时检查;参见[其上下文影响](../../extensions/tool-cordis/README.zh.md#model-experience)。标准模式、PTC 模式和创造模式包含 `dsh-doc` skill,用于 DSH 相关问题以及你要求的插件或预设工作。该 skill 引导 agent 查阅已安装版本的文档和源码。加载方式及其对上下文的影响参见[模型体验](#model-experience)。 diff --git a/packages/bundle/web-app/presets/ptc.patch.yml b/packages/bundle/web-app/presets/ptc.patch.yml index dd935b1edd..8de9ed6727 100644 --- a/packages/bundle/web-app/presets/ptc.patch.yml +++ b/packages/bundle/web-app/presets/ptc.patch.yml @@ -135,7 +135,7 @@ name: '@deepseek-ai/dsh-tool-office' - id: tool-plugin-manager name: '@deepseek-ai/dsh-plugin-manager/tools' - disabled: true + disabled: !!js "!ctx.get('profileContext')" - id: tool-plugin-market name: '@deepseek-ai/dsh-plugin-market/tools' disabled: true diff --git a/packages/client/ui-agent-preset/src/client/guide-locales.ts b/packages/client/ui-agent-preset/src/client/guide-locales.ts index 2401935497..3c4af46d2c 100644 --- a/packages/client/ui-agent-preset/src/client/guide-locales.ts +++ b/packages/client/ui-agent-preset/src/client/guide-locales.ts @@ -30,7 +30,7 @@ export const guideEn = { '### What reaches the model', 'Tool results first reach the program, which can filter and combine them. The model receives what the program prints or returns; image results are attached separately. Nested tool calls are still recorded and remain subject to tool permissions.', '### Compared with Standard mode', - 'Both modes can handle coding and batch tasks. Standard mode exposes individual tools directly; PTC organizes tool calls in code. The current PTC preset leaves the workflow and plugin management tools disabled. Speed and token use depend on the task and how the program handles its results.', + 'Both modes can handle coding and batch tasks. Standard mode exposes individual tools directly; PTC organizes tool calls in code. The current PTC preset leaves the workflow tool disabled. Speed and token use depend on the task and how the program handles its results.', ].join('\n\n'), guidePtcUsage: [ '### Check a set of configuration files', @@ -109,7 +109,7 @@ export const guideZh: Record = { '### 哪些结果交给模型', '工具返回的数据先交给程序,经过筛选、计算或合并,再通过输出或返回值交给模型;图片结果会另行附加。程序中的工具调用仍会被记录,也仍受工具权限约束。', '### 与标准模式的区别', - '两种模式都能编程、批量处理文件。标准模式直接向模型提供各个工具;PTC 让模型用代码组织工具调用。当前 PTC 预设未启用 workflow 和插件管理工具。速度和 token 用量取决于具体任务与结果处理方式。', + '两种模式都能编程、批量处理文件。标准模式直接向模型提供各个工具;PTC 让模型用代码组织工具调用。当前 PTC 预设未启用 workflow 工具。速度和 token 用量取决于具体任务与结果处理方式。', ].join('\n\n'), guidePtcUsage: [ '### 批量检查配置文件', @@ -166,7 +166,7 @@ export const guideJa = { 'guideStandardExplanation': '### 仕組み\n\nエージェントはツールを直接呼び出してファイルの読み取りや編集、検索、ターミナルコマンドの実行を行います。スキル、計画、目標、サブエージェント、ワークフロー、プラグイン管理、読み取り専用のランタイム検査、コンテキストの圧縮に対応しています。\n\n### 選ぶべき場面\n\n日々のコーディング、ファイル作業、調査はまずここから始めてください。標準モードではスクリプトの作成やファイルの一括処理も行えます。PTC はツール呼び出しの構成を変えるものであり、一括処理に必須ではありません。', 'guideStandardUsage': '### バグを修正する\n\n> 検索フォームを二度送信すると結果が消える原因を調べてください。修正して関連するテストを実行し、原因と変更内容を説明してください。\n\n期待される出力: コードの変更、関連するテスト結果、原因の説明。\n\n### プロジェクトのメモを整理する\n\n> このプロジェクト内の Markdown メモを読み、合意された決定と未解決の課題を、元ファイルへのリンク付きで要約してください。\n\n期待される出力: 元のメモと照合できる参照付きの要約。', 'guidePtcIntro': '新しいタスクを始めるときは PTC モードを選びます。入力ファイル、処理ルール、出力形式を指定してください。コードはエージェントが書きます。', - 'guidePtcExplanation': '### ツールの呼び出され方\n\nPTC は Programmatic Tool Calling の略です。この組み込みプリセットでは、エージェントは run_code を使い、生成された SDK 経由でツールを呼び出す TypeScript プログラムを書きます。プログラムではループ、条件分岐、エラー処理、必要に応じて並行呼び出しを利用できます。\n\n### モデルに届くもの\n\nツールの結果はまずプログラムに届き、そこでフィルタリングや結合ができます。モデルが受け取るのはプログラムが出力または返した内容です。画像の結果は別途添付されます。ネストされたツール呼び出しも記録され、ツール権限の対象のままです。\n\n### 標準モードとの比較\n\nどちらのモードもコーディングや一括処理のタスクを扱えます。標準モードは個々のツールを直接公開し、PTC はツール呼び出しをコードで整理します。現在の PTC プリセットではワークフローとプラグイン管理ツールが無効になっています。速度とトークン消費はタスクやプログラムの結果の扱い方によって変わります。', + 'guidePtcExplanation': '### ツールの呼び出され方\n\nPTC は Programmatic Tool Calling の略です。この組み込みプリセットでは、エージェントは run_code を使い、生成された SDK 経由でツールを呼び出す TypeScript プログラムを書きます。プログラムではループ、条件分岐、エラー処理、必要に応じて並行呼び出しを利用できます。\n\n### モデルに届くもの\n\nツールの結果はまずプログラムに届き、そこでフィルタリングや結合ができます。モデルが受け取るのはプログラムが出力または返した内容です。画像の結果は別途添付されます。ネストされたツール呼び出しも記録され、ツール権限の対象のままです。\n\n### 標準モードとの比較\n\nどちらのモードもコーディングや一括処理のタスクを扱えます。標準モードは個々のツールを直接公開し、PTC はツール呼び出しをコードで整理します。現在の PTC プリセットではワークフローツールが無効になっています。速度とトークン消費はタスクやプログラムの結果の扱い方によって変わります。', 'guidePtcUsage': '### 設定ファイルのセットを検証する\n\n> configs/ 内のすべての JSON ファイルを検査してください。schema.json に基づき、必須フィールドの欠落と無効な値を一覧にしてください。問題ごとに 1 行の CSV を保存してください。読み取れないファイルもレポートに含め、残りの検査は続けてください。元のファイルは変更しないでください。\n\n期待される出力: 問題の要約と CSV レポート。プログラムは同じ検査を繰り返し、個々の失敗に対処し、結果を集約できます。\n\n### エラーログを要約する\n\n> logs/ 内のログファイルを分析してください。エラーをサービスとエラー種別でグループ化し、頻度上位 10 グループと各 1 件の例を示してください。完全な件数を CSV に保存してください。\n\n期待される出力: 上位のエラーグループと完全な件数表。中間データは要約がモデルに届く前にプログラム内で集約できます。', 'guideMinimalIntro': '新しいタスクには最小モードを選びます。比較を行う場合は、モデル、権限、入力、開始時のワークスペース状態を実行間で一定に保ってください。', 'guideMinimalExplanation': '### 含まれるもの\n\n永続的なシェルツール 1 つ、read_image、固定のシステムプロンプト。画像の読み取りには画像対応モデルが必要です。古い履歴はコンテキストの負荷に応じて自動的に圧縮されます。エージェントがアイドル状態のときに /compact を使えば手動で圧縮できます。この組み込みプリセットはスキル、計画、標準のランタイムコンテキストを読み込みません。\n\n### 選ぶべき場面\n\n実験や比較のベースラインとして使用します。シェルコマンド経由でファイルの読み取りやスクリプトの実行はできますが、長いタスクを管理するための組み込み手段は少なくなります。ツールが少ないからといって、初心者にとって必ずしも簡単になるわけではありません。', @@ -207,7 +207,7 @@ export const guideEs = { '### Lo que llega al modelo', 'Los resultados de la herramienta llegan primero al programa, que puede filtrarlos y combinarlos. El modelo recibe lo que el programa imprime o devuelve; Los resultados de la imagen se adjuntan por separado. Las llamadas a herramientas anidadas aún se registran y permanecen sujetas a los permisos de la herramienta.', '### Comparado con el modo Estándar', - 'Ambos modos pueden manejar tareas de codificación y por lotes. El modo estándar expone herramientas individuales directamente; PTC organiza llamadas a herramientas en código. El ajuste preestablecido actual PTC deja las herramientas de administración de complementos y flujo de trabajo deshabilitadas. La velocidad y el uso de tokens dependen de la tarea y de cómo el programa maneja sus resultados.', + 'Ambos modos pueden manejar tareas de codificación y por lotes. El modo estándar expone herramientas individuales directamente; PTC organiza llamadas a herramientas en código. El ajuste preestablecido actual PTC deja deshabilitada la herramienta de flujo de trabajo. La velocidad y el uso de tokens dependen de la tarea y de cómo el programa maneja sus resultados.', ].join('\n\n\n\n'), guidePtcUsage: [ '### Verifique un conjunto de archivos de configuración', @@ -282,7 +282,7 @@ export const guideFr = { '### Ce qui arrive au modèle', "Les résultats des outils parviennent d’abord au programme, qui peut les filtrer et les combiner. Le modèle reçoit ce que le programme imprime ou renvoie ; les résultats des images sont joints séparément. Les appels d'outils imbriqués sont toujours enregistrés et restent soumis aux autorisations de l'outil.", '### Par rapport au mode Standard', - "Les deux modes peuvent gérer les tâches de codage et par lots. Le mode standard expose directement les outils individuels ; PTC organise les appels d'outils dans le code. Le préréglage PTC actuel laisse les outils de gestion de flux de travail et de plugins désactivés. La vitesse et l'utilisation des jetons dépendent de la tâche et de la manière dont le programme gère ses résultats.", + "Les deux modes peuvent gérer les tâches de codage et par lots. Le mode standard expose directement les outils individuels ; PTC organise les appels d'outils dans le code. Le préréglage PTC actuel laisse l’outil de flux de travail désactivé. La vitesse et l'utilisation des jetons dépendent de la tâche et de la manière dont le programme gère ses résultats.", ].join('\n\n\n\n'), guidePtcUsage: [ '### Vérifier un ensemble de fichiers de configuration', @@ -357,7 +357,7 @@ export const guideDe = { '### Was das Modell erreicht', 'Werkzeugergebnisse gelangen zunächst in das Programm, das diese filtern und kombinieren kann. Das Modell empfängt, was das Programm ausgibt oder zurückgibt; Bildergebnisse sind separat beigefügt. Verschachtelte Werkzeugaufrufe werden weiterhin aufgezeichnet und unterliegen weiterhin den Werkzeugberechtigungen.', '### Im Vergleich zum Standardmodus', - 'Beide Modi können Codierungs- und Batch-Aufgaben bewältigen. Im Standardmodus werden einzelne Tools direkt verfügbar gemacht. PTC organisiert Toolaufrufe im Code. Die aktuelle Voreinstellung PTC lässt die Workflow- und Plugin-Verwaltungstools deaktiviert. Geschwindigkeit und Token-Nutzung hängen von der Aufgabe ab und davon, wie das Programm mit seinen Ergebnissen umgeht.', + 'Beide Modi können Codierungs- und Batch-Aufgaben bewältigen. Im Standardmodus werden einzelne Tools direkt verfügbar gemacht. PTC organisiert Toolaufrufe im Code. Die aktuelle Voreinstellung PTC lässt das Workflow-Tool deaktiviert. Geschwindigkeit und Token-Nutzung hängen von der Aufgabe ab und davon, wie das Programm mit seinen Ergebnissen umgeht.', ].join('\n\n\n\n'), guidePtcUsage: [ '### Überprüfen Sie eine Reihe von Konfigurationsdateien', @@ -432,7 +432,7 @@ export const guideRu = { '### Что достигает модели', 'Результаты инструмента сначала поступают в программу, которая может их фильтровать и комбинировать. Модель получает то, что программа печатает или возвращает; Результаты изображения прилагаются отдельно. Вызовы вложенных инструментов по-прежнему записываются, и для них действуют разрешения инструмента.', '### По сравнению со стандартным режимом', - 'Оба режима могут выполнять кодирование и пакетные задачи. Стандартный режим напрямую предоставляет доступ к отдельным инструментам; PTC организует вызовы инструментов в коде. Текущая предустановка PTC оставляет инструменты управления рабочим процессом и плагинами отключенными. Скорость и использование токенов зависят от задачи и того, как программа обрабатывает ее результаты.', + 'Оба режима могут выполнять кодирование и пакетные задачи. Стандартный режим напрямую предоставляет доступ к отдельным инструментам; PTC организует вызовы инструментов в коде. Текущая предустановка PTC оставляет инструмент рабочего процесса отключенным. Скорость и использование токенов зависят от задачи и того, как программа обрабатывает ее результаты.', ].join('\n\n\n\n'), guidePtcUsage: [ '### Проверка набора файлов конфигурации', @@ -507,7 +507,7 @@ export const guidePt = { '### O que chega ao modelo', 'Os resultados da ferramenta chegam primeiro ao programa, que pode filtrá-los e combiná-los. O modelo recebe o que o programa imprime ou retorna; os resultados da imagem são anexados separadamente. As chamadas de ferramentas aninhadas ainda são gravadas e permanecem sujeitas às permissões da ferramenta.', '### Comparado com o modo Padrão', - 'Ambos os modos podem lidar com tarefas de codificação e em lote. O modo padrão expõe ferramentas individuais diretamente; PTC organiza chamadas de ferramentas em código. A predefinição PTC atual deixa o fluxo de trabalho e as ferramentas de gerenciamento de plug-ins desativados. A velocidade e o uso do token dependem da tarefa e de como o programa lida com seus resultados.', + 'Ambos os modos podem lidar com tarefas de codificação e em lote. O modo padrão expõe ferramentas individuais diretamente; PTC organiza chamadas de ferramentas em código. A predefinição PTC atual deixa a ferramenta de fluxo de trabalho desativada. A velocidade e o uso do token dependem da tarefa e de como o programa lida com seus resultados.', ].join('\n\n\n\n'), guidePtcUsage: [ '### Verifique um conjunto de arquivos de configuração', diff --git a/snapshots/web/official-subagent-bundle/system-prompt.expected.md b/snapshots/web/official-subagent-bundle/system-prompt.expected.md index 522e00a6cf..1908330c8f 100644 --- a/snapshots/web/official-subagent-bundle/system-prompt.expected.md +++ b/snapshots/web/official-subagent-bundle/system-prompt.expected.md @@ -160,6 +160,27 @@ interface ToolArgsMap { /** Exact model id; requires provider. */ model?: string; } & Record; + /** List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. The application field of a change result is authoritative: applied means the change is in effect and needs no restart; any other value carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one. */ + plugin_manager: { + /** Management operation. */ + action: "list_plugins" | "list_bundles" | "set_plugin" | "set_bundle" | "install_bundle" | "remove_bundle" | "list_version_exemptions" | "set_version_exemption"; + /** Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle. */ + target?: string; + /** Required for set operations; defaults to true for installation. For set_version_exemption, true grants and false revokes. */ + enabled?: boolean; + /** For set_version_exemption: exact DSH version from list_version_exemptions. Target must be the manifest package-name@version, not an alias or version range. */ + runtimeVersion?: string; + /** For granting an exemption: true only after warning the user about possible crashes and data loss and receiving explicit permission for this exact plugin/runtime pair. General installation permission is not enough. */ + acceptRisk?: boolean; + /** For install_bundle: pass names from pendingBuilds only after the user explicitly approves running their install scripts in the conversation. This grants persistent permission for this profile. */ + approvedBuilds?: string[]; + /** For install_bundle: the npm registry URL asked first, when the user names one; otherwise the configured registry is asked, and its configured fallbacks while a registry is unreachable. */ + registry?: string; + /** Zero-based list offset; defaults to 0. */ + offset?: number; + /** List page size, from 1 to 100; defaults to 25. */ + limit?: number; + } & Record; /** Declare existing files as final deliverables for the user. Hosts may show presented files only after your turn ends, so call it once the files are final. If the user needs to review files earlier, such as before a tool call that waits for their answer, link them in your message instead. Use it when the user needs a separate file, especially Office documents, spreadsheets, and slide decks; prefer your final response when that suffices. The user opens the current files; their contents are not copied. */ present: { /** Usually the 1-2 most important deliverables; at most 4 per call. */ @@ -464,6 +485,7 @@ interface ToolOutputMap { })[]; }; list_subagent_models: string; + plugin_manager: string; present: { turn: number; files: { diff --git a/snapshots/web/optional-string-editor/system-prompt.expected.md b/snapshots/web/optional-string-editor/system-prompt.expected.md index cb149f93ad..6ac932a5b7 100644 --- a/snapshots/web/optional-string-editor/system-prompt.expected.md +++ b/snapshots/web/optional-string-editor/system-prompt.expected.md @@ -160,6 +160,27 @@ interface ToolArgsMap { /** Exact model id; requires provider. */ model?: string; } & Record; + /** List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. The application field of a change result is authoritative: applied means the change is in effect and needs no restart; any other value carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one. */ + plugin_manager: { + /** Management operation. */ + action: "list_plugins" | "list_bundles" | "set_plugin" | "set_bundle" | "install_bundle" | "remove_bundle" | "list_version_exemptions" | "set_version_exemption"; + /** Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle. */ + target?: string; + /** Required for set operations; defaults to true for installation. For set_version_exemption, true grants and false revokes. */ + enabled?: boolean; + /** For set_version_exemption: exact DSH version from list_version_exemptions. Target must be the manifest package-name@version, not an alias or version range. */ + runtimeVersion?: string; + /** For granting an exemption: true only after warning the user about possible crashes and data loss and receiving explicit permission for this exact plugin/runtime pair. General installation permission is not enough. */ + acceptRisk?: boolean; + /** For install_bundle: pass names from pendingBuilds only after the user explicitly approves running their install scripts in the conversation. This grants persistent permission for this profile. */ + approvedBuilds?: string[]; + /** For install_bundle: the npm registry URL asked first, when the user names one; otherwise the configured registry is asked, and its configured fallbacks while a registry is unreachable. */ + registry?: string; + /** Zero-based list offset; defaults to 0. */ + offset?: number; + /** List page size, from 1 to 100; defaults to 25. */ + limit?: number; + } & Record; /** Declare existing files as final deliverables for the user. Hosts may show presented files only after your turn ends, so call it once the files are final. If the user needs to review files earlier, such as before a tool call that waits for their answer, link them in your message instead. Use it when the user needs a separate file, especially Office documents, spreadsheets, and slide decks; prefer your final response when that suffices. The user opens the current files; their contents are not copied. */ present: { /** Usually the 1-2 most important deliverables; at most 4 per call. */ @@ -472,6 +493,7 @@ interface ToolOutputMap { })[]; }; list_subagent_models: string; + plugin_manager: string; present: { turn: number; files: { diff --git a/snapshots/web/ptc-round/system-prompt.expected.md b/snapshots/web/ptc-round/system-prompt.expected.md index 938887a755..597b378fe8 100644 --- a/snapshots/web/ptc-round/system-prompt.expected.md +++ b/snapshots/web/ptc-round/system-prompt.expected.md @@ -160,6 +160,27 @@ interface ToolArgsMap { /** Exact model id; requires provider. */ model?: string; } & Record; + /** List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. The application field of a change result is authoritative: applied means the change is in effect and needs no restart; any other value carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one. */ + plugin_manager: { + /** Management operation. */ + action: "list_plugins" | "list_bundles" | "set_plugin" | "set_bundle" | "install_bundle" | "remove_bundle" | "list_version_exemptions" | "set_version_exemption"; + /** Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle. */ + target?: string; + /** Required for set operations; defaults to true for installation. For set_version_exemption, true grants and false revokes. */ + enabled?: boolean; + /** For set_version_exemption: exact DSH version from list_version_exemptions. Target must be the manifest package-name@version, not an alias or version range. */ + runtimeVersion?: string; + /** For granting an exemption: true only after warning the user about possible crashes and data loss and receiving explicit permission for this exact plugin/runtime pair. General installation permission is not enough. */ + acceptRisk?: boolean; + /** For install_bundle: pass names from pendingBuilds only after the user explicitly approves running their install scripts in the conversation. This grants persistent permission for this profile. */ + approvedBuilds?: string[]; + /** For install_bundle: the npm registry URL asked first, when the user names one; otherwise the configured registry is asked, and its configured fallbacks while a registry is unreachable. */ + registry?: string; + /** Zero-based list offset; defaults to 0. */ + offset?: number; + /** List page size, from 1 to 100; defaults to 25. */ + limit?: number; + } & Record; /** Declare existing files as final deliverables for the user. Hosts may show presented files only after your turn ends, so call it once the files are final. If the user needs to review files earlier, such as before a tool call that waits for their answer, link them in your message instead. Use it when the user needs a separate file, especially Office documents, spreadsheets, and slide decks; prefer your final response when that suffices. The user opens the current files; their contents are not copied. */ present: { /** Usually the 1-2 most important deliverables; at most 4 per call. */ @@ -455,6 +476,7 @@ interface ToolOutputMap { })[]; }; list_subagent_models: string; + plugin_manager: string; present: { turn: number; files: { From e36f37e5e4cf4ad871491a959c82a9b5df85a71a Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 19 Nov 2026 19:51:31 +0800 Subject: [PATCH 18/54] test(sdk): drop the PTC tool parity exceptions that the aligned presets retire --- apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts | 3 +-- apps/cli/tests/profiles/sdk/tool-parity.ts | 4 ---- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts index 3faedc4a74..ca858d5871 100644 --- a/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts +++ b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts @@ -136,8 +136,7 @@ it.for(['standard', 'ptc'] as const)('compares the shipped %s tool sets and perm expect(sdk.names).toContain('plugin_manager') const optOut = await collect('sdk', mode, [{ id: 'tool-plugin-manager', disabled: true }]) expect(optOut.names).not.toContain('plugin_manager') - expect(() => { assertToolParity(mode, optOut.names, desktop.names) }).toThrow( - mode === 'ptc' ? 'Stale exceptions: sdk:plugin_manager' : 'Missing from SDK: plugin_manager') + expect(() => { assertToolParity(mode, optOut.names, desktop.names) }).toThrow('Missing from SDK: plugin_manager') }) it.for(['standard', 'ptc'] as const)('detects missing shared tools in %s', async (mode, test) => { diff --git a/apps/cli/tests/profiles/sdk/tool-parity.ts b/apps/cli/tests/profiles/sdk/tool-parity.ts index 0b6299051e..77190c53dc 100644 --- a/apps/cli/tests/profiles/sdk/tool-parity.ts +++ b/apps/cli/tests/profiles/sdk/tool-parity.ts @@ -18,10 +18,6 @@ export const toolParityExceptions: Record = { ptc: [ { tool: 'list_subagent_models', side: 'desktop', reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }, - { tool: 'plugin_manager', side: 'sdk', - reason: 'SDK PTC changes are persisted for restart without replacing active bindings because HMR is disabled; Desktop PTC excludes management in its HMR-enabled preset.' }, - { tool: 'workflow', side: 'sdk', - reason: 'The SDK PTC overlay changes only the executor so existing base workflow callers keep working; Desktop PTC uses run_code orchestration and omits the separate workflow surface.' }, ], } From cb820dd34dfa41eea3c6c2b5a329303c57474d81 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 19 Nov 2026 19:51:32 +0800 Subject: [PATCH 19/54] docs: list PTC among the modes that provide Plugin Manager --- .../2026-09-16-creator-persistent-plugin-management.i18n.yaml | 4 ++-- .../2026-09-16-creator-persistent-plugin-management.md | 2 +- .../2026-09-16-creator-persistent-plugin-management.zh.md | 2 +- docs/user/develop/practice/dynamic-cordis.i18n.yaml | 4 ++-- docs/user/develop/practice/dynamic-cordis.md | 2 +- docs/user/develop/practice/dynamic-cordis.zh.md | 2 +- packages/extensions/README.i18n.yaml | 4 ++-- packages/extensions/README.md | 2 +- packages/extensions/README.zh.md | 2 +- 9 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml index 6f1e439bdf..cf82708a64 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml @@ -9,8 +9,8 @@ en: 44615a7a0939054e zh: b8efa721321ba0d7 /agent-note-creator-mode-installs-persistent-plugin-bundles/decision: - en: 013a2088d8f8c435 - zh: 5491ff817716696b + en: bc4c98ac82cae462 + zh: 17a1588f93b056a7 /agent-note-creator-mode-installs-persistent-plugin-bundles/alternatives-considered: en: af527d8aabdfd59c zh: 34388da992d2ab56 diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md index f831e40520..69e87f24c8 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md @@ -12,7 +12,7 @@ Agents need to install capabilities and use them during the same conversation. G Creator mode enables the existing `plugin_manager` tool. Agents author packages and Loader YAML patches as workspace files, then install them through `install_bundle`. An MCP connection is a configuration-only bundle inserting the installed `dsh-mcp-client`; a UI bundle includes a Host entry and a Client artifact. Profile locking, package installation, enablement and HMR remain owned by the existing manager. The entire management tool requires `danger-full-access` or approval for one call: profile changes can load code with host permissions and affect other sessions. Each execution, including inventory reads, uses the shared sandbox escalation helper and approval service before accessing the manager. Under lower sandbox modes, `ask` requests approval and `never` denies; a full-access session needs no additional approval. A grant does not change session permissions, but its profile changes persist. This keeps shell-equivalent Host access explicit without requiring a permanent session-wide elevation. Human-operated Web and CLI controls retain their existing behavior. -The default Standard mode enables the same tool under the same profile condition and approval gate. Without it, Standard sessions did not install plugins directly and spent extra turns and tokens working around the missing tool; the change also moves Standard and Creator toward one capability set. A full-access Standard session can therefore install Host code without a separate prompt, as its shell already can. PTC and Minimal keep the tool disabled. +The default Standard mode enables the same tool under the same profile condition and approval gate. Without it, Standard sessions did not install plugins directly and spent extra turns and tokens working around the missing tool; the change also moves Standard and Creator toward one capability set. A full-access Standard session can therefore install Host code without a separate prompt, as its shell already can. PTC enables it under the same condition, and Minimal keeps the tool disabled. Standard and Creator expose one read-only Cordis inspection tool, `cordis_inspect`. Omitting `query` discovers providers; supplying `query` reads one declared method. The shared entry keeps runtime discovery available in the default mode without duplicating tool descriptions. Generated-code define/run/stop/undefine and dynamic self-inspection tool APIs are absent. Existing runtime and Client consumers retain their services; historical session cards remain readable. This supersedes only the model-facing mutation workflow in the [self-referential toolset reference](../../../../packages/extensions/cordis-host-runner/README.md); its runtime ownership and sandbox rationale remain independently relevant. The [profile transaction decision](2026-09-14-current-profile-plugin-management.md) continues to govern locking, package installation, and partial failures. diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md index b3b686385f..c450d35a9e 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md @@ -12,7 +12,7 @@ agent 需要安装能力并在同一段对话中使用。生成代码工具在 创造模式启用现有的 `plugin_manager` 工具。agent 将包和 Loader YAML patch 写入工作区文件,再通过 `install_bundle` 安装。MCP 连接是插入已安装 `dsh-mcp-client` 的纯配置组合包;UI 组合包包含 Host 入口和 Client 产物。profile 锁、包安装、启停和 HMR 继续由现有管理器负责。 整个管理工具要求 `danger-full-access` 或单次调用的批准:profile 变更能以宿主权限加载代码,并影响其他会话。每次执行(包括查询列表)都会先使用共享沙箱提权函数和审批服务,再访问管理器。在较低沙箱模式下,`ask` 请求审批,`never` 拒绝;完整权限会话无需额外审批。批准不改变会话权限,但本次操作的 profile 变更会持久化。这让与 shell 等价的宿主访问需要明确授权,同时不必永久提升整个会话的权限。由用户直接操作的 Web 和 CLI 控件保持原有行为。 -默认的标准模式以相同的 profile 条件和审批门槛启用同一工具。缺少该工具时,标准模式会话不会直接安装插件,而要额外花费轮次和 token 绕过;此改动也让标准模式和创造模式朝同一能力集收敛。因此,完整权限的标准模式会话无需单独审批即可安装 Host 代码,与其 shell 已有的能力一致。PTC 和 Minimal 仍禁用该工具。 +默认的标准模式以相同的 profile 条件和审批门槛启用同一工具。缺少该工具时,标准模式会话不会直接安装插件,而要额外花费轮次和 token 绕过;此改动也让标准模式和创造模式朝同一能力集收敛。因此,完整权限的标准模式会话无需单独审批即可安装 Host 代码,与其 shell 已有的能力一致。PTC 以相同条件启用该工具,Minimal 仍禁用。 标准模式和创造模式提供一个只读 Cordis 检查工具 `cordis_inspect`。省略 `query` 以发现 provider;提供 `query` 以读取一个已声明的方法。共用此入口使默认模式能够进行运行时发现,同时避免重复的工具描述。不再提供生成代码的 define/run/stop/undefine 和动态自省工具 API。现有运行时和 Client 消费者保留其服务;历史会话卡片仍然可读。这仅取代[自引用工具集参考](../../../../packages/extensions/cordis-host-runner/README.zh.md)中的模型侧变更流程;其运行时所有权和沙箱依据仍有独立价值。[profile 事务决策](2026-09-14-current-profile-plugin-management.zh.md)继续规定锁、包安装和部分失败行为。 diff --git a/docs/user/develop/practice/dynamic-cordis.i18n.yaml b/docs/user/develop/practice/dynamic-cordis.i18n.yaml index 9e99bfb6fd..629f387443 100644 --- a/docs/user/develop/practice/dynamic-cordis.i18n.yaml +++ b/docs/user/develop/practice/dynamic-cordis.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/user/develop/practice/dynamic-cordis.md /configure-persistent-plugins-from-a-prompt: - en: e61e42a805142826 - zh: da51aa93305f2a3c + en: a1d683397b43c3f8 + zh: 77faaf707f8be306 /configure-persistent-plugins-from-a-prompt/connect-an-mcp-server: en: f9fefda94ba8a005 zh: f1a9a977a0732fc0 diff --git a/docs/user/develop/practice/dynamic-cordis.md b/docs/user/develop/practice/dynamic-cordis.md index ea805bc92f..b8219c917b 100644 --- a/docs/user/develop/practice/dynamic-cordis.md +++ b/docs/user/develop/practice/dynamic-cordis.md @@ -2,7 +2,7 @@ English | [中文](dynamic-cordis.zh.md) -Standard and Creator modes provide [Plugin Manager](../../../../packages/boot/plugin-manager/README.md) and read-only [runtime inspection](../../../../packages/extensions/tool-cordis/README.md). Plugin configuration belongs to the current profile, affects its sessions, and survives process restarts. +Standard, PTC, and Creator modes provide [Plugin Manager](../../../../packages/boot/plugin-manager/README.md); Standard and Creator also provide read-only [runtime inspection](../../../../packages/extensions/tool-cordis/README.md). Plugin configuration belongs to the current profile, affects its sessions, and survives process restarts. ## Connect an MCP server diff --git a/docs/user/develop/practice/dynamic-cordis.zh.md b/docs/user/develop/practice/dynamic-cordis.zh.md index 5c1d10bd56..060282bd77 100644 --- a/docs/user/develop/practice/dynamic-cordis.zh.md +++ b/docs/user/develop/practice/dynamic-cordis.zh.md @@ -2,7 +2,7 @@ [English](dynamic-cordis.md) | 中文 -标准模式和创造模式提供 [Plugin Manager](../../../../packages/boot/plugin-manager/README.zh.md) 和只读[运行时检查](../../../../packages/extensions/tool-cordis/README.zh.md)。插件配置属于当前 profile,影响其会话,并在进程重启后保留。 +标准模式、PTC 模式和创造模式提供 [Plugin Manager](../../../../packages/boot/plugin-manager/README.zh.md);标准模式和创造模式还提供只读[运行时检查](../../../../packages/extensions/tool-cordis/README.zh.md)。插件配置属于当前 profile,影响其会话,并在进程重启后保留。 ## 连接 MCP 服务器 diff --git a/packages/extensions/README.i18n.yaml b/packages/extensions/README.i18n.yaml index c4cbdd3559..693ae0657a 100644 --- a/packages/extensions/README.i18n.yaml +++ b/packages/extensions/README.i18n.yaml @@ -9,8 +9,8 @@ en: 3629b9b795f2e174 zh: 30dbc9ce39af47c4 /packages-extensions/summary: - en: f2af0050da10ada3 - zh: 177da09eb60caa9a + en: b48e31899d4a59be + zh: e35be15b7cd41060 /packages-extensions/table-of-contents: en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 diff --git a/packages/extensions/README.md b/packages/extensions/README.md index 0029d3b79a..80b3403e6e 100644 --- a/packages/extensions/README.md +++ b/packages/extensions/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -The extensions group provides read-only runtime API discovery for agents, process-local runners for programmatic and browser consumers, and historical generated-plugin cards. Standard and Creator modes install persistent plugins through [Plugin Manager](../boot/plugin-manager/README.md). Choose a child package for inspection, Host execution, Client execution, or browser controls. +The extensions group provides read-only runtime API discovery for agents, process-local runners for programmatic and browser consumers, and historical generated-plugin cards. Standard, PTC, and Creator modes install persistent plugins through [Plugin Manager](../boot/plugin-manager/README.md). Choose a child package for inspection, Host execution, Client execution, or browser controls. ## Table of Contents diff --git a/packages/extensions/README.zh.md b/packages/extensions/README.zh.md index 90d61acb91..2dc2a588b3 100644 --- a/packages/extensions/README.zh.md +++ b/packages/extensions/README.zh.md @@ -9,7 +9,7 @@ kind: "package-group" ## 概述 -extensions 组为 agent 提供只读运行时 API 发现、供程序和浏览器消费者使用的进程内 runner,以及历史生成插件卡片。标准模式和 Creator 模式通过 [Plugin Manager](../boot/plugin-manager/README.zh.md) 安装持久化插件。按需选择检查、Host 执行、Client 执行或浏览器控件子包。 +extensions 组为 agent 提供只读运行时 API 发现、供程序和浏览器消费者使用的进程内 runner,以及历史生成插件卡片。标准模式、PTC 模式和 Creator 模式通过 [Plugin Manager](../boot/plugin-manager/README.zh.md) 安装持久化插件。按需选择检查、Host 执行、Client 执行或浏览器控件子包。 ## 目录 From c6b8146b513b8226644cdebb9a895813cd2fcc9e Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:28:04 +0800 Subject: [PATCH 20/54] feat(ptc-runtime-node): default executionMode to persistent-in-memory with the scoped REPL --- ...09-11-sandboxed-node-ptc-runtime.i18n.yaml | 8 +++--- .../2026-09-11-sandboxed-node-ptc-runtime.md | 4 +-- ...026-09-11-sandboxed-node-ptc-runtime.zh.md | 4 +-- ...09-23-best-effort-persistent-ptc.i18n.yaml | 4 +-- .../2026-09-23-best-effort-persistent-ptc.md | 2 +- ...026-09-23-best-effort-persistent-ptc.zh.md | 2 +- .../2026-11-09-cua-program-tool.i18n.yaml | 4 +-- .../2026-11-09-cua-program-tool.md | 2 +- .../2026-11-09-cua-program-tool.zh.md | 2 +- apps/web/tests/bundle-platform.e2e.ts | 4 +-- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/tool-catalog.i18n.yaml | 4 +-- docs/tool-catalog.md | 4 +-- docs/tool-catalog.zh.md | 4 +-- .../ptc-default-scoped-repl/guide.i18n.yaml | 16 +++++++++++ .../ptc-default-scoped-repl/guide.md | 27 +++++++++++++++++++ .../ptc-default-scoped-repl/guide.zh.md | 27 +++++++++++++++++++ .../core/tool-executor-ptc/README.i18n.yaml | 4 +-- packages/core/tool-executor-ptc/README.md | 2 +- packages/core/tool-executor-ptc/README.zh.md | 2 +- .../ptc-runtime-node/README.i18n.yaml | 16 +++++------ .../ptc-runtime/ptc-runtime-node/README.md | 12 ++++----- .../ptc-runtime/ptc-runtime-node/README.zh.md | 12 ++++----- .../ptc-runtime-node/src/config.ts | 4 +-- .../ptc-runtime-node/src/configuration.ts | 2 +- .../tests/execution-mode.spec.ts | 6 ++--- 27 files changed, 126 insertions(+), 56 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.zh.md diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml index be10ec257c..c2187c2371 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml @@ -9,8 +9,8 @@ en: 66ac3d7ce7eb8e15 zh: abb9d41b71900bbf /agent-note-sandboxed-node-execution-for-ptc/decision: - en: d6b9c22603a4f933 - zh: f324b91830078d9a + en: 3dac0013b3577b16 + zh: 066e9b55fc3f457e /agent-note-sandboxed-node-execution-for-ptc/decision/resolved-inputs-and-policy: en: e544f1a5b7f5b0ec zh: 3195e0008313a5c6 @@ -18,8 +18,8 @@ en: a8897bae00f5f674 zh: 2c959353c5a885a4 /agent-note-sandboxed-node-execution-for-ptc/decision/resource-limits: - en: 3f1d8a30f6d48243 - zh: faa7c01d7c959893 + en: 9fc1a3c6e06ab156 + zh: 7fcf818c3411eff4 /agent-note-sandboxed-node-execution-for-ptc/alternatives-considered: en: 8ffcc2b32a2243d7 zh: 81d48d38947abc76 diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md index 1401159b86..6110df0886 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md @@ -12,7 +12,7 @@ The [PTC foundation](../feature/2026-06-15-ptc.md) remains responsible for regis ## Decision -`dsh-ptc-runtime-node` in its default `per-call` mode runs each program in one fresh Node process. The host resolves execution choices, confines the launch through the same `ctx.sandbox` provider as Bash, and gives process lifetime to `ctx.subprocess`. The child evaluates erasable TypeScript with direct Node APIs, an empty model environment and host-provided asynchronous bindings. No worker or persistent kernel remains after a per-call execution. +`dsh-ptc-runtime-node` in its `per-call` mode runs each program in one fresh Node process. The host resolves execution choices, confines the launch through the same `ctx.sandbox` provider as Bash, and gives process lifetime to `ctx.subprocess`. The child evaluates erasable TypeScript with direct Node APIs, an empty model environment and host-provided asynchronous bindings. No worker or persistent kernel remains after a per-call execution. The host preserves `ELECTRON_RUN_AS_NODE` for child startup; the bootstrap removes it from the native environment before evaluation, and model-visible `process.env` stays empty. Nested Electron launches require their own explicit Node-mode selection. Desktop uses Electron as its Node executable; removing this selector launches Electron's application path instead of the PTC bootstrap. Sandbox permission changes cannot repair that launch mismatch. The macOS Desktop regression uses real Electron to verify binding writes, direct workspace writes, and rejection of writes outside the workspace under restricted policy. It requires an installed Electron binary; ordinary runtime tests cover environment filtering without that dependency. @@ -32,7 +32,7 @@ For temporary executions, program completion, timeout, cancellation and protocol The default elapsed deadline is 120 seconds, capped at 600 seconds by default. Trusted service consumers may request `timeoutMs: null` to disable this timer; [workflow sandbox reuse](2026-09-13-workflow-ptc-sandbox-reuse.md) owns that caller-controlled lifetime. Omitted and numeric requests, including model-facing `run_code`, retain the numeric defaults and caps. An enabled deadline includes runtime setup and nested tool or approval waits. V8 old-generation memory, serialized outer output and control traffic have separate configured bounds. The heap limit excludes native allocations and descendant memory, and elapsed time is not a process-tree CPU budget. -The opt-in [in-memory execution mode](2026-09-23-best-effort-persistent-ptc.md) retains disposable memory under the same file policy; [retained-process permissions](2026-10-08-persistent-ptc-sandbox.md) govern policy changes and temporary escalation. +The default [in-memory execution mode](2026-09-23-best-effort-persistent-ptc.md) retains disposable memory under the same file policy; [retained-process permissions](2026-10-08-persistent-ptc-sandbox.md) govern policy changes and temporary escalation. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md index e8e55290a6..5b18000121 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md @@ -12,7 +12,7 @@ Node worker 隔离 JavaScript 状态,但不应用调用 Session 的 OS 沙箱 ## 决策 -`dsh-ptc-runtime-node` 的默认 `per-call` 模式在一个全新 Node 进程中运行每个程序。Host 解析执行选择,通过与 Bash 相同的 `ctx.sandbox` 提供方约束启动,并将进程生命周期交给 `ctx.subprocess`。子进程以直接 Node API、空模型环境和 Host 提供的异步绑定求值可擦除 TypeScript。逐次执行结束后不保留 worker 或持久内核。 +`dsh-ptc-runtime-node` 的 `per-call` 模式在一个全新 Node 进程中运行每个程序。Host 解析执行选择,通过与 Bash 相同的 `ctx.sandbox` 提供方约束启动,并将进程生命周期交给 `ctx.subprocess`。子进程以直接 Node API、空模型环境和 Host 提供的异步绑定求值可擦除 TypeScript。逐次执行结束后不保留 worker 或持久内核。 Host 在子进程启动时保留 `ELECTRON_RUN_AS_NODE`;bootstrap 在求值前将其从原生环境中删除,模型可见的 `process.env` 仍为空。嵌套启动 Electron 需要自行显式选择 Node 模式。桌面端使用 Electron 作为 Node 可执行文件;删除此选择变量会启动 Electron 应用路径,而不是 PTC bootstrap。更改沙箱权限无法修复这一启动模式不匹配。macOS 桌面端回归测试使用真实 Electron 验证绑定写入、直接工作区写入以及受限策略对工作区外写入的拒绝。该测试需要已安装的 Electron 二进制文件;普通运行时测试无需此依赖即可覆盖环境过滤。 @@ -32,7 +32,7 @@ Host 在子进程启动时保留 `ELECTRON_RUN_AS_NODE`;bootstrap 在求值前 默认经过时间截止为 120 秒,默认上限为 600 秒。可信服务消费方可以请求 `timeoutMs: null` 来禁用该定时器;[工作流沙箱复用](2026-09-13-workflow-ptc-sandbox-reuse.zh.md)负责这种由调用方控制的生命周期。省略 timeout 或使用数值的请求(包括面向模型的 `run_code`)保留数值默认值与上限。启用的截止包括运行时准备以及嵌套工具或审批等待。V8 老生代内存、序列化外层输出与控制通信具有独立配置的上限。堆限制不包含原生分配和后代内存,经过时间也不是进程树 CPU 预算。 -显式启用的[内存保留执行模式](2026-09-23-best-effort-persistent-ptc.zh.md)在相同文件策略下保留可丢弃内存;[常驻进程权限](2026-10-08-persistent-ptc-sandbox.zh.md)负责策略切换和临时提权。 +默认的[内存保留执行模式](2026-09-23-best-effort-persistent-ptc.zh.md)在相同文件策略下保留可丢弃内存;[常驻进程权限](2026-10-08-persistent-ptc-sandbox.zh.md)负责策略切换和临时提权。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml index e1b5d0b632..cb9ba7c932 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml @@ -9,8 +9,8 @@ en: e42db40b879fdbf4 zh: 6017da9c4da17835 /agent-note-node-ptc-execution-modes-and-in-memory-state/decision: - en: 13a72b9728d25394 - zh: 1f44510fe93836dc + en: 2d5306e76dc8170a + zh: eab993b4d2f3acf0 /agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered: en: 396157a9fc293198 zh: a061f05b4423e26f diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md index 1998b28e64..790617b414 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md @@ -10,7 +10,7 @@ Interactive automation retains application objects, imported modules and helper ## Decision -The existing `@deepseek-ai/dsh-ptc-runtime-node` plugin selects its execution mode through `executionMode`. The default `per-call` mode starts a fresh process under the configured file policy. Opt-in `persistent-in-memory` mode keeps a Node REPL process per explicit, object-identity state owner. Both modes provide the same `ctx.ptcRuntime` service. PTC uses the live Agent as owner and awaits release during its context disposal. Changing the configuration reloads the provider and releases its processes. The [sandboxed Node decision](2026-09-11-sandboxed-node-ptc-runtime.md) owns per-call confinement; the [PTC foundation](../feature/2026-06-15-ptc.md) owns tool dispatch and logged model requests. +The existing `@deepseek-ai/dsh-ptc-runtime-node` plugin selects its execution mode through `executionMode`. The `per-call` mode starts a fresh process under the configured file policy. The default `persistent-in-memory` mode keeps a Node REPL process per explicit, object-identity state owner. Both modes provide the same `ctx.ptcRuntime` service. PTC uses the live Agent as owner and awaits release during its context disposal. Changing the configuration reloads the provider and releases its processes. The [sandboxed Node decision](2026-09-11-sandboxed-node-ptc-runtime.md) owns per-call confinement; the [PTC foundation](../feature/2026-06-15-ptc.md) owns tool dispatch and logged model requests. The `per-call` and `persistent-in-memory` names describe their fixed state-retention policies: one invocation or across invocations until the process or owner ends. The [Script evaluation decision](2026-10-20-ptc-script-evaluation-and-retention.md) extends these modes with independently configured syntax and retention. `durable` names the deferred ability to save and restore execution state across restarts. It is not an accepted configuration value: a future implementation must define its recovery point, recoverable values and external-resource handling before exposing that mode. The [retained-process permission decision](2026-10-08-persistent-ptc-sandbox.md) owns confinement, policy changes and temporary escalation. diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md index c9fe0a24a5..f56c7e8d28 100644 --- a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -现有 `@deepseek-ai/dsh-ptc-runtime-node` 插件通过 `executionMode` 选择执行模式。默认的 `per-call` 模式按配置的文件策略启动新进程。显式启用的 `persistent-in-memory` 模式为每个以对象身份标识的状态所有者保留一个 Node REPL 进程。两种模式都提供同一个 `ctx.ptcRuntime` 服务。PTC 使用存活的 Agent 作为所有者,在其上下文销毁时等待释放。修改配置会重载提供方并释放其进程。[Node 沙箱决策](2026-09-11-sandboxed-node-ptc-runtime.zh.md)负责逐次执行的文件约束,[PTC 基础决策](../feature/2026-06-15-ptc.zh.md)负责工具分派与模型请求日志。 +现有 `@deepseek-ai/dsh-ptc-runtime-node` 插件通过 `executionMode` 选择执行模式。`per-call` 模式按配置的文件策略启动新进程。默认的 `persistent-in-memory` 模式为每个以对象身份标识的状态所有者保留一个 Node REPL 进程。两种模式都提供同一个 `ctx.ptcRuntime` 服务。PTC 使用存活的 Agent 作为所有者,在其上下文销毁时等待释放。修改配置会重载提供方并释放其进程。[Node 沙箱决策](2026-09-11-sandboxed-node-ptc-runtime.zh.md)负责逐次执行的文件约束,[PTC 基础决策](../feature/2026-06-15-ptc.zh.md)负责工具分派与模型请求日志。 `per-call` 和 `persistent-in-memory` 名称描述各自固定的状态保留策略:只保留一次调用,或跨调用保留至进程或所有者结束。[Script 求值决策](2026-10-20-ptc-script-evaluation-and-retention.zh.md)在这两种模式之外增加独立配置的语法与保留方式。`durable` 用于命名未来跨重启保存与恢复执行状态的能力。它不是可接受的配置值:实现必须先明确恢复点、可恢复的值以及外部资源的处理方式,才能公开这个模式。[常驻进程权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)负责文件约束、权限切换与临时提权。 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 index 9994778c04..c3c45a74b5 100644 --- 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 @@ -12,8 +12,8 @@ en: a9124b9053b16a12 zh: 7d4005cbca138015 /agent-note-cua-programs-outside-the-ptc-preset/alternatives-considered: - en: b5d8e00cbe4b53ae - zh: 4ef81611150a8d75 + en: a549b92ccdf837df + zh: e012821576eb54e2 /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 index 2e27d5c0b1..73dba27a09 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md +++ b/.agents/notes/implemented/architecture/2026-11-09-cua-program-tool.md @@ -22,7 +22,7 @@ This partially supersedes the exclusion of a CUA program entry in [native CUA ob **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. +**The profile's shared runtime** couples CUA state to unrelated PTC and workflow settings. A per-call mode selected there 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. 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 index c584bde8de..098fc1e3a4 100644 --- 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 @@ -22,7 +22,7 @@ CUA 在隔离运行时首次接纳运行前,通过 `registerEnvironmentInitial **CUA 专用求值器**会重复实现执行生命周期策略。复用 PTC 工厂和运行时,使取消、限制、沙箱和结果处理继续由现有实现负责。 -**profile 的共享运行时**会使 CUA 状态依赖无关的 PTC 和工作流设置。其默认逐次调用模式无法保留对象。独立的 CUA 运行时保留 profile 选定的执行模式。 +**profile 的共享运行时**会使 CUA 状态依赖无关的 PTC 和工作流设置。在那里选择的逐次调用模式无法保留对象。独立的 CUA 运行时保留 profile 选定的执行模式。 **全局注册两种工具形态**会在 PTC 程序中暴露另一个程序执行器,并向其他 preset 暴露原始 CUA 调用。按 Agent 选择一种形态,可以保留各模式预期的工具列表。在 `cua_run_code` 内绑定所有会话工具,会重复普通的直接调用及其声明。 diff --git a/apps/web/tests/bundle-platform.e2e.ts b/apps/web/tests/bundle-platform.e2e.ts index 0784bd132c..6ade4d22f3 100644 --- a/apps/web/tests/bundle-platform.e2e.ts +++ b/apps/web/tests/bundle-platform.e2e.ts @@ -40,7 +40,7 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct const runtimeId = () => [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'ptc-runtime')?.fiber?.uid const beforeRuntime = runtimeId() expect(beforeRuntime).toBeTypeOf('number') - expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body') + expect(scaffold.ctx.ptcRuntime.programFormat).toBe('scoped-repl') 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"]') @@ -58,6 +58,6 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct } expect(await readFile(manifest, 'utf8')).toBe(before) expect(runtimeId()).toBe(beforeRuntime) - expect(scaffold.ctx.ptcRuntime.programFormat).toBe('function-body') + expect(scaffold.ctx.ptcRuntime.programFormat).toBe('scoped-repl') expect(scaffold.ctx.get('computerUse')).toBeUndefined() }) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 9b46ade20d..41e1b1c415 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -3160,7 +3160,7 @@ export interface Config { export interface Config { /** Worker invocation in the subprocess world; omitted selects the local carrier. */ launch?: LaunchConfig - /** per-call uses fresh async function bodies; vm-script uses VM contexts; persistent-in-memory retains a REPL per owner. */ + /** persistent-in-memory, the default, retains a REPL per owner; per-call uses fresh async function bodies; vm-script uses VM contexts. */ executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script' /** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */ scriptPersistence?: boolean diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 5a60ec42e6..ee9068f5e4 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -3162,7 +3162,7 @@ export interface Config { export interface Config { /** Worker invocation in the subprocess world; omitted selects the local carrier. */ launch?: LaunchConfig - /** per-call uses fresh async function bodies; vm-script uses VM contexts; persistent-in-memory retains a REPL per owner. */ + /** persistent-in-memory, the default, retains a REPL per owner; per-call uses fresh async function bodies; vm-script uses VM contexts. */ executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script' /** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */ scriptPersistence?: boolean diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index b65cf0a716..679756eb45 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: 93d8526bbc4936d2 - zh: 963af83582d289c5 + en: 839345c3b7a0414d + zh: 906c029c30394562 /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 6362317eaf..7538893da3 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -612,7 +612,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. 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. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. 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 program to execute, 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 contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically. ```json { @@ -620,7 +620,7 @@ Execute a TypeScript program against the available tools. Takes two required arg "properties": { "code": { "type": "string", - "description": "The program: the body of an async TypeScript function." + "description": "The TypeScript program to execute, following this tool's execution instructions." }, "description": { "type": "string", diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index f7bebf58de..8753f7952d 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -616,7 +616,7 @@ ask_user_question 默认保持原有阻塞行为;设置 `mode: timed` 后才 ### `run_code` -针对可用工具执行 TypeScript 程序。接受两个必填参数:`code`,异步函数的函数体(仅限可擦除语法,支持顶层 `await` 和 `return`);以及 `description`,简要说明程序做什么。请按系统提示词中的声明,以 `await tools.name(args)` 调用工具。使用 inspect(...values) 展示选定的文本和图片。程序是异步 TypeScript 函数的函数体,只接受可擦除语法,不支持 enum 或 namespace。类型标注只作提示。支持顶层 await 和 return。使用 inspect(...values) 展示输出。不要使用 console。模板字面量的 raw 形式只用于反斜杠必须原样保留的短文本,例如正则表达式;其他文本,尤其是文件内容和命令,用普通字符串书写。文件内容写成引号字符串数组,每行一个元素,用换行符拼接;不要写成一个模板字面量。每次调用在新的 Node 进程中运行,可通过 await import(...) 使用 Node API。相对路径以传入的工作目录为准;process.env 初始为空。直接文件系统访问遵循本次执行的沙箱策略。每个程序从 Session 的当前目录启动,运行中保留初始目录。沙箱提权只为本次完整程序执行授权。嵌套工具保留自身策略与审批。只有在获得拒绝证据后才请求更宽访问。先前效果可能已经发生,请在显式重试前检查。程序不会自动重放。 +针对可用工具执行 TypeScript 程序。接受两个必填参数:`code`,要执行的程序;以及 `description`,简要说明程序做什么。请按系统提示词中的声明,以 `await tools.name(args)` 调用工具。使用 inspect(...values) 展示选定的文本和图片。程序由 TypeScript REPL 语句组成,只接受可擦除语法,不支持 enum 或 namespace。类型标注只作提示。支持顶层声明和 await;不支持顶层 return。使用 inspect(...values) 展示输出。不要使用 console。模板字面量的 raw 形式只用于反斜杠必须原样保留的短文本,例如正则表达式;其他文本,尤其是文件内容和命令,用普通字符串书写。文件内容写成引号字符串数组,每行一个元素,用换行符拼接;不要写成一个模板字面量。程序在严格模式下运行:给未声明的名字赋值会抛错,有意设置全局变量请使用 globalThis;eval 和 new Function 不可用。变量、函数和导入的模块在本 Agent 的多次调用之间保留在内存中。每次调用在自己的顶层作用域中运行一个程序。它的顶层 let、const、var、class 和 function 声明,以及它从之前程序收到的名字,会拷贝到之后程序的顶层作用域:之后的程序收到的是这些变量的拷贝而不是引用,因此它们持有的对象仍然共享。同一个程序里,要么使用拷贝来的名字,要么重新声明它;不要既声明一个名字又使用它拷贝来的值。给拷贝来的名字赋值,即使它是用 const 声明的,也只改变本程序的拷贝,之后的程序会收到这个拷贝。不要在块内声明 var;块级 var 会改变之后程序拷贝到的值。之前程序中的函数和仍在运行的代码保留它们捕获的值,它们之后的赋值不会被拷贝;共享的可变状态请放在对象中。如果程序在重新声明已有名字的声明完成前失败,之后的程序保留该名字原先的值。使用 await import(...) 加载模块;require 和 module 不可用。相对导入说明符按本环境第一个程序的工作目录解析,而 process.cwd() 和相对文件路径跟随每个程序的工作目录。直接文件系统访问遵循环境启动时的沙箱策略;process.env 初始为空。超时和取消结果会说明保留的变量是被保留还是被清除。重启、沙箱变更或进程失败会清除它们。请重新创建缺失的变量和资源;对话历史不会恢复状态。之前的修改和工具效果不会回滚。获批的沙箱提权使用全新环境,之后丢弃其中的变量。请在程序结束前等待工具调用和清理完成;未完成的工具调用会被拒绝。完成、超时或取消后,新的工具调用会被拒绝,捕获的输出会被丢弃;后台工作仍可能改变状态。请在程序结束前等待子进程完成;原始输出归属于当前执行。每个程序从 Session 的当前目录启动,运行中保留初始目录。沙箱提权只为本次完整程序执行授权。嵌套工具保留自身策略与审批。只有在获得拒绝证据后才请求更宽访问。先前效果可能已经发生,请在显式重试前检查。程序不会自动重放。 ```json { @@ -624,7 +624,7 @@ ask_user_question 默认保持原有阻塞行为;设置 `mode: timed` 后才 "properties": { "code": { "type": "string", - "description": "The program: the body of an async TypeScript function." + "description": "The TypeScript program to execute, following this tool's execution instructions." }, "description": { "type": "string", diff --git a/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.i18n.yaml new file mode 100644 index 0000000000..70c2ee3f4a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/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.5/ptc-default-scoped-repl/guide.md +/: + en: 3af3cc4793ec67d9 + zh: a9d8ce0a8546631c +/node-ptc-runs-the-scoped-repl-by-default: + en: 5a90a2b4a5bab5c8 + zh: f838c916dd69ede4 +/node-ptc-runs-the-scoped-repl-by-default/change: + en: be41401640bcd00e + zh: 97637a3404b2fb60 +/node-ptc-runs-the-scoped-repl-by-default/migration: + en: febb7a0bdf248d61 + zh: 6a971b47c9c07a7c diff --git a/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.md new file mode 100644 index 0000000000..0658cbdfdb --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Node PTC defaults to persistent-in-memory execution with the scoped REPL instead of per-call function bodies." +--- + +# Node PTC runs the scoped REPL by default + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-ptc-runtime-node` previously defaulted `executionMode` to `per-call`: each `run_code` program was an async function body in a fresh Node process, with top-level `return` and no state between calls. The default is now `persistent-in-memory`, which with the default `replScoped` runs the scoped REPL and reports program format `scoped-repl`. Each live Agent keeps one Node process whose top-level bindings carry into later calls; top-level `return` is rejected, and the last top-level expression statement is the completion value. The model guidance describes the new syntax. + +This affects every `ptc-runtime` entry that omits `executionMode`, including the default profile's PTC mode, workflow-ptc scripts that run on that runtime, and direct runtime consumers that mount the provider without configuration. Entries that set `executionMode` explicitly are unchanged. For profiles that omit it, the Computer Use detail page reports the shared PTC runtime as already persistent and its **Use persistent mode** action is disabled. + +## Migration + +1. To keep function bodies in fresh processes, set the mode in `$DSH_HOME/profiles//cordis.patch.yml`. The patch replaces the entry's whole `config`, so copy its existing fields into it: + + ```yaml + - id: ptc-runtime + config: + executionMode: per-call + ``` + +2. Programs written for the scoped REPL replace a final `return value` with a final `value` expression statement and use `await import(...)` instead of `require`. +3. Restart the profile, run `var probe = 1` in one call and `inspect(typeof probe)` in the next call of the same Session. The scoped REPL prints `number`; `per-call` prints `undefined`. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.zh.md new file mode 100644 index 0000000000..e8597c422b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/ptc-default-scoped-repl/guide.zh.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Node PTC 默认使用 persistent-in-memory 执行和 scoped REPL,不再默认使用 per-call 函数体。" +--- + +# Node PTC 默认运行 scoped REPL + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-ptc-runtime-node` 原先的 `executionMode` 默认值是 `per-call`:每个 `run_code` 程序是在新 Node 进程中运行的 async 函数体,可以使用顶层 `return`,调用之间不保留状态。现在默认值是 `persistent-in-memory`,在默认 `replScoped` 下运行 scoped REPL,并报告程序格式 `scoped-repl`。每个存活的 Agent 保留一个 Node 进程,顶层绑定带到之后的调用;顶层 `return` 会被拒绝,最后一条顶层表达式语句是完成值。模型说明描述了新语法。 + +受影响的是所有省略 `executionMode` 的 `ptc-runtime` 条目,包括默认 profile 的 PTC 模式、在该运行时上运行的 workflow-ptc 脚本,以及不带配置挂载该提供方的直接运行时使用方。显式设置了 `executionMode` 的条目不变。对于省略该项的 profile,Computer Use 详情页显示共享 PTC 运行时已是持久模式,「设为持久化」按钮不可用。 + +## 迁移 + +1. 如果要继续在新进程中运行函数体,在 `$DSH_HOME/profiles//cordis.patch.yml` 中设置执行方式。patch 会替换该条目的整个 `config`,所以要把条目已有的字段一并写进去: + + ```yaml + - id: ptc-runtime + config: + executionMode: per-call + ``` + +2. 为 scoped REPL 编写的程序,把末尾的 `return value` 改为末尾的 `value` 表达式语句,并用 `await import(...)` 代替 `require`。 +3. 重启 profile,在同一会话中先运行 `var probe = 1`,再在下一次调用中运行 `inspect(typeof probe)`。scoped REPL 输出 `number`;`per-call` 输出 `undefined`。 diff --git a/packages/core/tool-executor-ptc/README.i18n.yaml b/packages/core/tool-executor-ptc/README.i18n.yaml index 0acdbc39dc..3234d5ce54 100644 --- a/packages/core/tool-executor-ptc/README.i18n.yaml +++ b/packages/core/tool-executor-ptc/README.i18n.yaml @@ -60,8 +60,8 @@ en: f4703836365dc3d4 zh: a09ff48a6550fd69 /deepseek-ai-dsh-tool-executor-ptc/known-limitations-and-deferred-work: - en: 0159ba9c4dda070f - zh: 9be2f81d398868a1 + en: 872e593c876f4057 + zh: a197742ee74eefa6 /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 0d01bbd4ad..52e17b42cf 100644 --- a/packages/core/tool-executor-ptc/README.md +++ b/packages/core/tool-executor-ptc/README.md @@ -163,7 +163,7 @@ These constraints apply to the host integration and accepted calls. - **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 uses TypeScript, and presentation is per agent rather than per tool** — PTC execution requires `ctx.ptcRuntime.language === 'typescript'`; 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; 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. +- **State depends on the runtime**: Node `per-call` execution starts fresh; the default 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 876dd44b19..e9831fe6cf 100644 --- a/packages/core/tool-executor-ptc/README.zh.md +++ b/packages/core/tool-executor-ptc/README.zh.md @@ -163,7 +163,7 @@ Error: code run failed (abort): run_code exceeded its limit of 2048 tool calls ( - **没有内置重置控件**:自带的 Loader 插件不通过服务、GUI 控件或 SDK 端点暴露执行器实例。需要重置的宿主必须在自己的组合中挂载并保留 `PtcExecutor`,该集成负责失败后的重试。 - **PTC mode 使用 TypeScript,且呈现方式按 agent 而非按工具**:PTC 执行要求 `ctx.ptcRuntime.language === 'typescript'`;同一个 agent 内不能让一个工具仅使用 Native,而另一个仅使用 PTC。 - **PTC mode 中间值只存在于执行局部,且没有字节上限**:它们无法从会话回放重建,并可能耗尽进程或 worker 内存;只有外层 `run_code` 输出受 worker 可配置的硬上限约束。 -- **状态由运行时决定**:默认后端每次重新开始;Node 的 `persistent-in-memory` 执行和启用 `scriptPersistence: true` 的 Script 模式按存活 Agent 保留内存。Agent 销毁时等待环境释放。重启与执行失败可能清除内存;模型说明会指导重新创建缺失变量。程序与结果仍写入 Session 日志,不序列化运行中的对象。 +- **状态由运行时决定**:Node 的 `per-call` 执行每次重新开始;默认的 Node `persistent-in-memory` 执行和启用 `scriptPersistence: true` 的 Script 模式按存活 Agent 保留内存。Agent 销毁时等待环境释放。重启与执行失败可能清除内存;模型说明会指导重新创建缺失变量。程序与结果仍写入 Session 日志,不序列化运行中的对象。 ### 开发备注 diff --git a/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml b/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml index 19263a52b3..780b23dc46 100644 --- a/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml +++ b/packages/ptc-runtime/ptc-runtime-node/README.i18n.yaml @@ -9,8 +9,8 @@ en: 7e1a8657a212c70b zh: afb7a8c6a3afd718 /deepseek-ai-dsh-ptc-runtime-node/summary: - en: 7f80d74a7f87eb05 - zh: 6aa31b97ac920ca6 + en: e3350a3c7cde1663 + zh: 2850eec5715e6f80 /deepseek-ai-dsh-ptc-runtime-node/table-of-contents: en: d152484eb41ac6b4 zh: 725b47765ee8f30b @@ -18,14 +18,14 @@ en: 70e83ccdf8159a10 zh: 8282f1da5e844426 /deepseek-ai-dsh-ptc-runtime-node/use-this-package/configuration: - en: 2be5e2e5d17c7c7f - zh: 4de138d85dea1614 + en: b49a23785fd80315 + zh: 1167b2face1e1028 /deepseek-ai-dsh-ptc-runtime-node/use-this-package/execution-and-results: en: e4c2a44c600693e9 zh: d4690975a3f95b14 /deepseek-ai-dsh-ptc-runtime-node/use-this-package/in-memory-modes: - en: d5814e14a6b8cf9f - zh: 40968df6610e9d7f + en: 6751521701e314dd + zh: 9e6c2b179f728414 /deepseek-ai-dsh-ptc-runtime-node/use-this-package/deadlines-and-cancellation: en: d383ec7aeab8afec zh: 7c9c49e205fbbcd8 @@ -57,8 +57,8 @@ en: 40294c1c31b74824 zh: d91e7b78c0619c7e /deepseek-ai-dsh-ptc-runtime-node/known-limitations-and-deferred-work: - en: 66d2a67411aecb34 - zh: 9ccb065e98f432b5 + en: 1a4f709bbd6fdecf + zh: 5c60630d18220015 /deepseek-ai-dsh-ptc-runtime-node/known-limitations-and-deferred-work/dev-note: en: 6373aba4e08f7205 zh: 2a8c33d1f2839df4 diff --git a/packages/ptc-runtime/ptc-runtime-node/README.md b/packages/ptc-runtime/ptc-runtime-node/README.md index fb7fe112a5..95f6ecde83 100644 --- a/packages/ptc-runtime/ptc-runtime-node/README.md +++ b/packages/ptc-runtime/ptc-runtime-node/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Execute model-written TypeScript with host-provided async functions. The default `per-call` mode runs async function bodies in fresh Node processes; `vm-script` supports top-level await and optionally retains a context per Agent with `scriptPersistence`. Opt-in `persistent-in-memory` retains a REPL per Agent. All modes apply the file sandbox policy at process launch and return captured logs, lossless JSON, or structured failures. Elapsed deadlines, output bounds and a V8 heap limit constrain execution. Unacknowledged stops and one-shot completion clean up the managed process range; unavailable confinement fails execution. +Execute model-written TypeScript with host-provided async functions. The default `persistent-in-memory` mode retains a scoped REPL per Agent; `per-call` runs async function bodies in fresh Node processes; `vm-script` supports top-level await and optionally retains a context per Agent with `scriptPersistence`. All modes apply the file sandbox policy at process launch and return captured logs, lossless JSON, or structured failures. Elapsed deadlines, output bounds and a V8 heap limit constrain execution. Unacknowledged stops and one-shot completion clean up the managed process range; unavailable confinement fails execution. ## Table of Contents @@ -36,7 +36,7 @@ Configure the provider row after its required services are available: ```yaml - name: '@deepseek-ai/dsh-ptc-runtime-node' config: - executionMode: per-call + executionMode: persistent-in-memory timeoutMs: 120000 maxTimeoutMs: 600000 maxOutputBytes: 67108864 @@ -49,7 +49,7 @@ Configure the provider row after its required services are available: | Field | Default | Meaning | |---|---|---| -| `executionMode` | `per-call` | `per-call` runs async function bodies in fresh processes; `vm-script` evaluates Scripts; `persistent-in-memory` retains a confined REPL per owner | +| `executionMode` | `persistent-in-memory` | `persistent-in-memory` retains a confined REPL per owner; `per-call` runs async function bodies in fresh processes; `vm-script` evaluates Scripts | | `scriptPersistence` | `false` | With `executionMode: vm-script`, reuse a process and context per owner; `true` with another mode rejects at load | | `replScoped` | `true` with `persistent-in-memory`, otherwise `false` | With `executionMode: persistent-in-memory`, run scoped REPL statements whose calls receive copies of earlier top-level bindings; `false` selects Node's REPL evaluator, and `true` with another mode rejects at load | | `timeoutMs` | `120,000` | Default elapsed execution deadline, including nested tool and approval waits | @@ -102,12 +102,12 @@ Set `executionMode: vm-script` to evaluate erasable TypeScript through `node:vm` ### In-memory modes -The `persistent-in-memory` mode and Script mode with `scriptPersistence: true` retain state per owner. To retain a REPL, set `executionMode: persistent-in-memory` on the existing `@deepseek-ai/dsh-ptc-runtime-node` plugin; it runs the scoped REPL unless `replScoped: false` selects Node's REPL evaluator. All modes require `fs`, `subprocess`, `sandbox` and `sandboxPolicy` and apply the file sandbox policy at process launch. Enable it deliberately with a profile patch: +The `persistent-in-memory` mode and Script mode with `scriptPersistence: true` retain state per owner. `persistent-in-memory` is the default `executionMode` and runs the scoped REPL unless `replScoped: false` selects Node's REPL evaluator. All modes require `fs`, `subprocess`, `sandbox` and `sandboxPolicy` and apply the file sandbox policy at process launch. To run function bodies in fresh processes instead, select `per-call` with a profile patch: ```yaml - id: ptc-runtime config: - executionMode: persistent-in-memory + executionMode: per-call ``` Save the patch and pass its path to `dsh headless --patch ` in a composition with PTC tool presentation. The `per-call` mode and Script mode with `scriptPersistence: false` retain no program memory between calls. Changing the configuration reloads the provider and releases its execution resources. Packaged single-executable hosts use their embedded carrier by default; the host sends the selected program format and retention flag with each evaluation, so the embedded `process.js` bootstrap serves both per-call and retained execution. Remote script deployments use a `node-script` launch with `launch.bootstrapPath` pointing to this package's built `persistent-process.js`. @@ -247,7 +247,7 @@ These limits qualify the execution guarantees and retained output. - **Confinement inherits the selected backend's limits** — full and partial enforcement are reported separately; sandbox policy and managed-process containment are distinct guarantees. - **The heap cap is not a process-tree memory limit** — native allocations and descendant memory are outside the V8 old-generation bound. No process-tree CPU meter is supplied. - **Cleanup inherits subprocess observability** — escaped descendants on a fallback platform may remain outside the managed range; see the subprocess provider's stated limits. -- **Default execution is one-shot** — retained state requires `persistent-in-memory` mode or Script mode with `scriptPersistence: true`; no mode offers a yield/wait API. +- **`per-call` execution is one-shot** — retained state requires `persistent-in-memory`, the default, or Script mode with `scriptPersistence: true`; no mode offers a yield/wait API. - **Await lowering relaxes declaration semantics** — in transformed programs, top-level `let`, `const`, and `class` bindings are mutable and initialized to `undefined` before execution; the native temporal dead zone does not apply. Function declarations populate retained globals when execution reaches them, and a `var` declaration without an initializer resets its binding to `undefined`. Direct-eval declarations stay within that evaluation. Top-level `using` declarations are rejected; put disposable bindings inside a block. Runtime stack locations refer to the transformed source. Scripts that compile without lowering keep native semantics. - **Failed native lexical initialization can reserve a name** — if a top-level `let`, `const`, or `class` initializer throws before initializing its binding, that name remains uninitialized in the retained Script context. Reading, assigning or redeclaring it fails; use a new name or release and recreate the environment. - **Scoped REPL copies values when a call starts** — with `replScoped` omitted or `true`, assignments that earlier code makes afterwards stay invisible to later calls, and a `let`, `const` or `class` redeclaration cannot read the earlier value of its own name. A `var` redeclaration starts from that value, so `var count = count + 1` adds to it, also after an earlier `let` or `const` of the same name. Relative `import()` specifiers keep resolving from the environment's first working directory after a later call changes directory; relative file access follows the current directory. The `codeGeneration` limit rejects only the program context's own `eval`, `Function` and WebAssembly compilation and is no isolation: main-realm functions copied into the context, such as `setTimeout.constructor`, still compile code. Columns after the inserted completion on the final expression's line shift right by 17, programs that start with `#!` or contain `__$binding_` anywhere are rejected, binding-global and error-class names containing that prefix fail before process launch, and a surviving function keeps every value copied into its call. The [scoped REPL decision](../../../.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.md) lists the complete behavior. diff --git a/packages/ptc-runtime/ptc-runtime-node/README.zh.md b/packages/ptc-runtime/ptc-runtime-node/README.zh.md index 7d6b785bf5..91ddb9ed20 100644 --- a/packages/ptc-runtime/ptc-runtime-node/README.zh.md +++ b/packages/ptc-runtime/ptc-runtime-node/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -执行模型编写的 TypeScript,并提供宿主异步函数。默认的 `per-call` 模式在全新 Node 进程中运行异步函数体;`vm-script` 支持顶层 await,并可通过 `scriptPersistence` 为每个 Agent 保留 context。显式启用的 `persistent-in-memory` 为每个 Agent 保留 REPL。所有模式都在进程启动时应用文件沙箱策略,返回捕获日志、无损 JSON 或结构化失败。执行时限、输出上限和 V8 堆上限约束运行。未确认的停止请求与单次执行完成后清理受管进程范围;约束不可用时执行失败。 +执行模型编写的 TypeScript,并提供宿主异步函数。默认的 `persistent-in-memory` 模式为每个 Agent 保留 scoped REPL;`per-call` 在全新 Node 进程中运行异步函数体;`vm-script` 支持顶层 await,并可通过 `scriptPersistence` 为每个 Agent 保留 context。所有模式都在进程启动时应用文件沙箱策略,返回捕获日志、无损 JSON 或结构化失败。执行时限、输出上限和 V8 堆上限约束运行。未确认的停止请求与单次执行完成后清理受管进程范围;约束不可用时执行失败。 ## 目录 @@ -36,7 +36,7 @@ kind: "package-reference" ```yaml - name: '@deepseek-ai/dsh-ptc-runtime-node' config: - executionMode: per-call + executionMode: persistent-in-memory timeoutMs: 120000 maxTimeoutMs: 600000 maxOutputBytes: 67108864 @@ -49,7 +49,7 @@ kind: "package-reference" | 字段 | 默认值 | 含义 | |---|---|---| -| `executionMode` | `per-call` | `per-call` 在全新进程中运行异步函数体;`vm-script` 求值 Script;`persistent-in-memory` 为每个所有者保留受限 REPL | +| `executionMode` | `persistent-in-memory` | `persistent-in-memory` 为每个所有者保留受限 REPL;`per-call` 在全新进程中运行异步函数体;`vm-script` 求值 Script | | `scriptPersistence` | `false` | 在 `executionMode: vm-script` 下,为每个所有者复用进程与 context;其他模式下设为 `true` 会在加载时拒绝 | | `replScoped` | `persistent-in-memory` 下为 `true`,其他模式下为 `false` | 在 `executionMode: persistent-in-memory` 下,按 scoped REPL 语句执行,每次调用拿到之前顶层绑定的拷贝;设为 `false` 时使用 Node 的 REPL 求值器,其他模式下设为 `true` 会在加载时拒绝 | | `timeoutMs` | `120,000` | 默认经过时间截止,包括嵌套工具与审批等待 | @@ -102,12 +102,12 @@ profile 编辑器可从 `@deepseek-ai/dsh-ptc-runtime-node/configuration` 导入 ### 内存保留模式 -`persistent-in-memory` 模式和启用 `scriptPersistence: true` 的 Script 模式都按所有者保留状态。要保留 REPL,在现有 `@deepseek-ai/dsh-ptc-runtime-node` 插件上设置 `executionMode: persistent-in-memory`;默认运行 scoped REPL,设置 `replScoped: false` 时使用 Node 的 REPL 求值器。所有模式都需要 `fs`、`subprocess`、`sandbox` 和 `sandboxPolicy`,并在进程启动时应用文件沙箱策略。通过配置档补丁显式启用: +`persistent-in-memory` 模式和启用 `scriptPersistence: true` 的 Script 模式都按所有者保留状态。`persistent-in-memory` 是 `executionMode` 的默认值,运行 scoped REPL,设置 `replScoped: false` 时使用 Node 的 REPL 求值器。所有模式都需要 `fs`、`subprocess`、`sandbox` 和 `sandboxPolicy`,并在进程启动时应用文件沙箱策略。如果要改为在全新进程中运行函数体,通过配置档补丁选择 `per-call`: ```yaml - id: ptc-runtime config: - executionMode: persistent-in-memory + executionMode: per-call ``` 保存补丁,在使用 PTC 工具展示的配置中通过 `dsh headless --patch ` 加载。`per-call` 模式和 `scriptPersistence: false` 的 Script 模式不跨调用保留程序内存。修改配置会重载提供方并释放其执行资源。单文件打包宿主默认使用内嵌载体;宿主在每次执行中发送所选的程序格式和保留标志,因此内嵌的 `process.js` bootstrap 同时服务单次执行和保留执行。远端脚本部署使用 `node-script` 启动方式,并将 `launch.bootstrapPath` 指向本包构建出的 `persistent-process.js`。 @@ -247,7 +247,7 @@ AsyncFunction 和 Node REPL 共用同步 `registerHooks` 和以 symbol 为键的 - **约束继承所选后端的限制**——完整与部分强制能力分开报告;沙箱策略与受管进程约束是不同保证。 - **堆上限不是进程树内存限制**——原生分配与后代进程内存不属于 V8 老生代上限。不提供进程树 CPU 计量器。 - **清理继承子进程的可观测范围**——使用 fallback 的平台上,逃逸的后代可能仍在受管范围之外;参见子进程提供方声明的限制。 -- **默认执行是一次性的**:保留状态需要设置 `persistent-in-memory` 模式,或在 Script 模式下启用 `scriptPersistence: true`;所有模式都不提供 yield/wait API。 +- **`per-call` 执行是一次性的**:保留状态需要使用默认的 `persistent-in-memory` 模式,或在 Script 模式下启用 `scriptPersistence: true`;所有模式都不提供 yield/wait API。 - **await 转换放宽声明语义**——转换后程序的顶层 `let`、`const` 和 `class` 绑定可修改,且在执行前初始化为 `undefined`,不再具有原生暂时性死区。执行到函数声明时才会为其设置保留的全局变量;没有初始化器的 `var` 声明会将其绑定重置为 `undefined`。直接 eval 中的声明仅在本次求值内有效。不接受顶层 `using` 声明;可释放绑定需放在块内。运行时堆栈位置指向转换后的源码。无需转换即可编译的脚本保持原生语义。 - **原生词法初始化失败可能占用名称**——顶层 `let`、`const` 或 `class` 的初始化器在完成绑定初始化前抛错时,该名称会在保留的 Script context 中持续处于未初始化状态。读取、赋值和重新声明都会失败;应使用新名称,或释放并重新创建环境。 - **scoped REPL 在调用开始时拷贝值**——省略 `replScoped` 或设为 `true` 时,之前的代码之后再赋的值,后面的调用看不到;`let`、`const` 或 `class` 重新声明的初始化表达式读不到同名旧值;`var` 重新声明从旧值开始,所以 `var count = count + 1` 在旧值上加 1,之前是同名的 `let` 或 `const` 时也是这样。之后的调用换了目录,相对的 `import()` 仍按这个环境第一次的工作目录解析;读写文件的相对路径跟随当前目录。`codeGeneration` 限制只拒绝程序环境自己的 `eval`、`Function` 和 WebAssembly 编译,不构成隔离:复制进程序环境的主环境函数,例如 `setTimeout.constructor`,仍能编译代码。最后一条表达式所在行,插入完成值之后的列号右移 17;以 `#!` 开头或任何位置含 `__$binding_` 的程序会被拒绝;包含此前缀的 binding-global 和 error-class 名称会在启动进程前失败;存活的函数会留住它那次调用拷贝进来的所有值。[scoped REPL 决策](../../../.agents/notes/implemented/architecture/2026-11-09-retained-ptc-scoped-repl.zh.md)列出完整行为。 diff --git a/packages/ptc-runtime/ptc-runtime-node/src/config.ts b/packages/ptc-runtime/ptc-runtime-node/src/config.ts index 6fde898608..1b16e35250 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/config.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/config.ts @@ -8,7 +8,7 @@ import { resolvePersistentExecution } from './configuration.ts' export interface Config { /** Worker invocation in the subprocess world; omitted selects the local carrier. */ launch?: LaunchConfig - /** per-call uses fresh async function bodies; vm-script uses VM contexts; persistent-in-memory retains a REPL per owner. */ + /** persistent-in-memory, the default, retains a REPL per owner; per-call uses fresh async function bodies; vm-script uses VM contexts. */ executionMode?: 'per-call' | 'persistent-in-memory' | 'vm-script' /** Retain a Script process and context per stateOwner; only supported with executionMode: vm-script. */ scriptPersistence?: boolean @@ -39,7 +39,7 @@ export interface Config { export type ResolvedConfig = Required /** Loader defaults for the Node PTC provider. */ export const NodeConfig: z = z.object({ - executionMode: z.union([z.const('per-call'), z.const('persistent-in-memory'), z.const('vm-script')]).default('per-call'), + executionMode: z.union([z.const('per-call'), z.const('persistent-in-memory'), z.const('vm-script')]).default('persistent-in-memory'), scriptPersistence: z.boolean().default(false), replScoped: z.boolean(), timeoutMs: z.number().default(120_000), diff --git a/packages/ptc-runtime/ptc-runtime-node/src/configuration.ts b/packages/ptc-runtime/ptc-runtime-node/src/configuration.ts index 55400733c6..c674744dac 100644 --- a/packages/ptc-runtime/ptc-runtime-node/src/configuration.ts +++ b/packages/ptc-runtime/ptc-runtime-node/src/configuration.ts @@ -8,7 +8,7 @@ const SCOPED_REPL_BY_DEFAULT: boolean = true /** * Select retained Node execution while preserving Script and scoped REPL syntax. - * @param programFormat - Effective syntax; omission uses the Node provider's default function-body syntax. + * @param programFormat - Effective syntax; omission selects function bodies. * @returns All three settings to merge into the profile atomically, replacing stale values; function bodies and REPL statements * switch to `persistent-in-memory` with `SCOPED_REPL_BY_DEFAULT`, which is also the default when `replScoped` is omitted. */ diff --git a/packages/ptc-runtime/ptc-runtime-node/tests/execution-mode.spec.ts b/packages/ptc-runtime/ptc-runtime-node/tests/execution-mode.spec.ts index bdc594a89b..b25d822681 100644 --- a/packages/ptc-runtime/ptc-runtime-node/tests/execution-mode.spec.ts +++ b/packages/ptc-runtime/ptc-runtime-node/tests/execution-mode.spec.ts @@ -58,10 +58,10 @@ it.each(['per-call', 'persistent-in-memory'] as const)('rejects Script retention }) // The only ptc-runtime-node mode test that omits executionMode; it pins the provider default. -it('selects per-call function bodies when executionMode is omitted', async () => { +it('selects the retained scoped REPL when executionMode is omitted', async () => { const { runtime } = await mountConfiguredRuntime(new Context(), {}) - expect(runtime.retainsState).toBe(false) - expect(runtime.programFormat).toBe('function-body') + expect(runtime.retainsState).toBe(true) + expect(runtime.programFormat).toBe('scoped-repl') }) // The only ptc-runtime-node mode test that omits replScoped; it pins SCOPED_REPL_BY_DEFAULT from configuration.ts. From b7b18abef7ebc5e465bbab83f944f67de009a173 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 20 Nov 2026 11:02:53 +0800 Subject: [PATCH 21/54] fix(ui-conversation): keep hand-typed path references in typed order Typing a path one character at a time, such as @src/index.ts, produced @src/indexs.t. The "." counts as punctuation outside the reference until the next character arrives. The entity transform then extended the reference over ".t" after collapsing the selection to the reference's previous end, so later characters landed before the moved text. A transform registered ahead of the entity transforms now makes that extension with splitText and mergeWithSibling, which keep the selection beside the moved characters. --- apps/web/tests/reference-composer.e2e.ts | 17 ++++++ .../src/client/input/editor/text-ref.ts | 28 +++++++++- .../tests/draft-document.client.spec.ts | 52 +++++++++++++++++++ 3 files changed, 96 insertions(+), 1 deletion(-) diff --git a/apps/web/tests/reference-composer.e2e.ts b/apps/web/tests/reference-composer.e2e.ts index 0931c525f4..47cdb171ed 100644 --- a/apps/web/tests/reference-composer.e2e.ts +++ b/apps/web/tests/reference-composer.e2e.ts @@ -311,6 +311,23 @@ describe.skipIf(MODE === 'record')('web e2e: file and session references through expect(tripwire.warnings).toEqual([]) }) + it('keeps a file path typed by hand in typed order', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-typed-path')) + const input = page.locator('[data-composer-input]').first() + + // No menu pick: every character of the path arrives as its own key press. + await writeComposerDraft(page, input, '@folderx/nested/leaf.txt') + await expect.poll(() => input.textContent()).toBe('@folderx/nested/leaf.txt') + // The caret follows the last character, and the sentence's period stays outside the reference. + await page.keyboard.type('. Done') + await expect.poll(() => input.textContent()).toBe('@folderx/nested/leaf.txt. Done') + await expect.poll(() => input.locator('[data-composer-text-ref]').allTextContents()) + .toEqual(['@folderx/nested/leaf.txt']) + + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) + it('settles a folder as an atomic chip; Tab and the chevron drill instead', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-reference-folder')) const input = page.locator('[data-composer-input]').first() diff --git a/packages/client/ui-conversation/src/client/input/editor/text-ref.ts b/packages/client/ui-conversation/src/client/input/editor/text-ref.ts index 5221b38a57..6a09b0c741 100644 --- a/packages/client/ui-conversation/src/client/input/editor/text-ref.ts +++ b/packages/client/ui-conversation/src/client/input/editor/text-ref.ts @@ -69,6 +69,27 @@ export class TextRefNode extends TextNode { } } +/** First reference range of a text, or null. */ +type TextRefMatch = (text: string) => { start: number; end: number } | null + +/** + * Extend a text-ref over the plain text directly after it when both together + * match one reference, such as `@src/a` followed by `.ts`. A selection point + * in the moved text stays beside the same character. + * @param node - plain text node the editor marked dirty. + * @param getMatch - the reference matcher. + */ +function $growTextRef(node: TextNode, getMatch: TextRefMatch): void { + const textRef = node.getPreviousSibling() + if (!(textRef instanceof TextRefNode)) return + const length = textRef.getTextContentSize() + const match = getMatch(textRef.getTextContent() + node.getTextContent()) + if (match === null || match.end <= length) return + if (match.end - length < node.getTextContentSize()) node.splitText(match.end - length) + // A split keeps the leading text under this node's key, possibly in a new writable copy. + textRef.mergeWithSibling(node.getLatest()) +} + /** * Register the plain-text reference entity transform. * @param editor - the shell-owned editor. @@ -79,11 +100,16 @@ export function registerTextRefDecoration( editor: LexicalEditor, lexiconOf: () => ReadonlyMap<'/' | '@', readonly string[]>, ): () => void { - const getMatch = (text: string): { start: number; end: number } | null => { + const getMatch: TextRefMatch = (text) => { const range = scanTextRefs(text, lexiconOf())[0] return range === undefined ? null : { start: range.start, end: range.end } } return mergeRegister( + // The entity transforms below also extend a text-ref over following text, but collapse the + // selection to the text-ref's previous end first, so the next typed character lands before + // the moved text (https://github.com/facebook/lexical/issues/3054). Transforms of one node + // type run in registration order; this one leaves them nothing to extend. + editor.registerNodeTransform(TextNode, (node) => { $growTextRef(node, getMatch) }), ...registerLexicalTextEntity( editor, getMatch, diff --git a/packages/client/ui-conversation/tests/draft-document.client.spec.ts b/packages/client/ui-conversation/tests/draft-document.client.spec.ts index 8e50e1ad3a..957fdd9f1e 100644 --- a/packages/client/ui-conversation/tests/draft-document.client.spec.ts +++ b/packages/client/ui-conversation/tests/draft-document.client.spec.ts @@ -14,6 +14,7 @@ import { scanTextRefs } from '../src/client/input/decorations.ts' import { ReferenceChipNode } from '../src/client/input/editor/chip-node.tsx' import { CommandChipNode } from '../src/client/input/editor/command-chip-node.tsx' import { QuoteNode } from '../src/client/input/editor/QuoteNode.tsx' +import { $selectDetectSpan } from '../src/client/input/editor/span-map.ts' import { TextRefNode } from '../src/client/input/editor/text-ref.ts' import { SessionInputShell, type SessionInputDeps } from '../src/client/input/facade.ts' @@ -856,3 +857,54 @@ describe('plain-text reference catalogs', () => { expect(slices('drill @"open dir/。')).toEqual(['@"open dir/']) }) }) + +describe('path references typed one character at a time', () => { + /** Insert each character at the live selection as its own edit, the way key presses arrive. */ + function typeText(shell: SessionInputShell, text: string): void { + for (const char of text) shell.paste(char) + } + + it.each([ + ['@src/index.ts', ['@src/index.ts']], + ['@vite.config.ts', ['@vite.config.ts']], + ['@out/v1.2/readme', ['@out/v1.2/readme']], + ['@out/w1,x', ['@out/w1,x']], + ['看下 @src/app.test.ts 有问题', ['@src/app.test.ts']], + ])('keeps %s in typed order with the caret after the last character', (text, references) => { + const shell = makeShell() + typeText(shell, text) + expect(shell.snapshot.draft).toBe(text) + expect(shell.caretSpan()).toEqual({ start: text.length, end: text.length }) + expect(textReferences(shell)).toEqual(references) + }) + + it('leaves punctuation that ends a sentence outside the reference', () => { + const shell = makeShell() + typeText(shell, '@src/a.ts. Next') + expect(shell.snapshot.draft).toBe('@src/a.ts. Next') + expect(shell.caretSpan()).toEqual({ start: 15, end: 15 }) + expect(textReferences(shell)).toEqual(['@src/a.ts']) + }) + + it('extends a reference over the start of a longer run and keeps the caret after the typed character', () => { + const shell = makeShell() + typeText(shell, '@src/a. x') + expect(textReferences(shell)).toEqual(['@src/a']) + shell.editor.update(() => { $selectDetectSpan({ start: 7, end: 7 }) }, { discrete: true }) + typeText(shell, 't') + expect(shell.snapshot.draft).toBe('@src/a.t x') + expect(shell.caretSpan()).toEqual({ start: 8, end: 8 }) + expect(textReferences(shell)).toEqual(['@src/a.t']) + }) + + it('leaves the text after a named reference in place when its catalog drops the name', async () => { + const lexicon = createSnapshotStore>(new Map([['@', ['alice']]])) + const provider = triggerProvider(lexicon) + const shell = makeShell({ inputTriggers: () => provider }) + typeText(shell, '@alice.') + expect(textReferences(shell)).toEqual(['@alice']) + lexicon.set(new Map()) + await vi.waitFor(() => { expect(textReferences(shell)).toEqual([]) }) + expect(shell.snapshot.draft).toBe('@alice.') + }) +}) From 61df0dbc599175e407d383633a13c381374f7aa2 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 20 Nov 2026 11:32:53 +0800 Subject: [PATCH 22/54] chore(website): ignore VitePress .vitepress/.temp directory Co-authored-by: brickmaker <21122249+brickmaker@users.noreply.github.com> --- website/.gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/website/.gitignore b/website/.gitignore index 29099c8fe6..dba03a0454 100644 --- a/website/.gitignore +++ b/website/.gitignore @@ -2,3 +2,4 @@ node_modules/ .cache/ .dist/ .generated/ +/.vitepress/.temp/ From c7dbc538c0926474fc6c9ca74aa5e025607758b1 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 20 Nov 2026 11:38:35 +0800 Subject: [PATCH 23/54] chore: ignore __pycache__ in every directory Refs #8888 Co-authored-by: Tuyixiang <34904872+Tuyixiang@users.noreply.github.com> --- .github/review-ownership/.gitignore | 1 - .gitignore | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) delete mode 100644 .github/review-ownership/.gitignore diff --git a/.github/review-ownership/.gitignore b/.github/review-ownership/.gitignore deleted file mode 100644 index c18dd8d83c..0000000000 --- a/.github/review-ownership/.gitignore +++ /dev/null @@ -1 +0,0 @@ -__pycache__/ diff --git a/.gitignore b/.gitignore index e3b3ba67b0..7024b069d8 100644 --- a/.gitignore +++ b/.gitignore @@ -34,9 +34,8 @@ dist-exe/ apps/desktop/.desktop-build/ apps/desktop/.desktop-dev/ python/sdk-runtime/src/deepseek_harness_runtime/runtime/ -python/**/__pycache__/ +__pycache__/ python/**/.pytest_cache/ -packages/**/__pycache__/ apps/web/dist/ apps/cli/docs/ .artifacts/ From 54f44f3681cd150a8fff5f3bcd8aa7be809e36fe Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 19 Nov 2026 16:33:13 +0800 Subject: [PATCH 24/54] docs(agents): prefer rebase with rerere for PR branch refreshes Refs #8817 Co-authored-by: imccyu <276526105+imccyu@users.noreply.github.com> --- ...thub-stacks-and-optional-rebases.i18n.yaml | 4 +-- ...tive-github-stacks-and-optional-rebases.md | 2 ++ ...e-github-stacks-and-optional-rebases.zh.md | 2 ++ ...-11-19-prefer-rebase-with-rerere.i18n.yaml | 19 +++++++++++ .../2026-11-19-prefer-rebase-with-rerere.md | 32 +++++++++++++++++++ ...2026-11-19-prefer-rebase-with-rerere.zh.md | 32 +++++++++++++++++++ .../skills/dsh-merging-stacked-prs/SKILL.md | 6 ++-- .agents/skills/dsh-pre-push-checks/SKILL.md | 2 +- AGENTS.md | 2 +- ...sponding-to-pr-review-on-a-stack.i18n.yaml | 8 ++--- .../responding-to-pr-review-on-a-stack.md | 4 +-- .../responding-to-pr-review-on-a-stack.zh.md | 4 +-- 12 files changed, 102 insertions(+), 15 deletions(-) create mode 100644 .agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml create mode 100644 .agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md create mode 100644 .agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md diff --git a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.i18n.yaml b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.i18n.yaml index 88fc7212bb..f41dbe794d 100644 --- a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.i18n.yaml +++ b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md /agent-note-native-github-stacks-and-optional-pr-rebases: - en: 9427ca53db68d50b - zh: 9e72b34deee3bb9f + en: b20dd8917f43b935 + zh: c9d6f3d2a04da072 /agent-note-native-github-stacks-and-optional-pr-rebases/problem: en: 21312af191207fa6 zh: 86306b4c6dd08a0c diff --git a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md index 394f0d7b45..b9e9402f13 100644 --- a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md +++ b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md @@ -4,6 +4,8 @@ Status: implemented English | [中文](2026-08-02-native-github-stacks-and-optional-rebases.zh.md) +The equal choice between merge-forward and rebase below is superseded by [rebase with rerere](2026-11-19-prefer-rebase-with-rerere.md), which keeps merge-forward for an explicit PR author request. Stack linkage, landing, lease protection, and post-rewrite audits remain current. + ## Problem A dependent PR chain represented only by base branches has no official stack identity. Landing it requires manually merging one PR at a time, preserving intermediate branches, retargeting every child, and reconstructing whether the chain survived. GitHub's native stacked-PR feature instead carries the order, applies trunk rules and CI to every layer, and owns bottom-up merges and retargeting. diff --git a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.zh.md b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.zh.md index 6266619fa1..dbfcf227e6 100644 --- a/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.zh.md +++ b/.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.zh.md @@ -4,6 +4,8 @@ Status: implemented [English](2026-08-02-native-github-stacks-and-optional-rebases.md) | 中文 +下文在 merge-forward 与 rebase 之间同等选择的规定已被 [使用 rerere 的 rebase](2026-11-19-prefer-rebase-with-rerere.zh.md) 取代,后者仅在 PR 作者明确要求时保留 merge-forward。堆叠关联、落地、lease 保护和改写后的审计仍然有效。 + ## 问题 仅以 base 分支表示的依赖 PR(Pull Request)链没有官方的堆叠身份。要让它落地,就必须逐个手动合并 PR、保留中间分支、调整每个子 PR 的 base,并重新查证这条链是否仍然完整。GitHub 原生的堆叠 PR 功能则会承载顺序,对每一层应用 trunk 规则和 CI,并负责自底向上的合并与 base 调整。 diff --git a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml new file mode 100644 index 0000000000..adac3c1f40 --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-19-prefer-rebase-with-rerere.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/process/2026-11-19-prefer-rebase-with-rerere.md +/agent-note-prefer-rebase-with-rerere-for-pr-refreshes: + en: bee37c92f02c4b62 + zh: 9db32f3400ca6426 +/agent-note-prefer-rebase-with-rerere-for-pr-refreshes/problem: + en: 3c585b97c13a98b1 + zh: 040d30dcaadfbdf2 +/agent-note-prefer-rebase-with-rerere-for-pr-refreshes/decision: + en: 03821a54b63dd691 + zh: 34f599c07fdef838 +/agent-note-prefer-rebase-with-rerere-for-pr-refreshes/alternatives-considered: + en: 35d2f27bc5712a11 + zh: 5bd1eaaaa200666f +/agent-note-prefer-rebase-with-rerere-for-pr-refreshes/consequences: + en: c29ffb478f78ddfe + zh: 4d11a569f2e1c5d7 diff --git a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md new file mode 100644 index 0000000000..6e6fa5d61f --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md @@ -0,0 +1,32 @@ +# Agent Note: Prefer rebase with rerere for PR refreshes + +Status: implemented + +English | [中文](2026-11-19-prefer-rebase-with-rerere.zh.md) + +## Problem + +The [native stack decision](2026-08-02-native-github-stacks-and-optional-rebases.md) allows merge-forward and rebase equally for standalone and stacked PR branches. Agents therefore pick a history per refresh, and long-lived branches accumulate merge commits that reviewers must skip. Rebasing also asks again for conflict resolutions already made when a rebase is aborted and retried, when a stack child is rebased after its parent was rewritten, or when several commits of one rebase touch the same hunk. + +## Decision + +Agents refresh standalone and stacked PR branches by rebase, including after review. Before rebasing, the agent enables, once per clone, Git's reuse of recorded resolutions with `git config rerere.enabled true`, so Git records each resolved conflict and applies the recorded resolution when the same conflict recurs in a later rebase. Git leaves a replayed resolution unstaged for inspection; the agent reviews and stages it before continuing the rebase. + +Merge-forward is used only when the PR author explicitly asks for it. The incremental merge-forward procedure and its rule to preserve an in-progress checkpoint before taking a newer base remain available for that case. + +Lease protection is unchanged: a standalone rewrite publishes with `--force-with-lease=:`, `gh stack push` and `gh stack sync` supply lease protection for their managed branches, and raw `--force` is forbidden. The native stack decision continues to own stack linkage, landing, and post-rewrite review audits. + +## Alternatives considered + +**Keep merge-forward and rebase equally allowed.** This leaves the history choice to each refresh and keeps the merge commits the rebase preference removes. + +**Require rebase without exception.** A PR author can have a reason to keep merge checkpoints, such as preserving a large completed conflict resolution as a recovery point; the author request keeps that option. + +**Rebase without rerere.** Retried rebases and stack cascades would ask for conflict resolutions already made, which costs time and can produce inconsistent resolutions. + +## Consequences + +- PR branches keep linear history, and reviewers see the branch's own commits on top of the current base. +- Every refresh rewrites commit OIDs, so the post-rewrite audit of heads, review threads, approvals, mergeability, and checks applies to every refresh. +- A recorded resolution can apply to a conflict whose correct resolution changed; the agent still inspects every replayed resolution before staging it. +- Recorded resolutions live in `rr-cache` under the repository's common Git directory, so linked worktrees of one clone share them and other clones do not. diff --git a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md new file mode 100644 index 0000000000..8e1b89d3ce --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md @@ -0,0 +1,32 @@ +# Agent Note: Prefer rebase with rerere for PR refreshes + +Status: implemented + +[English](2026-11-19-prefer-rebase-with-rerere.md) | 中文 + +## 问题 + +[原生堆叠决策](2026-08-02-native-github-stacks-and-optional-rebases.zh.md)对独立 PR 分支和堆叠 PR 分支同等允许 merge-forward 与 rebase。因此 agent 每次刷新都要选择一种历史,长期存在的分支会积累评审者必须跳过的合并提交。中止后重试 rebase、在父层被改写后 rebase 堆叠子层,或一次 rebase 中多个提交改动同一 hunk 时,rebase 还会要求重新解决已经解决过的冲突。 + +## 决策 + +agent 以 rebase 刷新独立 PR 分支和堆叠 PR 分支,包括评审后。rebase 前,agent 在每个克隆中用 `git config rerere.enabled true` 启用一次 Git 的已记录冲突解决复用(rerere),Git 会记录每个已解决的冲突,并在之后的 rebase 中再次出现相同冲突时应用记录的解决结果。Git 把复用的解决结果留在未暂存状态以供检查;agent 检查并暂存后再继续 rebase。 + +只有 PR 作者明确要求时才使用 merge-forward。增量 merge-forward 流程,以及在合入更新的 base 之前保留进行中检查点的规则,仍可用于这种情况。 + +lease 保护不变:独立分支的改写以 `--force-with-lease=:` 发布,`gh stack push` 与 `gh stack sync` 为其管理的分支提供 lease 保护,禁止直接使用 `--force`。原生堆叠决策继续负责堆叠关联、落地,以及改写后的评审审计。 + +## 曾考虑的替代方案 + +**继续同等允许 merge-forward 与 rebase。** 这会把历史选择留给每次刷新,并保留 rebase 优先所消除的合并提交。 + +**无例外地要求 rebase。** PR 作者可能有理由保留合并检查点,例如把一次已完成的大规模冲突解决保留为恢复点;作者要求这一例外保留了该选项。 + +**不启用 rerere 的 rebase。** 重试的 rebase 和堆叠级联 rebase 会要求重新解决已经解决过的冲突,既耗时,也可能产生不一致的解决结果。 + +## 后果 + +- PR 分支保持线性历史,评审者看到的是位于当前 base 之上的分支自身提交。 +- 每次刷新都会改写 commit OID,因此每次刷新后都要审计 head、评审线程、批准状态、可合并性和检查结果。 +- 记录的解决结果可能应用到正确解决方式已经变化的冲突上;agent 仍要在暂存前检查每个复用的解决结果。 +- 记录的解决结果存放在仓库公共 Git 目录下的 `rr-cache` 中,因此同一克隆的关联 worktree 共享这些记录,其他克隆则不共享。 diff --git a/.agents/skills/dsh-merging-stacked-prs/SKILL.md b/.agents/skills/dsh-merging-stacked-prs/SKILL.md index 7e6a985614..69a7869df5 100644 --- a/.agents/skills/dsh-merging-stacked-prs/SKILL.md +++ b/.agents/skills/dsh-merging-stacked-prs/SKILL.md @@ -5,7 +5,7 @@ description: Use when landing a stack of dependent GitHub PRs (A ← B ← C, wh # Landing an official GitHub PR stack -Land dependent PRs through GitHub's native stack object and `gh stack merge`. Do not reproduce stack semantics by merging and retargeting individual PRs with `gh pr merge` and `gh pr edit`. The root [AGENTS.md](../../../AGENTS.md) owns the allowed merge-forward and rebase histories; the [stack review guide](../../../docs/cookbook/responding-to-pr-review-on-a-stack.md) owns review-fix propagation. +Land dependent PRs through GitHub's native stack object and `gh stack merge`. Do not reproduce stack semantics by merging and retargeting individual PRs with `gh pr merge` and `gh pr edit`. The root [AGENTS.md](../../../AGENTS.md) owns the rebase-with-rerere default and the author-requested merge-forward exception; the [stack review guide](../../../docs/cookbook/responding-to-pr-review-on-a-stack.md) owns review-fix propagation. ## Require native stack support @@ -67,10 +67,10 @@ Never dissolve, reorder, or rebuild an existing stack automatically; `gh stack l ## Refresh only when needed -Do not rewrite branches merely because a refresh mechanism exists. When the live merge state or repository rules require an updated trunk, choose either allowed history: +Do not rewrite branches merely because a refresh mechanism exists. When the live merge state or repository rules require an updated trunk, enable rerere (`git config rerere.enabled true`), then rebase; inspect each replayed resolution before staging it. Use merge-forward only when the PR author explicitly asks for it: - **Native cascading rebase:** check out the remote stack with `gh stack checkout ` when it is not tracked locally, then run `gh stack sync`. The command may rebase and lease-protected force-push every active layer before local validation. Immediately inspect the rewritten scope, run the relevant checks for every affected layer, and do not merge or claim readiness until they pass. If sync detects a rebase conflict, use `gh stack rebase`, resolve and validate it, then publish with `gh stack push`. If checkout or sync reports divergent local and remote stack compositions, cancel and ask rather than deleting or recreating the remote stack automatically. -- **Incremental merge-forward:** merge the trunk into the bottom affected branch, then propagate each updated parent into its child in bottom-to-top order and push normally. If the base advances during an in-progress merge, preserve that checkpoint before merging the newer tip. +- **Incremental merge-forward, on the PR author's explicit request:** merge the trunk into the bottom affected branch, then propagate each updated parent into its child in bottom-to-top order and push normally. If the base advances during an in-progress merge, preserve that checkpoint before merging the newer tip. Any history rewrite is allowed after review, but it invalidates commit-OID assumptions. Re-fetch exact heads and re-audit unresolved review threads, approvals, mergeability, and checks after the push. Never use raw `--force` or overwrite a concurrently advanced remote head. diff --git a/.agents/skills/dsh-pre-push-checks/SKILL.md b/.agents/skills/dsh-pre-push-checks/SKILL.md index e10d03cecc..5b36b1007f 100644 --- a/.agents/skills/dsh-pre-push-checks/SKILL.md +++ b/.agents/skills/dsh-pre-push-checks/SKILL.md @@ -80,7 +80,7 @@ Run the complete local approximation only when the user explicitly requests it, ## Protect history-rewriting pushes -Rebase is allowed for standalone and stacked PR branches, including after review. Before a standalone history rewrite, fetch the current remote branch and record its exact OID; publish with `--force-with-lease=:` so a concurrent update aborts the push. `gh stack push` and `gh stack sync` supply lease protection for their managed branches. Raw `--force` is never allowed. +Rebase is the default refresh for standalone and stacked PR branches, including after review; the root [AGENTS.md](../../../AGENTS.md) owns that choice and its rerere setting. Before a standalone history rewrite, fetch the current remote branch and record its exact OID; publish with `--force-with-lease=:` so a concurrent update aborts the push. `gh stack push` and `gh stack sync` supply lease protection for their managed branches. Raw `--force` is never allowed. After any rewritten push, fetch the live heads again and re-audit unresolved review threads, approvals, mergeability, and checks. Commit hashes and inline-comment anchors from before the rewrite are not current evidence. diff --git a/AGENTS.md b/AGENTS.md index 6a2ccfad64..beb634cc61 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,7 +163,7 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and - **Design each tool's UI presentation up front.** Host presenters stay pure; Web cards derive from raw events and persisted result metadata ([cookbook](docs/cookbook/adding-a-tool.md)). - **Plan unit, e2e, and snapshot coverage** for capability seams, lifecycle paths, and transcript output; include missing snapshot-harness support in the same change. - **Both SDKs project the loop.** Agent-loop, session-lifecycle, and `SessionEventMap` changes update the TypeScript and Python SDK expected outputs in the same PR; `pnpm run test` covers neither ([surfaces](docs/testing.md#when-a-snapshot-test-is-required)). -- **Choose PR history deliberately.** Split independent changes and fix the introducing PR before propagation. Standalone/stack branches may merge-forward or rebase. Rewrites use `--force-with-lease`, abort on remote movement, never raw `--force`; preserve an in-progress merge-forward checkpoint before taking a newer base ([rationale](.agents/notes/implemented/process/2026-08-02-native-github-stacks-and-optional-rebases.md)). +- **Choose PR history deliberately.** Split independent changes and fix the introducing PR before propagation. Rebase branches with `rerere.enabled`; merge-forward only on the PR author's explicit request, keeping in-progress checkpoints. Rewrites use `--force-with-lease`, abort on remote movement, never raw `--force` ([rationale](.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md)). - **Labels:** one PR `kind/*`, all material `area/*`, and native Issue Type ([taxonomy](.agents/notes/implemented/process/2026-08-08-unified-github-label-taxonomy.md)). - **PR descriptions:** write and update every PR description with [dsh-pr-description](.agents/skills/dsh-pr-description/SKILL.md). - TODO markers: `FIXME`/`TODO`/`XXX` by urgency ([semantics](docs/development.md)). diff --git a/docs/cookbook/responding-to-pr-review-on-a-stack.i18n.yaml b/docs/cookbook/responding-to-pr-review-on-a-stack.i18n.yaml index a974d598d1..732ee119e7 100644 --- a/docs/cookbook/responding-to-pr-review-on-a-stack.i18n.yaml +++ b/docs/cookbook/responding-to-pr-review-on-a-stack.i18n.yaml @@ -6,11 +6,11 @@ en: f41561de1c6dbfef zh: 83b863e1ac91d913 /responding-to-review-across-a-stacked-pr-chain/ground-rules: - en: 5545e41aea74b5d6 - zh: 7105f51939753a1a + en: e5b1b3c2b7db3d92 + zh: 2fb7defc040f453d /responding-to-review-across-a-stacked-pr-chain/resolve-comments-through-the-stack: - en: 4d58b207c8ecbcaa - zh: 38673a460674b8d6 + en: 0699f3b7a2791606 + zh: 6ca53b1dc25bd38d /responding-to-review-across-a-stacked-pr-chain/verify: en: 07cfbae7602fc30e zh: 19782f06ee3c4a74 diff --git a/docs/cookbook/responding-to-pr-review-on-a-stack.md b/docs/cookbook/responding-to-pr-review-on-a-stack.md index 61b15fd5e7..79d783cc37 100644 --- a/docs/cookbook/responding-to-pr-review-on-a-stack.md +++ b/docs/cookbook/responding-to-pr-review-on-a-stack.md @@ -10,15 +10,15 @@ Review comments may target several PRs in a dependent stack (`A ← B ← C …` 2. **GitHub's stack object is authoritative.** Base branches establish the expected dependency order, while `PullRequest.stack` and `stackEntry.position` prove that GitHub recognizes it. Do not treat a matching branch chain as an official stack without checking those fields. 3. **A fix lands on the PR that INTRODUCED the issue, then flows up-stack.** When a comment on PR `B` points at code `B` introduced, fix it on `B` and propagate `B` into `C` — even if `C` also carries the file. Originating the fix downstream leaves `B` shipping the unfixed code and hides the fix from `B`'s reviewer. 4. **Each review fix remains a distinct commit.** A later rebase may change its OID, but do not amend a reviewed fix out of the branch history. Amend only your own not-yet-pushed, not-yet-reviewed work. -5. **Choose merge-forward or rebase deliberately.** Both histories are allowed after review. A rewritten push must be lease-protected and must abort rather than overwrite a concurrently advanced remote head; raw `--force` is forbidden. +5. **Propagate by rebase with rerere.** Run `git config rerere.enabled true` before rebasing so Git replays recorded conflict resolutions; inspect each replayed resolution before staging it. Use merge-forward only when the PR author explicitly asks for it. A rewritten push must be lease-protected and must abort rather than overwrite a concurrently advanced remote head; raw `--force` is forbidden ([rationale](../../.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md)). ## Resolve comments through the stack 1. Triage every comment on the merits before acting: verify the claim against the code — a reviewer flagging the right symptom can still misdiagnose the cause. 2. Map each accepted finding to its originating PR and fix it there. 3. Propagate the fixed layer through every affected child in order: - - **Merge-forward:** merge the fixed parent branch into its child, validate the child, and continue upward. Preserve each in-progress checkpoint. - **Native cascading rebase:** use `gh stack rebase`, validate the rewritten layers, then publish with `gh stack push`; or use `gh stack sync`, which may publish first and therefore requires immediate post-sync validation under [dsh-pre-push-checks](../../.agents/skills/dsh-pre-push-checks/SKILL.md). + - **Merge-forward, only on the PR author's explicit request:** merge the fixed parent branch into its child, validate the child, and continue upward. Preserve each in-progress checkpoint. 4. Treat delegated fixes as trust-but-verify: a sub-agent's report describes intent, not necessarily what landed. Re-run the gates yourself on the actual tree, and for a regression guard, prove it FAILS on the unfixed code (introduce the regression, watch red, revert) — a guard that passes both ways guards nothing. A sub-agent that reframes a problem as already handled is a signal to dig in personally. 5. Reply in the review thread (`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`), not as a top-level comment, stating the fix and the current commit or head that carries it. 6. After any rewritten push, re-read unresolved threads, approvals, mergeability, and checks. A force-pushed commit OID or outdated inline anchor is not current evidence that the finding remains resolved. diff --git a/docs/cookbook/responding-to-pr-review-on-a-stack.zh.md b/docs/cookbook/responding-to-pr-review-on-a-stack.zh.md index a33418d342..4b35491c23 100644 --- a/docs/cookbook/responding-to-pr-review-on-a-stack.zh.md +++ b/docs/cookbook/responding-to-pr-review-on-a-stack.zh.md @@ -10,15 +10,15 @@ 2. **GitHub 的 stack 对象是权威依据。** base 分支确定预期的依赖顺序,`PullRequest.stack` 和 `stackEntry.position` 则证明 GitHub 已识别该堆叠。未经检查这些字段,不得仅凭分支链吻合就将其视为官方堆叠。 3. **修复落在引入问题的那个 PR 上,然后沿堆叠向上流动。** 当 PR `B` 上的评论指向 `B` 引入的代码时,在 `B` 上修复,再将 `B` 的变更传播到 `C`,即使 `C` 也包含该文件。把修复发起在下游会导致 `B` 带着未修复的代码交付,并对 `B` 的评审者隐藏修复。 4. **每项评审修复都保留为独立 commit。** 后续 rebase 可能改变其 OID,但不得通过 amend 把已经评审的修复从分支历史中抹去。只有你自己尚未推送且尚未评审的工作才可以 amend。 -5. **明确选择 merge-forward 或 rebase。** 评审后允许采用这两种历史更新方式。改写历史的推送必须受 lease 保护;如果远端 head 在此期间前移,操作必须中止,不得将其覆盖。禁止直接使用 `--force`。 +5. **以启用 rerere 的 rebase 传播修复。** rebase 前运行 `git config rerere.enabled true`,让 Git 复用已记录的冲突解决结果;暂存前检查每个复用的解决结果。只有 PR 作者明确要求时才使用 merge-forward。改写历史的推送必须受 lease 保护;如果远端 head 在此期间前移,操作必须中止,不得将其覆盖。禁止直接使用 `--force`([理由](../../.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md))。 ## 沿堆叠解决评审意见 1. 在行动之前先就事论事地审视每条评论:对照代码验证其论断——评审者指出了正确的症状,但仍可能误诊原因。 2. 将每个被接受的发现映射到引入该问题的 PR,并在那里修复。 3. 将修复后的层按顺序传播到每个受影响的子 PR: - - **Merge-forward:** 将修复后的父分支合并到其子分支,验证子分支,然后继续沿堆叠向上传播。保留每个正在处理的检查点。 - **原生级联 rebase:** 使用 `gh stack rebase`,验证所有已改写的层,然后通过 `gh stack push` 发布;也可以使用 `gh stack sync`,该命令可能先发布,因此必须按照 [dsh-pre-push-checks](../../.agents/skills/dsh-pre-push-checks/SKILL.md) 在同步后立即验证。 + - **Merge-forward(仅在 PR 作者明确要求时):** 将修复后的父分支合并到其子分支,验证子分支,然后继续沿堆叠向上传播。保留每个正在处理的检查点。 4. 委派的修复需要信任但验证:subagent 的报告描述的是意图,不一定是实际落地的内容。请亲自在实际代码树上重新运行门禁;对于回归守卫,要证明它在未修复的代码上**失败**(引入回归、观察变红、再还原)——两种情况都通过的守卫什么也守不住。subagent 将问题重新定性为「已处理」时,这是一个需要亲自深入的信号。 5. 在评审线程中回复(`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`),而非发顶层评论;说明修复内容及当前承载修复的 commit 或 head。 6. 每次改写推送后,都要重新读取未解决线程、批准状态、可合并性和检查结果。经 force-push 改写的 commit OID 或已过时的内联锚点,都不足以证明该发现当前仍处于已解决状态。 From 477e646e1c12ded7a53cf1f464b7ea8aad3e3f50 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 19 Nov 2026 16:51:12 +0800 Subject: [PATCH 25/54] docs(agents): require unset rerere.autoUpdate and translate zh note title Co-authored-by: imccyu <276526105+imccyu@users.noreply.github.com> --- .../process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml | 6 +++--- .../process/2026-11-19-prefer-rebase-with-rerere.md | 2 +- .../process/2026-11-19-prefer-rebase-with-rerere.zh.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml index adac3c1f40..8dd88ae7ef 100644 --- a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml +++ b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.i18n.yaml @@ -4,13 +4,13 @@ # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md /agent-note-prefer-rebase-with-rerere-for-pr-refreshes: en: bee37c92f02c4b62 - zh: 9db32f3400ca6426 + zh: da3f086fc09072b3 /agent-note-prefer-rebase-with-rerere-for-pr-refreshes/problem: en: 3c585b97c13a98b1 zh: 040d30dcaadfbdf2 /agent-note-prefer-rebase-with-rerere-for-pr-refreshes/decision: - en: 03821a54b63dd691 - zh: 34f599c07fdef838 + en: 8c6753ecfaf6b246 + zh: d6850cd7ee0afb2a /agent-note-prefer-rebase-with-rerere-for-pr-refreshes/alternatives-considered: en: 35d2f27bc5712a11 zh: 5bd1eaaaa200666f diff --git a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md index 6e6fa5d61f..19fd7a8705 100644 --- a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md +++ b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.md @@ -10,7 +10,7 @@ The [native stack decision](2026-08-02-native-github-stacks-and-optional-rebases ## Decision -Agents refresh standalone and stacked PR branches by rebase, including after review. Before rebasing, the agent enables, once per clone, Git's reuse of recorded resolutions with `git config rerere.enabled true`, so Git records each resolved conflict and applies the recorded resolution when the same conflict recurs in a later rebase. Git leaves a replayed resolution unstaged for inspection; the agent reviews and stages it before continuing the rebase. +Agents refresh standalone and stacked PR branches by rebase, including after review. Before rebasing, the agent enables, once per clone, Git's reuse of recorded resolutions with `git config rerere.enabled true`, so Git records each resolved conflict and applies the recorded resolution when the same conflict recurs in a later rebase. The agent leaves `rerere.autoUpdate` unset, so Git leaves a replayed resolution unstaged for inspection; the agent reviews and stages it before continuing the rebase. Merge-forward is used only when the PR author explicitly asks for it. The incremental merge-forward procedure and its rule to preserve an in-progress checkpoint before taking a newer base remain available for that case. diff --git a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md index 8e1b89d3ce..e0af8b6f10 100644 --- a/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md +++ b/.agents/notes/implemented/process/2026-11-19-prefer-rebase-with-rerere.zh.md @@ -1,4 +1,4 @@ -# Agent Note: Prefer rebase with rerere for PR refreshes +# Agent Note: 以启用 rerere 的 rebase 刷新 PR 分支 Status: implemented @@ -10,7 +10,7 @@ Status: implemented ## 决策 -agent 以 rebase 刷新独立 PR 分支和堆叠 PR 分支,包括评审后。rebase 前,agent 在每个克隆中用 `git config rerere.enabled true` 启用一次 Git 的已记录冲突解决复用(rerere),Git 会记录每个已解决的冲突,并在之后的 rebase 中再次出现相同冲突时应用记录的解决结果。Git 把复用的解决结果留在未暂存状态以供检查;agent 检查并暂存后再继续 rebase。 +agent 以 rebase 刷新独立 PR 分支和堆叠 PR 分支,包括评审后。rebase 前,agent 在每个克隆中用 `git config rerere.enabled true` 启用一次 Git 的已记录冲突解决复用(rerere),Git 会记录每个已解决的冲突,并在之后的 rebase 中再次出现相同冲突时应用记录的解决结果。agent 不设置 `rerere.autoUpdate`,因此 Git 把复用的解决结果留在未暂存状态以供检查;agent 检查并暂存后再继续 rebase。 只有 PR 作者明确要求时才使用 merge-forward。增量 merge-forward 流程,以及在合入更新的 base 之前保留进行中检查点的规则,仍可用于这种情况。 From 0ee562045e4ee96ab994305838f40b726282512a Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:09:36 +0800 Subject: [PATCH 26/54] ci: build once and fan web snapshots out across weighted shards (#8861) * ci: build once and fan web snapshots out across weighted shards * ci: stamp restored build output with the extraction time Build-time mtimes shifted past the clock made HMR treat freshly loaded lib/ modules as changed and reload a plugin context while it was still loading (plugin-manager-mcp headless snapshot). * ci(web): run the longest web snapshot files as round-robin test slices * ci: address review on the build-once fan-out --- .../2026-07-26-ci-failover-runbook.i18n.yaml | 4 +- .../process/2026-07-26-ci-failover-runbook.md | 2 +- .../2026-07-26-ci-failover-runbook.zh.md | 2 +- ...0-11-build-artifacts-check-split.i18n.yaml | 4 +- .../2026-10-11-build-artifacts-check-split.md | 2 +- ...26-10-11-build-artifacts-check-split.zh.md | 2 +- ...6-07-24-web-gui-browser-e2e-lane.i18n.yaml | 4 +- .../2026-07-24-web-gui-browser-e2e-lane.md | 2 +- .../2026-07-24-web-gui-browser-e2e-lane.zh.md | 2 +- .github/workflows/ci.yml | 340 ++++++++++++++++-- package.json | 3 + scripts/ci-workflow.spec.ts | 70 +++- scripts/run-gates.spec.ts | 53 +++ scripts/run-gates.ts | 71 +++- scripts/run-web-snapshots.ts | 31 +- scripts/web-snapshot-projects.spec.ts | 84 +++++ scripts/web-snapshot-projects.ts | 136 +++++++ scripts/web-snapshot-sequencer.spec.ts | 44 +++ scripts/web-snapshot-sequencer.ts | 83 +++++ scripts/web-snapshot-slice.setup.ts | 52 +++ vitest.snapshot.config.ts | 10 +- vitest.web.config.ts | 11 +- vitest.web.perf.config.ts | 6 +- 23 files changed, 951 insertions(+), 67 deletions(-) create mode 100644 scripts/web-snapshot-projects.spec.ts create mode 100644 scripts/web-snapshot-projects.ts create mode 100644 scripts/web-snapshot-sequencer.spec.ts create mode 100644 scripts/web-snapshot-sequencer.ts create mode 100644 scripts/web-snapshot-slice.setup.ts diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml index 907c19c6e6..3215401d0a 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml @@ -9,8 +9,8 @@ en: bcdd24f3c39d593c zh: 3e576d09c8c3bfd4 /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision: - en: fed13ca92e488b69 - zh: 9e5c9cdc118ab84e + en: 23fc560e2c12be5e + zh: 89071bd1735823ff /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision/release-rehearsals-share-the-linux-switch: en: 01e74068e0a96375 zh: aa811861ce30cb47 diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md index 8c03479ba2..360a39a640 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md @@ -10,7 +10,7 @@ The three required Linux worker jobs in [CI](../../../../.github/workflows/ci.ym ## Decision -The three primary Linux jobs (`node-24`, `node-24-coverage`, `node-24-consumers`), the two `node-compat` matrix entries, and the `all-checks-passed`, `windows-checks-passed`, and `python-checks-passed` verdicts resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; the `blacksmith` value routes the participating jobs per the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); unset or any other value retains the workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain the `ubuntu-latest` fallback under unset and non-special values; the blacksmith branch carries none of those predicates. Under the `selfhosted` value, Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The three verdict jobs follow the Linux switch so they do not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes. +The primary Linux jobs (`node-24`, `node-24-coverage`, `node-24-build`, `node-24-consumers`, which restores the `node-24-build` output, and both entries of the `node-24-web-snapshot` shard matrix), the two `node-compat` matrix entries, and the `all-checks-passed`, `windows-checks-passed`, and `python-checks-passed` verdicts resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; the `blacksmith` value routes the participating jobs per the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); unset or any other value retains the workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain the `ubuntu-latest` fallback under unset and non-special values; the blacksmith branch carries none of those predicates. Under the `selfhosted` value, Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The three verdict jobs follow the Linux switch so they do not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes. The [superseded-CI cancellation policy](../../../../.github/workflows/ci.yml) governs master pushes and manual runs in the same workflow/ref group, including standby drills. Rapid master updates can starve a drill before it reaches a verdict. Use the latest completed standby verdict and check its age and commit before treating it as readiness evidence; a cancelled or merely scheduled run is not proof of readiness. diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md index e72908e3fc..c89acf64ea 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -三个主要 Linux 作业(`node-24`、`node-24-coverage`、`node-24-consumers`)、两个 `node-compat` 矩阵条目,以及 `all-checks-passed`、`windows-checks-passed`、`python-checks-passed` 三个判定作业通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;`blacksmith` 取值按 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md) 路由参与切换的作业;未设置或任何其它值保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并在未设置与非特殊值下保留 `ubuntu-latest` 回退;blacksmith 分支不带上述任何条件。在 `selfhosted` 取值下,Linux 故障切换会限制快照并发,并跳过托管软件包缓存恢复。三个判定作业跟随 Linux 开关,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。 +主要 Linux 作业(`node-24`、`node-24-coverage`、`node-24-build`、恢复 `node-24-build` 产物的 `node-24-consumers`,以及 `node-24-web-snapshot` 分片矩阵的两个条目)、两个 `node-compat` 矩阵条目,以及 `all-checks-passed`、`windows-checks-passed`、`python-checks-passed` 三个判定作业通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;`blacksmith` 取值按 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md) 路由参与切换的作业;未设置或任何其它值保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并在未设置与非特殊值下保留 `ubuntu-latest` 回退;blacksmith 分支不带上述任何条件。在 `selfhosted` 取值下,Linux 故障切换会限制快照并发,并跳过托管软件包缓存恢复。三个判定作业跟随 Linux 开关,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。 [被取代 CI 的取消策略](../../../../.github/workflows/ci.yml) 管理同一工作流/引用组内的 master 推送和手动运行,包括热备演练。master 快速更新可能让演练因反复被取消而始终无法得出结论。判断就绪状态时,使用最近一次已完成的热备结论,并核对其时间和提交;已取消或仅被调度的运行不构成就绪证据。 diff --git a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml index ab4b4c81af..f830421900 100644 --- a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml +++ b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml @@ -21,8 +21,8 @@ en: 6a1b4ed0d9910133 zh: f32c6882208ded71 /agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/callers: - en: 895968956b86a9d2 - zh: 5218d9ab8c60a53a + en: dad172a1cabc42cb + zh: 0180238dcb53ee3f /agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/measurements: en: b3a753ac2aab6073 zh: 19cbd0e32751896f diff --git a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md index fcd4fed452..8f43ccd136 100644 --- a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md +++ b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md @@ -50,7 +50,7 @@ Each command does only its own job. | `typecheck` (run by the pre-push hook) | `build.ts --scope typecheck`: host-typert (the source-only Typert pass `generate-typert.ts`) → package compilation, with `tsc -b tsconfig.{host,client}.json` after each face's package compilation; no bundle | Yes | | `dev:web` ([`scripts/dev-web.ts`](../../../../scripts/dev-web.ts)), `dev:desktop` (`apps/desktop/scripts/dev.ts`) | `build:artifacts` | None before launch; after `dev:web` launches, its `tsc -b tsconfig.client.json --watch` keeps checking the Client aggregate root program | | Prerequisite step of `lint`, `lint:fix`, `doc-typecheck`, and the CI Typert contracts gate | Source-only Typert generation before Host package compilation (`compile-referenced-projects.ts host-contracts`), without any bundle | None | -| CI node 24 / snapshots and artifacts (`check:ci:consumers`), windows node 24 / build & observational (`check:ci:windows-blocking`) | `build` | Yes, the two required lanes | +| CI node 24 / build (`check:ci:build`), whose restored output `node 24 / snapshots and artifacts` (`check:ci:consumers-prebuilt`) and `node 24 / web snapshots /2` consume, windows node 24 / build & observational (`check:ci:windows-blocking`) | `build` | Yes, the two required lanes | | CI node-compat 24.9 | `build:artifacts` (through run-gates) | None | | CI python runtime | `build-exe-for-python-sdk.ts --build-artifacts` | None | | PR rehearsals in `e2e.yml` and `release.yml` | `pnpm run build:artifacts --profile official` | None | diff --git a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md index cc52a1a925..8eb2ed11e0 100644 --- a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md +++ b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md @@ -50,7 +50,7 @@ Status: implemented | `typecheck`(pre-push hook 运行它) | `build.ts --scope typecheck`:host-typert(只读源码的 Typert 生成 `generate-typert.ts`)→ 包编译,各 face 包编译后运行 `tsc -b tsconfig.{host,client}.json`;不含任何 bundle | 有 | | `dev:web`([`scripts/dev-web.ts`](../../../../scripts/dev-web.ts))、`dev:desktop`(`apps/desktop/scripts/dev.ts`) | `build:artifacts` | 启动前无;`dev:web` 启动后的 `tsc -b tsconfig.client.json --watch` 持续检查 Client 聚合根程序 | | `lint`、`lint:fix`、`doc-typecheck` 与 CI 的 Typert contracts gate 的前置步骤 | 仅源码 Typert 生成后进行 Host 包编译(`compile-referenced-projects.ts host-contracts`),不含任何 bundle | 无 | -| CI node 24 / snapshots and artifacts(`check:ci:consumers`)、windows node 24 / build & observational(`check:ci:windows-blocking`) | `build` | 有,两个必需 lane | +| CI node 24 / build(`check:ci:build`,`node 24 / snapshots and artifacts`(`check:ci:consumers-prebuilt`)与 `node 24 / web snapshots /2` 恢复并消费其产物)、windows node 24 / build & observational(`check:ci:windows-blocking`) | `build` | 有,两个必需 lane | | CI node-compat 24.9 | `build:artifacts`(经 run-gates) | 无 | | CI python runtime | `build-exe-for-python-sdk.ts --build-artifacts` | 无 | | `e2e.yml`、`release.yml` 的 PR 演练 | `pnpm run build:artifacts --profile official` | 无 | diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml index 3554853dcc..d114a1219a 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml @@ -27,8 +27,8 @@ en: c529437d4fbaeeb3 zh: fe13551e56cba7df /agent-note-keyless-browser-e2e-lane-for-the-web-gui/decision/ci-stance: - en: a4ed258cd19db1c0 - zh: 913e079a6250d7d7 + en: 2e5329f8291bd365 + zh: fb8c72b71232847d /agent-note-keyless-browser-e2e-lane-for-the-web-gui/prior-art: en: 7472e212043721dd zh: 61dd9f5a8e12730b diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md index cbbcee49c7..aee36a5101 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md @@ -50,7 +50,7 @@ The lane covers three behavior families. Live-turn scenarios pin ordinary tool e ### CI stance -The lane is a required compare-only gate for Linux pull requests under the [browser snapshot CI reference](../../../../docs/testing.md). The `node 24 / snapshots and artifacts` consumer job owns the [single Linux build](../../archived/process/2026-07-30-independent-ci-consumer-build.md), installs the lockfile-selected Chromium and WebKit, restores their OS-and-lockfile-keyed cache, and runs the lane with `DSH_SNAPSHOT=replay`. This is an intentional plane split: the host and specs use the [tsx source-launch contract](../architecture/2026-07-29-dsh-source-launch-tsx-esm.md), while the browser consumes `apps/web/dist` and package `lib/client.js` artifacts, so the gate depends on `build` for those client artifacts. The self-hosted default-branch Linux serial standby runs the same gate; there is no hosted Linux serial producer of the browser cache consumed by pull requests, and the persistent self-hosted pool needs no hosted cache. CI never records or refreshes goldens. Scenarios remain POSIX-oriented and stay outside the Windows and macOS matrices. +The lane is a required compare-only gate for Linux pull requests under the [browser snapshot CI reference](../../../../docs/testing.md). The `node 24 / build` job owns the single Linux build and publishes its output; the two entries of the `node 24 / web snapshots /2` matrix job restore that output, install the lockfile-selected Chromium and WebKit from their OS-and-lockfile-keyed cache, and each run one weighted shard of the lane with `DSH_SNAPSHOT=replay`. The longest files run as round-robin test slices, one Vitest project per slice, so no single file bounds a shard ([slice plan](../../../../scripts/web-snapshot-projects.ts)). The recorded-session corpus in `node 24 / snapshots and artifacts` does not run the Web adapters under `apps/web/tests/`. This is an intentional plane split: the host and specs use the [tsx source-launch contract](../architecture/2026-07-29-dsh-source-launch-tsx-esm.md), while the browser consumes `apps/web/dist` and package `lib/client.js` artifacts, so the gate depends on `build` for those client artifacts. The self-hosted default-branch Linux serial standby runs the same gate; there is no hosted Linux serial producer of the browser cache consumed by pull requests, and the persistent self-hosted pool needs no hosted cache. CI never records or refreshes goldens. Scenarios remain POSIX-oriented and stay outside the Windows and macOS matrices. High-cardinality performance diagnostics use the separate opt-in `apps/web/tests/**/*.perf.ts` inventory selected only by `vitest.web.perf.config.ts`. The isolated `complex-history.perf.ts` cases reuse the real scaffold: the workspace case seeds 1,000 compact sessions plus one 500-turn history containing 500 tool calls, exhausts and remounts that history in Chat, and reports Chromium main-thread, DOM, listener, heap, paging, search, and Trajectory measurements. Two continuation cases seed the same long history but compare the default 24-turn Chat window with all 500 turns expanded before each continues eight identical turns through the real composer, agent loop, SSE wire, tools, and persistence; two turns execute a real `bash` call and assert its durable result, while the final turn fills an 8,232-character mixed-language prompt and replays 120 paced text deltas. A separate soak case starts from a blank session, drives 100 consecutive real composer turns with a `bash` call and result every tenth turn, forces GC every ten turns, and reports ten-turn latency windows plus retained browser state. It then submits a 101st text-only turn with a trusted browser click and measures browser-clock send-to-transcript-DOM and send-to-post-paint latency, excluding the composer's draft mirrors, separately from full-turn completion. Per-turn diagnostics cover composer fill, click-to-user-echo, click-to-first-chunk, completion, browser mutations, persisted chunks, and tool events; the synthetic replay model has enough context capacity to keep fixture cardinality stable instead of consuming scripted calls through compaction. Structural assertions pin the intended load, stream, and tool shapes, but timing remains threshold-free because machine speed is not a correctness contract. The required `vitest.web.config.ts` inventory remains limited to `*.e2e.ts` and `*.snapshot.ts`, so neither `test:web:built` nor its CI gate collects performance cases. diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md index f9c522a559..e85d57e1a6 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md @@ -50,7 +50,7 @@ Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bu ### CI 立场 -根据[浏览器快照 CI 说明](../../../../docs/testing.zh.md),该车道是 Linux 拉取请求必需的只比较门禁。`node 24 / snapshots and artifacts` 消费方任务在[消费方独立构建](../../archived/process/2026-07-30-independent-ci-consumer-build.md)中负责唯一一次 Linux 构建,安装锁文件选定的 Chromium 和 WebKit,恢复以操作系统和锁文件为键的缓存,并用 `DSH_SNAPSHOT=replay` 运行该车道。这是有意的平面切分:host 与 spec 使用 [tsx 源码启动约定](../architecture/2026-07-29-dsh-source-launch-tsx-esm.zh.md),浏览器则消费 `apps/web/dist` 和包的 `lib/client.js` 产物,因此门禁依赖 `build` 提供这些客户端产物。自托管的默认分支 Linux 串行热备运行同一门禁;不存在托管 Linux 串行生产者生成供 PR 消费的浏览器缓存,持久化自托管池则不需要托管侧缓存。CI 从不录制或刷新预期输出。场景仍面向 POSIX,并继续置于 Windows 和 macOS 矩阵之外。 +根据[浏览器快照 CI 说明](../../../../docs/testing.zh.md),该车道是 Linux 拉取请求必需的只比较门禁。`node 24 / build` 任务负责唯一一次 Linux 构建并发布其产物;`node 24 / web snapshots /2` 矩阵任务的两个条目恢复该产物,从以操作系统和锁文件为键的缓存安装锁文件选定的 Chromium 和 WebKit,并各自用 `DSH_SNAPSHOT=replay` 运行该车道的一个加权分片。最长的几个文件按测试轮转拆成切片,每个切片是一个 Vitest 项目,因此单个文件不会决定一个分片的耗时([切片计划](../../../../scripts/web-snapshot-projects.ts))。`node 24 / snapshots and artifacts` 中的录制会话语料不运行 `apps/web/tests/` 下的 Web 适配器。这是有意的平面切分:host 与 spec 使用 [tsx 源码启动约定](../architecture/2026-07-29-dsh-source-launch-tsx-esm.zh.md),浏览器则消费 `apps/web/dist` 和包的 `lib/client.js` 产物,因此门禁依赖 `build` 提供这些客户端产物。自托管的默认分支 Linux 串行热备运行同一门禁;不存在托管 Linux 串行生产者生成供 PR 消费的浏览器缓存,持久化自托管池则不需要托管侧缓存。CI 从不录制或刷新预期输出。场景仍面向 POSIX,并继续置于 Windows 和 macOS 矩阵之外。 高基数性能诊断使用单独按需启用的 `apps/web/tests/**/*.perf.ts` 清单,并且只由 `vitest.web.perf.config.ts` 选中。`complex-history.perf.ts` 的隔离用例复用真实 scaffold:工作区用例播种 1,000 个紧凑会话以及一份包含 500 次工具调用的 500 轮次历史,在 Chat 中穷尽并重新挂载该历史,并报告 Chromium 主线程、DOM、监听器、堆内存、分页、搜索和 Trajectory 测量结果。两个续聊用例播种同一份长历史,但比较默认的 24 轮次 Chat 窗口与展开全部 500 轮次的状态,然后各自通过真实输入框、agent loop、SSE wire、工具和持久化继续进行 8 个相同轮次;其中两轮执行真实 `bash` 调用并断言其持久化结果,最后一轮则填入一条包含 8,232 个字符的混合语言提示词,并回放 120 个带节奏的文本增量。一个单独的 soak 用例从空白会话开始,通过真实输入框连续驱动 100 轮,每第 10 轮执行一次 `bash` 调用并产生结果,每 10 轮强制执行一次 GC,并报告每 10 轮的延迟窗口及保留的浏览器状态。随后它通过受信任的浏览器点击提交第 101 个纯文本轮次,并使用浏览器时钟分别测量发送到 transcript DOM 和发送到绘制后的延迟,排除输入框的草稿镜像,并与完整轮次完成时间分开。逐轮诊断涵盖输入框填入、点击到用户消息回显、点击到首个分片、完成、浏览器变更、持久化分片和工具事件;合成回放模型拥有足够的上下文容量,可使 fixture 基数保持稳定,而不会因压缩(compaction)消耗脚本化调用。结构性断言钉住预期的负载、流和工具形状,但时间仍不设阈值,因为机器速度不属于正确性约定。必需的 `vitest.web.config.ts` 清单仍仅限 `*.e2e.ts` 和 `*.snapshot.ts`,因此 `test:web:built` 及其 CI 门禁都不会收集性能用例。 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a1d0a0b7b5..146937a1bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,16 +56,16 @@ jobs: run: node --import tsx tests/isolated-install.mjs - # Three enterprise jobs isolate coverage, static analysis, and the - # build-backed consumer tail. The consumer job owns the only Linux build so - # all three jobs enter runner allocation independently. + # Enterprise jobs isolate coverage, static analysis, and the build-backed + # tail. The build job owns the only Linux artifact build; the consumer job + # and the two web snapshot shards restore its output instead of rebuilding. # # FAILOVER (Linux): each Linux enterprise job resolves its pool through the # DSH_CI_FAILOVER_LINUX repository variable. Unset (normal), the expressions # pick the hosted enterprise pools below. Setting the variable to # 'selfhosted' (repo Settings → Actions → Variables; writer-manageable - # repository state — not PR-editable, no merge required) retargets all - # three onto the in-house + # repository state — not PR-editable, no merge required) retargets them + # all onto the in-house # vm-backup pool and re-running the failed jobs is the entire switch — # see .agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md. # Setting the variable to 'blacksmith' instead routes the same jobs onto @@ -387,7 +387,120 @@ jobs: if-no-files-found: warn retention-days: 7 + # Build the artifacts once, run the cheap readers, and publish the output + # for the downstream consumer and web snapshot jobs, which restore it + # instead of rebuilding. + node-24-build: + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'dsh-ubuntu-24-04-16core' }} + name: node 24 / build + env: + # Shared hosts expose host CPUs, not an isolated allocation. + DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '10' || '' }} + DSH_OXLINT_THREADS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} + DSH_PUBLINT_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} + DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '' }} + DSH_NODE_COMPAT_SKIP_TYPECHECK: '1' + # A failing gate aborts its running siblings. + DSH_GATE_FAIL_FAST: '1' + steps: + # Runner cleanup owns tool caches and fixtures, including cancelled runs. + - name: Use runner-owned temporary storage + run: | + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + + # Redirect the Node compile cache (enabled by pnpm and TypeScript) off + # the root partition's /tmp before the first pnpm call in this lane. + - name: Redirect Node compile cache to runner temp + run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v5.0.0 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v7.0.0 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + # Pull requests restore the pnpm store without paying compression and + # upload on the required path. Self-hosted runners reuse the shared + # persistent store instead of restoring the remote archive. + - uses: actions/cache/restore@v6.1.0 + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # Everything the build adds to the ignored or untracked set is its output. + - name: Record files before the build + run: git status --porcelain=v1 --ignored --untracked-files=normal > "$RUNNER_TEMP/files-before.txt" + + - name: Build artifacts and run the cheap readers + run: pnpm run check:ci:build + + - name: Pack build output + env: + # Compression costs well under a second at -T0; a smaller archive + # shortens the upload and every download. + ZSTD_LEVEL: '9' + run: | + set -o pipefail + out="$RUNNER_TEMP/build-output" + mkdir -p "$out" + git status --porcelain=v1 --ignored --untracked-files=normal > "$RUNNER_TEMP/files-after.txt" + comm -13 <(sort "$RUNNER_TEMP/files-before.txt") <(sort "$RUNNER_TEMP/files-after.txt") \ + | sed -n -E 's/^(!!|\?\?) //p' \ + | grep -v -E '(^|/)(node_modules|\.node-next-types-[^/]*|\.doc-typecheck-[^/]*|\.oxlint-contract-[^/]*|\.typert-[^/]*|\.cache)/?$' \ + | sed 's#/$##' > "$out/paths.txt" + echo "build output entries: $(wc -l < "$out/paths.txt")" + du -sch $(cat "$out/paths.txt") | tail -1 + tar -cf - -T "$out/paths.txt" | zstd -q -T0 -"$ZSTD_LEVEL" -o "$out/build-output.tar.zst" + zstd -dc "$out/build-output.tar.zst" | tar -tf - > "$out/contents.txt" + for required in apps/cli/lib/bin.js apps/web/dist/index.html .dsh-build/client-build-environment.json; do + grep -qx "$required" "$out/contents.txt" || { echo "::error::build output is missing $required"; exit 1; } + done + echo "archive entries: $(wc -l < "$out/contents.txt")" + rm "$out/contents.txt" + + - name: Upload build output + uses: actions/upload-artifact@v7.0.1 + with: + name: build-output + path: | + ${{ runner.temp }}/build-output/build-output.tar.zst + ${{ runner.temp }}/build-output/paths.txt + # Re-running a failed downstream job does not rebuild; keep the output + # for GitHub's 30-day re-run window. + retention-days: 30 + compression-level: 0 + if-no-files-found: error + # A re-run of this job replaces the previous attempt's output. + overwrite: true + node-24-consumers: + needs: node-24-build if: github.event_name == 'pull_request' runs-on: >- ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' @@ -404,13 +517,150 @@ jobs: DSH_WEB_SNAPSHOT_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }} DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '' }} DSH_NODE_COMPAT_SKIP_TYPECHECK: '1' - # Browsers install beside the build; only the browser readers wait for them. - # The persistent VM image owns Playwright's Linux system packages, so the - # failover pool skips apt instead of mutating the shared host each run. - DSH_CI_PLAYWRIGHT_INSTALL: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && 'browsers' || 'with-deps' }} - # A failing gate aborts its running siblings: a failing build stops the - # independent Node compatibility smoke, and a failing reader (e.g. - # publint) stops the remaining artifact consumers. + # A failing gate aborts its running siblings. + DSH_GATE_FAIL_FAST: '1' + steps: + # Runner cleanup owns tool caches and fixtures, including cancelled runs. + - name: Use runner-owned temporary storage + run: | + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + + # Redirect the Node compile cache (enabled by pnpm and TypeScript) off + # the root partition's /tmp before the first pnpm call in this lane. + - name: Redirect Node compile cache to runner temp + run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v5.0.0 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v7.0.0 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + # Pull requests restore the pnpm store without paying compression and + # upload on the required path. Self-hosted runners reuse the shared + # persistent store instead of restoring the remote archive. + - uses: actions/cache/restore@v6.1.0 + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + # The persistent self-hosted pool keeps ~/.cache between jobs on its own + # layout, so the archive cache follows the hosted-only pnpm store guard. + - name: Restore verified bubblewrap archive + id: bubblewrap-cache + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + uses: actions/cache/restore@v6.1.0 + with: + path: ~/.cache/dsh-ci/bubblewrap + key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} + + - name: Install dependencies and prepare bubblewrap + run: | + pnpm install --frozen-lockfile & + install_pid=$! + bash scripts/prepare-ci-bubblewrap.sh & + sandbox_pid=$! + install_status=0 + wait "$install_pid" || install_status=$? + sandbox_status=0 + wait "$sandbox_pid" || sandbox_status=$? + if (( install_status != 0 )); then exit "$install_status"; fi + exit "$sandbox_status" + + - name: Save verified bubblewrap archive + if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v6.1.0 + with: + path: ~/.cache/dsh-ci/bubblewrap + key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} + + # Restore the build job's output after the install, so no install or + # postinstall step can replace restored files. The fixed artifact name + # resolves within this run, including a re-run of this job alone. + - name: Download build output + uses: actions/download-artifact@v8.0.1 + with: + name: build-output + path: ${{ runner.temp }}/build-output + + - name: Unpack build output + run: | + set -o pipefail + archive="$RUNNER_TEMP/build-output/build-output.tar.zst" + # -m stamps restored files with the extraction time: newer than this + # checkout and never in the future. Build-time mtimes ahead of the + # clock make HMR treat freshly loaded lib/ modules as changed. + zstd -dc -T0 "$archive" | tar -xmf - + test -f apps/cli/lib/bin.js && test -f apps/web/dist/index.html && test -f .dsh-build/client-build-environment.json + + # No gate reads the Office runtime output, so it builds beside the gates. + # GitHub runners keep a background process started in one step alive for + # the later steps of the same job; the final step collects its status. + - name: Start the Linux Office runtime build + id: office-runtime + run: | + ( + status=0 + CI=true pnpm run prepare:primary-runtime --target linux-x64 --output "$RUNNER_TEMP/office-runtime" --cache "$RUNNER_TEMP/office-runtime-downloads" || status=$? + echo "$status" > "$RUNNER_TEMP/office-runtime.status" + ) > "$RUNNER_TEMP/office-runtime.log" 2>&1 & + echo "$!" > "$RUNNER_TEMP/office-runtime.pid" + + - name: Run compatibility, snapshot, and artifact gates + run: pnpm run check:ci:consumers-prebuilt + + - name: Wait for the Linux Office runtime + if: ${{ !cancelled() && steps.office-runtime.outcome == 'success' }} + run: | + pid=$(cat "$RUNNER_TEMP/office-runtime.pid") + while kill -0 "$pid" 2>/dev/null; do sleep 1; done + cat "$RUNNER_TEMP/office-runtime.log" + status=$(cat "$RUNNER_TEMP/office-runtime.status" 2>/dev/null || echo missing) + if [[ "$status" != 0 ]]; then + echo "::error::Linux Office runtime build failed with status $status" + exit 1 + fi + + node-24-web-snapshot: + needs: node-24-build + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'dsh-ubuntu-24-04-16core' }} + strategy: + fail-fast: false + matrix: + shard: [1, 2] + name: node 24 / web snapshots ${{ matrix.shard }}/2 + env: + # Shared hosts expose host CPUs, not an isolated allocation. + DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '10' || '' }} + DSH_WEB_SNAPSHOT_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }} + DSH_WEB_SNAPSHOT_SHARD: ${{ matrix.shard }}/2 + # Every shard reads these shares. Each shard runs alone on its + # machine; the last shard also runs the ~40s of serial files first. + DSH_WEB_SNAPSHOT_SHARD_SHARES: '0.54,0.46' + # A failing gate aborts its running siblings. DSH_GATE_FAIL_FAST: '1' steps: # Runner cleanup owns tool caches and fixtures, including cancelled runs. @@ -444,11 +694,9 @@ jobs: store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) echo "path=$store_path" >> "$GITHUB_OUTPUT" - # Pull requests restore the pnpm store and Playwright caches without paying - # compression and upload on the required path. No master job saves these - # hosted cache keys, so each restore-keys fallback hits the matching archived - # entry until it evicts, after which the store is cold. Self-hosted runners - # reuse the shared persistent store instead of restoring the remote archive. + # Pull requests restore the pnpm store without paying compression and + # upload on the required path. Self-hosted runners reuse the shared + # persistent store instead of restoring the remote archive. - uses: actions/cache/restore@v6.1.0 if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' with: @@ -497,8 +745,8 @@ jobs: key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} # Ubuntu HTTP archive mirrors can stall for tens of seconds per package - # (Blacksmith lists http://azure.archive.ubuntu.com first), so ephemeral - # runners fetch the archive over HTTPS before the Playwright gate's apt. + # (Blacksmith lists http://azure.archive.ubuntu.com first), so every + # ephemeral runner fetches the archive over HTTPS before Playwright's apt. - name: Use HTTPS for Ubuntu archives if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' run: | @@ -517,12 +765,56 @@ jobs: r'https://\1.ubuntu.com/', source.read_text())) PY - - name: Build and execute the Linux Office runtime - run: CI=true pnpm run prepare:primary-runtime --target linux-x64 --output "$RUNNER_TEMP/office-runtime" --cache "$RUNNER_TEMP/office-runtime-downloads" + # The browser install overlaps the artifact download and unpack. GitHub + # runners keep a background process started in one step alive for the + # later steps of the same job, and the wait step below collects its exit + # status. The persistent VM image owns Playwright's Linux system packages, + # so the failover pool skips apt instead of mutating the shared host. + - name: Start Playwright browser install + env: + PLAYWRIGHT_INSTALL_MODE: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && 'browsers' || 'with-deps' }} + run: | + deps=() + if [[ "$PLAYWRIGHT_INSTALL_MODE" == with-deps ]]; then deps=(--with-deps); fi + ( + status=0 + pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install "${deps[@]}" chromium webkit || status=$? + echo "$status" > "$RUNNER_TEMP/playwright-install.status" + ) > "$RUNNER_TEMP/playwright-install.log" 2>&1 & + echo "$!" > "$RUNNER_TEMP/playwright-install.pid" - - name: Run compatibility, snapshot, and artifact gates - run: pnpm run check:ci:consumers + # Restore the build job's output after the install, so no install or + # postinstall step can replace restored files. The fixed artifact name + # resolves within this run, including a re-run of this job alone. + - name: Download build output + uses: actions/download-artifact@v8.0.1 + with: + name: build-output + path: ${{ runner.temp }}/build-output + - name: Unpack build output + run: | + set -o pipefail + archive="$RUNNER_TEMP/build-output/build-output.tar.zst" + # -m stamps restored files with the extraction time: newer than this + # checkout and never in the future. Build-time mtimes ahead of the + # clock make HMR treat freshly loaded lib/ modules as changed. + zstd -dc -T0 "$archive" | tar -xmf - + test -f apps/cli/lib/bin.js && test -f apps/web/dist/index.html && test -f .dsh-build/client-build-environment.json + + - name: Wait for Playwright browsers + run: | + pid=$(cat "$RUNNER_TEMP/playwright-install.pid") + while kill -0 "$pid" 2>/dev/null; do sleep 1; done + cat "$RUNNER_TEMP/playwright-install.log" + status=$(cat "$RUNNER_TEMP/playwright-install.status" 2>/dev/null || echo missing) + if [[ "$status" != 0 ]]; then + echo "::error::Playwright browser install failed with status $status" + exit 1 + fi + + - name: Run web browser snapshot shard + run: pnpm run check:ci:web-snapshot-prebuilt node-compat: needs: publisher-isolated @@ -656,7 +948,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [publisher-isolated, node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat] + needs: [publisher-isolated, node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-build, node-24-consumers, node-24-web-snapshot, node-compat] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/package.json b/package.json index b92f86fc6c..e433b1d4fd 100644 --- a/package.json +++ b/package.json @@ -97,6 +97,9 @@ "check:ci:snapshot": "tsx scripts/run-gates.ts ci-snapshot", "check:ci:artifacts": "tsx scripts/run-gates.ts ci-artifacts", "check:ci:consumers": "tsx scripts/run-gates.ts ci-consumers", + "check:ci:build": "tsx scripts/run-gates.ts ci-build", + "check:ci:consumers-prebuilt": "tsx scripts/run-gates.ts ci-consumers-prebuilt", + "check:ci:web-snapshot-prebuilt": "tsx scripts/run-gates.ts ci-web-snapshot-prebuilt", "check:windows-wine": "bash scripts/wine-windows-gates.sh", "check:ci:windows-blocking": "tsx scripts/run-gates.ts ci-windows-blocking", "check:ci:windows-complete": "tsx scripts/run-gates.ts ci-windows-complete", diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index 449e3c1f31..3b7cb0a347 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -15,7 +15,7 @@ const runnerPrivatePnpmDestination = /^\$\{\{ runner\.temp \}\}\/setup-pnpm-\$\{ const nativeWindowsPnpmDestination = '${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}' describe('CI workflow', () => { - it('keeps at most eleven worker jobs active across PR workflows while Python runtime targets follow the SDK suite', () => { + it('keeps at most fourteen worker jobs active across PR workflows while Python runtime targets follow the SDK suite', () => { const ci = loadWorkflow('.github/workflows/ci.yml') const ciWindows = loadWorkflow('.github/workflows/ci-windows.yml') const ciPython = loadWorkflow('.github/workflows/ci-python.yml') @@ -40,8 +40,13 @@ describe('CI workflow', () => { matrix: { include: [{ node: '24.9' }, { node: 26 }] }, }) expect(workflowJob(ci, 'all-checks-passed').needs).toContain('node-compat') + // The web snapshot shards are the only other matrix: one job, one runner per shard. + const webSnapshot = workflowJob(ci, 'node-24-web-snapshot') + expect(webSnapshot.strategy).toEqual({ 'fail-fast': false, matrix: { shard: [1, 2] } }) + const webSnapshotShards = isRecord(webSnapshot.strategy) && isRecord(webSnapshot.strategy.matrix) + && Array.isArray(webSnapshot.strategy.matrix.shard) ? webSnapshot.strategy.matrix.shard.length : 0 const ordinaryJobs = Object.entries(ci.jobs) - .filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated'].includes(name)) + .filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated', 'node-24-web-snapshot'].includes(name)) for (const [name, job] of ordinaryJobs) { if (!isRecord(job)) throw new TypeError(`${name} must define a job`) expect(job).not.toHaveProperty('strategy') @@ -94,10 +99,13 @@ describe('CI workflow', () => { const windowsActive = windowsJobs.length // The lint lane owns its own runner, so it raises the ceiling by one; the // self-hosted failover pool is still admitted only up to its own limit. - const beforeSdk = ordinaryJobs.length + compatibilityLimit + windowsActive + 1 - const afterSdk = ordinaryJobs.length + compatibilityLimit + windowsActive + Math.max(1, targets.split(',').length) - expect(beforeSdk).toBeLessThanOrEqual(11) - expect(afterSdk).toBeLessThanOrEqual(11) + // The build job finishes before its downstream jobs start, so the + // static count overstates the peak by one. + const linuxActive = ordinaryJobs.length + webSnapshotShards + const beforeSdk = linuxActive + compatibilityLimit + windowsActive + 1 + const afterSdk = linuxActive + compatibilityLimit + windowsActive + Math.max(1, targets.split(',').length) + expect(beforeSdk).toBeLessThanOrEqual(14) + expect(afterSdk).toBeLessThanOrEqual(14) }) it('keeps required PR verdicts covering runtime and publisher jobs', () => { @@ -121,9 +129,11 @@ describe('CI workflow', () => { expect(blocking.sort()).toEqual([ 'node-24', 'node-24-bench', + 'node-24-build', 'node-24-consumers', 'node-24-coverage', 'node-24-lint', + 'node-24-web-snapshot', 'node-compat', 'publisher-isolated', 'python-runtime', @@ -136,7 +146,9 @@ describe('CI workflow', () => { it('retains aggregate diagnostics in required builds and protected publication', () => { for (const [file, name, command] of [ - ['ci.yml', 'node-24-consumers', 'pnpm run check:ci:consumers'], + ['ci.yml', 'node-24-build', 'pnpm run check:ci:build'], + ['ci.yml', 'node-24-consumers', 'pnpm run check:ci:consumers-prebuilt'], + ['ci.yml', 'node-24-web-snapshot', 'pnpm run check:ci:web-snapshot-prebuilt'], ['ci-windows.yml', 'windows-build', 'pnpm run check:ci:windows-blocking'], ] as const) { const job = workflowJob(loadWorkflow('.github/workflows/' + file), name) @@ -158,6 +170,41 @@ describe('CI workflow', () => { expect(scripts.scripts.typecheck).toBe('tsx scripts/build.ts --scope typecheck') }) + it('node-24-web-snapshot installs browsers over HTTPS archives while the build output downloads', () => { + const jobName = 'node-24-web-snapshot' + const job = workflowJob(loadWorkflow('.github/workflows/ci.yml'), jobName) + if (!Array.isArray(job.steps)) throw new TypeError(`${jobName} must define steps`) + const names = job.steps.map(step => isRecord(step) ? step.name : undefined) + const order = ['Install dependencies and prepare bubblewrap', 'Use HTTPS for Ubuntu archives', + 'Start Playwright browser install', 'Download build output', 'Unpack build output', + 'Wait for Playwright browsers', 'Run web browser snapshot shard'].map(name => names.indexOf(name)) + expect(order).not.toContain(-1) + expect([...order].sort((a, b) => a - b)).toEqual(order) + expect(isRecord(job.env) && 'DSH_CI_PLAYWRIGHT_INSTALL' in job.env).toBe(false) + const start: unknown = job.steps.find(step => isRecord(step) && step.name === 'Start Playwright browser install') + if (!isRecord(start) || !isRecord(start.env)) throw new TypeError('the Playwright install step must define env') + expect(String(start.env.PLAYWRIGHT_INSTALL_MODE)).toContain("&& 'browsers' || 'with-deps'") + expect(String(start.run)).toContain('exec playwright install "${deps[@]}" chromium webkit') + }) + + it('writes the web snapshot shard shares once for every shard', () => { + const job = workflowJob(loadWorkflow('.github/workflows/ci.yml'), 'node-24-web-snapshot') + expect(job.name).toBe('node 24 / web snapshots ${{ matrix.shard }}/2') + expect(job.env).toMatchObject({ DSH_WEB_SNAPSHOT_SHARD: '${{ matrix.shard }}/2', DSH_WEB_SNAPSHOT_SHARD_SHARES: '0.54,0.46' }) + }) + + it('builds the Linux Office runtime beside the consumer gates and fails on its status', () => { + const job = workflowJob(loadWorkflow('.github/workflows/ci.yml'), 'node-24-consumers') + if (!Array.isArray(job.steps)) throw new TypeError('node-24-consumers must define steps') + const names = job.steps.map(step => isRecord(step) ? step.name : undefined) + expect(names.slice(-3)).toEqual(['Start the Linux Office runtime build', 'Run compatibility, snapshot, and artifact gates', 'Wait for the Linux Office runtime']) + expect(job.steps.at(-1)).toMatchObject({ if: "${{ !cancelled() && steps.office-runtime.outcome == 'success' }}" }) + const start: unknown = job.steps.at(-3) + if (!isRecord(start)) throw new TypeError('the Office runtime step must be a mapping') + expect(start.id).toBe('office-runtime') + expect(String(start.run)).toContain('pnpm run prepare:primary-runtime --target linux-x64') + }) + it('selects artifact builds only for PR release and API rehearsals', () => { const official = "${{ github.event_name == 'pull_request' && 'pnpm run build:artifacts --profile official' || 'pnpm run build:official' }}" const vendor = "${{ github.event_name == 'pull_request' && 'pnpm exec tsx scripts/compile-referenced-projects.ts host-libraries' || 'pnpm run build:lib:host' }}" @@ -310,7 +357,7 @@ describe('CI workflow', () => { } }) - it.each(['node-24', 'node-24-coverage', 'node-24-consumers'])( + it.each(['node-24', 'node-24-coverage', 'node-24-build', 'node-24-consumers', 'node-24-web-snapshot'])( '%s keeps tool and fixture temporary files under runner cleanup', (jobName) => { const job = workflowJob(loadWorkflow('.github/workflows/ci.yml'), jobName) @@ -319,13 +366,13 @@ describe('CI workflow', () => { name: 'Use runner-owned temporary storage', run: [ 'echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"', - ...(jobName === 'node-24-consumers' + ...(jobName === 'node-24-web-snapshot' ? ['echo "PLAYWRIGHT_BROWSERS_PATH=${RUNNER_TEMP%/*}/ms-playwright" >> "$GITHUB_ENV"'] : []), '', ].join('\n'), }) - if (jobName === 'node-24-consumers') { + if (jobName === 'node-24-web-snapshot') { const browserCache: unknown = job.steps.find(step => isRecord(step) && isRecord(step.with) && step.with.path === '${{ env.PLAYWRIGHT_BROWSERS_PATH }}') expect(browserCache).toMatchObject({ uses: 'actions/cache/restore@v6.1.0' }) @@ -889,7 +936,9 @@ describe('CI workflow', () => { const redirectLanes = [ [prWorkflow, 'node-24'], [prWorkflow, 'node-24-coverage'], + [prWorkflow, 'node-24-build'], [prWorkflow, 'node-24-consumers'], + [prWorkflow, 'node-24-web-snapshot'], [masterWorkflow, 'serial-linux-selfhosted'], ] as const for (const [workflow, jobKey] of redirectLanes) { @@ -1136,6 +1185,7 @@ describe('bubblewrap preparation script', () => { const cachedJobs = new Map([ ['ci.yml:node-24-coverage', hostedOnly], ['ci.yml:node-24-consumers', hostedOnly], + ['ci.yml:node-24-web-snapshot', hostedOnly], ['ci.yml:node-compat', hostedOnly], ['e2e.yml:e2e', undefined], ]) diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index 22da5fc0d0..4ac9318145 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -16,6 +16,7 @@ import { taskkillArgs, type Gate, type GateResult, + type Mode, } from './run-gates.ts' // Graph fixtures select their own browser pool instead of inheriting the CI @@ -254,6 +255,9 @@ describe('gate graph validation', () => { 'ci-snapshot', 'ci-artifacts', 'ci-consumers', + 'ci-build', + 'ci-consumers-prebuilt', + 'ci-web-snapshot-prebuilt', 'ci-windows-blocking', 'ci-windows-complete', 'ci-windows-observational-ready', @@ -886,6 +890,55 @@ describe('Typert contract preparation', () => { expect(needsOf('expected-output')).toEqual(['build']) }) + it('starts web snapshots after the build-artifact readers', () => { + vi.stubEnv('DSH_WEB_SNAPSHOT_WORKERS', '16') + const subject = withPnpmEntrypoint(() => gatesForMode('ci-consumers')).find(item => item.id === 'web-snapshot') + + expect(subject?.after).toEqual(['publint', 'snapshot', 'expected-output', 'doc-typecheck', 'node-next-types', 'built-bin-smoke']) + }) + + it('builds once and runs only the cheap readers in the build lane', () => { + vi.stubEnv('DSH_CI_PLAYWRIGHT_INSTALL', 'with-deps') + const subject = withPnpmEntrypoint(() => gatesForMode('ci-build')) + + expect(subject.map(item => [item.id, item.needs ?? []])).toEqual([ + ['build', []], + ['publint', ['build']], + ['node-next-types', ['build']], + ]) + expect(subject[0]).toMatchObject({ displayCommand: 'pnpm run build:artifacts', env: { DSH_BUILD_CLIENT_PROFILE: 'official' } }) + }) + + it('runs restored-artifact consumers without a build or browsers', () => { + vi.stubEnv('DSH_CI_PLAYWRIGHT_INSTALL', 'with-deps') + const subject = withPnpmEntrypoint(() => gatesForMode('ci-consumers-prebuilt')) + + expect(subject.map(item => [item.id, item.needs ?? [], item.after ?? []])).toEqual([ + ['node-compat', [], []], + ['snapshot', [], []], + ['expected-output', [], []], + ['doc-typecheck', [], []], + ['built-bin-smoke', [], []], + ]) + expect(subject.find(item => item.id === 'doc-typecheck')?.env).toMatchObject({ DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' }) + }) + + it('leaves the web snapshot adapters to the web shards only in the restored-artifact consumers', () => { + const snapshotEnv = (mode: Mode) => withPnpmEntrypoint(() => gatesForMode(mode)).find(item => item.id === 'snapshot')?.env + + expect(snapshotEnv('ci-consumers-prebuilt')).toEqual({ DSH_EXAMPLE_MODE: 'lib', DSH_SNAPSHOT_SKIP_WEB_ADAPTERS: '1' }) + for (const mode of ['ci-primary', 'check-all', 'ci-snapshot', 'ci-linux-primary', 'ci-consumers'] as const) { + expect(snapshotEnv(mode), mode).toEqual({ DSH_EXAMPLE_MODE: 'lib' }) + } + }) + + it('runs one restored-artifact web snapshot shard without installing browsers', () => { + vi.stubEnv('DSH_CI_PLAYWRIGHT_INSTALL', 'with-deps') + const subject = withPnpmEntrypoint(() => gatesForMode('ci-web-snapshot-prebuilt')) + + expect(subject.map(item => [item.id, item.needs ?? [], item.after ?? []])).toEqual([['web-snapshot', [], []]]) + }) + it('rejects an unknown Playwright install mode', () => { vi.stubEnv('DSH_CI_PLAYWRIGHT_INSTALL', 'deps') diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index 28c28bed88..9a3fe3e627 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -27,6 +27,9 @@ export type Mode = | 'ci-snapshot' | 'ci-artifacts' | 'ci-consumers' + | 'ci-build' + | 'ci-consumers-prebuilt' + | 'ci-web-snapshot-prebuilt' | 'ci-windows-blocking' | 'ci-windows-complete' | 'ci-windows-observational-ready' @@ -167,6 +170,9 @@ function parseMode(raw: string | undefined): Mode { case 'ci-snapshot': case 'ci-artifacts': case 'ci-consumers': + case 'ci-build': + case 'ci-consumers-prebuilt': + case 'ci-web-snapshot-prebuilt': case 'ci-windows-blocking': case 'ci-windows-complete': case 'ci-windows-observational-ready': @@ -179,7 +185,7 @@ function parseMode(raw: string | undefined): Mode { return raw default: throw new Error( - `run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | ci-unit | ci-bench | ci-snapshot | ci-artifacts | ci-consumers | ci-windows-blocking | ci-windows-complete | ci-windows-observational-ready | node-compat | check-all | hygiene | doc-sync | doc-quick | i18n, got ${JSON.stringify(raw)}.`, + `run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | ci-unit | ci-bench | ci-snapshot | ci-artifacts | ci-consumers | ci-build | ci-consumers-prebuilt | ci-web-snapshot-prebuilt | ci-windows-blocking | ci-windows-complete | ci-windows-observational-ready | node-compat | check-all | hygiene | doc-sync | doc-quick | i18n, got ${JSON.stringify(raw)}.`, ) } } @@ -334,6 +340,12 @@ export function gatesForMode(selected: Mode): Gate[] { return ciArtifactGates() case 'ci-consumers': return ciConsumerGates() + case 'ci-build': + return ciBuildOnceGates() + case 'ci-consumers-prebuilt': + return ciPrebuiltConsumerGates() + case 'ci-web-snapshot-prebuilt': + return ciPrebuiltWebSnapshotGates() case 'ci-windows-blocking': return ciWindowsBlockingGates() case 'ci-windows-complete': @@ -549,8 +561,9 @@ function ciConsumerGates(): Gate[] { const playwrightInstall = ciPlaywrightInstallGate() const browserTree = playwrightInstall === undefined ? builtTree : [...builtTree, playwrightInstall.id] // The HMR web test starts `dev:web`, which rewrites the shared `lib/` and - // `apps/web/dist/` trees. Let every build-artifact reader settle before that - // writer starts; `after` preserves the web diagnostic even if a reader fails. + // `apps/web/dist/` trees, and a browser pool beside the readers starves their + // timing-sensitive child processes of CPU. Let every build-artifact reader + // settle first; `after` preserves the web diagnostic even if a reader fails. const buildArtifactReaders = [ 'publint', 'snapshot', @@ -584,7 +597,7 @@ function ciConsumerGates(): Gate[] { } /** - * Install the Playwright browsers as a gate that runs beside the build; only the browser readers need it. + * Install the web snapshot browsers beside the build instead of before the aggregate. * `DSH_CI_PLAYWRIGHT_INSTALL` selects `with-deps` (ephemeral runners, which also install * system packages through apt) or `browsers` (persistent hosts whose image owns those packages); * unset leaves browser installation to the caller. @@ -605,6 +618,50 @@ function ciPlaywrightInstallGate(): Gate | undefined { } } +/** + * Build-once CI lane: emit official client artifacts once and run the cheap + * readers beside the packing job; downstream jobs restore this output. + */ +function ciBuildOnceGates(): Gate[] { + return [ + ciArtifactBuildGate(), + pnpmScript('publint', 'publint', { needs: ['build'] }), + pnpmScript('node-next-types', 'verify-node-next-types', { + label: 'node-next types', + needs: ['build'], + }), + ] +} + +/** + * Artifact consumers on a checkout whose build output was restored from the + * `ci-build` lane, so no gate builds or waits for a build. Node compatibility + * reads only source and runs here, off the build job's critical path. + */ +function ciPrebuiltConsumerGates(): Gate[] { + return [ + pnpmScript('node-compat', 'check:node-compat', { + label: 'Node compatibility', + env: { [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' }, + }), + // The web snapshot shards run the apps/web/tests/*.snapshot.ts adapters. + snapshotGate([], { skipWebAdapters: true }), + expectedOutputGate([]), + pnpmScript('doc-typecheck', 'doc-typecheck:contracts-ready', { + env: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' }, + }), + builtBinSmokeGate([]), + ] +} + +/** + * One web snapshot shard on a checkout with restored build output. The CI job + * installs the browsers itself, overlapped with the artifact download. + */ +function ciPrebuiltWebSnapshotGates(): Gate[] { + return [webSnapshotGate([])] +} + function webSnapshotGate(needs: string[], after?: string[]): Gate { const order = after === undefined ? { needs } : { needs, after } const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS @@ -808,9 +865,11 @@ function ciUnitGates(): Gate[] { // Recorded-session adapters boot process scenarios in `lib` mode. Callers wait // either on `build` or on a validation gate that transitively owns that build. -function snapshotGate(needs: string[] = ['build']): Gate { +// `skipWebAdapters` leaves the browser-backed apps/web/tests adapters to a lane +// that already runs them (vitest.snapshot.config.ts). +function snapshotGate(needs: string[] = ['build'], options: { skipWebAdapters?: boolean } = {}): Gate { return pnpmScript('snapshot', 'test:snapshot', { - env: { DSH_EXAMPLE_MODE: 'lib' }, + env: { DSH_EXAMPLE_MODE: 'lib', ...options.skipWebAdapters === true ? { DSH_SNAPSHOT_SKIP_WEB_ADAPTERS: '1' } : {} }, needs, }) } diff --git a/scripts/run-web-snapshots.ts b/scripts/run-web-snapshots.ts index e69ef7527c..af75bb2313 100644 --- a/scripts/run-web-snapshots.ts +++ b/scripts/run-web-snapshots.ts @@ -1,30 +1,41 @@ -/** Run serial browser owners before one bounded snapshot pool. */ +/** + * Run serial browser owners before one bounded snapshot pool of the other projects + * (scripts/web-snapshot-projects.ts). + * `DSH_WEB_SNAPSHOT_SHARD=/` runs one weighted shard of the pool + * (scripts/web-snapshot-sequencer.ts); the serial files, which rewrite the shared + * build output, run only in the last shard so no other shard needs to wait for them. + */ import { spawn } from 'node:child_process' import { pnpmInvocation } from './pnpm-invocation.ts' +import { + WEB_SNAPSHOT_POOL_PROJECTS, + WEB_SNAPSHOT_SERIAL_FILES, + WEB_SNAPSHOT_SERIAL_PROJECT, + ownsWebSnapshotSerialFiles, + parseWebSnapshotShard, +} from './web-snapshot-projects.ts' -const serialFiles = [ - 'apps/web/tests/hmr-live.e2e.ts', - 'apps/web/tests/client-plugin-live.e2e.ts', - // Recorded SVG streaming retains live heartbeat assertions; reserve its browser CPU budget. - 'apps/web/tests/present-svg.e2e.ts', -] const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS const workers = Number.parseInt(workerRaw ?? '', 10) if (!Number.isSafeInteger(workers) || workers < 1 || String(workers) !== workerRaw) { throw new Error(`DSH_WEB_SNAPSHOT_WORKERS must be a positive integer, got ${JSON.stringify(workerRaw)}.`) } +const shard = parseWebSnapshotShard(process.env.DSH_WEB_SNAPSHOT_SHARD) +const shardArgs = shard === undefined ? [] : [`--shard=${String(shard.index)}/${String(shard.count)}`] +const ownsSerialFiles = ownsWebSnapshotSerialFiles(shard) const invocation = pnpmInvocation(['exec', 'vitest', 'run', '--config', 'vitest.web.config.ts']) let serialStatus = 0 -for (const file of serialFiles) { - serialStatus = await run(invocation.command, [...invocation.args, file]) +for (const file of ownsSerialFiles ? WEB_SNAPSHOT_SERIAL_FILES : []) { + serialStatus = await run(invocation.command, [...invocation.args, `--project=${WEB_SNAPSHOT_SERIAL_PROJECT}`, file]) if (serialStatus !== 0) break } if (serialStatus === 0) { process.exitCode = await run(invocation.command, [ ...invocation.args, - ...serialFiles.map(file => `--exclude=${file}`), + ...WEB_SNAPSHOT_POOL_PROJECTS.map(project => `--project=${project}`), '--fileParallelism', `--maxWorkers=${String(workers)}`, + ...shardArgs, ]) } else { process.exitCode = serialStatus diff --git a/scripts/web-snapshot-projects.spec.ts b/scripts/web-snapshot-projects.spec.ts new file mode 100644 index 0000000000..e28c30f760 --- /dev/null +++ b/scripts/web-snapshot-projects.spec.ts @@ -0,0 +1,84 @@ +import { existsSync } from 'node:fs' +import { resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { describe, expect, it } from 'vitest' +import { + WEB_SNAPSHOT_SERIAL_FILES, + WEB_SNAPSHOT_SLICE_COUNTS, + ownsWebSnapshotSerialFiles, + parseWebSnapshotShard, + sliceOfTest, + sliceProjectName, + webSnapshotProjects, +} from './web-snapshot-projects.ts' + +describe('web snapshot test slices', () => { + it('assigns tests to slices round-robin by depth-first index', () => { + expect(Array.from({ length: 7 }, (_, index) => sliceOfTest(index, 3))).toEqual([1, 2, 3, 1, 2, 3, 1]) + }) + + it('names one project per slice by file stem', () => { + expect(sliceProjectName('apps/web/tests/document-preview.e2e.ts', 2)).toBe('web-slice:document-preview:2') + }) + + // The slice setup file checks at runtime that each slice receives a test. + it('plans only existing, non-serial files, each with at least two slices', () => { + const plans = Object.entries(WEB_SNAPSHOT_SLICE_COUNTS) + + expect(plans.length).toBeGreaterThan(0) + for (const [file, count] of plans) { + expect(existsSync(file), file).toBe(true) + expect(WEB_SNAPSHOT_SERIAL_FILES, file).not.toContain(file) + expect(Number.isSafeInteger(count) && count >= 2, file).toBe(true) + } + }) + + it('runs each sliced file only in its slice projects', () => { + const projects = webSnapshotProjects(['apps/web/tests/**/*.e2e.ts'], ['**/node_modules/**']) + const main = projects.find(project => project.test.name === 'web') + + for (const [file, count] of Object.entries(WEB_SNAPSHOT_SLICE_COUNTS)) { + expect(main?.test.exclude, file).toContain(file) + const slices = projects.filter(project => project.test.include.includes(file)).map(project => project.test.name) + expect(slices, file).toEqual(Array.from({ length: count }, (_, index) => sliceProjectName(file, index + 1))) + } + }) +}) + +describe('web snapshot shards', () => { + it('parses an in-range shard', () => { + expect(parseWebSnapshotShard('1/2')).toEqual({ index: 1, count: 2 }) + expect(parseWebSnapshotShard('2/2')).toEqual({ index: 2, count: 2 }) + }) + + it.each(['3/2', '0/2', 'a/b'])('rejects shard %s', (raw) => { + expect(() => parseWebSnapshotShard(raw)).toThrow( + `DSH_WEB_SNAPSHOT_SHARD must be / with 1 <= index <= count, got ${JSON.stringify(raw)}.`, + ) + }) + + it('runs the whole pool and the serial files when unset', () => { + expect(parseWebSnapshotShard(undefined)).toBeUndefined() + expect(parseWebSnapshotShard('')).toBeUndefined() + expect(ownsWebSnapshotSerialFiles(undefined)).toBe(true) + }) + + it('runs the serial files only in the last shard', () => { + expect(ownsWebSnapshotSerialFiles({ index: 1, count: 2 })).toBe(false) + expect(ownsWebSnapshotSerialFiles({ index: 2, count: 2 })).toBe(true) + }) +}) + +describe('web perf inventory', () => { + it('collects only the perf files, without the browser lane projects or sequencer', async () => { + // A runtime URL keeps the root Vitest configs outside the scripts type program. + const perfConfigUrl = pathToFileURL(resolve(import.meta.dirname, '../vitest.web.perf.config.ts')).href + const { default: webPerfConfig } = await import(perfConfigUrl) as { default: { test?: Record } } + expect(webPerfConfig.test).not.toHaveProperty('projects') + expect(webPerfConfig.test).not.toHaveProperty('sequence') + expect(webPerfConfig.test?.include).toEqual([ + 'apps/web/tests/**/*.perf.ts', + 'packages/client/ui-conversation/tests/**/*.perf.client.ts', + ]) + }) +}) diff --git a/scripts/web-snapshot-projects.ts b/scripts/web-snapshot-projects.ts new file mode 100644 index 0000000000..691883c466 --- /dev/null +++ b/scripts/web-snapshot-projects.ts @@ -0,0 +1,136 @@ +/** + * Vitest projects of the web snapshot lane (vitest.web.config.ts). + * + * Project `web-serial` holds the files that rewrite the shared build output; scripts/run-web-snapshots.ts + * runs them one at a time before the pool of every other project. Project `web` holds the remaining + * files except the sliced ones. Vitest applies a CLI `--exclude` to the root configuration only, not to + * `test.projects`, so the runner selects projects with `--project` instead of excluding files. + * + * A Vitest worker runs one file at about one CPU core, so a long browser file bounds the wall time of + * its shard. Each file in {@link WEB_SNAPSHOT_SLICE_COUNTS} runs as `count` Vitest projects named + * `web-slice::`, each of which includes only that file. Every slice imports the whole + * file and runs its file-level hooks, and `web-snapshot-slice.setup.ts` skips the tests outside slice + * `k` before they run, which also skips their `beforeEach`/`afterEach` hooks and every `describe` + * without a test in the slice. + * + * Test `i` of a file, counted depth-first in collection order from zero, belongs to slice `(i mod + * count) + 1`. Every slice computes the assignment from the same collected test list, so the slices of + * a file run each test exactly once. A file joins the plan only when no test reads state that an + * earlier test of the same file creates, and when concurrent copies of its hooks share no fixed port + * or path. + */ +import { basename } from 'node:path' + +/** Files that rewrite the shared build output, in the order the CI runner runs them alone. */ +export const WEB_SNAPSHOT_SERIAL_FILES: readonly string[] = [ + 'apps/web/tests/hmr-live.e2e.ts', + 'apps/web/tests/client-plugin-live.e2e.ts', + // Recorded SVG streaming retains live heartbeat assertions; reserve its browser CPU budget. + 'apps/web/tests/present-svg.e2e.ts', +] + +/** Name of the project that holds {@link WEB_SNAPSHOT_SERIAL_FILES}. */ +export const WEB_SNAPSHOT_SERIAL_PROJECT = 'web-serial' + +/** `--project` patterns that select every project of the parallel pool. */ +export const WEB_SNAPSHOT_POOL_PROJECTS: readonly string[] = ['web', 'web-slice:*'] + +/** One weighted shard of the parallel pool, from `DSH_WEB_SNAPSHOT_SHARD=/`. */ +export interface WebSnapshotShard { + readonly index: number + readonly count: number +} + +/** + * Parse `DSH_WEB_SNAPSHOT_SHARD`. + * @param raw - The variable's value; unset or empty selects the whole pool. + * @returns The shard, or `undefined` for the whole pool. + * @throws Error when the value is not `/` with 1 <= index <= count. + */ +export function parseWebSnapshotShard(raw: string | undefined): WebSnapshotShard | undefined { + if (raw === undefined || raw === '') return undefined + const match = /^([1-9]\d*)\/([1-9]\d*)$/.exec(raw) + if (match === null || Number(match[1]) > Number(match[2])) { + throw new Error(`DSH_WEB_SNAPSHOT_SHARD must be / with 1 <= index <= count, got ${JSON.stringify(raw)}.`) + } + return { index: Number(match[1]), count: Number(match[2]) } +} + +/** + * Whether a run owns {@link WEB_SNAPSHOT_SERIAL_FILES}: an unsharded run, or the last shard only, so no + * other shard waits for them. + * @param shard - The parsed shard, or `undefined` for the whole pool. + * @returns `true` when the run executes the serial files. + */ +export function ownsWebSnapshotSerialFiles(shard: WebSnapshotShard | undefined): boolean { + return shard === undefined || shard.index === shard.count +} + +/** Environment variable that tells a slice project's workers which slice they run, as `#`. */ +export const WEB_SNAPSHOT_SLICE_ENV = 'DSH_WEB_SNAPSHOT_SLICE' + +/** + * Slice count of each sliced file, keyed by its root-relative path. These files bound their shard's + * wall time when they run whole in one worker; each count must be at least two. + */ +export const WEB_SNAPSHOT_SLICE_COUNTS: Readonly> = { + 'apps/web/tests/forge-panel.e2e.ts': 4, + 'apps/web/tests/fold-blank-matrix.e2e.ts': 3, + 'apps/web/tests/document-preview.e2e.ts': 2, + 'apps/web/tests/chat-scroll-contract.e2e.ts': 2, +} + +/** + * Name of the Vitest project that runs one slice of a file. + * @param file - root-relative path of the sliced file. + * @param slice - one-based slice index. + * @returns `web-slice::`. + */ +export function sliceProjectName(file: string, slice: number): string { + return `web-slice:${basename(file).replace(/\.[^.]*\.ts$/, '')}:${String(slice)}` +} + +/** + * One-based slice of a test under round-robin assignment. + * @param index - zero-based depth-first index of the test within its file. + * @param count - slice count of the file. + * @returns `(index mod count) + 1`. + */ +export function sliceOfTest(index: number, count: number): number { + return (index % count) + 1 +} + +/** Inline Vitest project entry; every entry extends the root configuration. */ +export interface WebSnapshotProject { + readonly extends: true + readonly test: { + readonly name: string + readonly include: string[] + readonly exclude?: string[] + readonly env?: Record + readonly setupFiles?: string[] + } +} + +/** + * Projects of the web snapshot lane. + * @param include - globs of every web snapshot file. + * @param defaultExclude - Vitest's default exclude globs, which a project-level `exclude` replaces. + * @returns the serial project, the main project, and one project per slice of each sliced file. + */ +export function webSnapshotProjects(include: readonly string[], defaultExclude: readonly string[]): WebSnapshotProject[] { + return [ + { extends: true, test: { name: WEB_SNAPSHOT_SERIAL_PROJECT, include: [...WEB_SNAPSHOT_SERIAL_FILES] } }, + { extends: true, test: { name: 'web', include: [...include], exclude: [...defaultExclude, ...WEB_SNAPSHOT_SERIAL_FILES, ...Object.keys(WEB_SNAPSHOT_SLICE_COUNTS)] } }, + ...Object.entries(WEB_SNAPSHOT_SLICE_COUNTS).flatMap(([file, count]) => + Array.from({ length: count }, (_, index): WebSnapshotProject => ({ + extends: true, + test: { + name: sliceProjectName(file, index + 1), + include: [file], + env: { [WEB_SNAPSHOT_SLICE_ENV]: `${file}#${String(index + 1)}` }, + setupFiles: ['./scripts/web-snapshot-slice.setup.ts'], + }, + }))), + ] +} diff --git a/scripts/web-snapshot-sequencer.spec.ts b/scripts/web-snapshot-sequencer.spec.ts new file mode 100644 index 0000000000..5e3d0446dc --- /dev/null +++ b/scripts/web-snapshot-sequencer.spec.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { assignWeightedShards, parseShardShares } from './web-snapshot-sequencer.ts' + +describe('web snapshot shard assignment', () => { + const files = [ + { key: 'a.e2e.ts', weight: 90 }, + { key: 'b.e2e.ts', weight: 60 }, + { key: 'c.e2e.ts', weight: 50 }, + { key: 'd.e2e.ts', weight: 30 }, + { key: 'e.e2e.ts', weight: 20 }, + ] + + it('partitions every file exactly once and balances load longest-first', () => { + const shards = assignWeightedShards(files, [1, 1]) + + expect(shards.flat().sort()).toEqual(files.map(file => file.key)) + expect(shards).toEqual([['a.e2e.ts', 'd.e2e.ts'], ['b.e2e.ts', 'c.e2e.ts', 'e.e2e.ts']]) + }) + + it('gives a larger share proportionally more weight', () => { + const shards = assignWeightedShards(files, [1, 3]) + const load = (keys: readonly string[]) => keys.reduce((sum, key) => sum + (files.find(file => file.key === key)?.weight ?? 0), 0) + + expect(load(shards[0] ?? [])).toBeLessThan(load(shards[1] ?? [])) + }) + + it('places the slice specs of one file as separate weights', () => { + const slices = [1, 2, 3].map(slice => ({ key: `web-slice:long:${String(slice)}:long.e2e.ts`, weight: 40 })) + const shards = assignWeightedShards([...slices, { key: 'web:a.e2e.ts', weight: 60 }], [1, 1]) + + expect(shards).toEqual([['web:a.e2e.ts', 'web-slice:long:3:long.e2e.ts'], ['web-slice:long:1:long.e2e.ts', 'web-slice:long:2:long.e2e.ts']]) + }) + + it('returns the same assignment for any input order', () => { + expect(assignWeightedShards([...files].reverse(), [1, 1])).toEqual(assignWeightedShards(files, [1, 1])) + }) + + it('defaults to equal shares and rejects a malformed share list', () => { + expect(parseShardShares(undefined, 3)).toEqual([1, 1, 1]) + expect(parseShardShares('0.45, 0.55', 2)).toEqual([0.45, 0.55]) + expect(() => parseShardShares('1', 2)).toThrow(/must list 2 positive numbers/) + expect(() => parseShardShares('1,0', 2)).toThrow(/must list 2 positive numbers/) + }) +}) diff --git a/scripts/web-snapshot-sequencer.ts b/scripts/web-snapshot-sequencer.ts new file mode 100644 index 0000000000..aad4628d70 --- /dev/null +++ b/scripts/web-snapshot-sequencer.ts @@ -0,0 +1,83 @@ +/** + * Vitest sequencer that splits the web snapshot lane into capacity-weighted shards. + * + * Vitest's default `--shard` splits a hash-ordered file list into equal file counts, so one shard can + * receive most of the long browser files. This sequencer assigns files longest-first to the shard with + * the lowest load relative to its capacity share. A file's weight is its byte size, which tracks its + * serial browser time closely enough for balancing and needs no recorded history. A slice project of a + * long file (scripts/web-snapshot-projects.ts) weighs the file's size divided by its slice count. Every + * shard computes the same assignment from the same checkout, so the shards partition the spec set exactly. + * + * `DSH_WEB_SNAPSHOT_SHARD_SHARES` lists one positive capacity share per shard, comma-separated; unset + * gives every shard the same share. + */ +import { statSync } from 'node:fs' +import { relative } from 'node:path' +import { BaseSequencer } from 'vitest/node' +import type { TestSpecification } from 'vitest/node' +import { WEB_SNAPSHOT_SLICE_COUNTS } from './web-snapshot-projects.ts' + +/** Environment variable listing the capacity share of each web snapshot shard. */ +export const WEB_SNAPSHOT_SHARD_SHARES_ENV = 'DSH_WEB_SNAPSHOT_SHARD_SHARES' + +/** One spec to place, identified by its project name and root-relative path. */ +export interface WeightedFile { + readonly key: string + readonly weight: number +} + +/** + * Parse the per-shard capacity shares. + * @param raw - comma-separated positive numbers, or undefined for equal shares. + * @param count - number of shards. + * @returns one share per shard. + * @throws If the list length differs from `count` or a share is not a positive finite number. + */ +export function parseShardShares(raw: string | undefined, count: number): number[] { + if (raw === undefined || raw === '') return Array.from({ length: count }, () => 1) + const shares = raw.split(',').map(part => Number(part.trim())) + if (shares.length !== count || shares.some(share => !Number.isFinite(share) || share <= 0)) { + throw new Error(`${WEB_SNAPSHOT_SHARD_SHARES_ENV} must list ${String(count)} positive numbers, got ${JSON.stringify(raw)}.`) + } + return shares +} + +/** + * Assign files to shards longest-first, each to the shard with the lowest load per unit of share. + * Ties break by key and then by lower shard index, so the result depends only on the inputs. + * @param files - files with their weights. + * @param shares - capacity share of each shard. + * @returns the file keys of each shard. + */ +export function assignWeightedShards(files: readonly WeightedFile[], shares: readonly number[]): string[][] { + const loads = shares.map(() => 0) + const shards: string[][] = shares.map(() => []) + const ordered = [...files].sort((a, b) => b.weight - a.weight || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)) + for (const file of ordered) { + let target = 0 + for (let index = 1; index < shares.length; index++) { + if ((loads[index] ?? 0) / (shares[index] ?? 1) < (loads[target] ?? 0) / (shares[target] ?? 1)) target = index + } + loads[target] = (loads[target] ?? 0) + file.weight + shards[target]?.push(file.key) + } + return shards +} + +/** Web snapshot sequencer: weighted sharding, default ordering. */ +export default class WebSnapshotSequencer extends BaseSequencer { + override shard(files: TestSpecification[]): Promise { + const { index, count } = this.ctx.config.shard ?? { index: 1, count: 1 } + const root = this.ctx.config.root + const pathOf = (spec: TestSpecification) => relative(root, spec.moduleId).replaceAll('\\', '/') + const keyOf = (spec: TestSpecification) => `${spec.project.name}:${pathOf(spec)}` + // Only slice projects include a sliced file. + const weightOf = (spec: TestSpecification) => statSync(spec.moduleId).size / (WEB_SNAPSHOT_SLICE_COUNTS[pathOf(spec)] ?? 1) + const shards = assignWeightedShards( + files.map(spec => ({ key: keyOf(spec), weight: weightOf(spec) })), + parseShardShares(process.env[WEB_SNAPSHOT_SHARD_SHARES_ENV], count), + ) + const selected = new Set(shards[index - 1]) + return Promise.resolve(files.filter(spec => selected.has(keyOf(spec)))) + } +} diff --git a/scripts/web-snapshot-slice.setup.ts b/scripts/web-snapshot-slice.setup.ts new file mode 100644 index 0000000000..a09eedad5a --- /dev/null +++ b/scripts/web-snapshot-slice.setup.ts @@ -0,0 +1,52 @@ +/** + * Setup file of the web snapshot slice projects (scripts/web-snapshot-projects.ts). + * + * Its `beforeAll` runs after Vitest collects the file and before the file's own hooks. It sets the + * runner task mode of every test outside this worker's slice, and of every `describe` left without a + * test in the slice, to `'skip'`, so their tests and `beforeEach`/`afterEach` hooks do not run. + * Changing `task.mode` after collection relies on Vitest runner internals that are not public API, + * verified on Vitest 4.1.11. A worker fails instead of running the whole file when its collected file + * is not the planned file or when the file has fewer tests than slices. + */ +import type { RunnerTestCase, RunnerTestFile, RunnerTestSuite } from 'vitest' +import { beforeAll } from 'vitest' +import { WEB_SNAPSHOT_SLICE_COUNTS, WEB_SNAPSHOT_SLICE_ENV, sliceOfTest } from './web-snapshot-projects.ts' + +const sliceMatch = /^(.+)#([1-9]\d*)$/.exec(process.env[WEB_SNAPSHOT_SLICE_ENV] ?? '') +if (sliceMatch === null) throw new Error(`${WEB_SNAPSHOT_SLICE_ENV} must be #, got ${JSON.stringify(process.env[WEB_SNAPSHOT_SLICE_ENV])}.`) +const [, slicedFile = '', sliceRaw = ''] = sliceMatch +const count = WEB_SNAPSHOT_SLICE_COUNTS[slicedFile] +if (count === undefined) throw new Error(`${slicedFile} has no entry in WEB_SNAPSHOT_SLICE_COUNTS (scripts/web-snapshot-projects.ts).`) +const slice = Number(sliceRaw) + +// The first argument must destructure: Vitest parses hook parameters as fixtures. +beforeAll(({}, suite) => { + const file = suite.file + // A file task's name is its path relative to the project root. + const collected = file.name.replaceAll('\\', '/') + if (collected !== slicedFile) throw new Error(`Slice project for ${slicedFile} collected ${collected}.`) + const tests: RunnerTestCase[] = [] + const collect = (parent: RunnerTestFile | RunnerTestSuite) => { + for (const task of parent.tasks) { + if (task.type === 'test') tests.push(task) + else collect(task) + } + } + collect(file) + if (tests.length < count) { + throw new Error(`${slicedFile} has ${String(tests.length)} tests but WEB_SNAPSHOT_SLICE_COUNTS gives it ${String(count)} slices; lower its count in scripts/web-snapshot-projects.ts.`) + } + tests.forEach((test, index) => { + if (sliceOfTest(index, count) !== slice) test.mode = 'skip' + }) + const settle = (parent: RunnerTestFile | RunnerTestSuite): boolean => { + let runs = false + for (const task of parent.tasks) { + const taskRuns = task.type === 'test' ? task.mode === 'run' : settle(task) + if (task.type === 'suite' && !taskRuns && task.mode === 'run') task.mode = 'skip' + runs ||= taskRuns + } + return runs + } + settle(file) +}) diff --git a/vitest.snapshot.config.ts b/vitest.snapshot.config.ts index f17973a0f8..1202f4c6c0 100644 --- a/vitest.snapshot.config.ts +++ b/vitest.snapshot.config.ts @@ -21,6 +21,12 @@ const snapshotMaxConcurrency = positiveIntFromEnv( Math.min(DEFAULT_SNAPSHOT_MAX_CONCURRENCY, availableParallelism()), ) +const skipWebAdaptersRaw = process.env.DSH_SNAPSHOT_SKIP_WEB_ADAPTERS +if (skipWebAdaptersRaw !== undefined && skipWebAdaptersRaw !== '' && skipWebAdaptersRaw !== '1') { + throw new Error(`DSH_SNAPSHOT_SKIP_WEB_ADAPTERS must be 1 when set, got ${JSON.stringify(skipWebAdaptersRaw)}`) +} +const skipWebAdapters = skipWebAdaptersRaw === '1' + const snapshotMaxWorkers = process.env.DSH_SNAPSHOT_MAX_WORKERS ? positiveIntFromEnv('DSH_SNAPSHOT_MAX_WORKERS', availableParallelism()) : undefined @@ -52,7 +58,9 @@ export default defineConfig({ 'scripts/session-snapshot-corpus.corpus.ts', // The assembled Web snapshot executes generated client bundles; source // mode remains the zero-build path, while lib mode requires a prior build. - ...(process.env.DSH_EXAMPLE_MODE === 'lib' ? ['apps/web/tests/**/*.snapshot.ts'] : []), + // DSH_SNAPSHOT_SKIP_WEB_ADAPTERS=1 (only unset or 1) drops them for a CI + // lane whose web snapshot shards already run these files. + ...(process.env.DSH_EXAMPLE_MODE === 'lib' && !skipWebAdapters ? ['apps/web/tests/**/*.snapshot.ts'] : []), 'snapshots/**/*.snapshot.ts', ], // Replay never writes committed outputs and every scenario owns its diff --git a/vitest.web.config.ts b/vitest.web.config.ts index adbee35ef9..cdddf9484d 100644 --- a/vitest.web.config.ts +++ b/vitest.web.config.ts @@ -1,5 +1,7 @@ import tsconfigPaths from 'vite-tsconfig-paths' -import { defineConfig } from 'vitest/config' +import { configDefaults, defineConfig } from 'vitest/config' +import WebSnapshotSequencer from './scripts/web-snapshot-sequencer.ts' +import { webSnapshotProjects } from './scripts/web-snapshot-projects.ts' import { standardDecoratorPlugin, vitestExecArgv } from './vitest.shared.ts' // Web browser lane: real host entry points, built-client interaction snapshots, @@ -23,15 +25,18 @@ export default defineConfig({ ], test: { execArgv: vitestExecArgv, - include: [ + // Serial, main, and sliced long-file projects; see scripts/web-snapshot-projects.ts. + projects: webSnapshotProjects([ 'apps/web/tests/**/*.e2e.ts', 'apps/web/tests/**/*.snapshot.ts', 'packages/experimental/inspector/tests/client-browser.e2e.ts', - ], + ], configDefaults.exclude), // Local and record runs stay serial. CI runs workspace-mutating HMR and // dynamic Cordis lifecycle coverage before parallelizing the remaining files. testTimeout: 180_000, hookTimeout: 120_000, fileParallelism: false, + // `--shard` splits CI's two web snapshot machines by file weight, not file count. + sequence: { sequencer: WebSnapshotSequencer }, }, }) diff --git a/vitest.web.perf.config.ts b/vitest.web.perf.config.ts index 722de820c5..848e078e79 100644 --- a/vitest.web.perf.config.ts +++ b/vitest.web.perf.config.ts @@ -2,12 +2,16 @@ import { defineConfig } from 'vitest/config' import webConfig from './vitest.web.config.ts' import { vitestExecArgv } from './vitest.shared.ts' +// The browser lane's `projects` and `sequence` would replace this root +// `include`, so the perf inventory keeps only the shared test options. +const { projects: _projects, sequence: _sequence, ...webTest } = webConfig.test ?? {} + // Manual high-cardinality diagnostics stay outside every default Vitest // inventory and therefore outside CI's executed test lanes. export default defineConfig({ ...webConfig, test: { - ...webConfig.test, + ...webTest, // Memory diagnostics use forced-GC baselines only in this manual inventory. execArgv: [...vitestExecArgv, '--expose-gc'], include: [ From 330a13ba823368016e9d94eb342fbbd7724d2b2a Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:57:32 +0800 Subject: [PATCH 27/54] perf(ui-conversation): stop restyling the transcript on every resize frame Register the Conversation width axis inputs and its continuously varying derived lengths without inheritance, publish the content width and end inset to descendants as computed lengths, and derive the Session panel's docking step on the body as a registered 0px/1px length. A right Sidebar drag no longer restyles the whole transcript when the resolved width is unchanged. Refs #8856 --- apps/web/tests/markdown-wide-table.e2e.ts | 6 +- apps/web/tests/rightbar-drag.perf.ts | 245 ++++++++++++++++++ apps/web/tsconfig.json | 1 + .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../skeleton/ConversationRoot.module.css | 59 ++++- .../skeleton/ConversationWidthControls.tsx | 11 +- .../tests/end-reserve-styles.client.spec.ts | 26 +- .../tests/skeleton.client.spec.tsx | 19 +- .../client/ui-session-panel/README.i18n.yaml | 4 +- packages/client/ui-session-panel/README.md | 2 +- packages/client/ui-session-panel/README.zh.md | 2 +- .../src/client/SessionPanel.module.css | 29 ++- .../tests/session-panel-styles.client.spec.ts | 25 +- tsconfig.host.json | 1 + 16 files changed, 391 insertions(+), 47 deletions(-) create mode 100644 apps/web/tests/rightbar-drag.perf.ts diff --git a/apps/web/tests/markdown-wide-table.e2e.ts b/apps/web/tests/markdown-wide-table.e2e.ts index 16e45fd37a..f77ce2b3a9 100644 --- a/apps/web/tests/markdown-wide-table.e2e.ts +++ b/apps/web/tests/markdown-wide-table.e2e.ts @@ -216,13 +216,13 @@ async function awaitTableLayout(target: Page): Promise { const element = document.querySelector('[data-sidebar-collapsed][data-rightbar-collapsed]') if (element === null) return false const tracks = getComputedStyle(element).gridTemplateColumns.split(' ').map(Number.parseFloat) - const root = element.querySelector('div[data-phase]') + const body = element.querySelector('div[data-phase] [data-conversation-content]') // Desktop retains the rail; the mobile drawer leaves the whole width to the transcript. return tracks[0] === (element.hasAttribute('data-sidebar-drawer') ? 0 : 56) && tracks.at(-1) === 0 && element.getAnimations().every(animation => animation.playState === 'finished' || animation.playState === 'idle') - && root !== null - && root.style.getPropertyValue('--dsh-conversation-column-width') === `${String(root.offsetWidth)}px` + && body !== null + && body.style.getPropertyValue('--dsh-conversation-column-width') === `${String(body.offsetWidth)}px` }, undefined, { timeout: 10_000 }) } diff --git a/apps/web/tests/rightbar-drag.perf.ts b/apps/web/tests/rightbar-drag.perf.ts new file mode 100644 index 0000000000..015640f852 --- /dev/null +++ b/apps/web/tests/rightbar-drag.perf.ts @@ -0,0 +1,245 @@ +// Manual diagnostic: main-thread cost of dragging the right Sidebar's resize +// handle beside a long, fully loaded synthetic transcript. It reports frame +// gaps, style recalculation (with the element count it touched), layout, and +// the share of both forced synchronously from script, plus the final column +// and composer widths; host speed is not a correctness contract, so nothing is +// asserted beyond the loaded turn count. Run after `pnpm run build:artifacts`: +// RB_TURNS=200 RB_SAMPLES=3 RB_STEPS=40 DSH_SNAPSHOT=replay \ +// pnpm exec vitest run --config vitest.web.perf.config.ts apps/web/tests/rightbar-drag.perf.ts +import { performance } from 'node:perf_hooks' +import { chromium, type Browser, type Page } from 'playwright' +import { expect, it } from 'vitest' +import { brandString } from '@deepseek-ai/dsh-brand' +import { + type ToolCallId, + createAssistantMessage, + createSystemMessage, + createToolResultMessage, + createUserMessage, +} from '@deepseek-ai/dsh-llm' +import { SESSION_FORMAT_VERSION, Session, type SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-title' +import { launchWebScaffold, seedSession, webSnapshotMode } from './scaffold.ts' +import { newEnglishPage } from './support.ts' + +const TURNS = Number(process.env.RB_TURNS ?? 200) +const SAMPLES = Number(process.env.RB_SAMPLES ?? 3) +const STEPS = Number(process.env.RB_STEPS ?? 40) +const STEP_PX = 8 +const STEP_GAP_MS = 8 +const SESSION_ID = 'perf-rightbar-drag' +const TAIL = '[data-chat-flow-key*="turn-tail"]' +/** A narrow window where the column falls below the content width, a wide one, and a wide one with a dragged preference. */ +const SCENARIOS = [ + { viewport: 1680, preference: null }, + { viewport: 2560, preference: null }, + { viewport: 2560, preference: 720 }, +] as const + +function prose(turn: number): string { + const paragraph = `Turn ${String(turn)} synthetic analysis: the renderer measures every row, wraps mixed text 混合中文段落用于换行测量, and keeps \`inline code\` beside **bold** words. ` + const parts = [paragraph.repeat(6), paragraph.repeat(4)] + parts.push(Array.from({ length: 6 }, (_, i) => `- item ${String(i)}: ${paragraph.slice(0, 120)}`).join('\n')) + if (turn % 10 === 0) parts.push('```ts\n' + Array.from({ length: 40 }, (_, i) => `const value${String(i)} = compute(${String(i)}, "${'x'.repeat(30)}")`).join('\n') + '\n```') + if (turn % 15 === 0) parts.push('| a | b | c |\n|---|---|---|\n' + Array.from({ length: 8 }, (_, i) => `| ${String(i)} | ${paragraph.slice(0, 60)} | ${String(i * 3)} |`).join('\n')) + return parts.join('\n\n') +} + +function historyFixture(): string { + const session = Session.create(brandString(SESSION_ID)) + for (let turn = 1; turn <= TURNS; turn++) { + session.append('turn/start', { turn }) + session.append('step/start', { turn, step: 1 }) + if (turn === 1) session.append('system/message', { turn, step: 1, message: createSystemMessage('') }, { surfaceOp: 'append' }) + const user = session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: `Question ${String(turn)}: ` + '请检查宽度变化时的排版。 '.repeat(12) }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + if (turn === 1) session.append('session/title', { title: 'RIGHTBAR_DRAG_PERF', messageSeqs: [user.seq], source: { kind: 'fallback' } }) + const tool = turn % 5 === 0 + const callId = brandString(`rb-call-${String(turn)}`) + session.append('assistant/message', { + turn, step: 1, stream: [], + message: createAssistantMessage({ + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + content: [ + { type: 'reasoning', text: 'Compare the synthetic module and test. '.repeat(20) }, + { type: 'text', text: prose(turn) }, + ...tool ? [{ type: 'tool-call' as const, id: callId, name: 'synthetic_tool', arguments: '{"path":"src/a.ts"}' }] : [], + ], + }), + usage: { inputTokens: 4000, outputTokens: 800 }, + }, { surfaceOp: 'append' }) + if (tool) { + const call = session.append('tool/call', { turn, step: 1, callId, name: 'synthetic_tool', arguments: '{"path":"src/a.ts"}' }) + session.append('tool/result', { turn, step: 1, message: createToolResultMessage({ + callId, isError: false, content: [{ type: 'text', text: 'Synthetic tool output line.\n'.repeat(40) }], + }) }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + } + session.append('step/end', { turn, step: 1 }) + session.append('turn/end', { turn, reason: { kind: 'completed' } }) + } + return [JSON.stringify({ type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 1700000000000, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0 }), + ...session.snapshotEvents().map(event => JSON.stringify(event)), ''].join('\n') +} + +interface TraceEvent { + name: string + ph: string + dur?: number + ts: number + tid: number + pid: number + args?: { elementCount?: number } +} + +const SCRIPT_EVENTS = new Set(['FunctionCall', 'EventDispatch', 'FireAnimationFrame', 'TimerFire', 'RunMicrotasks', 'v8.callFunction']) + +/** Frame timestamps the page collects during one drag. */ +type FrameProbe = Window & { rightbarFrames?: { frames: number[]; running: boolean } } + +/** Sum style recalculation, layout, and the share of each forced synchronously from script. */ +function summarizeTrace(buffer: Buffer): Record { + const parsed = JSON.parse(buffer.toString('utf8')) as { traceEvents: TraceEvent[] } | TraceEvent[] + const events = (Array.isArray(parsed) ? parsed : parsed.traceEvents).filter(e => e.ph === 'X') + const scripts = events.filter(e => SCRIPT_EVENTS.has(e.name)) + // Style or layout run inside a script task is forced (synchronous) by a geometry read or style query. + const nested = (e: TraceEvent) => scripts.some(s => + s.tid === e.tid && s.pid === e.pid && s.ts <= e.ts && e.ts + (e.dur ?? 0) <= s.ts + (s.dur ?? 0)) + const ms = (list: TraceEvent[]) => list.reduce((t, e) => t + (e.dur ?? 0), 0) / 1000 + const layouts = events.filter(e => e.name === 'Layout') + const styles = events.filter(e => e.name === 'UpdateLayoutTree') + const forcedLayouts = layouts.filter(nested) + const forcedStyles = styles.filter(nested) + return { + layoutMs: ms(layouts), layouts: layouts.length, + forcedLayouts: forcedLayouts.length, forcedLayoutMs: ms(forcedLayouts), + styleMs: ms(styles), styles: styles.length, + forcedStyles: forcedStyles.length, forcedStyleMs: ms(forcedStyles), + styledElements: styles.reduce((t, e) => t + (e.args?.elementCount ?? 0), 0), + maxStyleMs: Math.max(0, ...styles.map(e => (e.dur ?? 0) / 1000)), + maxLayoutMs: Math.max(0, ...layouts.map(e => (e.dur ?? 0) / 1000)), + scriptMs: ms(events.filter(e => e.name === 'FunctionCall' || e.name === 'EventDispatch' || e.name === 'FireAnimationFrame')), + paintMs: ms(events.filter(e => e.name === 'Paint')), + } +} + +async function loadAll(page: Page): Promise { + let count = await page.locator(TAIL).count() + while (count < TURNS) { + const more = page.getByRole('button', { name: 'Load earlier', exact: true }) + await more.click({ timeout: 60_000 }) + await page.waitForFunction( + ({ selector, previous }) => document.querySelectorAll(selector).length > previous, + { selector: TAIL, previous: count }, + { timeout: 60_000 }, + ) + count = await page.locator(TAIL).count() + } + return count +} + +async function dragOnce(browser: Browser, page: Page, direction: 1 | -1): Promise> { + const handle = page.locator('[data-side="rightbar"]') + const box = await handle.boundingBox() + if (box === null) throw new Error('rightbar handle missing') + const x0 = box.x + box.width / 2 + const y = box.y + box.height / 2 + await page.evaluate(() => { + const probe = { frames: [] as number[], running: true } + ;(window as FrameProbe).rightbarFrames = probe + const tick = (t: number) => { if (!probe.running) return; probe.frames.push(t); requestAnimationFrame(tick) } + requestAnimationFrame(tick) + }) + await browser.startTracing(page, { categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'] }) + await page.mouse.move(x0, y) + await page.mouse.down() + const start = performance.now() + for (let i = 1; i <= STEPS; i++) { + await page.mouse.move(x0 - direction * i * STEP_PX, y) + await page.waitForTimeout(STEP_GAP_MS) + } + const moved = performance.now() + await page.mouse.up() + // Settled: the last frame within a 600 ms window whose transcript column or composer width differs from its predecessor. + const settle = await page.evaluate(() => new Promise<{ settleMs: number; columnWidth: number; composerWidth: number }>((resolve) => { + const start = window.performance.now() + const read = () => [ + document.querySelector('[data-chat-flow]')?.getBoundingClientRect().width ?? 0, + document.querySelector('[data-composer-input]')?.getBoundingClientRect().width ?? 0, + ] + let last = read() + let changedAt = 0 + const tick = (t: number) => { + const next = read() + if (next[0] !== last[0] || next[1] !== last[1]) changedAt = t - start + last = next + if (t - start < 600) requestAnimationFrame(tick) + else resolve({ settleMs: changedAt, columnWidth: next[0]!, composerWidth: next[1]! }) + } + requestAnimationFrame(tick) + })) + const settled = moved + settle.settleMs + const trace = summarizeTrace(await browser.stopTracing()) + const frames = await page.evaluate(() => { + const probe = (window as FrameProbe).rightbarFrames! + probe.running = false + return probe.frames + }) + const gaps = frames.slice(1).map((t, i) => t - frames[i]!).sort((a, b) => a - b) + const pick = (q: number) => gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * q))] ?? 0 + return { + dragMs: moved - start, settleMs: settle.settleMs, totalMs: settled - start, + columnWidth: settle.columnWidth, composerWidth: settle.composerWidth, + frames: frames.length, frameP50: pick(0.5), frameP95: pick(0.95), frameMax: gaps.at(-1) ?? 0, + ...trace, + } +} + +function median(values: number[]): number { + return values.toSorted((a, b) => a - b)[Math.floor(values.length / 2)]! +} + +it(`drags the right Sidebar beside ${String(TURNS)} loaded turns`, async () => { + if (webSnapshotMode() !== 'replay') throw new Error('requires DSH_SNAPSHOT=replay') + const scaffold = await launchWebScaffold() + const results: Record[]> = {} + try { + await seedSession(scaffold, historyFixture(), SESSION_ID) + const browser = await chromium.launch({ headless: true }) + try { + for (const { viewport, preference } of SCENARIOS) { + for (let sample = 0; sample < SAMPLES; sample++) { + const page = await newEnglishPage(browser) + await page.setViewportSize({ width: viewport, height: 1000 }) + page.setDefaultTimeout(60_000) + if (preference !== null) await page.addInitScript((value) => { localStorage.setItem('dsh.conversation.contentWidth', value) }, String(preference)) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.getByRole('treeitem').first().click() + await page.getByRole('treeitem').nth(1).click() + await page.locator(TAIL).last().waitFor() + const loaded = await loadAll(page) + expect(loaded).toBe(TURNS) + await page.getByRole('button', { name: 'Open right sidebar' }).first().click() + await page.locator('[data-side="rightbar"]').waitFor() + await page.waitForTimeout(800) + const nodes = await page.evaluate(() => document.querySelectorAll('*').length) + for (const direction of [1, -1] as const) { + const key = `${String(viewport)}/${preference === null ? 'auto' : 'pref' + String(preference)}/${direction === 1 ? 'widen' : 'narrow'}` + const result = { ...await dragOnce(browser, page, direction), nodes } + ;(results[key] ??= []).push(result) + console.log(JSON.stringify({ rb: 'sample', key, sample, ...result })) + } + await page.close() + } + } + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } + const summary = Object.fromEntries(Object.entries(results).map(([key, samples]) => [key, + Object.fromEntries(Object.keys(samples[0]!).map(metric => [metric, Math.round(median(samples.map(s => s[metric]!)) * 10) / 10]))])) + console.log(JSON.stringify({ rb: 'median', turns: TURNS, steps: STEPS, summary }, null, 1)) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index cd716a0177..43561279e8 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -276,6 +276,7 @@ "tests/window-drag-inheritance.e2e.ts", "tests/complex-history.perf.ts", "tests/dingtalk-connection.e2e.ts", + "tests/rightbar-drag.perf.ts", "tests/pwsh-terminal.e2e.ts", "tests/wecom-connection.e2e.ts", "tests/tencent-meeting-connection.e2e.ts", diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 6f5dab646a..b98644469b 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: fe90de63be885e2d - zh: 8ab904422097357f + en: 756022173490c1ca + zh: 2d4d493cbb535f42 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry: en: 876be274c65b56d9 zh: c3adbf5a16e0e38e diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 946c5b45bb..81102ed21b 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -126,7 +126,7 @@ The width-handle indicator follows the pointer only during a captured drag; ordi -The main Conversation body can keep room free at its inline end for something that stays beside the transcript, such as the docked [Session panel](../ui-session-panel/README.md#docking). A stylesheet asks for it by setting the `--dsh-chat-end-reserve` length on the `[data-conversation-content]` element. The scrollport then pads its end by `--dsh-chat-end-inset`, twice the missing gutter, which moves the centered transcript column and the composer toward the start edge at their own widths until the space after the column equals the reserve. `--dsh-chat-end-reserve-max` is the largest reserve the start gutter can give while the column keeps its width and its side inset; a larger request gets no inset, so whatever asks for room reads the maximum before it relies on that room. The body derives these lengths from the scrollport's width, which it publishes as `--dsh-conversation-viewport-width`, so they have the same values in the scrollport, the width handles, and the Chat aside layer. The width handles move with the column. While the inset is above zero the reserve holds the column's end edge, so a drag on either handle moves only the start edge and changes the width by the pointer's travel instead of twice it; a column dragged wider than the start gutter can give gets no inset and centers again. The inset applies at once. A stylesheet that wants a change of it animated also sets `--dsh-chat-end-reserve-transition`, a duration and an easing, on the same element for as long as that change lasts; the scrollport's padding and the Chat aside layer's margin then follow it together. An embedded occurrence makes no room: its maximum and its inset are 0. +The main Conversation body can keep room free at its inline end for something that stays beside the transcript, such as the docked [Session panel](../ui-session-panel/README.md#docking). A stylesheet asks for it by setting the `--dsh-chat-end-reserve` length on the `[data-conversation-content]` element. The scrollport then pads its end by `--dsh-chat-end-inset`, twice the missing gutter, which moves the centered transcript column and the composer toward the start edge at their own widths until the space after the column equals the reserve. `--dsh-chat-end-reserve-max` is the largest reserve the start gutter can give while the column keeps its width and its side inset; a larger request gets no inset, so whatever asks for room reads the maximum before it relies on that room. The maximum changes on every resize and is not inherited: a stylesheet reads it on the `[data-conversation-content]` element itself and derives what its descendants need there as a registered length, which changes only when the derived value does. The body keeps its other varying inputs uninherited as well and gives descendants `--dsh-chat-content-width` and `--dsh-chat-end-inset` as computed lengths, so resizing restyles the transcript only when one of those changes. The body derives these lengths from the scrollport's width, which it publishes as `--dsh-conversation-viewport-width`, so they have the same values in the scrollport, the width handles, and the Chat aside layer. The width handles move with the column. While the inset is above zero the reserve holds the column's end edge, so a drag on either handle moves only the start edge and changes the width by the pointer's travel instead of twice it; a column dragged wider than the start gutter can give gets no inset and centers again. The inset applies at once. A stylesheet that wants a change of it animated also sets `--dsh-chat-end-reserve-transition`, a duration and an easing, on the same element for as long as that change lasts; the scrollport's padding and the Chat aside layer's margin then follow it together. An embedded occurrence makes no room: its maximum and its inset are 0. The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), the claimed slash command is an atomic leading chip that carries its claim, folder text references carry the folder glyph as an icon prefix, and the draft's text and semantic references are persisted by the per-Session Conversation store. QueueDock reads `next-turn` from the Session `inbox` projection, including cold recovered messages, and excludes only requestIds still owned by local transcript submissions. Other queued rows retain their normal display and actions. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews use the [UserText Factory](#sent-user-text) (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text in the ui-primitives `InlineEditor`, so line breaks survive re-editing. Durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. On Apple platforms, Home and End move the caret to the start or end of the current visual line instead of scrolling the conversation, and Shift extends the selection; End immediately before a quote takes the same path as Cmd+Right to the end of that line. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 6fa3fd2049..12bc1b8efa 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -126,7 +126,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 -主 Conversation body 可以在行向末端空出一段位置,留给停在 transcript 旁边的内容,例如停靠的[会话面板](../ui-session-panel/README.zh.md#docking)。样式表在 `[data-conversation-content]` 元素上设置长度 `--dsh-chat-end-reserve` 来提出申请。滚动容器随即给末端加上 `--dsh-chat-end-inset` 的内边距,大小是所缺留白的两倍,居中的 transcript 列和输入框保持各自宽度向起始边缘移动,直到列后的空间等于预留值。`--dsh-chat-end-reserve-max` 是在列保持宽度和两侧内边距的前提下,起始留白能让出的最大预留;超出它的申请得不到任何内边距,因此申请方要先读取这个最大值,再依赖这段位置。主体从滚动容器的宽度推出这些长度,并把该宽度发布为 `--dsh-conversation-viewport-width`,因此它们在滚动容器、宽度拖拽条和 Chat 侧边层中的值相同。宽度拖拽条随列移动。内边距大于零时,预留固定了列的末端边缘,因此拖动任一拖拽条都只移动起始边缘,宽度的变化等于指针移动的距离而不是它的两倍;列被拖到超过起始留白能让出的宽度时不再有内边距,重新居中。内边距立即生效。样式表如果希望某次变化带动画,就在这次变化期间在同一个元素上再设置 `--dsh-chat-end-reserve-transition`(一个时长和一条缓动曲线),滚动容器的内边距和 Chat 侧边层的外边距随之一起过渡。嵌入式 occurrence 不让位:它的最大预留和内边距都是 0。 +主 Conversation body 可以在行向末端空出一段位置,留给停在 transcript 旁边的内容,例如停靠的[会话面板](../ui-session-panel/README.zh.md#docking)。样式表在 `[data-conversation-content]` 元素上设置长度 `--dsh-chat-end-reserve` 来提出申请。滚动容器随即给末端加上 `--dsh-chat-end-inset` 的内边距,大小是所缺留白的两倍,居中的 transcript 列和输入框保持各自宽度向起始边缘移动,直到列后的空间等于预留值。`--dsh-chat-end-reserve-max` 是在列保持宽度和两侧内边距的前提下,起始留白能让出的最大预留;超出它的申请得不到任何内边距,因此申请方要先读取这个最大值,再依赖这段位置。这个最大值随每次缩放变化且不继承:样式表在 `[data-conversation-content]` 元素本身上读取它,并在那里把后代需要的值推导为已注册的长度,只有推导结果变化时该长度才变化。主体的其他变化输入同样不继承,传给后代的 `--dsh-chat-content-width` 与 `--dsh-chat-end-inset` 是计算后的长度,因此缩放只有在它们变化时才重新计算正文样式。主体从滚动容器的宽度推出这些长度,并把该宽度发布为 `--dsh-conversation-viewport-width`,因此它们在滚动容器、宽度拖拽条和 Chat 侧边层中的值相同。宽度拖拽条随列移动。内边距大于零时,预留固定了列的末端边缘,因此拖动任一拖拽条都只移动起始边缘,宽度的变化等于指针移动的距离而不是它的两倍;列被拖到超过起始留白能让出的宽度时不再有内边距,重新居中。内边距立即生效。样式表如果希望某次变化带动画,就在这次变化期间在同一个元素上再设置 `--dsh-chat-end-reserve-transition`(一个时长和一条缓动曲线),滚动容器的内边距和 Chat 侧边层的外边距随之一起过渡。嵌入式 occurrence 不让位:它的最大预留和内边距都是 0。 常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 是携带认领的行首原子 chip,文件夹文本引用以图标前缀携带文件夹图形,草稿文字和引用语义字段由逐 Session Conversation store 持久化。QueueDock 从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息,仅排除仍由本地 transcript 提交承接的 requestId。其他排队行保留正常展示和操作。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览使用 [UserText Factory](#sent-user-text)(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态在 ui-primitives 的 `InlineEditor` 中展示字面发送文本,因此重新编辑不会丢失换行。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 在 Apple 平台上,Home 与 End 把光标移到当前视觉行的行首或行末,而不是滚动对话,按住 Shift 时扩展选区;光标紧贴在 quote 左侧时,End 与 Cmd+Right 走同一路径移到该行末尾。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css index 3848b08ee1..6fba9152d4 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css @@ -454,6 +454,49 @@ flex: none; } +/* The width axis's inputs and its continuously varying derived lengths are + registered without inheritance, so they exist only on the body: a resize + that changes them every frame does not restyle the transcript below it. + The resolved lengths compute to absolute values here, and the public + aliases the body declares from them inherit text that changes only when a + resolved width changes. */ +@property --dsh-conversation-column-width { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +@property --dsh-conversation-viewport-width { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +/* Without an initial value an unset preference stays invalid, so the body + falls back to the adaptive width. */ +@property --dsh-chat-user-width { + syntax: '*'; + inherits: false; +} + +@property --dsh-chat-content-width-resolved { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +@property --dsh-chat-end-reserve-max { + syntax: ''; + inherits: false; + initial-value: 0px; +} + +@property --dsh-chat-end-inset-resolved { + syntax: ''; + inherits: false; + initial-value: 0px; +} + /* Band below the header: the scrollport plus the width handles. Anchoring the handles here keeps their full-height strips and glow under the header's bottom edge at every header height. */ @@ -467,10 +510,11 @@ /* Shared width axis for the transcript, dock cards, composer, and takeover cards. Main width controls publish the live body width and optional user preference; embedded occurrences override this adaptive axis below. */ - --dsh-chat-content-width: var( + --dsh-chat-content-width-resolved: var( --dsh-chat-user-width, - clamp(680px, calc(var(--dsh-conversation-column-width, 0px) * 0.64), 880px) + clamp(680px, calc(var(--dsh-conversation-column-width) * 0.64), 880px) ); + --dsh-chat-content-width: var(--dsh-chat-content-width-resolved); --dsh-composer-card-max-width: calc(var(--dsh-chat-content-width) + 32px); --dsh-composer-side-clearance: 16px; --dsh-composer-dock-inset: 8px; @@ -484,23 +528,26 @@ --dsh-chat-end-reserve-max is the largest reserve the start gutter can give while the column keeps its width and its side inset; a larger one gets no inset at all, so the surface reads the maximum before it relies - on the room. Every length derives from the scrollport's measured width, + on the room. The maximum varies with every resize and is not inherited: + a stylesheet derives what it needs on this element, as a registered + length that changes only when its own value does. Every length derives from the scrollport's measured width, so the same values hold where a percentage would resolve against another box. The inset applies at once unless the stylesheet also sets --dsh-chat-end-reserve-transition, a duration and an easing, for as long as it wants a change of the inset animated. */ --dsh-chat-end-reserve-max: calc( - var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width) - var(--dsh-composer-side-clearance) - 16px + var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved) - var(--dsh-composer-side-clearance) - 16px ); /* The first term is 0 for a reserve above the maximum and at least 1000px, above any inset, otherwise: a step at the maximum, within a ten-thousandth of a pixel. */ - --dsh-chat-end-inset: min( + --dsh-chat-end-inset-resolved: min( max(0px, calc((var(--dsh-chat-end-reserve-max) - var(--dsh-chat-end-reserve, 0px)) * 10000000 + 1000px)), calc(2 * max( 0px, - var(--dsh-chat-end-reserve, 0px) - (var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width)) / 2 + var(--dsh-chat-end-reserve, 0px) - (var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved)) / 2 )) ); + --dsh-chat-end-inset: var(--dsh-chat-end-inset-resolved); } /* An embedded occurrence makes no room: its column already follows its frame's width. */ diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx index 824fac86ad..de9fe79a24 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx @@ -159,12 +159,12 @@ function WidthHandle(props: { */ export function ConversationWidthControls({ container, phase }: ConversationWidthControlsProps) { const publishWidths = useCallback((container: HTMLDivElement): void => { - const target = container.parentElement ?? container + // The axis registers these inputs without inheritance, so they belong on the body that derives from them. const column = container.offsetWidth - target.style.setProperty('--dsh-conversation-column-width', `${column}px`) + container.style.setProperty('--dsh-conversation-column-width', `${column}px`) const preference = readWidthPreference() - if (preference === null) target.style.removeProperty('--dsh-chat-user-width') - else target.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(column, preference)}px`) + if (preference === null) container.style.removeProperty('--dsh-chat-user-width') + else container.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(column, preference)}px`) }, []) useLayoutEffect(() => { @@ -181,8 +181,7 @@ export function ConversationWidthControls({ container, phase }: ConversationWidt }, [container]) const onDrag = useCallback((width: number): void => { if (container === null) return - const target = container.parentElement ?? container - target.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(container.offsetWidth, width)}px`) + container.style.setProperty('--dsh-chat-user-width', `${resolveContentWidth(container.offsetWidth, width)}px`) }, [container]) const onCommit = useCallback((width: number): void => { if (container === null) return diff --git a/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts b/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts index b662a89141..bf67551d06 100644 --- a/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts +++ b/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts @@ -27,13 +27,33 @@ describe('Conversation body end reserve', () => { it('derives the largest reserve and the inset from the scrollport width, the content width, and the side inset', () => { expect(body['--dsh-composer-side-clearance']).toBe('16px') expect(body['--dsh-chat-end-reserve-max']).toBe( - 'calc(var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width) - var(--dsh-composer-side-clearance) - 16px)', + 'calc(var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved) - var(--dsh-composer-side-clearance) - 16px)', ) - expect(body['--dsh-chat-end-inset']).toBe( + expect(body['--dsh-chat-end-inset-resolved']).toBe( 'min(max(0px, calc((var(--dsh-chat-end-reserve-max) - var(--dsh-chat-end-reserve, 0px)) * 10000000 + 1000px)),' + ' calc(2 * max(0px, var(--dsh-chat-end-reserve, 0px)' - + ' - (var(--dsh-conversation-viewport-width, 0px) - var(--dsh-chat-content-width)) / 2)))', + + ' - (var(--dsh-conversation-viewport-width) - var(--dsh-chat-content-width-resolved)) / 2)))', ) + expect(body['--dsh-chat-end-inset']).toBe('var(--dsh-chat-end-inset-resolved)') + }) + + it('keeps the continuously varying lengths on the body and publishes resolved lengths to its descendants', () => { + // Registered without inheritance: a resize that changes them every frame does not restyle the transcript. + const registered = Object.fromEntries([...css.matchAll(/@property\s+(--[\w-]+)\s*\{([^{}]*)\}/g)] + .map(([, name, block]) => [name, (block ?? '').replace(/\s+/g, ' ').trim()])) + expect(registered).toEqual({ + '--dsh-conversation-column-width': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-conversation-viewport-width': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-chat-user-width': "syntax: '*'; inherits: false;", + '--dsh-chat-content-width-resolved': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-chat-end-reserve-max': "syntax: ''; inherits: false; initial-value: 0px;", + '--dsh-chat-end-inset-resolved': "syntax: ''; inherits: false; initial-value: 0px;", + }) + // The inherited public names repeat a computed length, whose text changes only with the resolved width. + expect(body['--dsh-chat-content-width-resolved']).toBe( + 'var(--dsh-chat-user-width, clamp(680px, calc(var(--dsh-conversation-column-width) * 0.64), 880px))', + ) + expect(body['--dsh-chat-content-width']).toBe('var(--dsh-chat-content-width-resolved)') }) it('moves the column aside by twice the missing gutter at its own width, and makes no room once the start gutter is at the side inset', () => { diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index acb3f5dc6e..15c9a9aea0 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -950,24 +950,22 @@ describe('ConversationRoot resident composer', () => { expect(b.view.queryByRole('button', { name: 'Retry' })).toBeNull() }) - it('publishes the column width as a px variable for the shared width axis', () => { + it('publishes the column width as a px variable on the body for the shared width axis', () => { const b = mount(sessionSnapshotOf()) const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement - const root = content.parentElement as HTMLElement // jsdom offsetWidth is 0 until faked: the observer publishes whatever the // layout reports, and the CSS clamp() floors the axis at 680px either way. Object.defineProperty(content, 'offsetWidth', { value: 1200, configurable: true }) act(() => { fireResize(content) }) - expect(root.style.getPropertyValue('--dsh-conversation-column-width')).toBe('1200px') + expect(content.style.getPropertyValue('--dsh-conversation-column-width')).toBe('1200px') // No dragged preference: the user-width override stays absent so the // adaptive clamp term applies. - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('') }) it('drag → persist → window clamp round-trip on a width handle', () => { const b = mount(sessionSnapshotOf()) const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement - const root = content.parentElement as HTMLElement Object.defineProperty(content, 'offsetWidth', { value: 1600, configurable: true }) act(() => { fireResize(content) }) const handle = b.view.container.querySelector('[data-width-handle="right"]') as HTMLElement @@ -991,13 +989,13 @@ describe('ConversationRoot resident composer', () => { expect(handle.style.getPropertyValue('--dsh-width-handle-pointer-y')).toBe('300px') fireEvent.pointerUp(handle, { pointerId: 1, clientX: 825, clientY: 300 }) expect(handle.hasAttribute('data-dragging')).toBe(false) - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('930px') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('930px') expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') // Window shrinks: the displayed width re-clamps (900 − 176 = 724) but the // preference stays. Object.defineProperty(content, 'offsetWidth', { value: 900, configurable: true }) act(() => { fireResize(content) }) - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') // A press without travel (a real double-click delivers two such // press/release rounds) must not commit the clamped display value over @@ -1005,7 +1003,7 @@ describe('ConversationRoot resident composer', () => { fireEvent.pointerDown(handle, { pointerId: 1, clientX: 800, clientY: 300 }) fireEvent.pointerUp(handle, { pointerId: 1, clientX: 800, clientY: 300 }) expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') // No reset affordance on the handle: double-click leaves the preference alone. fireEvent.doubleClick(handle) expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') @@ -1020,7 +1018,6 @@ describe('ConversationRoot resident composer', () => { it('changes the width by the pointer travel, not twice it, while the scrollport pads its end for a reserve', () => { const b = mount(sessionSnapshotOf()) const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement - const root = content.parentElement as HTMLElement const scrollport = content.querySelector('[data-conversation-scroll]') as HTMLElement Object.defineProperty(content, 'offsetWidth', { value: 1600, configurable: true }) act(() => { fireResize(content) }) @@ -1042,12 +1039,12 @@ describe('ConversationRoot resident composer', () => { // The reserve holds the column's end edge: 25px outward on the start handle moves the start edge 25px → 880 + 25. fireEvent.pointerDown(handle, { pointerId: 1, clientX: 400, clientY: 300 }) fireEvent.pointerUp(handle, { pointerId: 1, clientX: 375, clientY: 300 }) - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('905px') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('905px') // Without the inset the column is centered and both edges move: 905 + 2 × 10. inset = '0px' fireEvent.pointerDown(handle, { pointerId: 1, clientX: 400, clientY: 300 }) fireEvent.pointerUp(handle, { pointerId: 1, clientX: 390, clientY: 300 }) - expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('925px') + expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('925px') } finally { for (const [name, descriptor] of originals) { if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, name) diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml index 9eebb14d6c..e14977457c 100644 --- a/packages/client/ui-session-panel/README.i18n.yaml +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -27,8 +27,8 @@ en: 27fdd4ec3c830299 zh: 0e70ac367e4176f8 /deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: - en: 78a25420651971d2 - zh: 8bd34e5624f08208 + en: fa42d7d9a77863fc + zh: ffd22e65cca99a3b /deepseek-ai-dsh-client-ui-session-panel/further-exploration: en: decfa1b92e25ec6c zh: 255c7862690a2f23 diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md index b9e600aedd..04b68ec568 100644 --- a/packages/client/ui-session-panel/README.md +++ b/packages/client/ui-session-panel/README.md @@ -83,7 +83,7 @@ A row whose single line clips its name or leaves out its owner, state, or measur
Implementation internals — click to expand -The panel is the `conversation.chat.aside` occupant of [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership), so it renders only in Chat Views. The toggle and the panel are separate Slot entries that share one plugin-owned state: the persisted docking preference, the Session whose overlay is open, and whether each mounted panel and each Session has room to dock. The stylesheets decide that room. The aside layer publishes its end gutter as `--dsh-chat-aside-gutter`, and the Conversation body publishes the largest end reserve its start gutter can give as `--dsh-chat-end-reserve-max`; the docked width and a zero-height dock probe derive from them and from one set of metrics (40px clear, 8px edge, 300px minimum width). The probe is 1px wide while the gutter holds the panel at its minimum width, from 348px, or while the largest reserve covers that gutter, and 0 otherwise. The panel always renders the probe and attaches it through the injected `createProbeRef`, and the plugin observes only that element with a `ResizeObserver`: it hears the docking decision flip and nothing while the window resizes on one side of it, the transcript width is dragged, or the transcript grows. A probe has room from 1px of width, a Session has room while any of its probes does, and a Session without a probe shows no Chat View. The panel reads its own probe and the toggle its Session, and both decide the presentation with the same pure function, so the toggle's state never disagrees with the panel; opening, closing, or docking the panel renders nothing in the Chat View. Without `ResizeObserver` no probe gains room, and the panel shows only as an overlay. The aside layer also inherits the scrollport's composer and viewport heights. +The panel is the `conversation.chat.aside` occupant of [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership), so it renders only in Chat Views. The toggle and the panel are separate Slot entries that share one plugin-owned state: the persisted docking preference, the Session whose overlay is open, and whether each mounted panel and each Session has room to dock. The stylesheets decide that room. The aside layer publishes its end gutter as `--dsh-chat-aside-gutter`, and the Conversation body publishes the largest end reserve its start gutter can give as `--dsh-chat-end-reserve-max`, which is readable only on the body, so the panel's stylesheet turns it there into a registered 0px or 1px step, `--dsh-session-panel-reserve-room`, that changes only when the reserve starts or stops covering the gutter; the docked width and a zero-height dock probe derive from them and from one set of metrics (40px clear, 8px edge, 300px minimum width). The probe is 1px wide while the gutter holds the panel at its minimum width, from 348px, or while the largest reserve covers that gutter, and 0 otherwise. The panel always renders the probe and attaches it through the injected `createProbeRef`, and the plugin observes only that element with a `ResizeObserver`: it hears the docking decision flip and nothing while the window resizes on one side of it, the transcript width is dragged, or the transcript grows. A probe has room from 1px of width, a Session has room while any of its probes does, and a Session without a probe shows no Chat View. The panel reads its own probe and the toggle its Session, and both decide the presentation with the same pure function, so the toggle's state never disagrees with the panel; opening, closing, or docking the panel renders nothing in the Chat View. Without `ResizeObserver` no probe gains room, and the panel shows only as an overlay. The aside layer also inherits the scrollport's composer and viewport heights. While the docking preference is on, the probe carries `data-session-panel-reserve`, and a `:has()` rule in the panel's stylesheet sets `--dsh-chat-end-reserve` to 348px on the Conversation body, which then pads its scrollport's end by the missing gutter ([end reserve](../ui-conversation/README.md#end-reserve)). The probe's second term reads the largest reserve, not the padding, so its answer is the same before and after the transcript moves: the room the transcript makes never changes the decision that asked for it. diff --git a/packages/client/ui-session-panel/README.zh.md b/packages/client/ui-session-panel/README.zh.md index 07c9732b39..c0b292a5d9 100644 --- a/packages/client/ui-session-panel/README.zh.md +++ b/packages/client/ui-session-panel/README.zh.md @@ -83,7 +83,7 @@ kind: "package-reference"
实现内幕——点击展开 -面板是 [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership) 中 `conversation.chat.aside` 的占位组件,因此只渲染在 Chat 视图中。开关与面板是两个独立的 Slot 条目,共享一份插件持有的状态:持久化的停靠偏好、打开了浮层的会话,以及每个已挂载的面板和每个会话是否有停靠空间。停靠空间由样式表决定。侧边层把末端留白发布为 `--dsh-chat-aside-gutter`,Conversation 主体把起始留白最多能让出的末端预留发布为 `--dsh-chat-end-reserve-max`;停靠宽度和一个零高度的停靠探针都由它们和同一组尺寸(间距 40px、边距 8px、最小宽度 300px)推出。留白放得下最小宽度的面板(从 348px 起),或者最大预留覆盖这段留白时,探针宽 1px,否则宽度为 0。面板始终渲染探针,并通过注入的 `createProbeRef` 挂接它;插件只用 `ResizeObserver` 观察这一个元素,所以只在停靠判断翻转时收到通知,窗口在阈值同一侧缩放、拖动正文宽度或正文增长时都不会。探针宽度达到 1px 即有停靠空间;会话的任一探针有空间时该会话就有停靠空间,没有探针的会话表示没有 Chat 视图在显示它。面板读取自己的探针,开关读取所在会话,两者用同一个纯函数决定呈现方式,因此开关状态始终与面板一致;打开、关闭或停靠面板也不会让 Chat 视图重新渲染。没有 `ResizeObserver` 时任何探针都不会获得空间,面板只以浮层显示。侧边层还从滚动容器继承输入框区域与视口高度。 +面板是 [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership) 中 `conversation.chat.aside` 的占位组件,因此只渲染在 Chat 视图中。开关与面板是两个独立的 Slot 条目,共享一份插件持有的状态:持久化的停靠偏好、打开了浮层的会话,以及每个已挂载的面板和每个会话是否有停靠空间。停靠空间由样式表决定。侧边层把末端留白发布为 `--dsh-chat-aside-gutter`,Conversation 主体把起始留白最多能让出的末端预留发布为 `--dsh-chat-end-reserve-max`,它只能在主体上读取,因此面板样式表在主体上把它转换为已注册的 0px 或 1px 阶跃值 `--dsh-session-panel-reserve-room`,只有预留开始或不再覆盖这段留白时才变化;停靠宽度和一个零高度的停靠探针都由它们和同一组尺寸(间距 40px、边距 8px、最小宽度 300px)推出。留白放得下最小宽度的面板(从 348px 起),或者最大预留覆盖这段留白时,探针宽 1px,否则宽度为 0。面板始终渲染探针,并通过注入的 `createProbeRef` 挂接它;插件只用 `ResizeObserver` 观察这一个元素,所以只在停靠判断翻转时收到通知,窗口在阈值同一侧缩放、拖动正文宽度或正文增长时都不会。探针宽度达到 1px 即有停靠空间;会话的任一探针有空间时该会话就有停靠空间,没有探针的会话表示没有 Chat 视图在显示它。面板读取自己的探针,开关读取所在会话,两者用同一个纯函数决定呈现方式,因此开关状态始终与面板一致;打开、关闭或停靠面板也不会让 Chat 视图重新渲染。没有 `ResizeObserver` 时任何探针都不会获得空间,面板只以浮层显示。侧边层还从滚动容器继承输入框区域与视口高度。 停靠偏好开启时,探针带有 `data-session-panel-reserve`,面板样式表中的一条 `:has()` 规则据此在 Conversation 主体上把 `--dsh-chat-end-reserve` 设为 348px,主体随即按所缺的留白给滚动容器的末端加上内边距([末端预留](../ui-conversation/README.zh.md#end-reserve))。探针的第二项读取的是最大预留而不是内边距,因此正文移动前后它的结果相同:正文让出的位置不会反过来改变提出让位的那项判断。 diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.module.css b/packages/client/ui-session-panel/src/client/SessionPanel.module.css index 9451d4b3c1..59309b9b9c 100644 --- a/packages/client/ui-session-panel/src/client/SessionPanel.module.css +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -6,8 +6,10 @@ /* The docked panel's inline metrics: 40px clear of the transcript column, past its width handle, 8px from the end edge, and at least 300px wide. The - panel's width and the dock probe both derive from them, so the gutter that - docks the panel is exactly the one that holds its minimum width. */ + panel's width, the dock probe, and the reserve it asks the Conversation + body for all derive from them, so the gutter that docks the panel is + exactly the one that holds its minimum width. */ +:global([data-conversation-content]), .panel, .dockProbe { --panel-clear: 40px; @@ -15,6 +17,25 @@ --panel-min-width: 300px; } +/* Whether the Conversation body's largest end reserve covers the docked + panel's gutter: 1px when it does, otherwise 0. The body's maximum is not + inherited and changes on every resize, so this step derives on the body + itself, and as a registered length it reaches the dock probe only when the + decision flips. */ +@property --dsh-session-panel-reserve-room { + syntax: ''; + inherits: true; + initial-value: 0px; +} + +:global([data-conversation-content]) { + --dsh-session-panel-reserve-room: clamp( + 0px, + calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px), + 1px + ); +} + /* While the docking preference is on, the dock probe carries a mark, and the panel asks the Conversation body to keep the gutter that docks it: the three metrics above, 348px. Where the gutter is narrower, the body @@ -22,7 +43,7 @@ (ui-conversation's end reserve) and makes no room when the start gutter cannot give it. */ :global([data-conversation-content]):has(.dockProbe[data-session-panel-reserve]) { - --dsh-chat-end-reserve: calc(40px + 8px + 300px); + --dsh-chat-end-reserve: calc(var(--panel-clear) + var(--panel-edge) + var(--panel-min-width)); } .panel { @@ -104,7 +125,7 @@ right: 0; width: max( calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px), - calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px) + var(--dsh-session-panel-reserve-room) ); max-width: 1px; height: 0; diff --git a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts index 0f494e5d1e..889998a773 100644 --- a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts +++ b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts @@ -31,10 +31,12 @@ const px = (value: string | undefined): number => { } describe('SessionPanel.module.css docking geometry', () => { - const metrics = declarationsOf('.panel, .dockProbe') + const metrics = declarationsOf(':global([data-conversation-content]), .panel, .dockProbe') const clear = px(metrics['--panel-clear']) const edge = px(metrics['--panel-edge']) const minWidth = px(metrics['--panel-min-width']) + /** The body's reserve step, evaluated: clamped to 0..1px. */ + const reserveRoom = (reserveMax: number): number => Math.min(1, Math.max(0, (reserveMax - clear - edge - minWidth) * 10000000 + 1)) it('derives the docked width and the dock probe from one set of metrics', () => { expect([clear, edge, minWidth]).toEqual([40, 8, 300]) @@ -46,15 +48,27 @@ describe('SessionPanel.module.css docking geometry', () => { const probe = declarationsOf('.dockProbe') expect(probe['width']).toBe( 'max(calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px),' - + ' calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px))', + + ' var(--dsh-session-panel-reserve-room))', ) expect(probe['max-width']).toBe('1px') }) + it('derives the reserve step on the Conversation body, where the non-inherited maximum is readable', () => { + expect(declarationsOf(':global([data-conversation-content])')).toEqual({ + '--dsh-session-panel-reserve-room': 'clamp(0px,' + + ' calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px),' + + ' 1px)', + }) + // Registered as a length, the step computes to 0px or 1px on the body, so descendants see a change only when it flips. + expect(css.replace(/\s+/g, ' ')).toContain( + "@property --dsh-session-panel-reserve-room { syntax: ''; inherits: true; initial-value: 0px; }", + ) + }) + it('makes the probe 1px wide exactly from the gutter that holds the panel at its minimum width', () => { // The declarations above, evaluated: a width below 0 is used as 0, and max-width caps the probe at 1px. const probeWidth = (gutter: number, reserveMax = 0): number => - Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, (reserveMax - clear - edge - minWidth) * 10000000 + 1)) + Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, reserveRoom(reserveMax))) const dockedWidth = (gutter: number): number => Math.min(360, Math.max(minWidth, gutter - clear - edge)) expect([probeWidth(0), probeWidth(347), probeWidth(347.5), probeWidth(348), probeWidth(900)]).toEqual([0, 0, 0.5, 1, 1]) // At the first gutter that docks, the panel is at its minimum width and keeps both clearances. @@ -65,7 +79,7 @@ describe('SessionPanel.module.css docking geometry', () => { it('gives the probe room as well from the largest end reserve that covers the gutter, whatever the gutter is', () => { const probeWidth = (gutter: number, reserveMax: number): number => - Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, (reserveMax - clear - edge - minWidth) * 10000000 + 1)) + Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1, reserveRoom(reserveMax))) // A 260px gutter holds no panel, and the transcript can leave 348px: room. This term is a step at 348px, as the // body's end inset is, so the probe has room exactly where the body makes it. expect([probeWidth(260, 347), probeWidth(260, 347.96), probeWidth(260, 348), probeWidth(260, 900)]).toEqual([0, 0, 1, 1]) @@ -77,8 +91,7 @@ describe('SessionPanel.module.css docking geometry', () => { it('asks the Conversation body for exactly the gutter that docks the panel while the probe carries the mark', () => { const request = declarationsOf(':global([data-conversation-content]):has(.dockProbe[data-session-panel-reserve])') - expect(request).toEqual({ '--dsh-chat-end-reserve': 'calc(40px + 8px + 300px)' }) - expect(40 + 8 + 300).toBe(clear + edge + minWidth) + expect(request).toEqual({ '--dsh-chat-end-reserve': 'calc(var(--panel-clear) + var(--panel-edge) + var(--panel-min-width))' }) }) it('keeps the probe out of sight, out of the layout flow, and away from the pointer', () => { diff --git a/tsconfig.host.json b/tsconfig.host.json index a80e298cba..74698483d1 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -264,6 +264,7 @@ "apps/web/tests/window-drag-inheritance.e2e.ts", "apps/web/tests/complex-history.perf.ts", "apps/web/tests/dingtalk-connection.e2e.ts", + "apps/web/tests/rightbar-drag.perf.ts", "apps/web/tests/pwsh-terminal.e2e.ts", "apps/web/tests/wecom-connection.e2e.ts", "apps/web/tests/tencent-meeting-connection.e2e.ts", From aa8c72d1d26bdbae2fb42b4ef1c3b601e80f0c4d Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:00:17 +0800 Subject: [PATCH 28/54] test(benchmarks): gate transcript restyles while the right Sidebar is dragged Move the right Sidebar drag diagnostic into the required serial browser benchmark inventory. It budgets the elements Chromium restyles during a drag that leaves the content width unchanged, as a dimensionless multiple of the page's elements, and replays recorded before/after samples as its negative control. Also type the registered-property entries in the end-reserve style test. Refs #8856 --- ...-20-rightbar-drag-restyle-budget.i18n.yaml | 22 ++ ...2026-11-20-rightbar-drag-restyle-budget.md | 37 +++ ...6-11-20-rightbar-drag-restyle-budget.zh.md | 37 +++ apps/web/tests/rightbar-drag.perf.ts | 245 ------------------ apps/web/tsconfig.json | 1 - .../rightbar-drag-browser/README.i18n.yaml | 13 + benchmarks/rightbar-drag-browser/README.md | 17 ++ benchmarks/rightbar-drag-browser/README.zh.md | 17 ++ .../rightbar-drag.bench.ts | 177 +++++++++++++ .../synthetic-history.ts | 67 +++++ .../tests/end-reserve-styles.client.spec.ts | 2 +- scripts/run-bench-suite.ts | 1 + tsconfig.host.json | 1 - 13 files changed, 389 insertions(+), 248 deletions(-) create mode 100644 .agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml create mode 100644 .agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md create mode 100644 .agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md delete mode 100644 apps/web/tests/rightbar-drag.perf.ts create mode 100644 benchmarks/rightbar-drag-browser/README.i18n.yaml create mode 100644 benchmarks/rightbar-drag-browser/README.md create mode 100644 benchmarks/rightbar-drag-browser/README.zh.md create mode 100644 benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts create mode 100644 benchmarks/rightbar-drag-browser/synthetic-history.ts diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml new file mode 100644 index 0000000000..f2675a7ede --- /dev/null +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-11-20-rightbar-drag-restyle-budget.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/testing/2026-11-20-rightbar-drag-restyle-budget.md +/agent-note-right-sidebar-drag-restyle-budget: + en: a467dea2219bda57 + zh: 7bcd04d8a6dd8481 +/agent-note-right-sidebar-drag-restyle-budget/problem: + en: 693e8d1e4423b78f + zh: c63608002d762c12 +/agent-note-right-sidebar-drag-restyle-budget/decision: + en: 7b21bc1115988534 + zh: 4929a26024ec4237 +/agent-note-right-sidebar-drag-restyle-budget/calibration: + en: 5a234a9e422c36dc + zh: e48d9f7fb8445cd9 +/agent-note-right-sidebar-drag-restyle-budget/alternatives-considered: + en: 721cbfb3276fcb5b + zh: 9557ee132f77f5a6 +/agent-note-right-sidebar-drag-restyle-budget/consequences: + en: 6f1a2842da26a0df + zh: 9bd23e840e900a7e diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md new file mode 100644 index 0000000000..38371e44da --- /dev/null +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md @@ -0,0 +1,37 @@ +# Agent Note: Right Sidebar drag restyle budget + +Status: implemented + +English | [中文](2026-11-20-rightbar-drag-restyle-budget.zh.md) + +## Problem + +Dragging the right Sidebar beside a long transcript stalled for hundreds of milliseconds per frame. The Conversation body published measured widths as unregistered, inherited custom properties on an ancestor of the whole transcript, so every frame restyled every transcript element, even when the resolved content width did not change; later resize observers that read geometry forced that work synchronously. Existing browser benchmarks open, page, and stream a long Session, but none resizes it, so the regression had no gate. + +## Decision + +The [right Sidebar drag benchmark](../../../../benchmarks/rightbar-drag-browser/README.md) joins the serial browser inventory. It loads a 120-turn synthetic Session completely, opens the right Sidebar, and drags its handle 40 trusted 8px mouse steps outward and back in a 1680×1000 viewport, in two fresh scaffold worlds and browsers. At that width the transcript column stays below the 680px content-width floor, and each drag asserts it, so the drag changes the column but not the resolved content width. + +The budget is a dimensionless count: the elements reported by every `UpdateLayoutTree` trace event during one drag, divided by the page's element count, as a median per direction, at most 1. A drag that restyles the transcript on every frame reaches about one multiple per frame; the fixed drag stays far below one multiple in total. The count does not depend on CPU speed, so it takes neither the shared time scale nor the variance headroom, and no wall-clock endpoint is budgeted or passed to the scaling report. + +## Calibration + +Local Linux x64 Chromium samples, 40-step drags: + +| Workload | Widen | Narrow | +|---|---:|---:| +| 200 turns, before the width axis change | 1,479,947 / 28,895 = 51.2 | 1,909,568 / 28,895 = 66.1 | +| 200 turns, after | 2,622 / 28,895 = 0.09 | 3,368 / 28,895 = 0.12 | +| 120 turns, after (both samples) | 2,622 / 18,383 = 0.14 | 3,368 / 18,383 = 0.18 | + +The restyled count after the change is identical across samples and history lengths, so the ratio leaves more than five times headroom at 120 turns, while the pre-change behavior exceeds the budget fifty-fold. The case's first test replays these recorded values as its negative control. + +## Alternatives considered + +- Budget frame gaps or style milliseconds. Rejected for the gate: they need browser-runner calibration that does not exist yet, and they also include the transcript reflow at each new column width, which a resize legitimately pays. They remain diagnostics. +- Add the drag to the manual `apps/web` performance lane. Rejected: that lane runs only on request, and this regression must fail CI. +- Budget a viewport where the content width changes during the drag. Rejected: inherited width changes legitimately restyle descendants, so the count would measure the content width's consumers rather than the regression. + +## Consequences + +A regression that again publishes per-frame inputs to the transcript fails CI within one benchmark run, with no timing calibration. The case does not measure layout or paint cost, window resizing, the Conversation's own width handles, or a docked Session panel, whose end reserve can change the content inset during a drag. Chromium's element counting may change across browser versions; an upgrade that moves the counts re-records the calibration values above and in the negative control. diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md new file mode 100644 index 0000000000..4802d8accd --- /dev/null +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md @@ -0,0 +1,37 @@ +# Agent Note:右侧栏拖动样式重算预算 + +Status: implemented + +[English](2026-11-20-rightbar-drag-restyle-budget.md) | 中文 + +## 问题 + +在长会话旁拖动右侧栏时,每帧会卡住数百毫秒。Conversation 主体把测得的宽度作为未注册、可继承的自定义属性写在整段记录的祖先元素上,因此即使解析后的正文宽度不变,每一帧也要重算整段记录所有元素的样式;随后读取几何值的 ResizeObserver 又迫使这些工作同步完成。现有浏览器基准覆盖打开、分页和流式输出长会话,但没有一个调整它的宽度,所以这一回归没有门禁。 + +## 决定 + +[右侧栏拖动基准](../../../../benchmarks/rightbar-drag-browser/README.zh.md)加入串行浏览器清单。它完整加载一个 120 轮合成会话,打开右侧栏,在 1680×1000 视口中把拖拽条向外拖 40 个 8px 的真实鼠标步再拖回,在两个全新的脚手架环境和浏览器中各做一次。该宽度下正文列始终窄于 680px 的正文宽度下限,每次拖动都会断言这一点,因此拖动改变的是列宽,而不是解析后的正文宽度。 + +预算是一个无量纲计数:一次拖动期间所有 `UpdateLayoutTree` trace 事件报告的元素数之和,除以页面元素数,按方向取中位数,最多为 1。每帧都重算整段记录的拖动大约每帧就达到一倍;修复后的拖动总计远低于一倍。该计数与 CPU 速度无关,因此既不使用共享的时间缩放系数,也不使用波动余量;没有为任何墙钟终点设预算,也不把它们传给缩放报告。 + +## 校准 + +本地 Linux x64 Chromium 样本,每次拖动 40 步: + +| 负载 | 加宽 | 缩窄 | +|---|---:|---:| +| 200 轮,宽度轴改动前 | 1,479,947 / 28,895 = 51.2 | 1,909,568 / 28,895 = 66.1 | +| 200 轮,改动后 | 2,622 / 28,895 = 0.09 | 3,368 / 28,895 = 0.12 | +| 120 轮,改动后(两个样本相同) | 2,622 / 18,383 = 0.14 | 3,368 / 18,383 = 0.18 | + +改动后重算的元素数在各样本和不同历史长度下完全相同,因此 120 轮时比值留有五倍以上余量,而改动前的行为超出预算五十倍。用例的第一个测试回放这些记录值作为负对照。 + +## 备选方案 + +- 为帧间隔或样式毫秒数设预算。门禁不采用:它们需要尚不存在的浏览器 runner 校准,而且还包含按每个新列宽重排正文的成本,这是缩放本应付出的。它们保留为诊断输出。 +- 把拖动加入 `apps/web` 的手动性能通道。不采用:该通道只按需运行,而这一回归必须让 CI 失败。 +- 选一个拖动中正文宽度会变化的视口设预算。不采用:继承的宽度变化本来就会重算后代样式,计数测到的会是正文宽度的使用者,而不是这一回归。 + +## 影响 + +再次把逐帧变化的输入传给整段记录的回归会在一次基准运行内让 CI 失败,不需要任何计时校准。本用例不测量布局或绘制成本、窗口缩放、Conversation 自身的宽度拖拽条,也不测量停靠的 Session 面板,因为它的末端预留可能在拖动中改变正文内边距。Chromium 的元素计数方式可能随浏览器版本变化;改变计数的升级需要重新记录上面的校准值和负对照中的值。 diff --git a/apps/web/tests/rightbar-drag.perf.ts b/apps/web/tests/rightbar-drag.perf.ts deleted file mode 100644 index 015640f852..0000000000 --- a/apps/web/tests/rightbar-drag.perf.ts +++ /dev/null @@ -1,245 +0,0 @@ -// Manual diagnostic: main-thread cost of dragging the right Sidebar's resize -// handle beside a long, fully loaded synthetic transcript. It reports frame -// gaps, style recalculation (with the element count it touched), layout, and -// the share of both forced synchronously from script, plus the final column -// and composer widths; host speed is not a correctness contract, so nothing is -// asserted beyond the loaded turn count. Run after `pnpm run build:artifacts`: -// RB_TURNS=200 RB_SAMPLES=3 RB_STEPS=40 DSH_SNAPSHOT=replay \ -// pnpm exec vitest run --config vitest.web.perf.config.ts apps/web/tests/rightbar-drag.perf.ts -import { performance } from 'node:perf_hooks' -import { chromium, type Browser, type Page } from 'playwright' -import { expect, it } from 'vitest' -import { brandString } from '@deepseek-ai/dsh-brand' -import { - type ToolCallId, - createAssistantMessage, - createSystemMessage, - createToolResultMessage, - createUserMessage, -} from '@deepseek-ai/dsh-llm' -import { SESSION_FORMAT_VERSION, Session, type SessionId } from '@deepseek-ai/dsh-session' -import type {} from '@deepseek-ai/dsh-session-title' -import { launchWebScaffold, seedSession, webSnapshotMode } from './scaffold.ts' -import { newEnglishPage } from './support.ts' - -const TURNS = Number(process.env.RB_TURNS ?? 200) -const SAMPLES = Number(process.env.RB_SAMPLES ?? 3) -const STEPS = Number(process.env.RB_STEPS ?? 40) -const STEP_PX = 8 -const STEP_GAP_MS = 8 -const SESSION_ID = 'perf-rightbar-drag' -const TAIL = '[data-chat-flow-key*="turn-tail"]' -/** A narrow window where the column falls below the content width, a wide one, and a wide one with a dragged preference. */ -const SCENARIOS = [ - { viewport: 1680, preference: null }, - { viewport: 2560, preference: null }, - { viewport: 2560, preference: 720 }, -] as const - -function prose(turn: number): string { - const paragraph = `Turn ${String(turn)} synthetic analysis: the renderer measures every row, wraps mixed text 混合中文段落用于换行测量, and keeps \`inline code\` beside **bold** words. ` - const parts = [paragraph.repeat(6), paragraph.repeat(4)] - parts.push(Array.from({ length: 6 }, (_, i) => `- item ${String(i)}: ${paragraph.slice(0, 120)}`).join('\n')) - if (turn % 10 === 0) parts.push('```ts\n' + Array.from({ length: 40 }, (_, i) => `const value${String(i)} = compute(${String(i)}, "${'x'.repeat(30)}")`).join('\n') + '\n```') - if (turn % 15 === 0) parts.push('| a | b | c |\n|---|---|---|\n' + Array.from({ length: 8 }, (_, i) => `| ${String(i)} | ${paragraph.slice(0, 60)} | ${String(i * 3)} |`).join('\n')) - return parts.join('\n\n') -} - -function historyFixture(): string { - const session = Session.create(brandString(SESSION_ID)) - for (let turn = 1; turn <= TURNS; turn++) { - session.append('turn/start', { turn }) - session.append('step/start', { turn, step: 1 }) - if (turn === 1) session.append('system/message', { turn, step: 1, message: createSystemMessage('') }, { surfaceOp: 'append' }) - const user = session.append('user/message', createUserMessage({ - content: [{ type: 'text', text: `Question ${String(turn)}: ` + '请检查宽度变化时的排版。 '.repeat(12) }], - source: { kind: 'user' }, - }), { surfaceOp: 'append' }) - if (turn === 1) session.append('session/title', { title: 'RIGHTBAR_DRAG_PERF', messageSeqs: [user.seq], source: { kind: 'fallback' } }) - const tool = turn % 5 === 0 - const callId = brandString(`rb-call-${String(turn)}`) - session.append('assistant/message', { - turn, step: 1, stream: [], - message: createAssistantMessage({ - source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, - content: [ - { type: 'reasoning', text: 'Compare the synthetic module and test. '.repeat(20) }, - { type: 'text', text: prose(turn) }, - ...tool ? [{ type: 'tool-call' as const, id: callId, name: 'synthetic_tool', arguments: '{"path":"src/a.ts"}' }] : [], - ], - }), - usage: { inputTokens: 4000, outputTokens: 800 }, - }, { surfaceOp: 'append' }) - if (tool) { - const call = session.append('tool/call', { turn, step: 1, callId, name: 'synthetic_tool', arguments: '{"path":"src/a.ts"}' }) - session.append('tool/result', { turn, step: 1, message: createToolResultMessage({ - callId, isError: false, content: [{ type: 'text', text: 'Synthetic tool output line.\n'.repeat(40) }], - }) }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) - } - session.append('step/end', { turn, step: 1 }) - session.append('turn/end', { turn, reason: { kind: 'completed' } }) - } - return [JSON.stringify({ type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 1700000000000, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0 }), - ...session.snapshotEvents().map(event => JSON.stringify(event)), ''].join('\n') -} - -interface TraceEvent { - name: string - ph: string - dur?: number - ts: number - tid: number - pid: number - args?: { elementCount?: number } -} - -const SCRIPT_EVENTS = new Set(['FunctionCall', 'EventDispatch', 'FireAnimationFrame', 'TimerFire', 'RunMicrotasks', 'v8.callFunction']) - -/** Frame timestamps the page collects during one drag. */ -type FrameProbe = Window & { rightbarFrames?: { frames: number[]; running: boolean } } - -/** Sum style recalculation, layout, and the share of each forced synchronously from script. */ -function summarizeTrace(buffer: Buffer): Record { - const parsed = JSON.parse(buffer.toString('utf8')) as { traceEvents: TraceEvent[] } | TraceEvent[] - const events = (Array.isArray(parsed) ? parsed : parsed.traceEvents).filter(e => e.ph === 'X') - const scripts = events.filter(e => SCRIPT_EVENTS.has(e.name)) - // Style or layout run inside a script task is forced (synchronous) by a geometry read or style query. - const nested = (e: TraceEvent) => scripts.some(s => - s.tid === e.tid && s.pid === e.pid && s.ts <= e.ts && e.ts + (e.dur ?? 0) <= s.ts + (s.dur ?? 0)) - const ms = (list: TraceEvent[]) => list.reduce((t, e) => t + (e.dur ?? 0), 0) / 1000 - const layouts = events.filter(e => e.name === 'Layout') - const styles = events.filter(e => e.name === 'UpdateLayoutTree') - const forcedLayouts = layouts.filter(nested) - const forcedStyles = styles.filter(nested) - return { - layoutMs: ms(layouts), layouts: layouts.length, - forcedLayouts: forcedLayouts.length, forcedLayoutMs: ms(forcedLayouts), - styleMs: ms(styles), styles: styles.length, - forcedStyles: forcedStyles.length, forcedStyleMs: ms(forcedStyles), - styledElements: styles.reduce((t, e) => t + (e.args?.elementCount ?? 0), 0), - maxStyleMs: Math.max(0, ...styles.map(e => (e.dur ?? 0) / 1000)), - maxLayoutMs: Math.max(0, ...layouts.map(e => (e.dur ?? 0) / 1000)), - scriptMs: ms(events.filter(e => e.name === 'FunctionCall' || e.name === 'EventDispatch' || e.name === 'FireAnimationFrame')), - paintMs: ms(events.filter(e => e.name === 'Paint')), - } -} - -async function loadAll(page: Page): Promise { - let count = await page.locator(TAIL).count() - while (count < TURNS) { - const more = page.getByRole('button', { name: 'Load earlier', exact: true }) - await more.click({ timeout: 60_000 }) - await page.waitForFunction( - ({ selector, previous }) => document.querySelectorAll(selector).length > previous, - { selector: TAIL, previous: count }, - { timeout: 60_000 }, - ) - count = await page.locator(TAIL).count() - } - return count -} - -async function dragOnce(browser: Browser, page: Page, direction: 1 | -1): Promise> { - const handle = page.locator('[data-side="rightbar"]') - const box = await handle.boundingBox() - if (box === null) throw new Error('rightbar handle missing') - const x0 = box.x + box.width / 2 - const y = box.y + box.height / 2 - await page.evaluate(() => { - const probe = { frames: [] as number[], running: true } - ;(window as FrameProbe).rightbarFrames = probe - const tick = (t: number) => { if (!probe.running) return; probe.frames.push(t); requestAnimationFrame(tick) } - requestAnimationFrame(tick) - }) - await browser.startTracing(page, { categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'] }) - await page.mouse.move(x0, y) - await page.mouse.down() - const start = performance.now() - for (let i = 1; i <= STEPS; i++) { - await page.mouse.move(x0 - direction * i * STEP_PX, y) - await page.waitForTimeout(STEP_GAP_MS) - } - const moved = performance.now() - await page.mouse.up() - // Settled: the last frame within a 600 ms window whose transcript column or composer width differs from its predecessor. - const settle = await page.evaluate(() => new Promise<{ settleMs: number; columnWidth: number; composerWidth: number }>((resolve) => { - const start = window.performance.now() - const read = () => [ - document.querySelector('[data-chat-flow]')?.getBoundingClientRect().width ?? 0, - document.querySelector('[data-composer-input]')?.getBoundingClientRect().width ?? 0, - ] - let last = read() - let changedAt = 0 - const tick = (t: number) => { - const next = read() - if (next[0] !== last[0] || next[1] !== last[1]) changedAt = t - start - last = next - if (t - start < 600) requestAnimationFrame(tick) - else resolve({ settleMs: changedAt, columnWidth: next[0]!, composerWidth: next[1]! }) - } - requestAnimationFrame(tick) - })) - const settled = moved + settle.settleMs - const trace = summarizeTrace(await browser.stopTracing()) - const frames = await page.evaluate(() => { - const probe = (window as FrameProbe).rightbarFrames! - probe.running = false - return probe.frames - }) - const gaps = frames.slice(1).map((t, i) => t - frames[i]!).sort((a, b) => a - b) - const pick = (q: number) => gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * q))] ?? 0 - return { - dragMs: moved - start, settleMs: settle.settleMs, totalMs: settled - start, - columnWidth: settle.columnWidth, composerWidth: settle.composerWidth, - frames: frames.length, frameP50: pick(0.5), frameP95: pick(0.95), frameMax: gaps.at(-1) ?? 0, - ...trace, - } -} - -function median(values: number[]): number { - return values.toSorted((a, b) => a - b)[Math.floor(values.length / 2)]! -} - -it(`drags the right Sidebar beside ${String(TURNS)} loaded turns`, async () => { - if (webSnapshotMode() !== 'replay') throw new Error('requires DSH_SNAPSHOT=replay') - const scaffold = await launchWebScaffold() - const results: Record[]> = {} - try { - await seedSession(scaffold, historyFixture(), SESSION_ID) - const browser = await chromium.launch({ headless: true }) - try { - for (const { viewport, preference } of SCENARIOS) { - for (let sample = 0; sample < SAMPLES; sample++) { - const page = await newEnglishPage(browser) - await page.setViewportSize({ width: viewport, height: 1000 }) - page.setDefaultTimeout(60_000) - if (preference !== null) await page.addInitScript((value) => { localStorage.setItem('dsh.conversation.contentWidth', value) }, String(preference)) - await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.getByRole('treeitem').first().click() - await page.getByRole('treeitem').nth(1).click() - await page.locator(TAIL).last().waitFor() - const loaded = await loadAll(page) - expect(loaded).toBe(TURNS) - await page.getByRole('button', { name: 'Open right sidebar' }).first().click() - await page.locator('[data-side="rightbar"]').waitFor() - await page.waitForTimeout(800) - const nodes = await page.evaluate(() => document.querySelectorAll('*').length) - for (const direction of [1, -1] as const) { - const key = `${String(viewport)}/${preference === null ? 'auto' : 'pref' + String(preference)}/${direction === 1 ? 'widen' : 'narrow'}` - const result = { ...await dragOnce(browser, page, direction), nodes } - ;(results[key] ??= []).push(result) - console.log(JSON.stringify({ rb: 'sample', key, sample, ...result })) - } - await page.close() - } - } - } finally { - await browser.close() - } - } finally { - await scaffold.close() - } - const summary = Object.fromEntries(Object.entries(results).map(([key, samples]) => [key, - Object.fromEntries(Object.keys(samples[0]!).map(metric => [metric, Math.round(median(samples.map(s => s[metric]!)) * 10) / 10]))])) - console.log(JSON.stringify({ rb: 'median', turns: TURNS, steps: STEPS, summary }, null, 1)) -}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 43561279e8..cd716a0177 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -276,7 +276,6 @@ "tests/window-drag-inheritance.e2e.ts", "tests/complex-history.perf.ts", "tests/dingtalk-connection.e2e.ts", - "tests/rightbar-drag.perf.ts", "tests/pwsh-terminal.e2e.ts", "tests/wecom-connection.e2e.ts", "tests/tencent-meeting-connection.e2e.ts", diff --git a/benchmarks/rightbar-drag-browser/README.i18n.yaml b/benchmarks/rightbar-drag-browser/README.i18n.yaml new file mode 100644 index 0000000000..e9474cdd86 --- /dev/null +++ b/benchmarks/rightbar-drag-browser/README.i18n.yaml @@ -0,0 +1,13 @@ +# Bilingual-pair consistency record for README.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 benchmarks/rightbar-drag-browser/README.md +/right-sidebar-drag-browser-benchmark: + en: bbe1460bb1b69b8d + zh: 3a87f9a9dbc13035 +/right-sidebar-drag-browser-benchmark/run: + en: 0dce8b92617ea78b + zh: 22ce9ccc29acda36 +/right-sidebar-drag-browser-benchmark/measurements: + en: e503574efa0e3661 + zh: 0e5ae1bc2e804773 diff --git a/benchmarks/rightbar-drag-browser/README.md b/benchmarks/rightbar-drag-browser/README.md new file mode 100644 index 0000000000..7147194aa5 --- /dev/null +++ b/benchmarks/rightbar-drag-browser/README.md @@ -0,0 +1,17 @@ +# Right Sidebar drag browser benchmark + +English | [中文](README.zh.md) + +The required Chromium case in [rightbar-drag.bench.ts](rightbar-drag.bench.ts) drags the right Sidebar's resize handle beside a synthetic 120-turn Session whose older pages are all loaded, and counts the elements Chromium restyles during the drag. The shipped Web scaffold owns the isolated home, persistence, and loopback listener; Chromium loads the built Web artifacts. + +## Run + +`pnpm run test:bench` builds libraries, workers, and Web artifacts before running the serial benchmark inventory. With artifacts already built, select this directory through `pnpm exec vitest run --config vitest.bench.config.ts benchmarks/rightbar-drag-browser`. A shell that exports `NODE_USE_ENV_PROXY` unsets it first, as the [test proxy setup](../../scripts/test-proxy-environment.ts) requires. + +## Measurements + +Two fresh browser processes and scaffold worlds each drag the handle 40 trusted mouse steps of 8px outward and then back, in a 1680×1000 viewport where the transcript column stays below the 680px content-width floor; each drag asserts that column width, so the resolved content width does not change. A Chromium timeline trace covers each drag through two animation frames after release. The budget is the median, per direction, of the elements counted by every style recalculation divided by the page's element count, and it must not exceed 1: the drag restyles less than one page's worth of elements in total. The count is dimensionless and does not scale with CPU speed. + +Before the Conversation width axis kept its resize inputs on the body, every frame restyled the whole transcript: 200-turn local samples restyled 51 and 66 times the page's elements. Afterwards the same drags restyle 0.09 and 0.12 times, and the 120-turn workload 0.14 and 0.18 times; the count is independent of the history length. Frame gaps, style and layout milliseconds, and the final column width are reported as diagnostics only: layout still reflows the transcript at each new column width, which this case does not budget. + +The fixture contains mixed-language prose, lists, 12 code fences, 8 tables, reasoning, and 24 tool results. No model, tool, external network, recorded Session, or private Harness home supplies its content. The [decision record](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md) owns the workload choice, calibration, alternatives, and exclusions. diff --git a/benchmarks/rightbar-drag-browser/README.zh.md b/benchmarks/rightbar-drag-browser/README.zh.md new file mode 100644 index 0000000000..86e824543e --- /dev/null +++ b/benchmarks/rightbar-drag-browser/README.zh.md @@ -0,0 +1,17 @@ +# 右侧栏拖动浏览器基准 + +[English](README.md) | 中文 + +[rightbar-drag.bench.ts](rightbar-drag.bench.ts) 中的必需 Chromium 用例在一个已加载全部更早分页的 120 轮合成会话旁拖动右侧栏的宽度拖拽条,并统计拖动期间 Chromium 重新计算样式的元素数。随产品发布的 Web 测试脚手架提供隔离的 home、持久化和回环监听;Chromium 加载已构建的 Web 产物。 + +## 运行 + +`pnpm run test:bench` 先构建库、worker 和 Web 产物,再运行串行基准清单。产物已构建时,可通过 `pnpm exec vitest run --config vitest.bench.config.ts benchmarks/rightbar-drag-browser` 只运行本目录。导出了 `NODE_USE_ENV_PROXY` 的 shell 需要先取消它,这是[测试代理设置](../../scripts/test-proxy-environment.ts)的要求。 + +## 测量 + +两个全新的浏览器进程和脚手架环境各自在 1680×1000 视口中把拖拽条向外拖 40 个真实鼠标步(每步 8px),再拖回;该视口下正文列始终窄于 680px 的正文宽度下限,每次拖动都断言这一列宽,因此解析后的正文宽度不变。每次拖动都由 Chromium timeline trace 覆盖,直到松开后的两个动画帧。预算是每个方向上,所有样式重算统计的元素数之和除以页面元素数的中位数,不得超过 1:整次拖动重算的元素少于一个页面的量。该计数无量纲,不随 CPU 速度缩放。 + +在 Conversation 宽度轴把缩放输入留在主体元素上之前,每一帧都会重算整段记录:200 轮的本地样本重算了页面元素数的 51 倍和 66 倍。之后同样的拖动只重算 0.09 倍和 0.12 倍,120 轮负载为 0.14 倍和 0.18 倍;该计数与历史长度无关。帧间隔、样式与布局毫秒数和最终列宽只作为诊断输出:布局仍会按每个新列宽重排正文,本用例不为它设预算。 + +夹具包含中英混排的正文、列表、12 个代码块、8 个表格、推理内容和 24 个工具结果。内容不来自任何模型、工具、外部网络、录制会话或私有 Harness home。[决策记录](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md)负责说明负载选择、校准、备选方案和排除项。 diff --git a/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts new file mode 100644 index 0000000000..e49c6104a6 --- /dev/null +++ b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts @@ -0,0 +1,177 @@ +/** Required browser budget for transcript restyles while the right Sidebar is dragged beside a long history. */ +import { chromium, type Browser, type Page } from 'playwright' +import { expect, it } from 'vitest' +import { launchWebScaffold, seedSession, watchConsole, webSnapshotMode } from '../../apps/web/tests/scaffold.ts' +import { newEnglishPage } from '../../apps/web/tests/support.ts' +import { HISTORY_TURNS, SESSION_ID, syntheticHistory } from './synthetic-history.ts' + +const SAMPLES = 2 +/** Below the content width's 680px floor at this width, so the drag changes the column but not the resolved content width. */ +const VIEWPORT = { width: 1680, height: 1000 } +const CONTENT_WIDTH_FLOOR_PX = 680 +const STEPS = 40 +const STEP_PX = 8 +const STEP_GAP_MS = 8 +const TAIL = '[data-chat-flow-key*="turn-tail"]' +/** + * Elements restyled over one whole drag, as a multiple of the page's elements. A drag that restyles the + * transcript on every frame reaches about one multiple per frame; one that restyles only what the resize + * changes stays far below a single multiple. + */ +const RESTYLE_BUDGET = 1 + +interface TraceEvent { + name: string + ph: string + dur?: number + args?: { elementCount?: number } +} + +/** Measurements of one drag; only `restyleRatio` is budgeted. */ +interface DragSample { + restyleRatio: number + styledElements: number + styleMs: number + layoutMs: number + frameP95Ms: number + columnWidth: number +} + +function expectRestylesWithinBudget(ratio: number): void { + expect(ratio).toBeLessThanOrEqual(RESTYLE_BUDGET) +} + +function median(values: number[]): number { + return values.toSorted((a, b) => a - b)[Math.floor(values.length / 2)]! +} + +/** Style recalculation and layout totals from a Chromium timeline trace. */ +function summarizeTrace(buffer: Buffer): { styledElements: number; styleMs: number; layoutMs: number } { + const parsed = JSON.parse(buffer.toString('utf8')) as { traceEvents: TraceEvent[] } | TraceEvent[] + const events = (Array.isArray(parsed) ? parsed : parsed.traceEvents).filter(event => event.ph === 'X') + const styles = events.filter(event => event.name === 'UpdateLayoutTree') + const ms = (list: TraceEvent[]): number => list.reduce((total, event) => total + (event.dur ?? 0), 0) / 1000 + return { + styledElements: styles.reduce((total, event) => total + (event.args?.elementCount ?? 0), 0), + styleMs: ms(styles), + layoutMs: ms(events.filter(event => event.name === 'Layout')), + } +} + +async function loadAll(page: Page): Promise { + let count = await page.locator(TAIL).count() + while (count < HISTORY_TURNS) { + await page.getByRole('button', { name: 'Load earlier', exact: true }).click() + await page.waitForFunction( + ({ selector, previous }) => document.querySelectorAll(selector).length > previous, + { selector: TAIL, previous: count }, + ) + count = await page.locator(TAIL).count() + } + return count +} + +/** Frame timestamps the page collects during one drag. */ +type FrameProbe = Window & { benchmarkFrames?: { frames: number[]; running: boolean } } + +async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: number): Promise { + const box = await page.locator('[data-side="rightbar"]').boundingBox() + if (box === null) throw new Error('right Sidebar resize handle missing') + const x = box.x + box.width / 2 + const y = box.y + box.height / 2 + await page.evaluate(() => { + const probe = { frames: [] as number[], running: true } + ;(window as FrameProbe).benchmarkFrames = probe + const tick = (time: number): void => { + if (!probe.running) return + probe.frames.push(time) + requestAnimationFrame(tick) + } + requestAnimationFrame(tick) + }) + await browser.startTracing(page, { categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'] }) + await page.mouse.move(x, y) + await page.mouse.down() + for (let step = 1; step <= STEPS; step++) { + await page.mouse.move(x - direction * step * STEP_PX, y) + await page.waitForTimeout(STEP_GAP_MS) + } + await page.mouse.up() + // Two animation frames let the release reach style and layout before the trace closes. + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))) + const trace = summarizeTrace(await browser.stopTracing()) + const frames = await page.evaluate(() => { + const probe = (window as FrameProbe).benchmarkFrames! + probe.running = false + return probe.frames + }) + const gaps = frames.slice(1).map((time, index) => time - frames[index]!).sort((a, b) => a - b) + const columnWidth = await page.locator('[data-chat-flow]').first().evaluate(element => element.getBoundingClientRect().width) + return { + restyleRatio: trace.styledElements / elements, + styledElements: trace.styledElements, + styleMs: trace.styleMs, + layoutMs: trace.layoutMs, + frameP95Ms: gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * 0.95))] ?? 0, + columnWidth, + } +} + +it('accepts recorded restyle ratios and rejects a drag that restyles the transcript every frame', () => { + // 200-turn local samples: 1,479,947 and 1,909,568 elements restyled beside 28,895 before the width axis + // kept resize inputs on the Conversation body; 2,622 and 3,368 after. + for (const restyled of [1_479_947, 1_909_568]) expect(() => expectRestylesWithinBudget(restyled / 28_895)).toThrow() + for (const restyled of [2_622, 3_368]) expectRestylesWithinBudget(restyled / 28_895) + expectRestylesWithinBudget(RESTYLE_BUDGET) + expect(() => expectRestylesWithinBudget(RESTYLE_BUDGET + 0.01)).toThrow() +}) + +it(`restyles a bounded share of the page while the right Sidebar is dragged beside ${String(HISTORY_TURNS)} turns`, async () => { + if (webSnapshotMode() !== 'replay') throw new Error('browser benchmarks require keyless replay mode') + const samples: Record<'widen' | 'narrow', DragSample[]> = { widen: [], narrow: [] } + for (let sample = 0; sample < SAMPLES; sample++) { + const failures: unknown[] = [] + // The scaffold owns a private home, persistence root, and loopback listener for this sample. + const scaffold = await launchWebScaffold() + try { + await seedSession(scaffold, syntheticHistory(), SESSION_ID) + const browser = await chromium.launch({ headless: true }) + try { + const page = await newEnglishPage(browser, VIEWPORT.height) + await page.setViewportSize(VIEWPORT) + const consoleWatch = watchConsole(page) + page.setDefaultTimeout(60_000) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.getByRole('treeitem').first().click() + await page.getByRole('treeitem').nth(1).click() + await page.locator(TAIL).last().waitFor() + expect(await loadAll(page)).toBe(HISTORY_TURNS) + await page.getByRole('button', { name: 'Open right sidebar' }).first().click() + await page.locator('[data-side="rightbar"]').waitFor() + // The Sidebar opens with a track transition; the drag starts from its settled width. + await page.waitForFunction(() => document.querySelector('[data-rightbar-collapsed], [data-animating]') === null) + const elements = await page.evaluate(() => document.querySelectorAll('*').length) + for (const [direction, key] of [[1, 'widen'], [-1, 'narrow']] as const) { + const result = await drag(browser, page, direction, elements) + // The budget presumes an unchanged content width: the column stays below its floor. + expect(result.columnWidth).toBeLessThan(CONTENT_WIDTH_FLOOR_PX) + samples[key].push(result) + console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/sample', sample, direction: key, elements, ...result })) + } + expect(consoleWatch.pageErrors).toEqual([]) + } catch (error) { failures.push(error) } finally { + await browser.close().catch((error: unknown) => failures.push(error)) + } + } catch (error) { failures.push(error) } finally { + await scaffold.close().catch((error: unknown) => failures.push(error)) + } + if (failures.length > 0) throw new AggregateError(failures, 'browser benchmark failed') + } + const aggregate = { + widen: median(samples.widen.map(sample => sample.restyleRatio)), + narrow: median(samples.narrow.map(sample => sample.restyleRatio)), + } + console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/median', turns: HISTORY_TURNS, steps: STEPS, budget: RESTYLE_BUDGET, aggregate, samples })) + expectRestylesWithinBudget(aggregate.widen) + expectRestylesWithinBudget(aggregate.narrow) +}) diff --git a/benchmarks/rightbar-drag-browser/synthetic-history.ts b/benchmarks/rightbar-drag-browser/synthetic-history.ts new file mode 100644 index 0000000000..46295614c4 --- /dev/null +++ b/benchmarks/rightbar-drag-browser/synthetic-history.ts @@ -0,0 +1,67 @@ +/** Synthetic current-generation history whose rows wrap, for measuring transcript restyles during a resize. */ +import { brandString } from '@deepseek-ai/dsh-brand' +import { createAssistantMessage, createSystemMessage, createToolResultMessage, createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import { Session, type SessionId, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-title' + +/** Closed turns in the workload; every one is loaded before the drag. */ +export const HISTORY_TURNS = 120 +/** Identity private to each isolated scaffold. */ +export const SESSION_ID = 'benchmark-rightbar-drag' +const TITLE = 'SYNTHETIC_RIGHTBAR_DRAG' + +function prose(turn: number): string { + const paragraph = `Turn ${String(turn)} synthetic analysis: the renderer measures every row, wraps mixed text 混合中文段落用于换行测量, and keeps \`inline code\` beside **bold** words. ` + const parts = [paragraph.repeat(6), paragraph.repeat(4)] + parts.push(Array.from({ length: 6 }, (_, i) => `- item ${String(i)}: ${paragraph.slice(0, 120)}`).join('\n')) + if (turn % 10 === 0) { + parts.push('```ts\n' + Array.from({ length: 40 }, (_, i) => `const value${String(i)} = compute(${String(i)}, "${'x'.repeat(30)}")`).join('\n') + '\n```') + } + if (turn % 15 === 0) { + parts.push('| a | b | c |\n|---|---|---|\n' + Array.from({ length: 8 }, (_, i) => `| ${String(i)} | ${paragraph.slice(0, 60)} | ${String(i * 3)} |`).join('\n')) + } + return parts.join('\n\n') +} + +/** + * Create prose, lists, code, tables, reasoning, and tool output without reading user data. + * @returns Current Session JSONL accepted by the shared Web seeder. + */ +export function syntheticHistory(): string { + const session = Session.create(brandString(SESSION_ID)) + for (let turn = 1; turn <= HISTORY_TURNS; turn++) { + session.append('turn/start', { turn }) + session.append('step/start', { turn, step: 1 }) + if (turn === 1) session.append('system/message', { turn, step: 1, message: createSystemMessage('') }, { surfaceOp: 'append' }) + const user = session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: `Question ${String(turn)}: ` + '请检查宽度变化时的排版。 '.repeat(12) }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + if (turn === 1) session.append('session/title', { title: TITLE, messageSeqs: [user.seq], source: { kind: 'fallback' } }) + const tool = turn % 5 === 0 + const callId = brandString(`synthetic-call-${String(turn)}`) + const args = '{"path":"src/a.ts"}' + session.append('assistant/message', { + turn, step: 1, stream: [], + message: createAssistantMessage({ + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + content: [ + { type: 'reasoning', text: 'Compare the synthetic module and test. '.repeat(20) }, + { type: 'text', text: prose(turn) }, + ...tool ? [{ type: 'tool-call' as const, id: callId, name: 'synthetic_tool', arguments: args }] : [], + ], + }), + usage: { inputTokens: 4000, outputTokens: 800 }, + }, { surfaceOp: 'append' }) + if (tool) { + const call = session.append('tool/call', { turn, step: 1, callId, name: 'synthetic_tool', arguments: args }) + session.append('tool/result', { turn, step: 1, message: createToolResultMessage({ + callId, isError: false, content: [{ type: 'text', text: 'Synthetic tool output line.\n'.repeat(40) }], + }) }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + } + session.append('step/end', { turn, step: 1 }) + session.append('turn/end', { turn, reason: { kind: 'completed' } }) + } + const header = { type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 1700000000000, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0 } + return [JSON.stringify(header), ...session.snapshotEvents().map(event => JSON.stringify(event)), ''].join('\n') +} diff --git a/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts b/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts index bf67551d06..d5a246296d 100644 --- a/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts +++ b/packages/client/ui-conversation/tests/end-reserve-styles.client.spec.ts @@ -40,7 +40,7 @@ describe('Conversation body end reserve', () => { it('keeps the continuously varying lengths on the body and publishes resolved lengths to its descendants', () => { // Registered without inheritance: a resize that changes them every frame does not restyle the transcript. const registered = Object.fromEntries([...css.matchAll(/@property\s+(--[\w-]+)\s*\{([^{}]*)\}/g)] - .map(([, name, block]) => [name, (block ?? '').replace(/\s+/g, ' ').trim()])) + .map((match): [string, string] => [match[1] ?? '', (match[2] ?? '').replace(/\s+/g, ' ').trim()])) expect(registered).toEqual({ '--dsh-conversation-column-width': "syntax: ''; inherits: false; initial-value: 0px;", '--dsh-conversation-viewport-width': "syntax: ''; inherits: false; initial-value: 0px;", diff --git a/scripts/run-bench-suite.ts b/scripts/run-bench-suite.ts index bb6b789a8f..d684e2bdb1 100644 --- a/scripts/run-bench-suite.ts +++ b/scripts/run-bench-suite.ts @@ -9,6 +9,7 @@ import { runPnpmCommand } from './compile-referenced-projects.ts' */ export const SERIAL_BENCH_FILES = [ 'benchmarks/long-session-browser/long-session.bench.ts', + 'benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts', 'benchmarks/user-text/user-text.bench.client.ts', 'benchmarks/conversation-fold/conversation-fold.bench.client.ts', 'benchmarks/active-stream-reconnect/reconnect.bench.client.ts', diff --git a/tsconfig.host.json b/tsconfig.host.json index 74698483d1..a80e298cba 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -264,7 +264,6 @@ "apps/web/tests/window-drag-inheritance.e2e.ts", "apps/web/tests/complex-history.perf.ts", "apps/web/tests/dingtalk-connection.e2e.ts", - "apps/web/tests/rightbar-drag.perf.ts", "apps/web/tests/pwsh-terminal.e2e.ts", "apps/web/tests/wecom-connection.e2e.ts", "apps/web/tests/tencent-meeting-connection.e2e.ts", From 0341b3b7acc0bd26000f9a1cddb3535f69592653 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:25:35 +0800 Subject: [PATCH 29/54] perf(web): avoid synchronous layout reads during sidebar resizing Paint a fixed tab-title fade, refresh split capacity from actual box changes instead of width-only React commits, and consume the sizes already delivered to the conversation header and width axis. Guard script-nested layout counts in the right Sidebar drag benchmark. Refs #8856. --- ...-20-rightbar-drag-restyle-budget.i18n.yaml | 12 +-- ...2026-11-20-rightbar-drag-restyle-budget.md | 6 +- ...6-11-20-rightbar-drag-restyle-budget.zh.md | 6 +- apps/web/tests/sidebar-right.e2e.ts | 9 +- .../rightbar-drag-browser/README.i18n.yaml | 8 +- benchmarks/rightbar-drag-browser/README.md | 9 +- benchmarks/rightbar-drag-browser/README.zh.md | 9 +- .../rightbar-drag.bench.ts | 64 ++++++++++--- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../client/skeleton/ConversationSession.tsx | 16 +++- .../skeleton/ConversationWidthControls.tsx | 15 +-- .../tests/skeleton.client.spec.tsx | 34 ++++--- packages/client/ui-dockkit/README.i18n.yaml | 4 +- packages/client/ui-dockkit/README.md | 4 +- packages/client/ui-dockkit/README.zh.md | 4 +- .../ui-dockkit/src/components/DockSurface.tsx | 24 +++-- .../ui-dockkit/src/components/TabTitle.tsx | 35 +------ .../src/components/dockkit.module.css | 37 ++------ .../tests/components.client.spec.tsx | 54 ++--------- .../tests/split-room.client.spec.tsx | 93 +++++++++++++++++++ 22 files changed, 262 insertions(+), 189 deletions(-) create mode 100644 packages/client/ui-dockkit/tests/split-room.client.spec.tsx diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml index f2675a7ede..286489ea70 100644 --- a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml @@ -9,14 +9,14 @@ en: 693e8d1e4423b78f zh: c63608002d762c12 /agent-note-right-sidebar-drag-restyle-budget/decision: - en: 7b21bc1115988534 - zh: 4929a26024ec4237 + en: 29248a81f83693d9 + zh: 2ebede7805c3374f /agent-note-right-sidebar-drag-restyle-budget/calibration: - en: 5a234a9e422c36dc - zh: e48d9f7fb8445cd9 + en: 6d4c3e3eea2a0e0f + zh: 739fffd374da8b16 /agent-note-right-sidebar-drag-restyle-budget/alternatives-considered: en: 721cbfb3276fcb5b zh: 9557ee132f77f5a6 /agent-note-right-sidebar-drag-restyle-budget/consequences: - en: 6f1a2842da26a0df - zh: 9bd23e840e900a7e + en: 8efe7bc510ccabc8 + zh: 7c3bca6253797e40 diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md index 38371e44da..837605dc89 100644 --- a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md @@ -12,7 +12,7 @@ Dragging the right Sidebar beside a long transcript stalled for hundreds of mill The [right Sidebar drag benchmark](../../../../benchmarks/rightbar-drag-browser/README.md) joins the serial browser inventory. It loads a 120-turn synthetic Session completely, opens the right Sidebar, and drags its handle 40 trusted 8px mouse steps outward and back in a 1680×1000 viewport, in two fresh scaffold worlds and browsers. At that width the transcript column stays below the 680px content-width floor, and each drag asserts it, so the drag changes the column but not the resolved content width. -The budget is a dimensionless count: the elements reported by every `UpdateLayoutTree` trace event during one drag, divided by the page's element count, as a median per direction, at most 1. A drag that restyles the transcript on every frame reaches about one multiple per frame; the fixed drag stays far below one multiple in total. The count does not depend on CPU speed, so it takes neither the shared time scale nor the variance headroom, and no wall-clock endpoint is budgeted or passed to the scaling report. +The restyle budget is a dimensionless count: the elements reported by every `UpdateLayoutTree` trace event during one drag, divided by the page's element count, as a median per direction, at most 1. A drag that restyles the transcript on every frame reaches about one multiple per frame; the fixed drag stays far below one multiple in total. The count does not depend on CPU speed, so it takes neither the shared time scale nor the variance headroom, and no wall-clock endpoint is budgeted or passed to the scaling report. ## Calibration @@ -26,6 +26,8 @@ Local Linux x64 Chromium samples, 40-step drags: The restyled count after the change is identical across samples and history lengths, so the ratio leaves more than five times headroom at 120 turns, while the pre-change behavior exceeds the budget fifty-fold. The case's first test replays these recorded values as its negative control. +In the 120-turn Chromium trace, 40 `Layout` events per direction ran inside script before the geometry-read fix and none afterwards. A second budget allows 20 script-nested layouts per drag: it rejects repeated synchronous layout without requiring every callback to be layout-free or penalizing normal reflow after script returns. + ## Alternatives considered - Budget frame gaps or style milliseconds. Rejected for the gate: they need browser-runner calibration that does not exist yet, and they also include the transcript reflow at each new column width, which a resize legitimately pays. They remain diagnostics. @@ -34,4 +36,4 @@ The restyled count after the change is identical across samples and history leng ## Consequences -A regression that again publishes per-frame inputs to the transcript fails CI within one benchmark run, with no timing calibration. The case does not measure layout or paint cost, window resizing, the Conversation's own width handles, or a docked Session panel, whose end reserve can change the content inset during a drag. Chromium's element counting may change across browser versions; an upgrade that moves the counts re-records the calibration values above and in the negative control. +A regression that again publishes per-frame inputs to the transcript fails CI within one benchmark run, with no timing calibration. The case does not cap total layout or paint cost, nor does it cover window resizing, the Conversation's own width handles, or a docked Session panel, whose end reserve can change the content inset during a drag. Chromium's element counting may change across browser versions; an upgrade that moves the counts re-records the calibration values above and in the negative control. diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md index 4802d8accd..b478aa270b 100644 --- a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md @@ -12,7 +12,7 @@ Status: implemented [右侧栏拖动基准](../../../../benchmarks/rightbar-drag-browser/README.zh.md)加入串行浏览器清单。它完整加载一个 120 轮合成会话,打开右侧栏,在 1680×1000 视口中把拖拽条向外拖 40 个 8px 的真实鼠标步再拖回,在两个全新的脚手架环境和浏览器中各做一次。该宽度下正文列始终窄于 680px 的正文宽度下限,每次拖动都会断言这一点,因此拖动改变的是列宽,而不是解析后的正文宽度。 -预算是一个无量纲计数:一次拖动期间所有 `UpdateLayoutTree` trace 事件报告的元素数之和,除以页面元素数,按方向取中位数,最多为 1。每帧都重算整段记录的拖动大约每帧就达到一倍;修复后的拖动总计远低于一倍。该计数与 CPU 速度无关,因此既不使用共享的时间缩放系数,也不使用波动余量;没有为任何墙钟终点设预算,也不把它们传给缩放报告。 +样式重算的预算是一个无量纲计数:一次拖动期间所有 `UpdateLayoutTree` trace 事件报告的元素数之和,除以页面元素数,按方向取中位数,最多为 1。每帧都重算整段记录的拖动大约每帧就达到一倍;修复后的拖动总计远低于一倍。该计数与 CPU 速度无关,因此既不使用共享的时间缩放系数,也不使用波动余量;没有为任何墙钟终点设预算,也不把它们传给缩放报告。 ## 校准 @@ -26,6 +26,8 @@ Status: implemented 改动后重算的元素数在各样本和不同历史长度下完全相同,因此 120 轮时比值留有五倍以上余量,而改动前的行为超出预算五十倍。用例的第一个测试回放这些记录值作为负对照。 +在 120 轮负载的 Chromium 追踪中,几何读取修复前每个方向都有 40 次 `Layout` 发生在脚本执行期间,修复后均为 0 次。第二项预算允许每次拖动最多 20 次脚本内布局:它能拦住反复触发同步布局的回归,而不要求每个回调都没有布局,也不惩罚脚本返回后的正常重排。 + ## 备选方案 - 为帧间隔或样式毫秒数设预算。门禁不采用:它们需要尚不存在的浏览器 runner 校准,而且还包含按每个新列宽重排正文的成本,这是缩放本应付出的。它们保留为诊断输出。 @@ -34,4 +36,4 @@ Status: implemented ## 影响 -再次把逐帧变化的输入传给整段记录的回归会在一次基准运行内让 CI 失败,不需要任何计时校准。本用例不测量布局或绘制成本、窗口缩放、Conversation 自身的宽度拖拽条,也不测量停靠的 Session 面板,因为它的末端预留可能在拖动中改变正文内边距。Chromium 的元素计数方式可能随浏览器版本变化;改变计数的升级需要重新记录上面的校准值和负对照中的值。 +再次把逐帧变化的输入传给整段记录的回归会在一次基准运行内让 CI 失败,不需要任何计时校准。本用例不为布局或绘制的总成本设限,也不覆盖窗口缩放、Conversation 自身的宽度拖拽条,也不测量停靠的 Session 面板,因为它的末端预留可能在拖动中改变正文内边距。Chromium 的元素计数方式可能随浏览器版本变化;改变计数的升级需要重新记录上面的校准值和负对照中的值。 diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 2928f03842..29ae958c80 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -474,7 +474,10 @@ describe('web e2e: shipped right Sidebar', () => { } await expect.poll(async () => await tabTitles(column)).toEqual(['Start']) - await expectTitleAlignment(column.locator('[data-dockkit-tab-title]')) + const guideTitle = column.locator('[data-dockkit-tab-title]') + await expectTitleAlignment(guideTitle) + // Even this short, unclosable title has the ordinary edge mask, not the close-button mask. + expect(await guideTitle.evaluate(el => getComputedStyle(el).maskImage)).toContain('16px') await expect.poll(async () => await column.locator('[data-sidebar-right-guide-entry]').count()).toBe(2) expect(await column.locator('[data-sidebar-right-guide-entry="browser"]').count()).toBe(0) await column.locator('[data-sidebar-right-guide-entry="files"]').click() @@ -484,7 +487,9 @@ describe('web e2e: shipped right Sidebar', () => { const addTab = column.locator('[data-dockkit-add-tab]') const filesTab = column.locator('[data-dockkit-tab]').filter({ hasText: 'Files' }) await expect.poll(async () => await tabTitles(column)).toEqual(['Files']) - await expectTitleAlignment(filesTab.locator('[data-dockkit-tab-title]')) + const filesTitle = filesTab.locator('[data-dockkit-tab-title]') + await expectTitleAlignment(filesTitle) + expect(await filesTitle.evaluate(el => getComputedStyle(el).maskImage)).toContain('14px') await column.locator('[data-files-state="tree"]').waitFor({ state: 'visible' }) expect(await filesTab.locator('[data-dockkit-tab-close]').count()).toBe(1) await expect.poll(async () => await addTab.count()).toBe(1) diff --git a/benchmarks/rightbar-drag-browser/README.i18n.yaml b/benchmarks/rightbar-drag-browser/README.i18n.yaml index e9474cdd86..d52b01e438 100644 --- a/benchmarks/rightbar-drag-browser/README.i18n.yaml +++ b/benchmarks/rightbar-drag-browser/README.i18n.yaml @@ -3,11 +3,11 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write benchmarks/rightbar-drag-browser/README.md /right-sidebar-drag-browser-benchmark: - en: bbe1460bb1b69b8d - zh: 3a87f9a9dbc13035 + en: 0ec06c11a4e9680c + zh: 2aa104d63575bfcf /right-sidebar-drag-browser-benchmark/run: en: 0dce8b92617ea78b zh: 22ce9ccc29acda36 /right-sidebar-drag-browser-benchmark/measurements: - en: e503574efa0e3661 - zh: 0e5ae1bc2e804773 + en: 9c4cc8759b4f90e8 + zh: 027d11cb574e36e0 diff --git a/benchmarks/rightbar-drag-browser/README.md b/benchmarks/rightbar-drag-browser/README.md index 7147194aa5..8163214eaa 100644 --- a/benchmarks/rightbar-drag-browser/README.md +++ b/benchmarks/rightbar-drag-browser/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The required Chromium case in [rightbar-drag.bench.ts](rightbar-drag.bench.ts) drags the right Sidebar's resize handle beside a synthetic 120-turn Session whose older pages are all loaded, and counts the elements Chromium restyles during the drag. The shipped Web scaffold owns the isolated home, persistence, and loopback listener; Chromium loads the built Web artifacts. +The required Chromium case in [rightbar-drag.bench.ts](rightbar-drag.bench.ts) drags the right Sidebar's resize handle beside a synthetic 120-turn Session whose older pages are all loaded, and counts restyled elements and layouts during the drag. The shipped Web scaffold owns the isolated home, persistence, and loopback listener; Chromium loads the built Web artifacts. ## Run @@ -10,8 +10,11 @@ The required Chromium case in [rightbar-drag.bench.ts](rightbar-drag.bench.ts) d ## Measurements -Two fresh browser processes and scaffold worlds each drag the handle 40 trusted mouse steps of 8px outward and then back, in a 1680×1000 viewport where the transcript column stays below the 680px content-width floor; each drag asserts that column width, so the resolved content width does not change. A Chromium timeline trace covers each drag through two animation frames after release. The budget is the median, per direction, of the elements counted by every style recalculation divided by the page's element count, and it must not exceed 1: the drag restyles less than one page's worth of elements in total. The count is dimensionless and does not scale with CPU speed. +Two fresh browser processes and scaffold worlds each widen the Sidebar by 40 trusted mouse steps of 8px and drag it back in a 1680×1000 viewport. A Chromium timeline trace covers each drag through two animation frames after release. Column widths measured before and after the trace must stay below the 680px content-width floor: widening the Sidebar must narrow the transcript column, and narrowing it must widen the column. -Before the Conversation width axis kept its resize inputs on the body, every frame restyled the whole transcript: 200-turn local samples restyled 51 and 66 times the page's elements. Afterwards the same drags restyle 0.09 and 0.12 times, and the 120-turn workload 0.14 and 0.18 times; the count is independent of the history length. Frame gaps, style and layout milliseconds, and the final column width are reported as diagnostics only: layout still reflows the transcript at each new column width, which this case does not budget. +- **Restyles:** Sum the elements reported by each style recalculation and divide by the page's element count. The upper median per direction must not exceed 1 (one page's worth). +- **Layouts:** Each drag must produce at least one `Layout` event. `layoutCount` includes them all; `scriptNestedLayoutCount` counts each layout fully enclosed by a script event on the same process and thread, including animation frame callbacks. This subset must not exceed 20 per drag (half the mouse steps). Nesting is a proxy for synchronous layout, not evidence that every nested layout is unnecessary; browser reflow outside script does not consume the budget. + +Frame gaps and style and layout durations are diagnostics only. Neither budget scales with CPU speed. The fixture contains mixed-language prose, lists, 12 code fences, 8 tables, reasoning, and 24 tool results. No model, tool, external network, recorded Session, or private Harness home supplies its content. The [decision record](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md) owns the workload choice, calibration, alternatives, and exclusions. diff --git a/benchmarks/rightbar-drag-browser/README.zh.md b/benchmarks/rightbar-drag-browser/README.zh.md index 86e824543e..3058f824e1 100644 --- a/benchmarks/rightbar-drag-browser/README.zh.md +++ b/benchmarks/rightbar-drag-browser/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -[rightbar-drag.bench.ts](rightbar-drag.bench.ts) 中的必需 Chromium 用例在一个已加载全部更早分页的 120 轮合成会话旁拖动右侧栏的宽度拖拽条,并统计拖动期间 Chromium 重新计算样式的元素数。随产品发布的 Web 测试脚手架提供隔离的 home、持久化和回环监听;Chromium 加载已构建的 Web 产物。 +[rightbar-drag.bench.ts](rightbar-drag.bench.ts) 中的必需 Chromium 用例在一个已加载全部更早分页的 120 轮合成会话旁拖动右侧栏的宽度拖拽条,并统计拖动期间重算样式的元素数和布局次数。随产品发布的 Web 测试脚手架提供隔离的 home、持久化和回环监听;Chromium 加载已构建的 Web 产物。 ## 运行 @@ -10,8 +10,11 @@ ## 测量 -两个全新的浏览器进程和脚手架环境各自在 1680×1000 视口中把拖拽条向外拖 40 个真实鼠标步(每步 8px),再拖回;该视口下正文列始终窄于 680px 的正文宽度下限,每次拖动都断言这一列宽,因此解析后的正文宽度不变。每次拖动都由 Chromium timeline trace 覆盖,直到松开后的两个动画帧。预算是每个方向上,所有样式重算统计的元素数之和除以页面元素数的中位数,不得超过 1:整次拖动重算的元素少于一个页面的量。该计数无量纲,不随 CPU 速度缩放。 +两个全新的浏览器进程和脚手架环境各自在 1680×1000 视口中用 40 个真实鼠标步(每步 8px)加宽右侧栏,再拖回。Chromium 的时间线追踪覆盖每次拖动,直到松开后的两个动画帧。追踪前后测得的正文列宽都必须低于 680px 的正文宽度下限:加宽侧栏必须使正文列变窄,缩窄侧栏必须使正文列变宽。 -在 Conversation 宽度轴把缩放输入留在主体元素上之前,每一帧都会重算整段记录:200 轮的本地样本重算了页面元素数的 51 倍和 66 倍。之后同样的拖动只重算 0.09 倍和 0.12 倍,120 轮负载为 0.14 倍和 0.18 倍;该计数与历史长度无关。帧间隔、样式与布局毫秒数和最终列宽只作为诊断输出:布局仍会按每个新列宽重排正文,本用例不为它设预算。 +- **样式重算:** 各次样式重算报告的元素数之和除以页面元素数。每个方向的上中位数不得超过 1(即一整个页面的元素数)。 +- **布局:** 每次拖动必须产生至少一个 `Layout` 事件。`layoutCount` 统计所有布局;`scriptNestedLayoutCount` 只统计起止时间均落在同一进程、同一线程的脚本事件内的布局,每次布局只计一次,动画帧回调也算脚本事件。每次拖动此项不得超过 20(鼠标步数的一半)。嵌套关系是判断同步布局的间接指标,并不说明每次嵌套布局都多余;脚本以外的浏览器重排不占用该预算。 + +帧间隔、样式重算耗时和布局耗时仅作诊断。两项预算都不随 CPU 速度缩放。 夹具包含中英混排的正文、列表、12 个代码块、8 个表格、推理内容和 24 个工具结果。内容不来自任何模型、工具、外部网络、录制会话或私有 Harness home。[决策记录](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md)负责说明负载选择、校准、备选方案和排除项。 diff --git a/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts index e49c6104a6..7e332650e8 100644 --- a/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts +++ b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts @@ -1,4 +1,4 @@ -/** Required browser budget for transcript restyles while the right Sidebar is dragged beside a long history. */ +/** Required browser budgets for restyles and script-nested layout while dragging the right Sidebar beside a long history. */ import { chromium, type Browser, type Page } from 'playwright' import { expect, it } from 'vitest' import { launchWebScaffold, seedSession, watchConsole, webSnapshotMode } from '../../apps/web/tests/scaffold.ts' @@ -19,21 +19,32 @@ const TAIL = '[data-chat-flow-key*="turn-tail"]' * changes stays far below a single multiple. */ const RESTYLE_BUDGET = 1 +/** The regression put one layout inside script per step; occasional script-nested layouts need not be waste. */ +const SCRIPT_NESTED_LAYOUT_BUDGET = STEPS / 2 +const SCRIPT_EVENTS = new Set(['FunctionCall', 'EventDispatch', 'FireAnimationFrame', 'TimerFire', 'RunMicrotasks', 'v8.callFunction']) interface TraceEvent { name: string ph: string + pid: number + tid: number + ts: number dur?: number args?: { elementCount?: number } } -/** Measurements of one drag; only `restyleRatio` is budgeted. */ -interface DragSample { - restyleRatio: number +interface TraceSummary { styledElements: number styleMs: number layoutMs: number + layoutCount: number + scriptNestedLayoutCount: number +} + +interface DragSample extends TraceSummary { + restyleRatio: number frameP95Ms: number + columnWidthBefore: number columnWidth: number } @@ -46,15 +57,23 @@ function median(values: number[]): number { } /** Style recalculation and layout totals from a Chromium timeline trace. */ -function summarizeTrace(buffer: Buffer): { styledElements: number; styleMs: number; layoutMs: number } { +function summarizeTrace(buffer: Buffer): TraceSummary { const parsed = JSON.parse(buffer.toString('utf8')) as { traceEvents: TraceEvent[] } | TraceEvent[] const events = (Array.isArray(parsed) ? parsed : parsed.traceEvents).filter(event => event.ph === 'X') const styles = events.filter(event => event.name === 'UpdateLayoutTree') + const layouts = events.filter(event => event.name === 'Layout') + const scripts = events.filter(event => SCRIPT_EVENTS.has(event.name)) + expect(scripts.length, 'drag trace must contain script events').toBeGreaterThan(0) + const end = (event: TraceEvent): number => event.ts + (event.dur ?? 0) const ms = (list: TraceEvent[]): number => list.reduce((total, event) => total + (event.dur ?? 0), 0) / 1000 return { styledElements: styles.reduce((total, event) => total + (event.args?.elementCount ?? 0), 0), styleMs: ms(styles), - layoutMs: ms(events.filter(event => event.name === 'Layout')), + layoutMs: ms(layouts), + layoutCount: layouts.length, + scriptNestedLayoutCount: layouts.filter(layout => scripts.some(script => + script.pid === layout.pid && script.tid === layout.tid && script.ts <= layout.ts && end(layout) <= end(script), + )).length, } } @@ -79,6 +98,8 @@ async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: n if (box === null) throw new Error('right Sidebar resize handle missing') const x = box.x + box.width / 2 const y = box.y + box.height / 2 + const readColumnWidth = (): Promise => page.locator('[data-chat-flow]').first().evaluate(element => element.getBoundingClientRect().width) + const columnWidthBefore = await readColumnWidth() await page.evaluate(() => { const probe = { frames: [] as number[], running: true } ;(window as FrameProbe).benchmarkFrames = probe @@ -106,14 +127,12 @@ async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: n return probe.frames }) const gaps = frames.slice(1).map((time, index) => time - frames[index]!).sort((a, b) => a - b) - const columnWidth = await page.locator('[data-chat-flow]').first().evaluate(element => element.getBoundingClientRect().width) return { + ...trace, restyleRatio: trace.styledElements / elements, - styledElements: trace.styledElements, - styleMs: trace.styleMs, - layoutMs: trace.layoutMs, frameP95Ms: gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * 0.95))] ?? 0, - columnWidth, + columnWidthBefore, + columnWidth: await readColumnWidth(), } } @@ -126,7 +145,18 @@ it('accepts recorded restyle ratios and rejects a drag that restyles the transcr expect(() => expectRestylesWithinBudget(RESTYLE_BUDGET + 0.01)).toThrow() }) -it(`restyles a bounded share of the page while the right Sidebar is dragged beside ${String(HISTORY_TURNS)} turns`, async () => { +it('counts each layout enclosed by script on the same thread once, including frame callbacks', () => { + const event = (name: string, ts: number, dur: number, pid = 1, tid = 1): TraceEvent => ({ name, ph: 'X', ts, dur, pid, tid }) + const events = [ + event('FireAnimationFrame', 10, 10), event('FunctionCall', 11, 5), + event('Layout', 10, 10), event('Layout', 12, 1), + event('Layout', 19, 2), event('Layout', 12, 1, 2, 1), event('Layout', 12, 1, 1, 2), + event('PrePaint', 30, 5), event('Layout', 31, 1), + ] + expect(summarizeTrace(Buffer.from(JSON.stringify(events)))).toMatchObject({ layoutCount: 6, scriptNestedLayoutCount: 2 }) +}) + +it(`bounds restyles and script-nested layouts while the right Sidebar is dragged beside ${String(HISTORY_TURNS)} turns`, async () => { if (webSnapshotMode() !== 'replay') throw new Error('browser benchmarks require keyless replay mode') const samples: Record<'widen' | 'narrow', DragSample[]> = { widen: [], narrow: [] } for (let sample = 0; sample < SAMPLES; sample++) { @@ -153,10 +183,14 @@ it(`restyles a bounded share of the page while the right Sidebar is dragged besi const elements = await page.evaluate(() => document.querySelectorAll('*').length) for (const [direction, key] of [[1, 'widen'], [-1, 'narrow']] as const) { const result = await drag(browser, page, direction, elements) - // The budget presumes an unchanged content width: the column stays below its floor. - expect(result.columnWidth).toBeLessThan(CONTENT_WIDTH_FLOOR_PX) - samples[key].push(result) console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/sample', sample, direction: key, elements, ...result })) + // The transcript column moves opposite the Sidebar width while the resolved content width stays at its floor. + expect(Math.max(result.columnWidthBefore, result.columnWidth)).toBeLessThan(CONTENT_WIDTH_FLOOR_PX) + if (key === 'widen') expect(result.columnWidth).toBeLessThan(result.columnWidthBefore) + else expect(result.columnWidth).toBeGreaterThan(result.columnWidthBefore) + expect(result.layoutCount).toBeGreaterThan(0) + expect(result.scriptNestedLayoutCount).toBeLessThanOrEqual(SCRIPT_NESTED_LAYOUT_BUDGET) + samples[key].push(result) } expect(consoleWatch.pageErrors).toEqual([]) } catch (error) { failures.push(error) } finally { diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index b98644469b..43af0180f8 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 756022173490c1ca - zh: 2d4d493cbb535f42 + en: a26620af27311633 + zh: 875ec18d3396feee /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry: en: 876be274c65b56d9 zh: c3adbf5a16e0e38e diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 81102ed21b..fb110a8223 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -94,7 +94,7 @@ The context-occupancy button shows a ring and percentage below the input card, a With Coding Tools off, the shell hides only Trajectory; other plugin-contributed Views remain available. The View tab bar is hidden when fewer than two Views are available. Turning Coding Tools off while Trajectory is active returns to Chat; stored View preferences and recorded Session data remain intact. Turning it on makes Trajectory available again. View owners receive the available roster so their navigation actions can follow the same visibility. -While the root-scoped `conversation.session.header.views.actions` list has registrations, a **More conversation views** button with a tooltip follows the View tabs in the tab row. It opens a menu whose rows are that list's registrations. Each receives `entries` (Views outside the header in registration order with `id`, `label`, `pinned`, and `active`; Chat is never listed), `onOpen(id)`, which selects the View in this Session, `onPinnedChange(id, pinned)`, and `onDismiss()`, which closes the menu. The header keeps an in-memory list of unpinned View ids shared by every Session; the tab bar omits unpinned Views and places registered Chat first so it always remains outside More. Plugin reload resets pin choices, and legacy localStorage values are ignored. The tab bar's visibility counts available Views, not pinned ones, so the bar and More stay while every other View is unpinned. Unpinning the active View hides its tab immediately without changing the selected content. More lists only Views outside the header and identifies the current View through `active`. The header reads its available row width, reserves 48px for More and padding, and estimates 120px per tab. Remaining Views keep registration order in More. A single ResizeObserver watches the tab row so window resizing and sidebar expansion update the split; active selection does not change the order. The observer disconnects when the row is removed. If ResizeObserver is unavailable, the initial width calculation still applies without subsequent observation. The More button highlights when the active View is folded. Each tab label estimates its text width from the glyphs; its full-name tooltip appears only when that estimate exceeds the 88px cell. At least one preferred tab remains outside. Unregistered View ids remain in the in-memory pin list until plugin reload. +While the root-scoped `conversation.session.header.views.actions` list has registrations, a **More conversation views** button with a tooltip follows the View tabs in the tab row. It opens a menu whose rows are that list's registrations. Each receives `entries` (Views outside the header in registration order with `id`, `label`, `pinned`, and `active`; Chat is never listed), `onOpen(id)`, which selects the View in this Session, `onPinnedChange(id, pinned)`, and `onDismiss()`, which closes the menu. The header keeps an in-memory list of unpinned View ids shared by every Session; the tab bar omits unpinned Views and places registered Chat first so it always remains outside More. Plugin reload resets pin choices, and legacy localStorage values are ignored. The tab bar's visibility counts available Views, not pinned ones, so the bar and More stay while every other View is unpinned. Unpinning the active View hides its tab immediately without changing the selected content. More lists only Views outside the header and identifies the current View through `active`. The header reads its available row width, reserves 48px for More and padding, and estimates 120px per tab. Remaining Views keep registration order in More. After the initial measurement, the header uses the tab row width delivered by ResizeObserver when the window or sidebar resizes; active selection does not change the order. The observer disconnects when the row is removed. If ResizeObserver is unavailable, the initial width calculation still applies without subsequent observation. The More button highlights when the active View is folded. Each tab label estimates its text width from the glyphs; its full-name tooltip appears only when that estimate exceeds the 88px cell. At least one preferred tab remains outside. Unregistered View ids remain in the in-memory pin list until plugin reload. The composer registers the File command action and owns its label, availability, and native file-dialog callback. Menu availability and invocation both consult the mounted composer's current attachment-intake policy. Unmounting or locking the composer disables that action; disposing the plugin removes its registration. The callback binding stays inside the input module. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 12bc1b8efa..3c0a13038e 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -94,7 +94,7 @@ composer 在挂载、切换 Session 和解除锁定时使用共享的[文字输 关闭代码工作工具时,外壳仅隐藏 Trajectory;其他插件贡献的 View 仍然可用。可用 View 少于两个时隐藏 View 标签栏。在 Trajectory 激活时关闭代码工作工具会返回 Chat;已保存的 View 偏好和 Session 记录保持不变。开启后,Trajectory 恢复可用。View 所有者接收可用列表,使导航操作跟随相同的可见性。 -root 作用域的 `conversation.session.header.views.actions` list 有注册项时,标签行中的 View 标签之后显示带提示框的**更多会话视图**按钮。它打开的菜单以该 list 的注册项为菜单行。每个注册项接收 `entries`(按注册顺序的头部之外的 View,含 `id`、`label`、`pinned` 与 `active`;不含 Chat)、在本 Session 选择 View 的 `onOpen(id)`、`onPinnedChange(id, pinned)`,以及关闭菜单的 `onDismiss()`。头部在内存中保存所有 Session 共用的已收起 View id 列表;标签栏不显示已收起的 View,并将已注册的 Chat 放在首位,确保它始终留在更多菜单外。插件重新加载时 Pin 选择重置,不读取旧 localStorage 值。标签栏是否显示按可用 View 计算,不按已固定的 View 计算,因此其他 View 全部收起时,标签栏和“更多”仍然显示。收起当前激活的 View 会立即隐藏其标签,但不会切走其内容。更多菜单仅包含头部之外的 View,通过 `active` 标识当前 View。头部读取当前行可用宽度,为更多按钮与内边距预留 48px,每个标签估算 120px,其余 View 按注册顺序进入更多。单个 ResizeObserver 观察标签行,使窗口缩放和侧栏展开能够更新分组;当前选中项变化不改变顺序。标签行移除时断开观察。如果环境没有 ResizeObserver,仍按初始宽度计算,但不继续观察。当前 View 收起时,更多按钮高亮。每个标签按字符宽度估算文本宽度;只有估算结果超过 88px 单元格时,才通过提示框提供全名。至少保留一个优先展示的外部标签。未注册 View 的 id 保留在内存 Pin 列表中,直到插件重新加载。 +root 作用域的 `conversation.session.header.views.actions` list 有注册项时,标签行中的 View 标签之后显示带提示框的**更多会话视图**按钮。它打开的菜单以该 list 的注册项为菜单行。每个注册项接收 `entries`(按注册顺序的头部之外的 View,含 `id`、`label`、`pinned` 与 `active`;不含 Chat)、在本 Session 选择 View 的 `onOpen(id)`、`onPinnedChange(id, pinned)`,以及关闭菜单的 `onDismiss()`。头部在内存中保存所有 Session 共用的已收起 View id 列表;标签栏不显示已收起的 View,并将已注册的 Chat 放在首位,确保它始终留在更多菜单外。插件重新加载时 Pin 选择重置,不读取旧 localStorage 值。标签栏是否显示按可用 View 计算,不按已固定的 View 计算,因此其他 View 全部收起时,标签栏和“更多”仍然显示。收起当前激活的 View 会立即隐藏其标签,但不会切走其内容。更多菜单仅包含头部之外的 View,通过 `active` 标识当前 View。头部读取当前行可用宽度,为更多按钮与内边距预留 48px,每个标签估算 120px,其余 View 按注册顺序进入更多。初次测量后,窗口或侧栏缩放时,头部使用 ResizeObserver 送达的标签行宽度更新分组;当前选中项变化不改变顺序。标签行移除时断开观察。如果环境没有 ResizeObserver,仍按初始宽度计算,但不继续观察。当前 View 收起时,更多按钮高亮。每个标签按字符宽度估算文本宽度;只有估算结果超过 88px 单元格时,才通过提示框提供全名。至少保留一个优先展示的外部标签。未注册 View 的 id 保留在内存 Pin 列表中,直到插件重新加载。 输入框注册「文件」命令动作,负责其标题、可用性和原生文件选择器回调。菜单可用性与实际调用都读取已挂载输入框当前的附件接收策略。输入框卸载或锁定后该动作不可用,插件 dispose(资源释放)时移除注册。回调绑定留在输入模块内部。 diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx index 83b3af7029..82ef114f86 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx @@ -123,13 +123,19 @@ export function ConversationSessionHeader({ useLayoutEffect(() => { const row = tabRow.current if (row === null || !hasEntryActions) return - const updateLimit = (): void => { - setVisibleViewLimit(Math.max(1, Math.floor((row.clientWidth - 48) / 120))) + const updateLimit = (width: number): void => { + setVisibleViewLimit(Math.max(1, Math.floor((width - 48) / 120))) } - updateLimit() + updateLimit(row.clientWidth) if (typeof ResizeObserver === 'undefined') return - const observer = new ResizeObserver(updateLimit) - observer.observe(row) + // The row has padding but no border or scrollbar. Its delivered border-box width, + // rounded like clientWidth, preserves the tab thresholds without forcing layout again. + const observer = new ResizeObserver((entries) => { + for (const entry of entries) { + for (const size of entry.borderBoxSize) updateLimit(Math.round(size.inlineSize)) + } + }) + observer.observe(row, { box: 'border-box' }) return () => { observer.disconnect() } }, [showTabs, hasEntryActions]) const { visibleTabs, moreTabs } = useMemo(() => { diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx index de9fe79a24..577b31830c 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationWidthControls.tsx @@ -158,9 +158,8 @@ function WidthHandle(props: { * @returns two active-phase width handles, or no controls outside the active phase. */ export function ConversationWidthControls({ container, phase }: ConversationWidthControlsProps) { - const publishWidths = useCallback((container: HTMLDivElement): void => { + const publishWidths = useCallback((container: HTMLDivElement, column: number): void => { // The axis registers these inputs without inheritance, so they belong on the body that derives from them. - const column = container.offsetWidth container.style.setProperty('--dsh-conversation-column-width', `${column}px`) const preference = readWidthPreference() if (preference === null) container.style.removeProperty('--dsh-chat-user-width') @@ -169,9 +168,13 @@ export function ConversationWidthControls({ container, phase }: ConversationWidt useLayoutEffect(() => { if (container === null) return - const observer = new ResizeObserver(() => { publishWidths(container) }) - observer.observe(container) - publishWidths(container) + const observer = new ResizeObserver((entries) => { + for (const entry of entries) { + for (const size of entry.borderBoxSize) publishWidths(container, Math.round(size.inlineSize)) + } + }) + observer.observe(container, { box: 'border-box' }) + publishWidths(container, container.offsetWidth) return () => { observer.disconnect() } }, [container, publishWidths]) @@ -188,7 +191,7 @@ export function ConversationWidthControls({ container, phase }: ConversationWidt localStorage.setItem(WIDTH_PREF_KEY, `${resolveContentWidth(container.offsetWidth, width)}`) }, [container]) const onEnd = useCallback((): void => { - if (container !== null) publishWidths(container) + if (container !== null) publishWidths(container, container.offsetWidth) }, [container, publishWidths]) if (container === null || phase !== 'active') return null diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 15c9a9aea0..245a1c23ab 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -79,9 +79,14 @@ class ResizeObserverStub { } /** Fires every recorded observer whose target list includes the element. */ -function fireResize(el: Element): void { +function fireResize(el: Element, inlineSize = 0): void { + const size = [{ inlineSize, blockSize: 0 }] + const change: ResizeObserverEntry = { + target: el, contentRect: new DOMRectReadOnly(0, 0, inlineSize, 0), + borderBoxSize: size, contentBoxSize: size, devicePixelContentBoxSize: size, + } for (const entry of resizeObservers) { - if (entry.targets.includes(el)) entry.callback([], undefined as never) + if (entry.targets.includes(el)) entry.callback([change], undefined as never) } } @@ -836,22 +841,22 @@ describe('ConversationRoot resident composer', () => { }) it('folds and restores Views on container resize without changing selection, and disconnects on unmount', () => { - let width = 1000 - vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(() => width) + const liveWidth = vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(1000) const viewTabs = ['chat', 'trajectory', 'timeline', 'inspector', 'notes'].map(id => ({ id, label: id })) const b = mount(sessionSnapshotOf(), undefined, undefined, { viewTabs, entryActions: true }) const row = b.view.getByRole('tablist').parentElement! const external = () => within(b.view.getByRole('tablist')).getAllByRole('tab').map(tab => tab.textContent) expect(external()).toEqual(viewTabs.map(tab => tab.label)) act(() => { b.store.actions.setView('notes') }) - width = 300 - act(() => { fireResize(row) }) + liveWidth.mockClear() + // 287.6px rounds to 288px (two Views); do not re-read a changed DOM during delivery. + act(() => { fireResize(row, 287.6) }) expect(external()).toEqual(['chat', 'trajectory']) fireEvent.click(b.view.getByRole('button', { name: zh['session.moreViews'] })) expect(b.actionsOwner().entries.map(entry => entry.id)).toEqual(['timeline', 'inspector', 'notes']) expect(b.actionsOwner().entries.find(entry => entry.id === 'notes')?.active).toBe(true) - width = 1000 - act(() => { fireResize(row) }) + act(() => { fireResize(row, 1000) }) + expect(liveWidth.mock.contexts).not.toContain(row) expect(external()).toEqual(viewTabs.map(tab => tab.label)) expect(b.view.getByRole('tab', { name: 'notes' }).getAttribute('aria-selected')).toBe('true') expect(b.actionsOwner().entries).toEqual([]) @@ -953,11 +958,10 @@ describe('ConversationRoot resident composer', () => { it('publishes the column width as a px variable on the body for the shared width axis', () => { const b = mount(sessionSnapshotOf()) const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement - // jsdom offsetWidth is 0 until faked: the observer publishes whatever the - // layout reports, and the CSS clamp() floors the axis at 680px either way. - Object.defineProperty(content, 'offsetWidth', { value: 1200, configurable: true }) - act(() => { fireResize(content) }) + const readWidth = vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get') + act(() => { fireResize(content, 1199.75) }) expect(content.style.getPropertyValue('--dsh-conversation-column-width')).toBe('1200px') + expect(readWidth.mock.contexts).not.toContain(content) // No dragged preference: the user-width override stays absent so the // adaptive clamp term applies. expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('') @@ -967,7 +971,7 @@ describe('ConversationRoot resident composer', () => { const b = mount(sessionSnapshotOf()) const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement Object.defineProperty(content, 'offsetWidth', { value: 1600, configurable: true }) - act(() => { fireResize(content) }) + act(() => { fireResize(content, 1600) }) const handle = b.view.container.querySelector('[data-width-handle="right"]') as HTMLElement expect(handle).not.toBeNull() // jsdom lacks pointer capture: emulate per-element so hasPointerCapture @@ -994,7 +998,7 @@ describe('ConversationRoot resident composer', () => { // Window shrinks: the displayed width re-clamps (900 − 176 = 724) but the // preference stays. Object.defineProperty(content, 'offsetWidth', { value: 900, configurable: true }) - act(() => { fireResize(content) }) + act(() => { fireResize(content, 900) }) expect(content.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px') expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930') // A press without travel (a real double-click delivers two such @@ -1020,7 +1024,7 @@ describe('ConversationRoot resident composer', () => { const content = b.view.container.querySelector('[data-conversation-content]') as HTMLElement const scrollport = content.querySelector('[data-conversation-scroll]') as HTMLElement Object.defineProperty(content, 'offsetWidth', { value: 1600, configurable: true }) - act(() => { fireResize(content) }) + act(() => { fireResize(content, 1600) }) const handle = b.view.container.querySelector('[data-width-handle="left"]') as HTMLElement const names = ['setPointerCapture', 'releasePointerCapture', 'hasPointerCapture'] as const const originals = names.map(name => diff --git a/packages/client/ui-dockkit/README.i18n.yaml b/packages/client/ui-dockkit/README.i18n.yaml index 73075677d1..ba8a0d242d 100644 --- a/packages/client/ui-dockkit/README.i18n.yaml +++ b/packages/client/ui-dockkit/README.i18n.yaml @@ -21,8 +21,8 @@ en: 5e025290e8881fa8 zh: 2bc9c3ff83914241 /deepseek-ai-dsh-client-ui-dockkit/interaction-rules-worth-keeping: - en: cf2d00ce2b7d5719 - zh: 5510420f8872e23a + en: a34ab619b8c1d740 + zh: b645bb7600e640db /deepseek-ai-dsh-client-ui-dockkit/build-shape: en: 69f87827f149270f zh: 65e41db2b2400cd5 diff --git a/packages/client/ui-dockkit/README.md b/packages/client/ui-dockkit/README.md index a8d99c1568..e3f725493f 100644 --- a/packages/client/ui-dockkit/README.md +++ b/packages/client/ui-dockkit/README.md @@ -80,9 +80,9 @@ The split control accepts localized tooltip text, separate effective keys throug These are not stylistic; each one fixes a defect found in a real browser. - **Capture the pointer** when a gesture starts. Without it any scroll container the pointer crosses can claim the gesture, which the browser reports as a cancelled pointer and an abandoned drag. Capture is hardening — the window listeners carry the gesture either way, so an environment without the API still works. -- **The chips give way; the strip's end controls never do.** The chip box is the strip's one shrinking part (`flex: 0 1 auto; min-width: 0; overflow-x: auto`): chips shrink down to an 80px floor and then scroll on the wheel with no scrollbar drawn, and the box fades its chips out over 24px at each side that hides some (`data-dockkit-strip-scroll`, written from the box's scroll reading after each commit, scroll, and resize). Whenever the active tab or the row of chips changes, the box scrolls so the active chip stands clear of the fade band; a chip already in view moves nothing. Where `DockLayout` draws a new strip for each newly selected tab, that strip first jumps to the offset the pane's previous strip recorded, so only the remaining distance animates; a strip with no recorded offset jumps straight to the active chip instead of scrolling from the row's start. A chip's title is never ellipsized: `TabTitle` reads its text against its box and sets `data-dockkit-tab-clipped` while the text is wider, which fades the text out over its last 16px. A chip's close control shows while the chip is active, hovered, or holds focus, over the title's last 14px, which fade under it, so the chip is the same width either way. The two slots beside the active chip draw no hairline, so the filled capsule stands between bare chips. The add, split, and chrome controls are `flex: none`, so they keep their width and place in any pane at least as wide as they are (about 130px with the chrome, 72px without). The surface's `min-width: 0` and the pane's `overflow: hidden` stop a body's longest unwrapped line from widening the pane past its box, which is what carried the controls and the body's scrollbar off-screen. +- **The chips give way; the strip's end controls never do.** The chip box is the strip's one shrinking part (`flex: 0 1 auto; min-width: 0; overflow-x: auto`): chips shrink down to an 80px floor and then scroll on the wheel with no scrollbar drawn, and the box fades its chips out over 24px at each side that hides some (`data-dockkit-strip-scroll`, written from the box's scroll reading after each commit, scroll, and resize). Whenever the active tab or the row of chips changes, the box scrolls so the active chip stands clear of the fade band; a chip already in view moves nothing. Where `DockLayout` draws a new strip for each newly selected tab, that strip first jumps to the offset the pane's previous strip recorded, so only the remaining distance animates; a strip with no recorded offset jumps straight to the active chip instead of scrolling from the row's start. A chip's title is never ellipsized: the last 16px of the title box always fade, including when a title just fits. The fade needs no width measurement. A chip's close control shows while the chip is active, hovered, or holds focus, over the title's last 14px, which fade under it, so the chip is the same width either way. The two slots beside the active chip draw no hairline, so the filled capsule stands between bare chips. The add, split, and chrome controls are `flex: none`, so they keep their width and place in any pane at least as wide as they are (about 130px with the chrome, 72px without). The surface's `min-width: 0` and the pane's `overflow: hidden` stop a body's longest unwrapped line from widening the pane past its box, which is what carried the controls and the body's scrollbar off-screen. - **The chip box scrolls, but never claims a gesture.** A horizontal scroller would take press-and-move for itself and cancel the pointer; the box, the chips, and the strip set `touch-action: none` and the gesture captures the pointer, so a press-and-move on a chip is a drag and only the wheel scrolls the box. -- **A split needs room for two working halves.** A pane splits into equal halves, so each half must hold what cannot shrink: the strip's fixed part — measured as the strip's width minus the chip box and the fill, which is the padding, the gaps, and every control that pane draws (its own chrome included, so the top-right pane asks more) — plus one chip at its minimum — `.tab` declares `min-width: 80px` on a content-box, so its footprint is 80px plus 10px + 10px of padding, 100px, read from a rendered chip's computed style (the stylesheet figure when none can be read); the divider between the halves takes its rendered thickness (0 — its hairline paints over the seam without taking layout room, so a body's own rules run unbroken past it). A column split, which only an edge drop makes, needs each half to hold the strip (34px) plus a 48px body: one 13px secondary line at 1.6 line-height inside 12px of the body's own insets — the pane body itself is unpadded, so a tab's body reaches the strip's bottom edge and the pane's edges and draws its own. `halvesFit` in `geometry.ts` is the arithmetic; `measure.ts` reads the rectangles after every commit and whenever the surface resizes, because the layout state carries fractions, never pixels, and the engine's planners stay that way. A pane without room keeps its split control, disabled with `splitPaneNarrow` (hidden instead under `hideSplitWhenBlocked`), and offers no edge drop zone for that axis (the release is then not a move). Under `hideSplitWhenBlocked` the split control's own footprint — its box plus the strip's gap — is left out of the fixed part: hiding the control sheds exactly that footprint from the strip, so a reading that counted it would flip with the control's visibility and re-render forever; leaving it out is also what the half being asked about would carry, since a half too narrow to split hides its own control. A pane the user narrows afterwards — a divider or the embedder's column dragged — keeps its size: the rule only decides its next split. +- **A split needs room for two working halves.** A pane splits into equal halves, so each half must hold what cannot shrink: the strip's fixed part — measured as the strip's width minus the chip box and the fill, which is the padding, the gaps, and every control that pane draws (its own chrome included, so the top-right pane asks more) — plus one chip at its minimum — `.tab` declares `min-width: 80px` on a content-box, so its footprint is 80px plus 10px + 10px of padding, 100px, read from a rendered chip's computed style (the stylesheet figure when none can be read); the divider between the halves takes its rendered thickness (0 — its hairline paints over the seam without taking layout room, so a body's own rules run unbroken past it). A column split, which only an edge drop makes, needs each half to hold the strip (34px) plus a 48px body: one 13px secondary line at 1.6 line-height inside 12px of the body's own insets — the pane body itself is unpadded, so a tab's body reaches the strip's bottom edge and the pane's edges and draws its own. `halvesFit` in `geometry.ts` is the arithmetic; `measure.ts` reads the rectangles when the dock layout or split policy changes, and on size notifications for the surface, panes, and strip boxes. An embedder resizing its column does not require a separate measurement during its render commit. A pane without room keeps its split control, disabled with `splitPaneNarrow` (hidden instead under `hideSplitWhenBlocked`), and offers no edge drop zone for that axis (the release is then not a move). Under `hideSplitWhenBlocked` the split control's own footprint — its box plus the strip's gap — is left out of the fixed part: hiding the control sheds exactly that footprint from the strip, so a reading that counted it would flip with the control's visibility and re-render forever; leaving it out is also what the half being asked about would carry, since a half too narrow to split hides its own control. A pane the user narrows afterwards — a divider or the embedder's column dragged — keeps its size: the rule only decides its next split. - **Focus lands on click, not on press.** A state change between `pointerdown` and the first `pointermove` rebuilds the pressed subtree, and a replaced element cancels the pointer. It also keeps a drag from recording a redundant focus operation first. Clicks on the chips, the strip's controls, and the embedder's chrome stop at the strip: the intent each reports already decides the active pane, or is the embedder's own, so the pane's click-to-focus records nothing extra. A floating panel's grip and corner report through their gesture the same way — a press released in place is a click that raises the panel, and a drag records only the move or resize, whose operation raises it — while a press on the panel's body raises it directly. A click on the pane that is active already, a click or key on that pane's selected chip, or a press on the panel that is active and on top already, changes nothing and records nothing. - **A control nested inside a draggable chip stops its own press.** Otherwise the press starts a drag, captures the pointer, and the nested control's click never lands. - **Emphasis takes the platform's accent, never `--dsw-alias-brand-primary`.** This platform binds `brand-primary` to its near-black (light) or near-white (dark) foreground, so the drop caret and the drop-zone hint use `--dsw-alias-brand-primary-new-colorprimary-new-color`, as the trajectory views do; a hovered divider takes the caption label ink instead, reading as a handle rather than a highlight. A floating panel draws no border — the menu's shadow (`--dsw-elevation-prominent`) outlines it — and the active panel gets no heavier frame: it is already on top and casts the same shadow; a darker frame around it read as a defect. diff --git a/packages/client/ui-dockkit/README.zh.md b/packages/client/ui-dockkit/README.zh.md index 6fbacf6dd5..67a227ff0b 100644 --- a/packages/client/ui-dockkit/README.zh.md +++ b/packages/client/ui-dockkit/README.zh.md @@ -80,9 +80,9 @@ Sidebar 使用的 `DockLayout` 在选中项变化、跨格移动与浮动期间 这些不是风格偏好;每一条都修复了在真实浏览器里发现的缺陷。 - **手势开始时捕获指针。** 不捕获的话,指针经过的任何滚动容器都可能接管手势,浏览器会将其报告为指针取消和拖动中止。捕获是加固——无论如何都由 window 监听器承载手势,所以没有该 API 的环境照样可用。 -- **chip 让位;tab 条末端的控件永不让位。** chip 盒是 tab 条里唯一会收缩的部分(`flex: 0 1 auto; min-width: 0; overflow-x: auto`):chip 先缩到 80px 下限,再在盒内随滚轮横向滚动、不画滚动条,且盒在每个藏有 chip 的一侧把 chip 在 24px 内渐隐(`data-dockkit-strip-scroll`,在每次提交、滚动与尺寸变化后由盒的滚动读数写入)。每当活动 tab 或 chip 的排列变化,盒会滚动到让活动 chip 避开渐隐带;已在视野内的 chip 不动。`DockLayout` 为每个新选中的 tab 画出新 tab 条时,新 tab 条先跳到该格上一条 tab 条记录的偏移,只让剩余距离带动画;没有记录偏移的 tab 条直接跳到活动 chip,而不是从排列起点滚动过去。chip 的标题从不加省略号:`TabTitle` 拿文字宽度对照它的盒子,文字更宽时置 `data-dockkit-tab-clipped`,让文字在末端 16px 内渐隐。chip 的关闭控件在 chip 活动、悬停或持有焦点时显示,压在标题末端 14px 之上、标题在其下渐隐,因此 chip 宽度两种情况下都一样。活动 chip 两侧的槽不画细线,让填色胶囊立在裸 chip 之间。添加、分栏与 chrome 控件都是 `flex: none`,因此在任何不窄于它们自身的格里(带 chrome 约 130px,不带约 72px)都保持宽度与位置。停靠面的 `min-width: 0` 与格的 `overflow: hidden` 阻止正文里最长的不换行行把格撑出自己的盒子——正是那种情况把控件和正文滚动条推到了屏幕外。 +- **chip 让位;tab 条末端的控件永不让位。** chip 盒是 tab 条里唯一会收缩的部分(`flex: 0 1 auto; min-width: 0; overflow-x: auto`):chip 先缩到 80px 下限,再在盒内随滚轮横向滚动、不画滚动条,且盒在每个藏有 chip 的一侧把 chip 在 24px 内渐隐(`data-dockkit-strip-scroll`,在每次提交、滚动与尺寸变化后由盒的滚动读数写入)。每当活动 tab 或 chip 的排列变化,盒会滚动到让活动 chip 避开渐隐带;已在视野内的 chip 不动。`DockLayout` 为每个新选中的 tab 画出新 tab 条时,新 tab 条先跳到该格上一条 tab 条记录的偏移,只让剩余距离带动画;没有记录偏移的 tab 条直接跳到活动 chip,而不是从排列起点滚动过去。chip 的标题从不加省略号:标题盒的末端 16px 始终渐隐,文字刚好放得下时也一样,无需测量宽度。chip 的关闭控件在 chip 活动、悬停或持有焦点时显示,压在标题末端 14px 之上、标题在其下渐隐,因此 chip 宽度两种情况下都一样。活动 chip 两侧的槽不画细线,让填色胶囊立在裸 chip 之间。添加、分栏与 chrome 控件都是 `flex: none`,因此在任何不窄于它们自身的格里(带 chrome 约 130px,不带约 72px)都保持宽度与位置。停靠面的 `min-width: 0` 与格的 `overflow: hidden` 阻止正文里最长的不换行行把格撑出自己的盒子——正是那种情况把控件和正文滚动条推到了屏幕外。 - **chip 盒会滚动,但绝不认领手势。** 横向滚动容器会把按下并移动的手势据为己有并取消指针;盒、chip 与 tab 条都设 `touch-action: none`,手势又捕获了指针,所以在 chip 上按下并移动是拖动,只有滚轮滚动盒子。 -- **分栏需要给两个可用的半格留出空间。** 格被等分成两半,因此每一半都必须容得下不可收缩的部分:tab 条的固定部分——按 tab 条宽减去 chip 盒与填充条测得,即内边距、间隙以及该格绘制的每个控件(含它自己的 chrome,所以右上格要求更多)——加上一枚最小尺寸的 chip——`.tab` 在 content-box 上声明 `min-width: 80px`,所以它的足印是 80px 加 10px + 10px 内边距,即 100px,从已渲染 chip 的计算样式读取(读不到时用样式表数值);两半之间的分隔条取其渲染厚度(0——它的细线画在接缝上、不占布局空间,因此正文自己画的分隔线能不断线地穿过接缝)。纵向分栏只由边缘落下产生,它要求每一半容得下 tab 条(34px)加 48px 正文:正文自留的 12px 内边距内一行 13px、行高 1.6 的次级文字——格的正文容器本身没有内边距,tab 的正文直接贴到 tab 条底边和格的边缘,由自己留白。`geometry.ts` 里的 `halvesFit` 是算术;`measure.ts` 在每次提交后与停靠面尺寸变化时读取矩形,因为布局状态只携带比例、从不携带像素,引擎的 planner 也保持如此。没有空间的格保留分栏控件,以 `splitPaneNarrow` 禁用(开启 `hideSplitWhenBlocked` 时改为隐藏),并且在该轴上不提供边缘落区(松手就不是移动)。开启 `hideSplitWhenBlocked` 时,分栏控件自己的占位——它的盒子加 tab 条的间隙——不计入固定部分:隐藏控件让 tab 条卸下的恰是这份占位,把它算进去的读数会随控件的可见性来回翻转、无限重渲染;不计入也正是被询问的那一半会承载的量,因为窄到无法分栏的一半会隐藏自己的控件。用户随后拖窄的格——通过拖动分隔条或嵌入方的列——会保持原尺寸:规则只决定它的下一次分栏。 +- **分栏需要给两个可用的半格留出空间。** 格被等分成两半,因此每一半都必须容得下不可收缩的部分:tab 条的固定部分——按 tab 条宽减去 chip 盒与填充条测得,即内边距、间隙以及该格绘制的每个控件(含它自己的 chrome,所以右上格要求更多)——加上一枚最小尺寸的 chip——`.tab` 在 content-box 上声明 `min-width: 80px`,所以它的足印是 80px 加 10px + 10px 内边距,即 100px,从已渲染 chip 的计算样式读取(读不到时用样式表数值);两半之间的分隔条取其渲染厚度(0——它的细线画在接缝上、不占布局空间,因此正文自己画的分隔线能不断线地穿过接缝)。纵向分栏只由边缘落下产生,它要求每一半容得下 tab 条(34px)加 48px 正文:正文自留的 12px 内边距内一行 13px、行高 1.6 的次级文字——格的正文容器本身没有内边距,tab 的正文直接贴到 tab 条底边和格的边缘,由自己留白。`geometry.ts` 里的 `halvesFit` 是算术;`measure.ts` 在停靠布局或分栏策略变化时读取矩形,也会响应停靠面、格和 tab 条各盒子的尺寸通知。嵌入方调整列宽时,不必在它的渲染提交中另测一次。没有空间的格保留分栏控件,以 `splitPaneNarrow` 禁用(开启 `hideSplitWhenBlocked` 时改为隐藏),并且在该轴上不提供边缘落区(松手就不是移动)。开启 `hideSplitWhenBlocked` 时,分栏控件自己的占位——它的盒子加 tab 条的间隙——不计入固定部分:隐藏控件让 tab 条卸下的恰是这份占位,把它算进去的读数会随控件的可见性来回翻转、无限重渲染;不计入也正是被询问的那一半会承载的量,因为窄到无法分栏的一半会隐藏自己的控件。用户随后拖窄的格——通过拖动分隔条或嵌入方的列——会保持原尺寸:规则只决定它的下一次分栏。 - **焦点落在 click 而不是按下。** 在 `pointerdown` 与第一次 `pointermove` 之间的状态变化会重建被按下的子树,而被替换的元素会取消指针。这也避免拖动先记录一条多余的焦点操作。chip、标签条各控件以及嵌入方 chrome 上的 click 都止于标签条:它们各自上报的意图已决定了活动格,或本就是嵌入方自己的事,所以格自身的点击聚焦不再多记一条。浮动面板的抓手与角柄同样通过手势上报——原地松开的按下是一次 click,抬起面板;真正的拖动只记录移动或缩放,由该操作自己抬起面板——而按在面板主体上则直接抬起它。点击本已活动的格、点击或按键选中该格本已选中的 chip,或按下本已活动且在最上层的面板,什么都不改变,也什么都不记录。 - **嵌套在可拖动 chip 里的控件要拦住自己的按下。** 否则按下会开始拖动、捕获指针,嵌套控件的 click 就永远落不下。 - **强调色用平台的强调 token,绝不用 `--dsw-alias-brand-primary`。** 本平台把 `brand-primary` 绑定到近黑(浅色)或近白(深色)的前景色,因此落点光标与落区提示都用 `--dsw-alias-brand-primary-new-colorprimary-new-color`,与轨迹视图一致;悬停的分隔条改用 caption 文字色,读起来是把手而不是高亮。浮窗不画边框——菜单同款阴影(`--dsw-elevation-prominent`)已勾出它的轮廓——活动浮窗也不加重边框:它本就在最上层、投同样的阴影;围它一圈更深的边框读起来像缺陷。 diff --git a/packages/client/ui-dockkit/src/components/DockSurface.tsx b/packages/client/ui-dockkit/src/components/DockSurface.tsx index 36ec07ca0b..72c4a3dffd 100644 --- a/packages/client/ui-dockkit/src/components/DockSurface.tsx +++ b/packages/client/ui-dockkit/src/components/DockSurface.tsx @@ -191,25 +191,31 @@ function Surface({ use(root) }, []) - // The room rule reads pixels, which the layout state does not carry: measure - // after every commit (a split, a divider drag, a closed tab all move panes) - // and whenever the surface itself is resized (the embedder's column dragged - // wider or narrower). A reading that changed nothing renders nothing. const remeasure = useCallback((): void => { withSurface((root) => { const next = measurePaneFits(root, hideSplitWhenBlocked) setFits(current => sameFits(current, next) ? current : next) }) }, [withSurface, hideSplitWhenBlocked]) - useLayoutEffect(() => { remeasure() }) - useEffect(() => { onRoom?.(fits) }, [fits, onRoom]) - useEffect(() => { + useLayoutEffect(() => { + if (typeof ResizeObserver === 'undefined') remeasure() + }) + useLayoutEffect(() => { const root = surface.current if (root === null || typeof ResizeObserver === 'undefined') return undefined - const observer = new ResizeObserver(() => { remeasure() }) + // A layout change can replace a selected tab's pane and strip. Measure its + // initial fit before paint; parent width changes need only the resize delivery. + remeasure() + const observer = new ResizeObserver(remeasure) observer.observe(root) + // A divider can resize a pane without resizing the surface. At fixed pane + // width, changing the strip controls takes space from its chips or its fill. + for (const box of root.querySelectorAll('[data-dockkit-pane], [data-dockkit-strip], [data-dockkit-strip-tabs], [data-dockkit-strip-fill]')) { + observer.observe(box, { box: 'border-box' }) + } return () => { observer.disconnect() } - }, [remeasure]) + }, [remeasure, state, canSplit]) + useEffect(() => { onRoom?.(fits) }, [fits, onRoom]) /** Why a pane cannot split right now: the budget first, then its own width. */ const splitBlock = (paneId: PaneId): SplitBlock | undefined => { diff --git a/packages/client/ui-dockkit/src/components/TabTitle.tsx b/packages/client/ui-dockkit/src/components/TabTitle.tsx index 679a27da02..477afa0f69 100644 --- a/packages/client/ui-dockkit/src/components/TabTitle.tsx +++ b/packages/client/ui-dockkit/src/components/TabTitle.tsx @@ -1,37 +1,8 @@ -/** - * A chip's title: one line, clipped at the chip's inset, never ellipsized. - * While the text is wider than its box the span carries - * `data-dockkit-tab-clipped`, and the stylesheet fades the text out at the - * clipped edge in place of an ellipsis. Written to the DOM directly rather - * than through state: a reading changes nothing that renders, only how the - * stylesheet paints it. Re-read after every commit (the text may have - * changed) and whenever the span's box resizes (the chip shrank or grew). - */ -import { useLayoutEffect, useRef } from 'react' +/** Title content shared by strip chips and floating-panel headers. */ import type { ReactNode } from 'react' import css from './dockkit.module.css' -/** Set or clear the span's `data-dockkit-tab-clipped` from its current geometry. */ -function markClipped(element: HTMLElement): void { - // Sub-pixel widths: the text counts as clipped past one whole pixel. - if (element.scrollWidth > element.clientWidth + 1) element.dataset.dockkitTabClipped = '' - else delete element.dataset.dockkitTabClipped -} - -/** The title span of a strip chip or a floating panel's header chip. */ +/** The chip stylesheet fades the trailing edge without measuring the title. */ export function TabTitle({ children }: { readonly children: ReactNode }): ReactNode { - const span = useRef(null) - useLayoutEffect(() => { - /* v8 ignore next -- the span is rendered unconditionally. */ - if (span.current !== null) markClipped(span.current) - }) - useLayoutEffect(() => { - const element = span.current - /* v8 ignore next -- the span is rendered unconditionally. */ - if (element === null || typeof ResizeObserver === 'undefined') return undefined - const observer = new ResizeObserver(() => { markClipped(element) }) - observer.observe(element) - return () => { observer.disconnect() } - }, []) - return {children} + return {children} } diff --git a/packages/client/ui-dockkit/src/components/dockkit.module.css b/packages/client/ui-dockkit/src/components/dockkit.module.css index 4499d879c5..51f2ba58a8 100644 --- a/packages/client/ui-dockkit/src/components/dockkit.module.css +++ b/packages/client/ui-dockkit/src/components/dockkit.module.css @@ -377,11 +377,8 @@ centres on the text's line rather than sitting on its baseline and keeps one distance from it. The clip is horizontal in intent; the line box must hold the descenders it would otherwise cut, hence a line-height above the - chip's own 1. No ellipsis: a title wider than its box (`TabTitle` sets - `data-dockkit-tab-clipped`) fades out over its last 16px instead. A mask on - the title rather than a painted gradient: the chip's fill is bare, - translucent hover, or the active tag colour, and a mask matches every one - without naming it. */ + chip's own 1. Only the last 16px of the title box fade, whether or not + the text overflows. A mask keeps the chip's fill visible underneath. */ .tabTitle { display: flex; flex: 1 1 auto; @@ -390,25 +387,20 @@ min-width: 0; overflow: hidden; line-height: 1.4; -} - -.tabTitle[data-dockkit-tab-clipped] { mask-image: linear-gradient(to right, black calc(100% - 16px), transparent); } /* While the close shows, the title is gone under the close's circle and fades out over the 16px before it: the circle spans the chip's last 24px and the title ends 10px inside the chip, so the title's last 14px are under it. - Later than the clipped mask, so a clipped chip showing its close fades - under the close. A floating panel's header chip has no close, so it keeps - the clipped mask alone. */ -.tab:not(.floatTitle):focus-within .tabTitle, -.tabActive .tabTitle { + Quiet and floating titles have no overlaid close. */ +.tab:not(.floatTitle, .tabQuiet):focus-within .tabTitle, +.tabActive:not(.tabQuiet) .tabTitle { mask-image: linear-gradient(to right, black calc(100% - 30px), transparent calc(100% - 14px)); } @media (hover: hover) { - .tab:not(.floatTitle):hover .tabTitle { + .tab:not(.floatTitle, .tabQuiet):hover .tabTitle { mask-image: linear-gradient(to right, black calc(100% - 30px), transparent calc(100% - 14px)); } } @@ -493,7 +485,7 @@ /* A pane's lone unclosable chip is a label, not a choice: no tab, no hover fill — the primary ink on the pane's own ground. Its title never - yields to a close control, so it keeps the clipped fade alone. */ + yields to a close control, so it keeps the ordinary title fade. */ .tab.tabQuiet { color: var(--dsw-alias-label-primary); background: transparent; @@ -508,21 +500,6 @@ } } -.tab.tabQuiet .tabTitle, -.tab.tabQuiet:focus-within .tabTitle { - mask-image: none; -} - -@media (hover: hover) { - .tab.tabQuiet:hover .tabTitle { - mask-image: none; - } -} - -.tab.tabQuiet .tabTitle[data-dockkit-tab-clipped] { - mask-image: linear-gradient(to right, black calc(100% - 16px), transparent); -} - .tabDragging { opacity: 0.5; } diff --git a/packages/client/ui-dockkit/tests/components.client.spec.tsx b/packages/client/ui-dockkit/tests/components.client.spec.tsx index 2954c76afb..8b3cdb9daa 100644 --- a/packages/client/ui-dockkit/tests/components.client.spec.tsx +++ b/packages/client/ui-dockkit/tests/components.client.spec.tsx @@ -19,6 +19,7 @@ import { applyOp } from '../src/engine/operations.ts' import { FLOAT_DEFAULT_SIZE, FLOAT_MIN_SIZE } from '../src/engine/constraints.ts' import { floatRectAt } from '../src/engine/geometry.ts' import { DockSurface, type DockSurfaceProps } from '../src/components/DockSurface.tsx' +import { TabTitle } from '../src/components/TabTitle.tsx' import type { TabMenuExtras } from '../src/contract/adapter.ts' import { FloatLayer, type FloatLayerProps } from '../src/components/FloatLayer.tsx' import { dockPaneIds, getPane } from '../src/engine/tree.ts' @@ -574,51 +575,14 @@ describe('DockSurface', () => { } }) - it('marks a chip title clipped while its text is wider than its box, re-reading on resize', () => { - class FakeResizeObserver implements ResizeObserver { - static readonly all: FakeResizeObserver[] = [] - readonly observe = vi.fn() - readonly unobserve = vi.fn() - readonly disconnect = vi.fn() - constructor(private readonly callback: ResizeObserverCallback) { - FakeResizeObserver.all.push(this) - } - - fire(): void { - this.callback([], this) - } - } - vi.stubGlobal('ResizeObserver', FakeResizeObserver) - let clientWidth = 200 - const descriptors = ['scrollWidth', 'clientWidth'].map(name => - [name, Object.getOwnPropertyDescriptor(Element.prototype, name)] as const) - const title = (element: Element): boolean => element.hasAttribute('data-dockkit-tab-title') - Object.defineProperty(Element.prototype, 'scrollWidth', { configurable: true, get(this: Element) { return title(this) ? 120 : 0 } }) - Object.defineProperty(Element.prototype, 'clientWidth', { configurable: true, get(this: Element) { return title(this) ? clientWidth : 0 } }) - try { - const controller = seededController() - const { unmount } = renderSurface(controller, spyIntents()) - const span = document.querySelector('[data-dockkit-tab-title]') - if (span === null) throw new Error('expected a chip title') - const observer = FakeResizeObserver.all.find(candidate => candidate.observe.mock.calls.some(([target]) => target === span)) - if (observer === undefined) throw new Error('expected the title to observe its own size') - expect(span.hasAttribute('data-dockkit-tab-clipped')).toBe(false) - // The chip narrowed under the text. - clientWidth = 80 - act(() => { observer.fire() }) - expect(span.hasAttribute('data-dockkit-tab-clipped')).toBe(true) - clientWidth = 200 - act(() => { observer.fire() }) - expect(span.hasAttribute('data-dockkit-tab-clipped')).toBe(false) - unmount() - expect(observer.disconnect).toHaveBeenCalledTimes(1) - } finally { - for (const [name, descriptor] of descriptors) { - if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, name) - else Object.defineProperty(Element.prototype, name, descriptor) - } - vi.unstubAllGlobals() - } + it('renders and renames a chip title without querying its width', () => { + const scrollWidth = vi.spyOn(Element.prototype, 'scrollWidth', 'get') + const clientWidth = vi.spyOn(Element.prototype, 'clientWidth', 'get') + const view = render(Files) + view.rerender(A long renamed file.ts) + expect(view.getByText('A long renamed file.ts').hasAttribute('data-dockkit-tab-title')).toBe(true) + expect(scrollWidth).not.toHaveBeenCalled() + expect(clientWidth).not.toHaveBeenCalled() }) it('asks for the seeded tab from the strip\'s add control, naming the pane and nothing else', () => { diff --git a/packages/client/ui-dockkit/tests/split-room.client.spec.tsx b/packages/client/ui-dockkit/tests/split-room.client.spec.tsx new file mode 100644 index 0000000000..ead65d6349 --- /dev/null +++ b/packages/client/ui-dockkit/tests/split-room.client.spec.tsx @@ -0,0 +1,93 @@ +// @vitest-environment jsdom +/** Split availability in the horizontal layout used by the right sidebar. */ +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { DockLayout } from '../src/components/DockSurface.tsx' +import { seededController, TEST_LABELS } from './fixtures.client.ts' + +afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) + +/** Deliver only size notifications for the given box, as opposed to a window resize. */ +function observeSizes() { + const observers = new Set() + class Observer { + readonly boxes = new Set() + constructor(readonly notify: () => void) { observers.add(this) } + observe(box: Element): void { this.boxes.add(box) } + disconnect(): void { observers.delete(this) } + } + vi.stubGlobal('ResizeObserver', Observer) + return (box: Element) => { + act(() => { + for (const observer of observers) if (observer.boxes.has(box)) observer.notify() + }) + } +} + +function panel() { + const controller = seededController() + controller.setExpanded(true) + const onRoom = vi.fn() + const paneReads = vi.fn() + let width = 300 + let fixed = 80 + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + if (this.hasAttribute('data-dockkit-pane')) { paneReads(); return new DOMRect(0, 0, width, 600) } + if (this.hasAttribute('data-dockkit-strip')) return new DOMRect(0, 0, width, 38) + if (this.hasAttribute('data-dockkit-strip-tabs')) return new DOMRect(0, 0, 100, 28) + if (this.hasAttribute('data-dockkit-strip-fill')) return new DOMRect(0, 0, width - fixed - 100, 0) + return new DOMRect() + }) + const tree = () =>
+
{tab.title}
} renderTabTitle={tab => {tab.title}} + chrome={} onRoom={onRoom} /> +
+ const view = render(tree()) + return { + controller, paneReads, onRoom, + box: (selector: string) => view.container.querySelector(selector)!, + blocked: () => view.getByRole('button', { name: TEST_LABELS.splitPane }).hasAttribute('disabled'), + redraw: (size: number, controls = fixed) => { width = size; fixed = controls; view.rerender(tree()) }, + } +} + +it('measures the mounted pane immediately but not on width-only React commits', () => { + const resized = observeSizes() + const h = panel() + expect(h.blocked()).toBe(true) + h.paneReads.mockClear() + h.redraw(450) + h.redraw(500) + expect(h.paneReads).not.toHaveBeenCalled() + resized(h.box('[data-dockkit-surface]')) + expect(h.blocked()).toBe(false) + expect(h.onRoom).toHaveBeenLastCalledWith(new Map([[h.controller.getSnapshot().state.rootId, { row: true, column: true }]])) +}) + +it('tracks changing strip controls at fixed pane width, including after the selected tab replaces its strip', () => { + const resized = observeSizes() + const h = panel() + h.redraw(500) + resized(h.box('[data-dockkit-surface]')) + expect(h.blocked()).toBe(false) + const oldFill = h.box('[data-dockkit-strip-fill]') + h.controller.openContent({ kind: 'file', contentId: 'file:a', title: 'A' }) + h.redraw(500, 180) + expect(h.blocked()).toBe(true) + const fill = h.box('[data-dockkit-strip-fill]') + expect(fill).not.toBe(oldFill) + h.redraw(500, 80) + resized(fill) + expect(h.blocked()).toBe(false) +}) + +it('keeps commit-time measurements when size observation is unavailable', () => { + vi.stubGlobal('ResizeObserver', undefined) + const h = panel() + expect(h.blocked()).toBe(true) + h.redraw(500) + expect(h.blocked()).toBe(false) + h.redraw(500, 180) + expect(h.blocked()).toBe(true) +}) From 081855ab12cdd050496345b70433b73d9f00d962 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:37:08 +0800 Subject: [PATCH 30/54] perf(web): keep sidebar resize signals out of unrelated subtrees Keep slide distance off settled open Sidebar content and stop the Session panel docking threshold from propagating into transcript rows. Exercise the threshold in both directions with a measured, fixed 720px message column and a real moving panel. Refs #8856. --- ...-20-rightbar-drag-restyle-budget.i18n.yaml | 8 +- ...2026-11-20-rightbar-drag-restyle-budget.md | 4 +- ...6-11-20-rightbar-drag-restyle-budget.zh.md | 4 +- .../rightbar-drag-browser/README.i18n.yaml | 4 +- benchmarks/rightbar-drag-browser/README.md | 9 +- benchmarks/rightbar-drag-browser/README.zh.md | 9 +- .../rightbar-drag.bench.ts | 111 +++++++++++++++--- .../client/ui-session-panel/README.i18n.yaml | 4 +- packages/client/ui-session-panel/README.md | 2 +- packages/client/ui-session-panel/README.zh.md | 2 +- .../src/client/SessionPanel.module.css | 6 + .../tests/session-panel-styles.client.spec.ts | 3 +- .../client/ui-sidebar-right/README.i18n.yaml | 4 +- packages/client/ui-sidebar-right/README.md | 2 +- packages/client/ui-sidebar-right/README.zh.md | 2 +- .../src/client/shell/SidebarRight.module.css | 19 +++ .../src/client/shell/SidebarRight.tsx | 3 +- .../tests/seat.client.spec.tsx | 23 +++- .../tests/sidebar-right-styles.client.spec.ts | 11 ++ 19 files changed, 185 insertions(+), 45 deletions(-) diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml index 286489ea70..b091330ead 100644 --- a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml @@ -9,11 +9,11 @@ en: 693e8d1e4423b78f zh: c63608002d762c12 /agent-note-right-sidebar-drag-restyle-budget/decision: - en: 29248a81f83693d9 - zh: 2ebede7805c3374f + en: 83d40f59669f4d33 + zh: 1e8de8d1b7e62861 /agent-note-right-sidebar-drag-restyle-budget/calibration: - en: 6d4c3e3eea2a0e0f - zh: 739fffd374da8b16 + en: dc1b35868c5ea353 + zh: 546aca16b16ca98b /agent-note-right-sidebar-drag-restyle-budget/alternatives-considered: en: 721cbfb3276fcb5b zh: 9557ee132f77f5a6 diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md index 837605dc89..dcc55127af 100644 --- a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md @@ -12,7 +12,7 @@ Dragging the right Sidebar beside a long transcript stalled for hundreds of mill The [right Sidebar drag benchmark](../../../../benchmarks/rightbar-drag-browser/README.md) joins the serial browser inventory. It loads a 120-turn synthetic Session completely, opens the right Sidebar, and drags its handle 40 trusted 8px mouse steps outward and back in a 1680×1000 viewport, in two fresh scaffold worlds and browsers. At that width the transcript column stays below the 680px content-width floor, and each drag asserts it, so the drag changes the column but not the resolved content width. -The restyle budget is a dimensionless count: the elements reported by every `UpdateLayoutTree` trace event during one drag, divided by the page's element count, as a median per direction, at most 1. A drag that restyles the transcript on every frame reaches about one multiple per frame; the fixed drag stays far below one multiple in total. The count does not depend on CPU speed, so it takes neither the shared time scale nor the variance headroom, and no wall-clock endpoint is budgeted or passed to the scaling report. +The restyle ratio is a dimensionless count: the elements reported by every `UpdateLayoutTree` trace event during one drag, divided by the page's element count. The 1680px case budgets the upper median per direction at 1. A second case keeps the rendered column at 720px and crosses the hidden Session panel's reserve-room threshold. It budgets each direction at 0.10: a single transcript-wide recalculation matters even if it happens on only one of the 40 steps. Neither count scales with CPU speed, and no wall-clock endpoint is budgeted or passed to the scaling report. ## Calibration @@ -28,6 +28,8 @@ The restyled count after the change is identical across samples and history leng In the 120-turn Chromium trace, 40 `Layout` events per direction ran inside script before the geometry-read fix and none afterwards. A second budget allows 20 script-nested layouts per drag: it rejects repeated synchronous layout without requiring every callback to be layout-free or penalizing normal reflow after script returns. +At 2560px with 120 turns and a 720px rendered column, the required benchmark traces the full drag against built Web artifacts, including the press and release. Before the fix, widening restyled 18,239 / 18,428 = 0.98974, failing the 0.10 budget. A diagnostic trace attributed 14,911 restyled elements to a single reserve-room flip. After the fix, widening restyled 380 / 18,428 = 0.02062 and narrowing restyled 379 / 18,428 = 0.02057. The Sidebar moved 80px each way, the column stayed at 720px, and the probe switched in both directions. The budget allows 1,842 restyles: nearly five times either passing count, but less than 40 updates of 82 elements even without the single large recalculation. + ## Alternatives considered - Budget frame gaps or style milliseconds. Rejected for the gate: they need browser-runner calibration that does not exist yet, and they also include the transcript reflow at each new column width, which a resize legitimately pays. They remain diagnostics. diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md index b478aa270b..39d852ed5c 100644 --- a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md @@ -12,7 +12,7 @@ Status: implemented [右侧栏拖动基准](../../../../benchmarks/rightbar-drag-browser/README.zh.md)加入串行浏览器清单。它完整加载一个 120 轮合成会话,打开右侧栏,在 1680×1000 视口中把拖拽条向外拖 40 个 8px 的真实鼠标步再拖回,在两个全新的脚手架环境和浏览器中各做一次。该宽度下正文列始终窄于 680px 的正文宽度下限,每次拖动都会断言这一点,因此拖动改变的是列宽,而不是解析后的正文宽度。 -样式重算的预算是一个无量纲计数:一次拖动期间所有 `UpdateLayoutTree` trace 事件报告的元素数之和,除以页面元素数,按方向取中位数,最多为 1。每帧都重算整段记录的拖动大约每帧就达到一倍;修复后的拖动总计远低于一倍。该计数与 CPU 速度无关,因此既不使用共享的时间缩放系数,也不使用波动余量;没有为任何墙钟终点设预算,也不把它们传给缩放报告。 +样式重算比值是一个无量纲计数:一次拖动期间所有 `UpdateLayoutTree` 追踪事件报告的元素数之和,除以页面元素数。1680px 用例按方向取上中位数,最多为 1。另一个用例让实际渲染的正文列保持 720px,同时跨越隐藏会话面板的空间预留阈值。其每个方向的比值不得超过 0.10:在 40 步中,即使只有一步重算整段记录的样式,也不能忽略。两种计数都不随 CPU 速度缩放;没有为墙钟终点设置预算,也不将其传给缩放报告。 ## 校准 @@ -28,6 +28,8 @@ Status: implemented 在 120 轮负载的 Chromium 追踪中,几何读取修复前每个方向都有 40 次 `Layout` 发生在脚本执行期间,修复后均为 0 次。第二项预算允许每次拖动最多 20 次脚本内布局:它能拦住反复触发同步布局的回归,而不要求每个回调都没有布局,也不惩罚脚本返回后的正常重排。 +在 2560px 视口中完整加载 120 轮、正文实际列宽固定为 720px 时,必需基准使用构建后的 Web 产物,追踪包含按下和松开鼠标的整个拖动过程。修复前,加宽方向的重算比值为 18,239 / 18,428 = 0.98974,超过 0.10 的预算。诊断追踪显示,仅一次预留状态翻转就重算了 14,911 个元素。修复后,加宽方向为 380 / 18,428 = 0.02062,缩窄方向为 379 / 18,428 = 0.02057。两个方向的侧栏都移动了 80px,正文列保持 720px,探针均发生翻转。预算允许重算 1,842 个元素,接近两个实测值的五倍;即使没有那次大幅重算,每步重算 82 个元素、连续 40 步也会超限。 + ## 备选方案 - 为帧间隔或样式毫秒数设预算。门禁不采用:它们需要尚不存在的浏览器 runner 校准,而且还包含按每个新列宽重排正文的成本,这是缩放本应付出的。它们保留为诊断输出。 diff --git a/benchmarks/rightbar-drag-browser/README.i18n.yaml b/benchmarks/rightbar-drag-browser/README.i18n.yaml index d52b01e438..0c75dcd69d 100644 --- a/benchmarks/rightbar-drag-browser/README.i18n.yaml +++ b/benchmarks/rightbar-drag-browser/README.i18n.yaml @@ -9,5 +9,5 @@ en: 0dce8b92617ea78b zh: 22ce9ccc29acda36 /right-sidebar-drag-browser-benchmark/measurements: - en: 9c4cc8759b4f90e8 - zh: 027d11cb574e36e0 + en: ece05c9d313f7906 + zh: 0c54ddf5bb75b162 diff --git a/benchmarks/rightbar-drag-browser/README.md b/benchmarks/rightbar-drag-browser/README.md index 8163214eaa..97b7ec9248 100644 --- a/benchmarks/rightbar-drag-browser/README.md +++ b/benchmarks/rightbar-drag-browser/README.md @@ -10,10 +10,13 @@ The required Chromium case in [rightbar-drag.bench.ts](rightbar-drag.bench.ts) d ## Measurements -Two fresh browser processes and scaffold worlds each widen the Sidebar by 40 trusted mouse steps of 8px and drag it back in a 1680×1000 viewport. A Chromium timeline trace covers each drag through two animation frames after release. Column widths measured before and after the trace must stay below the 680px content-width floor: widening the Sidebar must narrow the transcript column, and narrowing it must widen the column. +Each Chromium trace spans one trusted drag through two animation frames after release. The benchmark uses two fresh browser processes and scaffold worlds, with the Session panel hidden. -- **Restyles:** Sum the elements reported by each style recalculation and divide by the page's element count. The upper median per direction must not exceed 1 (one page's worth). -- **Layouts:** Each drag must produce at least one `Layout` event. `layoutCount` includes them all; `scriptNestedLayoutCount` counts each layout fully enclosed by a script event on the same process and thread, including animation frame callbacks. This subset must not exceed 20 per drag (half the mouse steps). Nesting is a proxy for synchronous layout, not evidence that every nested layout is unnecessary; browser reflow outside script does not consume the budget. +- **Changing column:** Each sample widens the right Sidebar by 40 steps of 8px and drags it back in a 1680×1000 viewport. The rendered transcript column must narrow as the Sidebar widens and widen on return; both endpoints must be below the 680px content-width floor. +- **Fixed column:** The first sample also opens the same 120 turns in a separate page with fresh storage, a 2560×1000 viewport and a saved 720px content width. After the opening slide settles, the visible Sidebar must reach each of 40 steps of 2px, from 1152px to 1232px and back. Every delivered transcript column width must be 720px. The Session panel's reserve-room value at its dock probe must switch from 1px to 0px and back. + +- **Restyles:** Sum the elements reported by each style recalculation and divide by the page's element count. For the changing column, the upper median per direction must not exceed 1 (one page's worth). For the fixed column, each direction must not exceed 0.10. +- **Layouts:** Each changing-column drag must produce at least one `Layout` event. `layoutCount` includes them all; `scriptNestedLayoutCount` counts each layout fully enclosed by a script event on the same process and thread, including animation frame callbacks. This subset must not exceed 20 per drag (half the mouse steps). Nesting is a proxy for synchronous layout, not evidence that every nested layout is unnecessary; browser reflow outside script does not consume the budget. Frame gaps and style and layout durations are diagnostics only. Neither budget scales with CPU speed. diff --git a/benchmarks/rightbar-drag-browser/README.zh.md b/benchmarks/rightbar-drag-browser/README.zh.md index 3058f824e1..cf0a9633bd 100644 --- a/benchmarks/rightbar-drag-browser/README.zh.md +++ b/benchmarks/rightbar-drag-browser/README.zh.md @@ -10,10 +10,13 @@ ## 测量 -两个全新的浏览器进程和脚手架环境各自在 1680×1000 视口中用 40 个真实鼠标步(每步 8px)加宽右侧栏,再拖回。Chromium 的时间线追踪覆盖每次拖动,直到松开后的两个动画帧。追踪前后测得的正文列宽都必须低于 680px 的正文宽度下限:加宽侧栏必须使正文列变窄,缩窄侧栏必须使正文列变宽。 +每次 Chromium 追踪覆盖一次真实鼠标拖动,直到松开后的两个动画帧。基准使用两个全新的浏览器进程和脚手架环境,均隐藏会话面板。 -- **样式重算:** 各次样式重算报告的元素数之和除以页面元素数。每个方向的上中位数不得超过 1(即一整个页面的元素数)。 -- **布局:** 每次拖动必须产生至少一个 `Layout` 事件。`layoutCount` 统计所有布局;`scriptNestedLayoutCount` 只统计起止时间均落在同一进程、同一线程的脚本事件内的布局,每次布局只计一次,动画帧回调也算脚本事件。每次拖动此项不得超过 20(鼠标步数的一半)。嵌套关系是判断同步布局的间接指标,并不说明每次嵌套布局都多余;脚本以外的浏览器重排不占用该预算。 +- **列宽变化:** 每个样本都在 1680×1000 视口中把右侧栏加宽 40 步(每步 8px),再拖回。实际渲染的正文列必须随侧栏加宽而变窄、随侧栏缩窄而变宽;起止列宽都必须低于 680px 的正文宽度下限。 +- **列宽固定:** 第一个样本还在单独页面中打开相同的 120 轮记录;该页面使用独立存储,视口为 2560×1000,预存的正文宽度为 720px。侧栏展开动画结束后,从 1152px 到 1232px 再拖回,每个方向 40 步,每步 2px,可见侧栏必须逐步到达目标宽度。每次观察到的正文列宽都必须是 720px。会话面板的停靠探针上,标记预留空间是否足够的值必须从 1px 变为 0px,再变回 1px。 + +- **样式重算:** 各次样式重算报告的元素数之和除以页面元素数。列宽变化时,每个方向的上中位数不得超过 1(即一整个页面的元素数)。列宽固定时,每个方向的比值不得超过 0.10。 +- **布局:** 列宽变化时,每次拖动必须产生至少一个 `Layout` 事件。`layoutCount` 统计所有布局;`scriptNestedLayoutCount` 只统计起止时间均落在同一进程、同一线程的脚本事件内的布局,每次布局只计一次,动画帧回调也算脚本事件。每次拖动此项不得超过 20(鼠标步数的一半)。嵌套关系是判断同步布局的间接指标,并不说明每次嵌套布局都多余;脚本以外的浏览器重排不占用该预算。 帧间隔、样式重算耗时和布局耗时仅作诊断。两项预算都不随 CPU 速度缩放。 diff --git a/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts index 7e332650e8..f5ed1431a4 100644 --- a/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts +++ b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts @@ -9,6 +9,11 @@ const SAMPLES = 2 /** Below the content width's 680px floor at this width, so the drag changes the column but not the resolved content width. */ const VIEWPORT = { width: 1680, height: 1000 } const CONTENT_WIDTH_FLOOR_PX = 680 +const FIXED_VIEWPORT = { width: 2560, height: 1000 } +const FIXED_COLUMN_PX = 720 +const FIXED_PANEL_START_PX = 1152 +const FIXED_STEP_PX = 2 +const FIXED_RESTYLE_BUDGET = 0.1 const STEPS = 40 const STEP_PX = 8 const STEP_GAP_MS = 8 @@ -48,8 +53,8 @@ interface DragSample extends TraceSummary { columnWidth: number } -function expectRestylesWithinBudget(ratio: number): void { - expect(ratio).toBeLessThanOrEqual(RESTYLE_BUDGET) +function expectRestylesWithinBudget(ratio: number, budget = RESTYLE_BUDGET): void { + expect(ratio).toBeLessThanOrEqual(budget) } function median(values: number[]): number { @@ -90,10 +95,25 @@ async function loadAll(page: Page): Promise { return count } +async function openLoadedSidebar(page: Page, url: string): Promise { + page.setDefaultTimeout(60_000) + await page.goto(url, { waitUntil: 'load' }) + await page.getByRole('treeitem').first().click() + await page.getByRole('treeitem').nth(1).click() + await page.locator(TAIL).last().waitFor() + expect(await loadAll(page)).toBe(HISTORY_TURNS) + await page.getByRole('button', { name: 'Open right sidebar' }).first().click() + await page.locator('[data-side="rightbar"]').waitFor() + // The Sidebar opens with a track transition; the drag starts from its settled width. + await page.waitForFunction(() => document.querySelector('[data-rightbar-collapsed], [data-animating]') === null) + return page.evaluate(() => document.querySelectorAll('*').length) +} + /** Frame timestamps the page collects during one drag. */ type FrameProbe = Window & { benchmarkFrames?: { frames: number[]; running: boolean } } +type FixedWidthProbe = typeof window & { benchmarkWidths: { column: Set; panel: number } } -async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: number): Promise { +async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: number, fixedPanelStart?: number): Promise { const box = await page.locator('[data-side="rightbar"]').boundingBox() if (box === null) throw new Error('right Sidebar resize handle missing') const x = box.x + box.width / 2 @@ -114,8 +134,13 @@ async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: n await page.mouse.move(x, y) await page.mouse.down() for (let step = 1; step <= STEPS; step++) { - await page.mouse.move(x - direction * step * STEP_PX, y) - await page.waitForTimeout(STEP_GAP_MS) + const delta = direction * step * (fixedPanelStart === undefined ? STEP_PX : FIXED_STEP_PX) + await page.mouse.move(x - delta, y) + if (fixedPanelStart === undefined) await page.waitForTimeout(STEP_GAP_MS) + else { + // Observe the actual panel before sending the next move; a freeze or coalesced drag must not reduce the work count. + await page.waitForFunction(width => (window as FixedWidthProbe).benchmarkWidths.panel === width, fixedPanelStart + delta) + } } await page.mouse.up() // Two animation frames let the release reach style and layout before the trace closes. @@ -136,6 +161,63 @@ async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: n } } +async function measureFixedColumn(browser: Browser, url: string): Promise { + const page = await newEnglishPage(browser, FIXED_VIEWPORT.height) + try { + const consoleWatch = watchConsole(page) + await page.setViewportSize(FIXED_VIEWPORT) + await page.addInitScript(width => { localStorage.setItem('dsh.conversation.contentWidth', String(width)) }, FIXED_COLUMN_PX) + const elements = await openLoadedSidebar(page, url) + const panelSelector = '[data-sidebar-right-panel="push"][data-sidebar-right-open]' + const panel = page.locator(panelSelector) + // The sliding dock items animate inside the panel, independently of its grid track. + await panel.evaluate(async node => { + await Promise.all(node.getAnimations({ subtree: true }).filter(animation => animation instanceof CSSTransition && animation.transitionProperty === 'transform').map(animation => animation.finished)) + }) + await page.evaluate(selector => { + const panel = document.querySelector(selector)! + const column = document.querySelector('[data-chat-flow]')! + const widths = { column: new Set(), panel: 0 } + ;(window as FixedWidthProbe).benchmarkWidths = widths + // Use delivered border boxes rather than forcing layout from a per-frame geometry read. + const observer = new ResizeObserver(entries => { + for (const entry of entries) { + const width = entry.borderBoxSize[0]!.inlineSize + if (entry.target === panel) widths.panel = width + else widths.column.add(width) + } + }) + observer.observe(panel, { box: 'border-box' }) + observer.observe(column, { box: 'border-box' }) + }, panelSelector) + await page.waitForFunction(() => (window as FixedWidthProbe).benchmarkWidths.column.size > 0) + const reserveRoom = (): Promise => page.locator('[data-session-panel-probe]').first().evaluate(node => + getComputedStyle(node).getPropertyValue('--dsh-session-panel-reserve-room').trim()) + let panelStart = FIXED_PANEL_START_PX + for (const direction of [1, -1] as const) { + expect(await page.evaluate(() => (window as FixedWidthProbe).benchmarkWidths.panel)).toBe(panelStart) + const reserveBefore = await reserveRoom() + const result = await drag(browser, page, direction, elements, panelStart) + const reserveAfter = await reserveRoom() + const geometry = await page.evaluate(() => { + const { panel, column } = (window as FixedWidthProbe).benchmarkWidths + return { panelWidth: panel, columnWidths: [...column] } + }) + console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/fixed-column', direction, elements, budget: FIXED_RESTYLE_BUDGET, panelStart, ...geometry, reserveBefore, reserveAfter, ...result })) + panelStart += direction * STEPS * FIXED_STEP_PX + expect(geometry.panelWidth).toBe(panelStart) + expect(geometry.columnWidths).toEqual([FIXED_COLUMN_PX]) + expect([result.columnWidthBefore, result.columnWidth]).toEqual([FIXED_COLUMN_PX, FIXED_COLUMN_PX]) + expect([reserveBefore, reserveAfter]).toEqual(direction === 1 ? ['1px', '0px'] : ['0px', '1px']) + expect(result.styledElements).toBeGreaterThan(0) + expectRestylesWithinBudget(result.restyleRatio, FIXED_RESTYLE_BUDGET) + } + expect(consoleWatch.pageErrors).toEqual([]) + } finally { + await page.close() + } +} + it('accepts recorded restyle ratios and rejects a drag that restyles the transcript every frame', () => { // 200-turn local samples: 1,479,947 and 1,909,568 elements restyled beside 28,895 before the width axis // kept resize inputs on the Conversation body; 2,622 and 3,368 after. @@ -145,6 +227,12 @@ it('accepts recorded restyle ratios and rejects a drag that restyles the transcr expect(() => expectRestylesWithinBudget(RESTYLE_BUDGET + 0.01)).toThrow() }) +it('rejects the fixed-column drag that restyled the transcript when reserve room flipped', () => { + const elements = 18_428 + expect(() => expectRestylesWithinBudget(18_239 / elements, FIXED_RESTYLE_BUDGET)).toThrow() + for (const restyled of [380, 379]) expectRestylesWithinBudget(restyled / elements, FIXED_RESTYLE_BUDGET) +}) + it('counts each layout enclosed by script on the same thread once, including frame callbacks', () => { const event = (name: string, ts: number, dur: number, pid = 1, tid = 1): TraceEvent => ({ name, ph: 'X', ts, dur, pid, tid }) const events = [ @@ -167,20 +255,11 @@ it(`bounds restyles and script-nested layouts while the right Sidebar is dragged await seedSession(scaffold, syntheticHistory(), SESSION_ID) const browser = await chromium.launch({ headless: true }) try { + if (sample === 0) await measureFixedColumn(browser, scaffold.authenticatedUrl) const page = await newEnglishPage(browser, VIEWPORT.height) await page.setViewportSize(VIEWPORT) const consoleWatch = watchConsole(page) - page.setDefaultTimeout(60_000) - await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.getByRole('treeitem').first().click() - await page.getByRole('treeitem').nth(1).click() - await page.locator(TAIL).last().waitFor() - expect(await loadAll(page)).toBe(HISTORY_TURNS) - await page.getByRole('button', { name: 'Open right sidebar' }).first().click() - await page.locator('[data-side="rightbar"]').waitFor() - // The Sidebar opens with a track transition; the drag starts from its settled width. - await page.waitForFunction(() => document.querySelector('[data-rightbar-collapsed], [data-animating]') === null) - const elements = await page.evaluate(() => document.querySelectorAll('*').length) + const elements = await openLoadedSidebar(page, scaffold.authenticatedUrl) for (const [direction, key] of [[1, 'widen'], [-1, 'narrow']] as const) { const result = await drag(browser, page, direction, elements) console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/sample', sample, direction: key, elements, ...result })) diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml index e14977457c..708a107bed 100644 --- a/packages/client/ui-session-panel/README.i18n.yaml +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -27,8 +27,8 @@ en: 27fdd4ec3c830299 zh: 0e70ac367e4176f8 /deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: - en: fa42d7d9a77863fc - zh: ffd22e65cca99a3b + en: a772926387782a82 + zh: 909966795290c52e /deepseek-ai-dsh-client-ui-session-panel/further-exploration: en: decfa1b92e25ec6c zh: 255c7862690a2f23 diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md index 04b68ec568..26b04ec3bf 100644 --- a/packages/client/ui-session-panel/README.md +++ b/packages/client/ui-session-panel/README.md @@ -83,7 +83,7 @@ A row whose single line clips its name or leaves out its owner, state, or measur
Implementation internals — click to expand -The panel is the `conversation.chat.aside` occupant of [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership), so it renders only in Chat Views. The toggle and the panel are separate Slot entries that share one plugin-owned state: the persisted docking preference, the Session whose overlay is open, and whether each mounted panel and each Session has room to dock. The stylesheets decide that room. The aside layer publishes its end gutter as `--dsh-chat-aside-gutter`, and the Conversation body publishes the largest end reserve its start gutter can give as `--dsh-chat-end-reserve-max`, which is readable only on the body, so the panel's stylesheet turns it there into a registered 0px or 1px step, `--dsh-session-panel-reserve-room`, that changes only when the reserve starts or stops covering the gutter; the docked width and a zero-height dock probe derive from them and from one set of metrics (40px clear, 8px edge, 300px minimum width). The probe is 1px wide while the gutter holds the panel at its minimum width, from 348px, or while the largest reserve covers that gutter, and 0 otherwise. The panel always renders the probe and attaches it through the injected `createProbeRef`, and the plugin observes only that element with a `ResizeObserver`: it hears the docking decision flip and nothing while the window resizes on one side of it, the transcript width is dragged, or the transcript grows. A probe has room from 1px of width, a Session has room while any of its probes does, and a Session without a probe shows no Chat View. The panel reads its own probe and the toggle its Session, and both decide the presentation with the same pure function, so the toggle's state never disagrees with the panel; opening, closing, or docking the panel renders nothing in the Chat View. Without `ResizeObserver` no probe gains room, and the panel shows only as an overlay. The aside layer also inherits the scrollport's composer and viewport heights. +The panel is the `conversation.chat.aside` occupant of [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership), so it renders only in Chat Views. The toggle and the panel are separate Slot entries that share one plugin-owned state: the persisted docking preference, the Session whose overlay is open, and whether each mounted panel and each Session has room to dock. The stylesheets decide that room. The aside layer publishes its end gutter as `--dsh-chat-aside-gutter`, and the Conversation body publishes the largest end reserve its start gutter can give as `--dsh-chat-end-reserve-max`, which is readable only on the body, so the panel's stylesheet turns it there into a registered 0px or 1px step, `--dsh-session-panel-reserve-room`, that changes only when the reserve starts or stops covering the gutter; the docked width and a zero-height dock probe derive from them and from one set of metrics (40px clear, 8px edge, 300px minimum width). The message flow does not inherit that step; crossing the docking threshold does not restyle its rows. The probe is 1px wide while the gutter holds the panel at its minimum width, from 348px, or while the largest reserve covers that gutter, and 0 otherwise. The panel always renders the probe and attaches it through the injected `createProbeRef`, and the plugin observes only that element with a `ResizeObserver`: it hears the docking decision flip and nothing while the window resizes on one side of it, the transcript width is dragged, or the transcript grows. A probe has room from 1px of width, a Session has room while any of its probes does, and a Session without a probe shows no Chat View. The panel reads its own probe and the toggle its Session, and both decide the presentation with the same pure function, so the toggle's state never disagrees with the panel; opening, closing, or docking the panel renders nothing in the Chat View. Without `ResizeObserver` no probe gains room, and the panel shows only as an overlay. The aside layer also inherits the scrollport's composer and viewport heights. While the docking preference is on, the probe carries `data-session-panel-reserve`, and a `:has()` rule in the panel's stylesheet sets `--dsh-chat-end-reserve` to 348px on the Conversation body, which then pads its scrollport's end by the missing gutter ([end reserve](../ui-conversation/README.md#end-reserve)). The probe's second term reads the largest reserve, not the padding, so its answer is the same before and after the transcript moves: the room the transcript makes never changes the decision that asked for it. diff --git a/packages/client/ui-session-panel/README.zh.md b/packages/client/ui-session-panel/README.zh.md index c0b292a5d9..3e29442737 100644 --- a/packages/client/ui-session-panel/README.zh.md +++ b/packages/client/ui-session-panel/README.zh.md @@ -83,7 +83,7 @@ kind: "package-reference"
实现内幕——点击展开 -面板是 [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership) 中 `conversation.chat.aside` 的占位组件,因此只渲染在 Chat 视图中。开关与面板是两个独立的 Slot 条目,共享一份插件持有的状态:持久化的停靠偏好、打开了浮层的会话,以及每个已挂载的面板和每个会话是否有停靠空间。停靠空间由样式表决定。侧边层把末端留白发布为 `--dsh-chat-aside-gutter`,Conversation 主体把起始留白最多能让出的末端预留发布为 `--dsh-chat-end-reserve-max`,它只能在主体上读取,因此面板样式表在主体上把它转换为已注册的 0px 或 1px 阶跃值 `--dsh-session-panel-reserve-room`,只有预留开始或不再覆盖这段留白时才变化;停靠宽度和一个零高度的停靠探针都由它们和同一组尺寸(间距 40px、边距 8px、最小宽度 300px)推出。留白放得下最小宽度的面板(从 348px 起),或者最大预留覆盖这段留白时,探针宽 1px,否则宽度为 0。面板始终渲染探针,并通过注入的 `createProbeRef` 挂接它;插件只用 `ResizeObserver` 观察这一个元素,所以只在停靠判断翻转时收到通知,窗口在阈值同一侧缩放、拖动正文宽度或正文增长时都不会。探针宽度达到 1px 即有停靠空间;会话的任一探针有空间时该会话就有停靠空间,没有探针的会话表示没有 Chat 视图在显示它。面板读取自己的探针,开关读取所在会话,两者用同一个纯函数决定呈现方式,因此开关状态始终与面板一致;打开、关闭或停靠面板也不会让 Chat 视图重新渲染。没有 `ResizeObserver` 时任何探针都不会获得空间,面板只以浮层显示。侧边层还从滚动容器继承输入框区域与视口高度。 +面板是 [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership) 中 `conversation.chat.aside` 的占位组件,因此只渲染在 Chat 视图中。开关与面板是两个独立的 Slot 条目,共享一份插件持有的状态:持久化的停靠偏好、打开了浮层的会话,以及每个已挂载的面板和每个会话是否有停靠空间。停靠空间由样式表决定。侧边层把末端留白发布为 `--dsh-chat-aside-gutter`,Conversation 主体把起始留白最多能让出的末端预留发布为 `--dsh-chat-end-reserve-max`,它只能在主体上读取,因此面板样式表在主体上把它转换为已注册的 0px 或 1px 阶跃值 `--dsh-session-panel-reserve-room`,只有预留开始或不再覆盖这段留白时才变化;停靠宽度和一个零高度的停靠探针都由它们和同一组尺寸(间距 40px、边距 8px、最小宽度 300px)推出。消息流不继承这个阶跃值,因此跨过停靠阈值不会让消息行重算样式。留白放得下最小宽度的面板(从 348px 起),或者最大预留覆盖这段留白时,探针宽 1px,否则宽度为 0。面板始终渲染探针,并通过注入的 `createProbeRef` 挂接它;插件只用 `ResizeObserver` 观察这一个元素,所以只在停靠判断翻转时收到通知,窗口在阈值同一侧缩放、拖动正文宽度或正文增长时都不会。探针宽度达到 1px 即有停靠空间;会话的任一探针有空间时该会话就有停靠空间,没有探针的会话表示没有 Chat 视图在显示它。面板读取自己的探针,开关读取所在会话,两者用同一个纯函数决定呈现方式,因此开关状态始终与面板一致;打开、关闭或停靠面板也不会让 Chat 视图重新渲染。没有 `ResizeObserver` 时任何探针都不会获得空间,面板只以浮层显示。侧边层还从滚动容器继承输入框区域与视口高度。 停靠偏好开启时,探针带有 `data-session-panel-reserve`,面板样式表中的一条 `:has()` 规则据此在 Conversation 主体上把 `--dsh-chat-end-reserve` 设为 348px,主体随即按所缺的留白给滚动容器的末端加上内边距([末端预留](../ui-conversation/README.zh.md#end-reserve))。探针的第二项读取的是最大预留而不是内边距,因此正文移动前后它的结果相同:正文让出的位置不会反过来改变提出让位的那项判断。 diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.module.css b/packages/client/ui-session-panel/src/client/SessionPanel.module.css index 59309b9b9c..e66f108901 100644 --- a/packages/client/ui-session-panel/src/client/SessionPanel.module.css +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -36,6 +36,12 @@ ); } +/* The dock probe lives in the aside, not the message flow. Crossing its + threshold must not change the inherited style of every message. */ +:global([data-slot='conversation.chat.flow']) { + --dsh-session-panel-reserve-room: initial; +} + /* While the docking preference is on, the dock probe carries a mark, and the panel asks the Conversation body to keep the gutter that docks it: the three metrics above, 348px. Where the gutter is narrower, the body diff --git a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts index 889998a773..0502f0042d 100644 --- a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts +++ b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts @@ -59,7 +59,8 @@ describe('SessionPanel.module.css docking geometry', () => { + ' calc((var(--dsh-chat-end-reserve-max, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width)) * 10000000 + 1px),' + ' 1px)', }) - // Registered as a length, the step computes to 0px or 1px on the body, so descendants see a change only when it flips. + expect(declarationsOf(":global([data-slot='conversation.chat.flow'])")['--dsh-session-panel-reserve-room']).toBe('initial') + // The aside inherits the computed step when it flips; the message rows keep the initial value. expect(css.replace(/\s+/g, ' ')).toContain( "@property --dsh-session-panel-reserve-room { syntax: ''; inherits: true; initial-value: 0px; }", ) diff --git a/packages/client/ui-sidebar-right/README.i18n.yaml b/packages/client/ui-sidebar-right/README.i18n.yaml index 6d7698bd31..da608e47a8 100644 --- a/packages/client/ui-sidebar-right/README.i18n.yaml +++ b/packages/client/ui-sidebar-right/README.i18n.yaml @@ -18,8 +18,8 @@ en: 3b007cc4d2d89c60 zh: 74d9795c6392ad74 /deepseek-ai-dsh-client-ui-sidebar-right/presentations: - en: 5024c4e5fe5dfd2e - zh: 535a7f585e1bcd97 + en: aa03c00f30ef88f7 + zh: b9b2cbe86775a864 /deepseek-ai-dsh-client-ui-sidebar-right/the-expand-button: en: ca7a1966ad9cef31 zh: b9a7a967a14f067e diff --git a/packages/client/ui-sidebar-right/README.md b/packages/client/ui-sidebar-right/README.md index 8b0b721eb5..17af9ab49b 100644 --- a/packages/client/ui-sidebar-right/README.md +++ b/packages/client/ui-sidebar-right/README.md @@ -47,7 +47,7 @@ With a coarse pointer, a disabled split button is hidden, whether blocked by ins In Windows Electron, `html[data-windows-titlebar]` keeps fullscreen panels below the caption and to the right of the expanded sidebar. The frame's `--dsh-windows-sidebar-width` supplies that inset and maximum width; `--dsh-windows-content-radius` supplies the top-left radius. Only fullscreen panels clip overflow for that corner. -The seat reports presentation through `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()`; the frame does not inject this package. Switching fullscreen on a wide viewport leaves the center width unchanged, and the width handle appears only in expanded normal mode. Independent floating panels and `float`/`dock` operations remain available. +The seat reports presentation through `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()`; the frame does not inject this package. Switching fullscreen on a wide viewport leaves the center width unchanged, and the width handle appears only in expanded normal mode. After the panel opens, dragging changes its width without sending an inherited slide distance to tab contents. Closing moves each docked item by the full panel width, even in a split layout. Independent floating panels and `float`/`dock` operations remain available. The panel has no header row. Its two controls — the presentation switch and the collapse button — ride the kit's chrome seat at the far end of the top-right pane's tab strip, so the strip is the panel's whole top edge. Each strip reads, left to right: the tab capsules with close controls where allowed, the add control (drawn only while that pane holds no guide tab; it opens the guide there through `ctx.sidebarRight.openTab`), the pane's split control, and in the top-right pane the two panel controls. Only the chips give way in a narrow pane; the controls after them never shrink or clip. diff --git a/packages/client/ui-sidebar-right/README.zh.md b/packages/client/ui-sidebar-right/README.zh.md index b821383e49..fbdd30a557 100644 --- a/packages/client/ui-sidebar-right/README.zh.md +++ b/packages/client/ui-sidebar-right/README.zh.md @@ -47,7 +47,7 @@ kind: "package-reference" 在 Windows Electron 中,`html[data-windows-titlebar]` 让全屏面板保持在顶栏下方及展开侧栏的右侧。框架的 `--dsh-windows-sidebar-width` 提供该缩进及最大宽度;`--dsh-windows-content-radius` 提供左上圆角。仅全屏面板为该圆角裁剪溢出内容。 -席位通过 `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()` 报告呈现,框架不注入本包。宽屏切换全屏不改变中栏宽度;宽度拖拽区只在普通展开态显示。独立浮窗及 `float`/`dock` 操作保持可用。 +席位通过 `ctx.layout.openRightbar(track, fullscreen)` / `closeRightbar()` 报告呈现,框架不注入本包。宽屏切换全屏不改变中栏宽度;宽度拖拽区只在普通展开态显示。面板展开后,拖动只更新面板宽度,不向标签页内容传递滑动距离。即使分栏,收起时每个停靠项也按整个面板的宽度滑动。独立浮窗及 `float`/`dock` 操作保持可用。 面板没有标题行。它的两个控件——形态切换与折叠按钮——搭在套件 chrome 席位上,位于右上格 tab 条的最末端,因此 tab 条就是面板的整条上边。每条 tab 条从左到右读作:在允许时带关闭按钮的 tab 胶囊,添加控件(只在该格没有引导 tab 时绘制;它通过 `ctx.sidebarRight.openTab` 在该格打开引导页),该格的分栏控件,以及右上格里的两个面板控件。窄格里只有 chip 让位;其后的控件从不收缩或被裁切。 diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 94d08c4f24..c1d72cec1c 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -28,7 +28,14 @@ display: none; } +@property --dsh-sidebar-right-panel-width { + syntax: ''; + inherits: false; + initial-value: 0px; +} + .panel { + width: var(--dsh-sidebar-right-panel-width); --dsh-dockkit-dock-layer: 10; --dsh-dockkit-float-layer: 60; position: absolute; @@ -47,6 +54,18 @@ pointer-events: none; } +/* A split pane slides the full panel width, not its own width. An open panel + needs this inherited distance only for items mounting during an animated opening. */ +.panel:not([data-sidebar-right-open]) { + --dsh-sidebar-width: var(--dsh-sidebar-right-panel-width); +} + +@media (prefers-reduced-motion: no-preference) { + .panel[data-sidebar-right-opening] { + --dsh-sidebar-width: var(--dsh-sidebar-right-panel-width); + } +} + /* Only docked Grid items slide. Their common ancestor remains untransformed and without a stacking context, so fixed floating children escape. */ .panel :global([data-dockkit-host='dock']), diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx index 8dd62420fe..deac734d53 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx @@ -346,8 +346,7 @@ function SidebarPanel(panel: PanelProps & { width: number; panelRef: RefObject { expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) }) + it('resizes the split panel without writing an inherited slide distance', async () => { + const h = await mountSeat() + h.open() + const panel = element(h.view.container, '[data-sidebar-right-panel]') + fireEvent.transitionEnd(element(panel, "[data-dockkit-host='dock']")) + act(() => { h.actions.splitPane(SESSION) }) + expect(h.view.container.querySelectorAll('[data-dockkit-pane]')).toHaveLength(2) + for (const width of [518, 620]) { + h.view.update({ width, viewportWidth: 1440, canShow: true }) + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe(`${width}px`) + expect(panel.style.getPropertyValue('--dsh-sidebar-width')).toBe('') + } + act(() => { h.actions.setExpanded(SESSION, false) }) + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('620px') + }) + it('fills the viewport without replacing the content tree or releasing the wide track', async () => { const h = await mountSeat() const tab = h.open() const panel = element(h.view.container, '[data-sidebar-right-panel]') const body = element(h.view.container, '[data-tab-body]') - expect(panel.style.width).toBe('420px') + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('420px') fireEvent.click(element(h.view.container, '[data-sidebar-right-mode]')) expect(h.layout().mode).toBe('fullscreen') - expect(panel.style.width).toBe('calc(1px + 100vw)') - expect(panel.style.getPropertyValue('--dsh-sidebar-width')).toBe('calc(100vw + 1px)') + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('calc(100vw + 1px)') expect(panel.dataset['sidebarRightPanel']).toBe('fullscreen') expect(element(h.view.container, '[data-tab-body]')).toBe(body) expect(h.frame.openRightbar).toHaveBeenLastCalledWith(true, true) expect(h.bodies.get(tab.id)?.sidebar).toEqual({ expanded: true, fullscreen: true }) fireEvent.click(element(h.view.container, '[data-sidebar-right-mode]')) - expect(panel.style.width).toBe('420px') + expect(panel.style.getPropertyValue('--dsh-sidebar-right-panel-width')).toBe('420px') expect(element(h.view.container, '[data-tab-body]')).toBe(body) expect(h.frame.openRightbar).toHaveBeenLastCalledWith(true, false) fireEvent.click(element(h.view.container, '[data-sidebar-right-toggle]')) diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index d59a3c843f..536e183bc5 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -8,6 +8,17 @@ const css = readFileSync(fileURLToPath(new URL('../src/client/shell/SidebarRight const host = String.raw`:global\(\[data-dockkit-host='dock'\]\)` describe('SidebarRight.module.css', () => { + it('keeps panel width local except for closed docks and items joining an animated opening', () => { + const distance = String.raw`--dsh-sidebar-width:\s*var\(--dsh-sidebar-right-panel-width\);` + expect(css).toMatch(/@property --dsh-sidebar-right-panel-width\s*\{\s*syntax: '';\s*inherits: false;\s*initial-value: 0px;/) + expect(css).toMatch(/\.panel\s*\{[^{}]*\bwidth: var\(--dsh-sidebar-right-panel-width\);/) + expect(css).toMatch(new RegExp(String.raw`\.panel:not\(\[data-sidebar-right-open\]\)\s*\{\s*${distance}\s*}`)) + // Reduced motion need not produce a transitionend to clear the opening marker. + expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: no-preference\)\s*\{\s*` + + String.raw`\.panel\[data-sidebar-right-opening\]\s*\{\s*${distance}\s*}\s*}`)) + expect(css.match(/--dsh-sidebar-width:/g)).toHaveLength(2) + }) + it('starts docked items mounted by an opening at the closed position', () => { expect(css).toMatch(new RegExp(String.raw`@starting-style\s*\{\s*\.panel\[data-sidebar-right-opening\] ${host},[^{}]*\{` + String.raw`\s*transform: translateX\(var\(--dsh-sidebar-width\)\);\s*}\s*}`)) From 277160418299506a4558f2580667e8cc86a5789d Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Fri, 20 Nov 2026 12:24:19 +0800 Subject: [PATCH 31/54] =?UTF-8?q?fix(extensions):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E5=AD=90=E4=BB=A3=E7=90=86=20Client=20inspect=20=E6=8C=81?= =?UTF-8?q?=E7=BB=AD=E8=B6=85=E6=97=B6=20(#8615)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(extensions): route client inspect replies by session identity * fix(extensions): preserve inspect reply wire identity in source mode --- apps/web/tests/cordis-inspect-subagent.e2e.ts | 60 +++++++++++++++++++ apps/web/tsconfig.json | 1 + docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/persistence-catalog.i18n.yaml | 4 +- docs/persistence-catalog.md | 2 +- docs/persistence-catalog.zh.md | 2 +- docs/persistence-schema.json | 2 +- docs/subsystems/extensions.md | 12 ++-- docs/subsystems/extensions.zh.md | 12 ++-- .../cordis-host-runner/README.i18n.yaml | 4 +- .../extensions/cordis-host-runner/README.md | 2 + .../cordis-host-runner/README.zh.md | 2 + .../cordis-host-runner/src/index.ts | 9 +-- .../src/inspect-registry.ts | 7 ++- .../tests/inspect-registry.spec.ts | 16 ++--- .../cordis-host-runner/tests/runner.spec.ts | 36 ++++++++++- .../client-fixture.mjs | 6 +- .../cordis-inspect-timeout/client-fixture.mjs | 6 +- tsconfig.host.json | 1 + 20 files changed, 143 insertions(+), 45 deletions(-) create mode 100644 apps/web/tests/cordis-inspect-subagent.e2e.ts diff --git a/apps/web/tests/cordis-inspect-subagent.e2e.ts b/apps/web/tests/cordis-inspect-subagent.e2e.ts new file mode 100644 index 0000000000..8e6fc4358c --- /dev/null +++ b/apps/web/tests/cordis-inspect-subagent.e2e.ts @@ -0,0 +1,60 @@ +/** Client inspection replies preserve child Session ownership through the shipped Web RPC path. */ +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import { Peer } from '@deepseek-ai/dsh-client-connection' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { SessionId } from '@deepseek-ai/dsh-session' +import { launchWebScaffold } from './scaffold.ts' +import { newEnglishPage } from './support.ts' + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + /** Test page permitted to use global RPCs but no Session. */ + 'inspect-test-page': { readonly kind: 'inspect-test-page' } + } +} + +it('answers Client queries for subagents without adopting their Session as an ordinary Agent', async () => { + const scaffold = await launchWebScaffold() + try { + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await expect.poll(() => scaffold.ctx.cordisInspect.list().some(provider => provider.platform === 'client')).toBe(true) + const child = await scaffold.ctx.agents.create({ + sessionId: brandString('inspect-child'), + meta: { origin: 'subagent', parentSession: brandString('inspect-parent') }, + }) + try { + expect(await scaffold.ctx.sessionController.resolveAgent(child.agent.id)).toMatchObject({ error: { code: 'session/agent-busy' } }) + const result = await scaffold.ctx.cordisInspect.query('client', 'Service', 'listService', undefined, child.agent, new AbortController().signal) + expect(result).toHaveProperty('mode', 'catalog') + expect(result).toHaveProperty('services', expect.arrayContaining([expect.objectContaining({ key: 'layout' })])) + const peer = new Peer(scaffold.ctx, { principal: { kind: 'inspect-test-page' } }) + const unregister = scaffold.ctx.remoteAccess.registerPolicy('inspect-test-page', { bindings: () => [{ + role: { name: 'inspect-global', resource: 'global', actions: ['dynamicCordisRunner/resolveInspectQuery'] }, + resource: { kind: 'global' }, + }] }) + try { + await expect(scaffold.ctx.typertGateway.invoke({ + peer, namespace: 'dynamicCordisRunner', method: 'resolveInspectQuery', + args: { agentId: child.agent.id, requestId: 'inspect-0', resolution: { ok: true, data: {} } }, + })).rejects.toMatchObject({ code: 'remote-access/denied' }) + } finally { + unregister() + await peer.dispose() + } + expect(child.agent.session.header.origin).toBe('subagent') + expect(scaffold.ctx.agents.get(child.agent.id)).toBe(child.agent) + } finally { + await child.dispose() + } + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index cd716a0177..b466f7c716 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -32,6 +32,7 @@ "tests/sidebar-drawer.e2e.ts", "tests/session-panel-layout.e2e.ts", "tests/creation-recommendations.e2e.ts", + "tests/cordis-inspect-subagent.e2e.ts", "tests/plugin-recommendations.e2e.ts", "tests/deepseek-chat-import.e2e.ts", "tests/japanese-plugin-metadata.e2e.ts", diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 9b46ade20d..cc84dac22a 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -936,7 +936,7 @@ export interface ToolResultPruneConfig { ## `@deepseek-ai/dsh-cordis-host-runner` - `inject`: `tools` -- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:106`](../packages/extensions/cordis-host-runner/src/index.ts) +- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:107`](../packages/extensions/cordis-host-runner/src/index.ts) ```ts config-catalog /** Runner configuration. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 5a60ec42e6..d8fb908f75 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -938,7 +938,7 @@ export interface ToolResultPruneConfig { ## `@deepseek-ai/dsh-cordis-host-runner` - `inject`: `tools` -- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:106`](../packages/extensions/cordis-host-runner/src/index.ts) +- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:107`](../packages/extensions/cordis-host-runner/src/index.ts) ```ts config-catalog /** Runner configuration. */ diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index b4a5b8c7ca..8b047915d9 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1629,8 +1629,8 @@ en: e4a4fc20bc145671 zh: 48bb675a3807ae42 /session-persistence-event-catalog/resolved-persistence-types/kind-cordis-host-runner: - en: e1fa1148ddbc8aa5 - zh: 1b8e71ec4dd6cbb3 + en: 919ed1e164b36cf1 + zh: 0bd2652c0862f1bf /session-persistence-event-catalog/resolved-persistence-types/kind-disposed: en: 9b4155c7c2c46023 zh: 1cd75eecdc41e8ad diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 4f8a0494fa..b42ff525e3 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -6803,7 +6803,7 @@ Sources: [`packages/core/session/src/types.ts:217`](../packages/core/session/src SHA-256: `02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79` -Sources: [`packages/extensions/cordis-host-runner/src/index.ts:15`](../packages/extensions/cordis-host-runner/src/index.ts) +Sources: [`packages/extensions/cordis-host-runner/src/index.ts:16`](../packages/extensions/cordis-host-runner/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 9a66e8b0c1..abda4e69e8 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -6805,7 +6805,7 @@ SHA-256: `b6ef9c6210be8350cd465f485cf520031fffa6bf3809c61a1e713e834c5982d0` SHA-256: `02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79` -来源:[`packages/extensions/cordis-host-runner/src/index.ts:15`](../packages/extensions/cordis-host-runner/src/index.ts) +来源:[`packages/extensions/cordis-host-runner/src/index.ts:16`](../packages/extensions/cordis-host-runner/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index e8dbd51202..ce13a39304 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -75,7 +75,7 @@ {"digest":"022623b9ef98ec47ec3c3bae0c51027c70d2601141c5e92e26a0d83d1b4cef06","names":[],"sources":[]}, {"digest":"023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4","names":[],"sources":["packages/core/session/src/types.ts:221"]}, {"digest":"025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc","names":[],"sources":[]}, - {"digest":"02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79","names":[],"sources":["packages/extensions/cordis-host-runner/src/index.ts:15"]}, + {"digest":"02b2c23f2d94b028c9588a8faace3fce1217405db346da3389368b495457bf79","names":[],"sources":["packages/extensions/cordis-host-runner/src/index.ts:16"]}, {"digest":"0341d4c3dfcd53253cdc1e789d9130d3cd848b6f8b0706bf92f313a68b39ff23","names":[],"sources":[]}, {"digest":"04c12e59a9ed4d7a59b642223a9bdd3b4303c1d27873c72c5e487760892bbb08","names":["packages/llm/llm/src/message.ts#SystemMessage"],"sources":["packages/llm/llm/src/message.ts:176"]}, {"digest":"05205074b24d8340cfd7995f6cb64779c7f1241490954700115601e264178877","names":[],"sources":[]}, diff --git a/docs/subsystems/extensions.md b/docs/subsystems/extensions.md index 4d8e592487..5d5c4ccca1 100644 --- a/docs/subsystems/extensions.md +++ b/docs/subsystems/extensions.md @@ -56,15 +56,15 @@ async query( platform: CordisInspectPlatform, providerId: string, methodName: st /** * Accept the first valid Client response for a pending query. - * @param agent - Agent whose Session owns the query. + * @param sessionId - Session identity recorded by the pending query, including subagent Sessions. * @param requestId - Pending Client query identity. * @param resolution - Client provider result or failure. * @returns acknowledgement with accepted true only for a success that settles the query; only the first failure diagnostic is retained. */ -resolveClientQuery( agent: Agent, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck +resolveClientQuery( sessionId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck ``` -Types: [Agent](core.md) +Types: [Agent](core.md) · [SessionId](core.md) Source: [`packages/extensions/cordis-host-runner/src/inspect-registry.ts`](../../packages/extensions/cordis-host-runner/src/inspect-registry.ts) @@ -173,13 +173,13 @@ async stop(agent: Agent, pluginId: CordisDynamicPluginId): Promise agentId } }) resolveInspectQuery( agentId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck /** * Frame-wide inventory, grouped as one row per stable Plugin. @@ -257,7 +257,7 @@ inspectPackage( agent: Agent, pluginId: CordisDynamicPluginId, packageId: Cordis @Remote('invoke') async invoke( pluginId: CordisDynamicPluginId, pluginRunId: CordisDynamicPluginRunId, method: string, args: JsonValue, ): Promise ``` -Types: [Agent](core.md) +Types: [Agent](core.md) · [SessionId](core.md) Source: [`packages/extensions/cordis-host-runner/src/index.ts`](../../packages/extensions/cordis-host-runner/src/index.ts) diff --git a/docs/subsystems/extensions.zh.md b/docs/subsystems/extensions.zh.md index 715653f19a..611ec66ae2 100644 --- a/docs/subsystems/extensions.zh.md +++ b/docs/subsystems/extensions.zh.md @@ -56,15 +56,15 @@ async query( platform: CordisInspectPlatform, providerId: string, methodName: st /** * Accept the first valid Client response for a pending query. - * @param agent - Agent whose Session owns the query. + * @param sessionId - Session identity recorded by the pending query, including subagent Sessions. * @param requestId - Pending Client query identity. * @param resolution - Client provider result or failure. * @returns acknowledgement with accepted true only for a success that settles the query; only the first failure diagnostic is retained. */ -resolveClientQuery( agent: Agent, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck +resolveClientQuery( sessionId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck ``` -Types: [Agent](core.zh.md) +Types: [Agent](core.zh.md) · [SessionId](core.zh.md) Source: [`packages/extensions/cordis-host-runner/src/inspect-registry.ts`](../../packages/extensions/cordis-host-runner/src/inspect-registry.ts) @@ -173,13 +173,13 @@ async stop(agent: Agent, pluginId: CordisDynamicPluginId): Promise agentId } }) resolveInspectQuery( agentId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck /** * Frame-wide inventory, grouped as one row per stable Plugin. @@ -257,7 +257,7 @@ inspectPackage( agent: Agent, pluginId: CordisDynamicPluginId, packageId: Cordis @Remote('invoke') async invoke( pluginId: CordisDynamicPluginId, pluginRunId: CordisDynamicPluginRunId, method: string, args: JsonValue, ): Promise ``` -Types: [Agent](core.zh.md) +Types: [Agent](core.zh.md) · [SessionId](core.zh.md) Source: [`packages/extensions/cordis-host-runner/src/index.ts`](../../packages/extensions/cordis-host-runner/src/index.ts) diff --git a/packages/extensions/cordis-host-runner/README.i18n.yaml b/packages/extensions/cordis-host-runner/README.i18n.yaml index e3c034b7ad..d87d60dbbd 100644 --- a/packages/extensions/cordis-host-runner/README.i18n.yaml +++ b/packages/extensions/cordis-host-runner/README.i18n.yaml @@ -21,8 +21,8 @@ en: ca844fa88b307274 zh: da2032bfe3c1b792 /deepseek-ai-dsh-cordis-host-runner/use-this-package/client-inspection: - en: eb3187e43eec0872 - zh: 096eef6a6d0c388b + en: 020438ac524974b4 + zh: 9f073882a68df78c /deepseek-ai-dsh-cordis-host-runner/use-this-package/what-a-run-does: en: a3c86c081974a710 zh: 180e1b7824c070d4 diff --git a/packages/extensions/cordis-host-runner/README.md b/packages/extensions/cordis-host-runner/README.md index 0857880744..fd8691f6b5 100644 --- a/packages/extensions/cordis-host-runner/README.md +++ b/packages/extensions/cordis-host-runner/README.md @@ -47,6 +47,8 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a When Gateway is mounted, a Client query with no live event stream fails before dispatch. This check does not subscribe to disconnections: queries already dispatched retain their original deadline. Standalone event transports without Gateway retain the same timeout behavior. +Replies carry the Session identity in the `agentId` RPC field in both source and built Hosts. They correlate the pending request without resolving or resuming an ordinary Agent, so subagent Sessions can receive Client results. Remote access still requires permission for that Session. + Client queries accept the first valid page response within `clientInspectTimeoutMs`. A failed page does not prevent another page from answering successfully. If no valid result arrives, the query rejects with the first Client failure or output-validation diagnostic; when no page answers, it asks the caller to open or reconnect the Harness page and retry. Cancellation and registry disposal also end pending queries. Reconnecting a page does not replay a missed request, so retry after the connection is restored. Host queries are unaffected by this timeout. Query failures throw `InspectError`: `INSPECT_PROVIDER_NOT_FOUND`, `INSPECT_METHOD_NOT_FOUND`, and `INSPECT_INVALID_INPUT` reject the request before dispatch; `INSPECT_INVALID_OUTPUT` rejects a provider value; `INSPECT_CLIENT_UNAVAILABLE` reports a missing page or registry disposal; and `INSPECT_TIMEOUT` reports the Client deadline. A Host provider may throw its own `HarnessError`, such as `INSPECT_TARGET_NOT_FOUND`; any other provider failure becomes `INSPECT_FAILED` with the original error as `cause`. Cancellation rethrows the signal's reason. diff --git a/packages/extensions/cordis-host-runner/README.zh.md b/packages/extensions/cordis-host-runner/README.zh.md index 289dc1b43c..4c3d476cd3 100644 --- a/packages/extensions/cordis-host-runner/README.zh.md +++ b/packages/extensions/cordis-host-runner/README.zh.md @@ -47,6 +47,8 @@ kind: "package-reference" 装载 Gateway 时,没有活动事件流的 Client 查询在发送前就会失败。此检查不订阅断连:已发送的查询仍沿用原期限。没有 Gateway 的独立事件传输保持相同的超时行为。 +源码运行与构建产物运行的 Host 均通过 `agentId` RPC 字段接收响应中的 Session 标识。响应据此关联待处理请求,不解析或恢复普通 Agent,因此 subagent 会话也能接收 Client 结果。Remote 访问仍要求拥有该 Session 的权限。 + Client 查询在 `clientInspectTimeoutMs` 内接受首个有效页面响应。某个页面失败不会阻止其他页面成功回答。若没有有效结果,查询返回首个 Client 错误或输出校验诊断;若没有页面回答,则提示调用方打开或重新连接 Harness 页面后重试。取消和注册表卸载也会结束待处理查询。页面重连不会重放错过的请求,因此需在连接恢复后重试。Host 查询不受此超时影响。 查询失败抛出 `InspectError`:`INSPECT_PROVIDER_NOT_FOUND`、`INSPECT_METHOD_NOT_FOUND` 与 `INSPECT_INVALID_INPUT` 在发送前拒绝请求;`INSPECT_INVALID_OUTPUT` 拒绝提供方返回值;`INSPECT_CLIENT_UNAVAILABLE` 表示没有页面或注册表已卸载;`INSPECT_TIMEOUT` 表示 Client 期限已到。Host 提供方可以抛出自己的 `HarnessError`,例如 `INSPECT_TARGET_NOT_FOUND`;其他提供方失败变为 `INSPECT_FAILED`,原始错误保留为 `cause`。取消时重新抛出信号的 reason。 diff --git a/packages/extensions/cordis-host-runner/src/index.ts b/packages/extensions/cordis-host-runner/src/index.ts index 6ec0560a7b..8ba2629163 100644 --- a/packages/extensions/cordis-host-runner/src/index.ts +++ b/packages/extensions/cordis-host-runner/src/index.ts @@ -9,6 +9,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import type { Fiber } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' +import type { SessionId } from '@deepseek-ai/dsh-session' import { createUserMessage } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { @@ -523,19 +524,19 @@ export class DynamicCordisRunnerService extends TypertRemoteService { /** * Submit a Client inspect result or failure for a pending query. - * @param agent - Session that owns the query. + * @param agentId - Session identity that owns the pending query; answering does not resolve or resume an Agent. * @param requestId - exact pending query identity. * @param resolution - provider result or structured refusal. * @returns acknowledgement with accepted true only for a valid success that settles the query; * pending-query failures return { accepted: false } and retain only the first diagnostic. */ - @Remote('resolveInspectQuery') + @Remote({ name: 'resolveInspectQuery', resources: { session: agentId => agentId } }) resolveInspectQuery( - agent: Agent, + agentId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck { - return this.inspectRegistry.resolveClientQuery(agent, requestId, resolution) + return this.inspectRegistry.resolveClientQuery(agentId, requestId, resolution) } /** diff --git a/packages/extensions/cordis-host-runner/src/inspect-registry.ts b/packages/extensions/cordis-host-runner/src/inspect-registry.ts index abf0db002f..ca79a16df5 100644 --- a/packages/extensions/cordis-host-runner/src/inspect-registry.ts +++ b/packages/extensions/cordis-host-runner/src/inspect-registry.ts @@ -3,6 +3,7 @@ import { Service } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' +import type { SessionId } from '@deepseek-ai/dsh-session' import { HarnessError } from '@deepseek-ai/dsh-error' import type {} from '@deepseek-ai/dsh-api-gateway' import { snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values' @@ -191,18 +192,18 @@ export class CordisInspectRegistryService extends Service { /** * Accept the first valid Client response for a pending query. - * @param agent - Agent whose Session owns the query. + * @param sessionId - Session identity recorded by the pending query, including subagent Sessions. * @param requestId - Pending Client query identity. * @param resolution - Client provider result or failure. * @returns acknowledgement with accepted true only for a success that settles the query; only the first failure diagnostic is retained. */ resolveClientQuery( - agent: Agent, + sessionId: SessionId, requestId: CordisInspectRequestId, resolution: CordisInspectQueryResolution, ): CordisInspectResolveAck { const pending = this.pending.get(requestId) - if (pending === undefined || pending.request.agentId !== agent.id) return { accepted: false } + if (pending === undefined || pending.request.agentId !== sessionId) return { accepted: false } // A failed page must not prevent another page from supplying a valid result. if (!resolution.ok) { pending.failure ??= `${resolution.reason}: ${resolution.message}` diff --git a/packages/extensions/cordis-host-runner/tests/inspect-registry.spec.ts b/packages/extensions/cordis-host-runner/tests/inspect-registry.spec.ts index 74db037f38..a91c394c4c 100644 --- a/packages/extensions/cordis-host-runner/tests/inspect-registry.spec.ts +++ b/packages/extensions/cordis-host-runner/tests/inspect-registry.spec.ts @@ -78,7 +78,7 @@ function start() { } function answer(query: ReturnType) { - return registry.resolveClientQuery(AGENT_A, query.request.requestId, { ok: true, data: { name: 'theme' } }) + return registry.resolveClientQuery(AGENT_A.id, query.request.requestId, { ok: true, data: { name: 'theme' } }) } async function connectGatewayClient(): Promise { @@ -142,7 +142,7 @@ describe('Client inspect completion', () => { it('returns the Client catalog failure at the deadline instead of losing it', async () => { const query = start() - expect(registry.resolveClientQuery(AGENT_A, query.request.requestId, { + expect(registry.resolveClientQuery(AGENT_A.id, query.request.requestId, { ok: false, reason: 'provider-error', message: 'no catalogued Service named "remote"', })).toEqual({ accepted: false }) await vi.advanceTimersByTimeAsync(99) @@ -156,7 +156,7 @@ describe('Client inspect completion', () => { it('allows a later successful page to win after another page fails', async () => { const query = start() - expect(registry.resolveClientQuery(AGENT_A, query.request.requestId, failure)).toEqual({ accepted: false }) + expect(registry.resolveClientQuery(AGENT_A.id, query.request.requestId, failure)).toEqual({ accepted: false }) await vi.advanceTimersByTimeAsync(99) expect(answer(query)).toEqual({ accepted: true }) expect(await query.result).toEqual({ value: { name: 'theme' } }) @@ -167,22 +167,22 @@ describe('Client inspect completion', () => { it('keeps the first failure when several pages fail', async () => { const query = start() - registry.resolveClientQuery(AGENT_A, query.request.requestId, failure) - registry.resolveClientQuery(AGENT_A, query.request.requestId, { ...failure, message: 'second failure' }) + registry.resolveClientQuery(AGENT_A.id, query.request.requestId, failure) + registry.resolveClientQuery(AGENT_A.id, query.request.requestId, { ...failure, message: 'second failure' }) await vi.advanceTimersByTimeAsync(100) expect(await query.result).toEqual({ error: timeout + 'Client failure: provider-error: page failed', code: 'INSPECT_TIMEOUT' }) }) it('retains output validation errors for timeout diagnostics', async () => { const query = start() - expect(registry.resolveClientQuery(AGENT_A, query.request.requestId, { ok: true, data: {} })).toEqual({ accepted: false }) + expect(registry.resolveClientQuery(AGENT_A.id, query.request.requestId, { ok: true, data: {} })).toEqual({ accepted: false }) await vi.advanceTimersByTimeAsync(100) expect(await query.result).toHaveProperty('error', expect.stringContaining('Client Cordis inspect Service.listService returned invalid output')) }) it('accepts valid output after an invalid response', async () => { const query = start() - registry.resolveClientQuery(AGENT_A, query.request.requestId, { ok: true, data: {} }) + registry.resolveClientQuery(AGENT_A.id, query.request.requestId, { ok: true, data: {} }) expect(answer(query)).toEqual({ accepted: true }) expect(await query.result).toEqual({ value: { name: 'theme' } }) expect(vi.getTimerCount()).toBe(0) @@ -190,7 +190,7 @@ describe('Client inspect completion', () => { it('ignores responses from another Agent without retaining their error', async () => { const query = start() - expect(registry.resolveClientQuery(AGENT_B, query.request.requestId, failure)).toEqual({ accepted: false }) + expect(registry.resolveClientQuery(AGENT_B.id, query.request.requestId, failure)).toEqual({ accepted: false }) await vi.advanceTimersByTimeAsync(100) expect(await query.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.', code: 'INSPECT_TIMEOUT' }) }) diff --git a/packages/extensions/cordis-host-runner/tests/runner.spec.ts b/packages/extensions/cordis-host-runner/tests/runner.spec.ts index cc20275e53..08badab936 100644 --- a/packages/extensions/cordis-host-runner/tests/runner.spec.ts +++ b/packages/extensions/cordis-host-runner/tests/runner.spec.ts @@ -1,5 +1,9 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { brandString } from '@deepseek-ai/dsh-brand' +import TypertGateway from '@deepseek-ai/dsh-api-gateway' +import RemoteAccessService from '@deepseek-ai/dsh-api-remote-access' +import TypertRegistry from '@deepseek-ai/dsh-typert-registry' +import { Peer } from '@deepseek-ai/dsh-client-connection' import type { ApprovalRequestId as ApprovalRequestIdType, CordisDynamicPluginId, } from '../src/types.ts' @@ -25,6 +29,36 @@ const HOST_CODE = ` type Runner = Awaited>['runner'] +it('routes source RPC inspect replies by agentId without resolving an Agent', async () => { + const { ctx } = await setup() + try { + await ctx.plugin(TypertRegistry) + await ctx.plugin(RemoteAccessService) + await ctx.plugin(TypertGateway) + const resolve = vi.fn(() => { throw new Error('Client replies must not resolve an Agent') }) + ctx.typert.lookups.register('agent', { + parameter: 'agent', wire: 'agentId', resource: 'session', + hostTypeSymbol: '@deepseek-ai/dsh-agent#Agent', + wireTypeSymbol: '@deepseek-ai/dsh-session/types#SessionId', + resolve, + }) + const peer = new Peer(ctx, { principal: { kind: 'owner' } }) + try { + // SRC infers lookup parameters from names; built descriptors infer them from types. + expect(ctx.typert.local.get('dynamicCordisRunner/resolveInspectQuery')).toBeUndefined() + await expect(ctx.typertGateway.invoke({ + peer, namespace: 'dynamicCordisRunner', method: 'resolveInspectQuery', + args: { agentId: AGENT_A.id, requestId: 'no-pending-query', resolution: { ok: true, data: {} } }, + })).resolves.toEqual({ accepted: false }) + expect(resolve).not.toHaveBeenCalled() + } finally { + await peer.dispose() + } + } finally { + await ctx.fiber.dispose() + } +}) + function define( runner: Runner, request: { diff --git a/snapshots/session/cordis-inspect-liveness/client-fixture.mjs b/snapshots/session/cordis-inspect-liveness/client-fixture.mjs index dbc7ec448d..c68f28b4c7 100644 --- a/snapshots/session/cordis-inspect-liveness/client-fixture.mjs +++ b/snapshots/session/cordis-inspect-liveness/client-fixture.mjs @@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs' import { registerSilentClientTransport } from '../cordis-inspect-timeout/client-fixture.mjs' export const name = 'client-inspect-liveness-fixture' -export const inject = ['cordisInspect', 'agents', 'llm', 'typertGateway'] +export const inject = ['cordisInspect', 'llm', 'typertGateway'] /** * Leave a disconnected query pending until timeout, then answer after reconnection. @@ -88,9 +88,7 @@ export function apply(ctx) { } assert.equal(queries.length, 2) assert.notEqual(queries[0], request.requestId) - const agent = ctx.agents.get(request.agentId) - assert.ok(agent, 'Client inspect request has an owning Agent') - assert.deepEqual(ctx.cordisInspect.resolveClientQuery(agent, request.requestId, { + assert.deepEqual(ctx.cordisInspect.resolveClientQuery(request.agentId, request.requestId, { ok: true, data: { service: 'remote' }, }), { accepted: true }) diff --git a/snapshots/session/cordis-inspect-timeout/client-fixture.mjs b/snapshots/session/cordis-inspect-timeout/client-fixture.mjs index da4556d4b5..37e3ade25a 100644 --- a/snapshots/session/cordis-inspect-timeout/client-fixture.mjs +++ b/snapshots/session/cordis-inspect-timeout/client-fixture.mjs @@ -4,7 +4,7 @@ import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' export const name = 'client-inspect-timeout-fixture' -export const inject = ['cordisInspect', 'agents', 'llm', 'typertGateway'] +export const inject = ['cordisInspect', 'llm', 'typertGateway'] /** * Register a silent event source and open real Gateway Client streams on demand. @@ -90,9 +90,7 @@ export async function apply(ctx) { let queries = 0 ctx.on('cordis/inspect-query', (request) => { if (++queries !== 1) return - const agent = ctx.agents.get(request.agentId) - if (agent === undefined) throw new Error('Client inspect request has no owning Agent') - ctx.cordisInspect.resolveClientQuery(agent, request.requestId, { + ctx.cordisInspect.resolveClientQuery(request.agentId, request.requestId, { ok: false, reason: 'provider-error', message: 'no catalogued Service named "remote"', diff --git a/tsconfig.host.json b/tsconfig.host.json index a80e298cba..ba4faed880 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -18,6 +18,7 @@ "apps/web/tests/sidebar-drawer.e2e.ts", "apps/web/tests/session-panel-layout.e2e.ts", "apps/web/tests/creation-recommendations.e2e.ts", + "apps/web/tests/cordis-inspect-subagent.e2e.ts", "apps/web/tests/plugin-recommendations.e2e.ts", "apps/web/tests/deepseek-chat-import.e2e.ts", "apps/web/tests/japanese-plugin-metadata.e2e.ts", From 99f8afd16f7db58921dd2d9029e5cd316929a4cc Mon Sep 17 00:00:00 2001 From: zhc Date: Thu, 19 Nov 2026 16:35:02 +0800 Subject: [PATCH 32/54] feat(ui-conversation): recall loaded prompts with ArrowUp and ArrowDown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Web 输入框不能用方向键调出刚发过的消息,修改或重发相似请求时只能重新输入。 候选菜单未处理按键、且光标位于草稿末尾时,不带修饰键的 ArrowUp 和 ArrowDown 按由新到旧的顺序,召回已加载的 Session 历史中用户发出的消息文本(user/message,source.kind 为 user)。召回直接读 Session 事件窗口,composer 不另存历史,刷新页面或切换会话后仍能召回。 - 只有空草稿才能开始浏览;只有草稿仍是上一次显示且未修改的消息时才能继续。任何编辑(包括撤销)都会结束浏览,已输入或改过的文字不会被替换。 - 每次切换都是一次普通的、可撤销的编辑;发送后撤销栈被清空时,会补上撤销基线。 - 按纯文本召回:引用 chip 以 mention 文本出现,quote 以 Markdown 出现;没有文字的消息和连续重复的消息会被跳过;命令、附件和发送失败的提交不召回。 - IME 组字、带修饰键的按键、命令提交或裁决进行中都不触发召回。 Closes #8360 --- apps/web/tests/composer-history.e2e.ts | 116 +++++ apps/web/tsconfig.json | 1 + .../client/ui-conversation/README.i18n.yaml | 8 +- packages/client/ui-conversation/README.md | 3 + packages/client/ui-conversation/README.zh.md | 3 + .../src/client/contract/draft-editor.ts | 12 + .../src/client/input/editor/keymap.ts | 47 +- .../src/client/input/editor/runtime.ts | 40 +- .../src/client/input/editor/view-binding.ts | 4 + .../src/client/input/facade.ts | 72 ++- .../ui-conversation/src/client/input/hub.ts | 1 + .../tests/apply-inject.client.spec.tsx | 2 +- .../tests/composer-history.client.spec.ts | 428 ++++++++++++++++++ .../tests/keymap-routing.client.spec.tsx | 10 +- tsconfig.host.json | 1 + 15 files changed, 725 insertions(+), 23 deletions(-) create mode 100644 apps/web/tests/composer-history.e2e.ts create mode 100644 packages/client/ui-conversation/tests/composer-history.client.spec.ts diff --git a/apps/web/tests/composer-history.e2e.ts b/apps/web/tests/composer-history.e2e.ts new file mode 100644 index 0000000000..2fa8cb0194 --- /dev/null +++ b/apps/web/tests/composer-history.e2e.ts @@ -0,0 +1,116 @@ +/** Composer ArrowUp/ArrowDown recall of loaded prompts in the shipped Web composition. */ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { chromium, type Browser, type Page } from 'playwright' +import { afterAll, beforeAll, expect, it, onTestFailed } from 'vitest' +import type { StreamChunk } from '@deepseek-ai/dsh-llm' +import type { ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay' +import { launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' + +const PROMPTS = ['First history prompt', 'Second history prompt\nwith a second line'] as const + +function reply(text: string): StreamChunk[] { + return [ + { type: 'block-start', index: 0, blockType: 'text' }, + { type: 'text-delta', index: 0, text }, + { type: 'block-end', index: 0, block: { type: 'text', text } }, + { type: 'usage', usage: { inputTokens: 16, outputTokens: 4 } }, + { type: 'finish', reason: { kind: 'stop' } }, + ] +} + +let browser: Browser +let page: Page +let replayDir: string +let scaffold: WebScaffold + +beforeAll(async () => { + replayDir = await mkdtemp(join(tmpdir(), 'dsh-composer-history-')) + const replayOverride = join(replayDir, 'replay.override.json') + const doc: ReplayOverrideDoc = PROMPTS.map((_, index) => ({ kind: 'chunks', chunks: reply(`Reply ${String(index + 1)}`) })) + await writeFile(replayOverride, JSON.stringify(doc)) + scaffold = await launchWebScaffold({ replayFixture: join(replayDir, 'override-only.jsonl'), replayOverride }) + browser = await chromium.launch() + page = await newEnglishPage(browser, 800) + watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd, 'composer-history-e2e') +}, 120_000) + +afterAll(async () => { + await browser?.close() + await scaffold?.close() + if (replayDir !== undefined) await rm(replayDir, { recursive: true, force: true }) +}) + +it.skipIf(webSnapshotMode() === 'record')('recalls loaded prompts with the arrow keys from an empty draft, also after a reload', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-history')) + const composer = page.locator('[data-composer-input][contenteditable="true"]').last() + await composer.waitFor({ timeout: 15_000 }) + for (const [index, prompt] of PROMPTS.entries()) { + const settled = scaffold.whenTurnSettled(30_000) + await composer.fill(prompt) + await composer.press('Enter') + await page.getByText(`Reply ${String(index + 1)}`, { exact: true }).waitFor({ timeout: 15_000 }) + await settled + await expect.poll(() => composer.textContent(), { timeout: 10_000 }).toBe('') + } + // The editor document's plain text: paragraphs and line-break nodes both end a line. + const draft = () => composer.evaluate((element) => { + interface Node { type: string; text?: string; children?: Node[] } + const editor = (element as HTMLElement & { __lexicalEditor: { getEditorState(): { toJSON(): { root: Node } } } }).__lexicalEditor + const line = (node: Node): string => node.type === 'linebreak' ? '\n' : node.text ?? (node.children ?? []).map(line).join('') + return (editor.getEditorState().toJSON().root.children ?? []).map(line).join('\n') + }) + + // Typed text is never displaced: ArrowUp only moves the caret. + await composer.pressSequentially('unsent') + await composer.press('ArrowUp') + expect(await draft()).toBe('unsent') + await composer.press('ControlOrMeta+a') + await composer.press('Backspace') + await expect.poll(draft).toBe('') + + // From an empty draft the arrows walk the history with the caret at the draft end. + await composer.press('ArrowUp') + await expect.poll(draft).toBe(PROMPTS[1]) + await composer.press('ArrowUp') + await expect.poll(draft).toBe(PROMPTS[0]) + // Past the oldest entry the native arrow moves the caret to the line start, + // so the next ArrowDown returns it to the end before recalling again. + await composer.press('ArrowUp') + expect(await draft()).toBe(PROMPTS[0]) + await composer.press('ArrowDown') + expect(await draft()).toBe(PROMPTS[0]) + await composer.press('ArrowDown') + await expect.poll(draft).toBe(PROMPTS[1]) + + // Away from the draft end the arrows move the caret inside the two-line entry. + await composer.press('ArrowLeft') + await composer.press('ArrowUp') + await composer.press('ArrowDown') + expect(await draft()).toBe(PROMPTS[1]) + await composer.press('End') + await composer.press('ArrowUp') + await expect.poll(draft).toBe(PROMPTS[0]) + await composer.press('ArrowDown') + await expect.poll(draft).toBe(PROMPTS[1]) + await composer.press('ArrowDown') + await expect.poll(draft).toBe('') + + // Recall reads the loaded Session history, so it survives a page reload. + await page.reload({ waitUntil: 'load' }) + const reloaded = page.locator('[data-composer-input][contenteditable="true"]').last() + await reloaded.waitFor({ timeout: 15_000 }) + await page.getByText('Reply 2', { exact: true }).waitFor({ timeout: 15_000 }) + await reloaded.click() + await reloaded.press('ArrowUp') + await expect.poll(() => reloaded.evaluate((element) => { + interface Node { type: string; text?: string; children?: Node[] } + const editor = (element as HTMLElement & { __lexicalEditor: { getEditorState(): { toJSON(): { root: Node } } } }).__lexicalEditor + const line = (node: Node): string => node.type === 'linebreak' ? '\n' : node.text ?? (node.children ?? []).map(line).join('') + return (editor.getEditorState().toJSON().root.children ?? []).map(line).join('\n') + })).toBe(PROMPTS[1]) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index b466f7c716..178a4e83c0 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -271,6 +271,7 @@ "tests/chat-scroll-contract.e2e.ts", "tests/chat-long-interactions.e2e.ts", "tests/chat-continuous-conversation.e2e.ts", + "tests/composer-history.e2e.ts", "tests/composer-tab-geometry.e2e.ts", "tests/conversation-view-tabs.e2e.ts", "tests/window-drag-coverage.e2e.ts", diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 43af0180f8..b014c29915 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: a26620af27311633 - zh: 875ec18d3396feee + en: 31c5701ade0335aa + zh: bde078fee666bb86 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry: en: 876be274c65b56d9 zh: c3adbf5a16e0e38e @@ -45,8 +45,8 @@ en: f8621bbc481c26ae zh: 5be844989dc80803 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work: - en: c65789c64093eb47 - zh: b58cccbeea767849 + en: 0db84c3de00194e4 + zh: bf4c4115b90387fb /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index fb110a8223..33e17a24d5 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -90,6 +90,8 @@ The composer exposes `retry(failureSeq)` for failed-generation recovery. The inp The composer uses the shared [text-input focus policy](../ui-primitives/README.md#use-this-package) on mount, Session switching, and unlock. Identified phones and tablets require tapping the input; desktop devices retain automatic focus. On these mobile devices, a submission that empties the focused draft moves focus to the non-text composer card, dismissing the keyboard while retaining its navigation position. Rejected submissions, retained newer draft text, and another control already holding focus preserve focus. The [Lexical patch](../../../patches/lexical@0.49.0.patch) keeps caret scrolling in the same coordinate system as DOM geometry when a mobile keyboard pans the page. +Unmodified ArrowUp and ArrowDown recall the text of human prompts in the loaded Session history when no candidate menu consumes the key and the caret sits at the end of the draft. Browsing starts only from an empty draft and continues only while the draft is the unedited prompt it last showed; any edit, including undo, ends browsing and leaves an ordinary draft, so typed or edited text is never replaced. While browsing, an arrow with the caret elsewhere moves the caret inside the shown prompt. Prompts are read newest first from the Session's event window when the arrow arrives; prompts without text and consecutive repeats are skipped, and moving past the newest prompt returns to the empty draft. Each step is an ordinary undoable edit: undo returns to the draft shown before the step. + The context-occupancy button shows a ring and percentage below the input card, after the Session statistics. Clicking it opens the token breakdown in a CSS-anchored panel bounded by the layout viewport, including when no statistics are shown; the button stays hidden until context usage and capacity are available. Browser zoom and panning move the panel with the page, so it may extend beyond the visual viewport. Outside the Hero, that row keeps one reading's height while it is empty, so statistics and context usage arriving later do not change the composer's height; the Hero shows no empty row. With Coding Tools off, the shell hides only Trajectory; other plugin-contributed Views remain available. The View tab bar is hidden when fewer than two Views are available. Turning Coding Tools off while Trajectory is active returns to Chat; stored View preferences and recorded Session data remain intact. Turning it on makes Trajectory available again. View owners receive the available roster so their navigation actions can follow the same visibility. @@ -240,6 +242,7 @@ Serialization of the empty retry message depends on the adapter. Prefix reuse de - **A reload discards draft attachments** — only switching between Sessions keeps them; after a reload the reopened composer reports the loss and asks the user to add them again, and a crash leaves no notice. While a Session is not shown, a pasted image keeps its bytes in memory ([decision](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.md)). - **Document file drops are not routed** — every mounted attachment view handles a document-level file drop, so with a continuable subagent chat open in the right Sidebar one drop adds the files to both composers; only window pastes pass through the single paste route. - **A failing Definition costs a full replay per publication** — after an incremental flush fails, the assembler replays the complete loaded window to keep the views correct. A Definition that fails on every update therefore replays the whole window on each publication until its owner fixes it ([window update paths](../../../docs/subsystems/conversation.md#window-update-paths)). +- **Prompt recall reads loaded history as plain text** — only prompts already in the Client event window are recalled, so older pages are reachable only after they load. Recall restores the prompt's text blocks: reference chips return as their mention text, quotes as their Markdown, and attachments are not restored. Prompts without text, such as an attachment-only submission, are skipped, and commands record no user prompt, so neither is recalled. A failed submission is not recalled because it never entered the log; the draft keeps it instead. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 3c0a13038e..c1e91ada17 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -90,6 +90,8 @@ composer 提供 `retry(failureSeq)` 处理生成失败后的恢复。输入栏 composer 在挂载、切换 Session 和解除锁定时使用共享的[文字输入框聚焦策略](../ui-primitives/README.zh.md#use-this-package)。识别出的手机和平板需要点击输入框;桌面设备保留自动聚焦。在这些移动设备上,提交清空正在聚焦的草稿后,焦点移到不接受文字输入的 composer 卡片,收起键盘并保留键盘导航位置。被拒绝的提交、保留的新草稿文字,以及已经聚焦的其他控件均保留原有焦点。移动端键盘平移页面时,[Lexical 补丁](../../../patches/lexical@0.49.0.patch)让光标滚动计算与 DOM 几何使用同一坐标系。 +候选菜单未处理按键且光标位于草稿末尾时,不带修饰键的 ArrowUp 和 ArrowDown 会召回已加载的 Session 历史中用户发出的消息文本。只有草稿为空时才能开始浏览,只有草稿仍是上一次显示且未修改的消息时才能继续浏览;任何修改(包括撤销)都会结束浏览,草稿变成普通草稿,因此已输入或改过的文字不会被替换。浏览期间光标不在末尾时,方向键在当前消息内移动光标。按键时从 Session 的事件窗口由新到旧读取消息;没有文字的消息和连续重复的消息会被跳过,越过最新一条时回到空草稿。每次切换都是一次普通的、可撤销的编辑:撤销回到切换前显示的草稿。 + 上下文占用按钮在输入卡片下方、会话统计右侧显示圆环和百分比。点击按钮可在受布局视口约束的 CSS 锚定面板中查看 token 构成,没有统计项时也可打开;上下文用量和容量尚不可用时,按钮保持隐藏。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。Hero 之外,这一行为空时仍保留一项读数的高度,因此会话统计和上下文用量稍后到达不会改变 composer 的高度;Hero 不显示空行。 关闭代码工作工具时,外壳仅隐藏 Trajectory;其他插件贡献的 View 仍然可用。可用 View 少于两个时隐藏 View 标签栏。在 Trajectory 激活时关闭代码工作工具会返回 Chat;已保存的 View 偏好和 Session 记录保持不变。开启后,Trajectory 恢复可用。View 所有者接收可用列表,使导航操作跟随相同的可见性。 @@ -240,6 +242,7 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match - **刷新会丢弃草稿附件**——只有在 Session 之间切换时附件才会保留;刷新后重新打开的输入框会提示丢失并请用户重新添加,崩溃时不会有提示。Session 未显示期间,粘贴的图片会把字节保留在内存中([决策](../../../.agents/notes/implemented/bug-fix/2026-11-13-draft-attachments-across-session-switches.zh.md))。 - **文档级文件拖放未经路由**——每个已挂载的附件视图都会处理文档级文件拖放,因此在右侧栏打开可继续的子代理对话时,一次拖放会把文件同时加入两个 composer;只有窗口级粘贴经过单一的粘贴路由。 - **出错的 Definition 让每次发布都完整回放**——增量 flush 失败后,assembler 回放已加载的完整窗口,以保持视图正确。若某个 Definition 在每次更新中都失败,在其 owner 修复前,每次发布都会回放整个窗口([Window 更新路径](../../../docs/subsystems/conversation.zh.md#window-update-paths))。 +- **消息召回按纯文本读取已加载的历史**——只召回已在 Client 事件窗口中的消息,更早的分页加载后才能召回。召回只还原消息的文本块:引用 chip 以 mention 文本出现,quote 以 Markdown 出现,附件不会还原。没有文字的消息(例如只带附件的提交)会被跳过,命令不会产生用户消息,因此两者都不召回。失败的提交从未写入日志,所以不召回,草稿会保留它。 diff --git a/packages/client/ui-conversation/src/client/contract/draft-editor.ts b/packages/client/ui-conversation/src/client/contract/draft-editor.ts index 86592a82db..ece545cb16 100644 --- a/packages/client/ui-conversation/src/client/contract/draft-editor.ts +++ b/packages/client/ui-conversation/src/client/contract/draft-editor.ts @@ -100,6 +100,18 @@ export interface ComposerKeyboard { space(): boolean /** Dismiss the popupSelect shell (any interaction outside the box). */ dismissPopup(): void + /** + * Replace the draft with the text of an adjacent human prompt in the loaded + * Session history; the caller passes only arrows with the caret at the + * draft end. Browsing starts from an empty draft and continues only while + * the draft is the unedited prompt it last showed, so typed or edited text + * is never replaced; moving past the newest prompt returns to the empty + * draft. Each step is an ordinary undoable edit. + * @param direction - history direction. + * @returns whether an adjacent prompt exists and the replacement is scheduled; + * inside a key command it runs after that update, and the caller consumes the key. + */ + recallHistory(direction: 'older' | 'newer'): boolean /** * Bind the mounted composer's file action and live intake availability. * @param picker - availability query and native file-dialog opener. diff --git a/packages/client/ui-conversation/src/client/input/editor/keymap.ts b/packages/client/ui-conversation/src/client/input/editor/keymap.ts index 8a3435d941..31c4a40c34 100644 --- a/packages/client/ui-conversation/src/client/input/editor/keymap.ts +++ b/packages/client/ui-conversation/src/client/input/editor/keymap.ts @@ -1,10 +1,11 @@ /** * Composer keymap over the Lexical command layer: menu arbitration - * (arrows/escape/enter), space adjudication, the Enter submit gesture, and - * paste routing. Registered at CRITICAL priority so it decides before - * @lexical/plain-text's own Enter/paste defaults; a handler returning false - * falls through to those defaults (Shift+Enter's line break, ordinary - * spaces, text paste the bar routes itself). + * (arrows/escape/enter), prompt recall on draft-end arrows, space + * adjudication, the Enter submit gesture, and paste routing. Registered at + * CRITICAL priority so it decides before @lexical/plain-text's own + * Enter/paste defaults; a handler returning false falls through to those + * defaults (Shift+Enter's line break, ordinary spaces, text paste the bar + * routes itself). * * IME guard: a composition-closing Enter/Space must not submit or adjudicate. * KeyboardEvent.isComposing covers most engines; Safari delivers the closing @@ -16,7 +17,7 @@ */ import type { LexicalEditor } from 'lexical' import { - $getAdjacentNode, $getSelection, $isElementNode, $isLineBreakNode, $isRangeSelection, $isTextNode, + $createRangeSelectionFromDom, $getAdjacentNode, $getSelection, $isElementNode, $isLineBreakNode, $isRangeSelection, $isTextNode, KEY_DOWN_COMMAND, MOVE_TO_END, COMMAND_PRIORITY_CRITICAL, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_UP_COMMAND, KEY_ENTER_COMMAND, KEY_ESCAPE_COMMAND, KEY_SPACE_COMMAND, KEY_TAB_COMMAND, PASTE_COMMAND, @@ -24,6 +25,7 @@ import { import { mergeRegister } from '@lexical/utils' import type { ArbitrateKey, ArbitrateOutcome } from '../../contract/draft-editor.ts' import { clipboardFiles } from '../file-intake.ts' +import { $composerLayout, $detectOffsetOfPoint } from './projection.ts' import { $isQuoteNode } from './QuoteNode.tsx' /** The bar-supplied behavior behind each intercepted gesture. */ @@ -34,6 +36,8 @@ export interface ComposerKeymapHandlers { space(): boolean /** Dismiss the popupSelect shell (Escape layering: an open overlay closes first). */ dismissPopup(): void + /** Replace the draft with an adjacent recalled prompt when recall applies; true = the arrow is consumed. */ + recallHistory(direction: 'older' | 'newer'): boolean /** Whether Enter may submit right now (locked/busy states refuse). */ canSubmit(): boolean /** Plain Enter submits; exactly Ctrl+Enter or Cmd+Enter selects accelerated delivery. */ @@ -86,6 +90,21 @@ function domCaretTouches(element: HTMLElement, backward: boolean): boolean { && (backward ? boundary.previousSibling : boundary.nextSibling) === element } +/** + * Whether the collapsed browser caret sits at the end of the draft. Must run + * inside an editor update. The DOM selection is mapped directly because + * Lexical's own selection lags a native caret move until the next + * selectionchange. + */ +function $caretAtDraftEnd(editor: LexicalEditor): boolean { + const domSelection = editor.getRootElement()?.ownerDocument.getSelection() ?? null + if (domSelection === null || domSelection.rangeCount === 0 || !domSelection.isCollapsed) return false + const point = $createRangeSelectionFromDom(domSelection, editor)?.focus + if (point === undefined) return false + const layout = $composerLayout() + return $detectOffsetOfPoint(layout, point) === layout.detectLength +} + /** Find an atomic quote immediately beside both editor and browser carets. */ function adjacentQuote(editor: LexicalEditor, backward: boolean) { const selection = $getSelection() @@ -229,6 +248,18 @@ export function registerComposerKeymap(editor: LexicalEditor, handlers: Composer return false } + // An unmodified arrow the menu passes may recall prompts only with + // the caret at the draft end; the handler decides whether recall applies. + const history = (key: 'up' | 'down') => (event: KeyboardEvent): boolean => { + if (arrow(key)(event)) return true + if (isComposingEvent(event, recentlyComposing) + || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return false + if (!$caretAtDraftEnd(editor)) return false + if (!handlers.recallHistory(key === 'up' ? 'older' : 'newer')) return false + event.preventDefault() + return true + } + return mergeRegister( editor.registerRootListener((root, prevRoot) => { prevRoot?.removeEventListener('compositionstart', onCompositionStart) @@ -254,8 +285,8 @@ export function registerComposerKeymap(editor: LexicalEditor, handlers: Composer return movePastQuote(editor, event) }, COMMAND_PRIORITY_CRITICAL), editor.registerUpdateListener(syncComposition), - editor.registerCommand(KEY_ARROW_UP_COMMAND, arrow('up'), COMMAND_PRIORITY_CRITICAL), - editor.registerCommand(KEY_ARROW_DOWN_COMMAND, arrow('down'), COMMAND_PRIORITY_CRITICAL), + editor.registerCommand(KEY_ARROW_UP_COMMAND, history('up'), COMMAND_PRIORITY_CRITICAL), + editor.registerCommand(KEY_ARROW_DOWN_COMMAND, history('down'), COMMAND_PRIORITY_CRITICAL), // Tab settles the highlighted completion and passes without one, keeping // native focus traversal; Shift+Tab leaves the menu like Escape whenever it // is open, highlight or not, so the two Tab gestures never disagree about diff --git a/packages/client/ui-conversation/src/client/input/editor/runtime.ts b/packages/client/ui-conversation/src/client/input/editor/runtime.ts index bed9912426..dbe711ea2d 100644 --- a/packages/client/ui-conversation/src/client/input/editor/runtime.ts +++ b/packages/client/ui-conversation/src/client/input/editor/runtime.ts @@ -11,6 +11,7 @@ import { } from 'lexical' import { registerPlainText } from '@lexical/plain-text' import { createEmptyHistoryState, registerHistory } from '@lexical/history' +import type { HistoryState } from '@lexical/history' import { mergeRegister } from '@lexical/utils' import type { DraftQuote, DraftReference, ReferenceInsert } from '../../contract/draft-editor.ts' import type { CommandClaim } from '../../contract/input.ts' @@ -79,6 +80,8 @@ export class DraftEditorRuntime { /** Live lexicon subscription disposer; undefined until the controller resolves. */ private lexiconOff: (() => void) | undefined private lexiconSource: ObservableSnapshot | undefined + /** Undo and redo state owned by the registered history listener. */ + private readonly history: HistoryState = createEmptyHistoryState() /** @param deps - model callbacks used by editor listeners and transforms. */ constructor(private readonly deps: DraftEditorRuntimeDeps) { @@ -117,7 +120,7 @@ export class DraftEditorRuntime { this.editor.registerNodeTransform(RootNode, preserveExternalSelection), registerReferenceActivation(this.editor, (source, reference) => this.deps.openReference(source, reference)), - registerHistory(this.editor, createEmptyHistoryState(), HISTORY_MERGE_DELAY_MS), + registerHistory(this.editor, this.history, HISTORY_MERGE_DELAY_MS), this.editor.registerUpdateListener(() => { this.deps.onUpdate() }), registerCommandChipSeat(this.editor), registerCommandChipSelection(this.editor), @@ -159,6 +162,19 @@ export class DraftEditorRuntime { this.editor.update(fn, { discrete: true, ...(tag === undefined ? {} : { tag }) }) } + /** + * Run a top-level edit now, or in a microtask when called from inside an + * update of this editor (a key command handler). Nested edits and update + * callbacks both run while the editor still counts as updating, so the + * edit's revision would not be observable when it returns. + * @param fn - the edit, run outside any update. + */ + afterUpdate(fn: () => void): void { + // Not an update onUpdate callback: it runs while the editor still commits, where a new update is unsafe. + if (this.editor._updating) queueMicrotask(fn) + else fn() + } + /** * Reconnect decorations when the optional trigger provider changes. * The rescan reads the current editor and does not replace its content. @@ -194,16 +210,19 @@ export class DraftEditorRuntime { /** * Replace the whole draft (persisted-draft seed and programmatic writes). * Placeholder-sanitized; newlines split paragraphs; the caret lands at the - * end. Merged into history so a seed is not an undoable step of its own. + * end. Merged into history so a seed is not an undoable step of its own, + * unless `undoable` makes the replacement its own undo step. * @param text - the full next draft. + * @param undoable - record the replacement as a separate undo step. */ - setDraft(text: string): void { + setDraft(text: string, undoable = false): void { const clean = text.replace(REFERENCE_PLACEHOLDER_RE, '') if (clean === this.projection.clipboardText && this.projection.occurrences.length === 0 && this.projection.quotes.length === 0) return + if (undoable) this.keepUndoBaseline() this.editor.update(() => { $getRoot().clear() $appendParagraphs(clean) - }, { discrete: true, tag: HISTORY_MERGE_TAG }) + }, { discrete: true, tag: undoable ? HISTORY_PUSH_TAG : HISTORY_MERGE_TAG }) } /** @@ -472,6 +491,19 @@ export class DraftEditorRuntime { }, { discrete: true, tag: HISTORY_MERGE_TAG }) } + /** + * Make the current document the undo target of the next pushed step. A cut + * history (after a submission) has no current entry to undo to, and Lexical + * refuses to restore a root without a paragraph, so an empty root gains one first. + */ + private keepUndoBaseline(): void { + if (this.history.current !== null) return + if (this.editor.getEditorState().read(() => $getRoot().isEmpty())) { + this.editor.update(() => { $getRoot().append($createParagraphNode()) }, { discrete: true, tag: HISTORY_MERGE_TAG }) + } + this.history.current = { editor: this.editor, editorState: this.editor.getEditorState() } + } + /** Cut the editor's undo history after a committed clear or restoration. */ clearHistory(): void { this.editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined) diff --git a/packages/client/ui-conversation/src/client/input/editor/view-binding.ts b/packages/client/ui-conversation/src/client/input/editor/view-binding.ts index 9018592b8b..477d7295bd 100644 --- a/packages/client/ui-conversation/src/client/input/editor/view-binding.ts +++ b/packages/client/ui-conversation/src/client/input/editor/view-binding.ts @@ -136,6 +136,10 @@ export function installDraftKeymap( return keyboard.space() }, dismissPopup: () => { keyboard.dismissPopup() }, + recallHistory: (direction) => { + if (gate.current.machineBusy || gate.current.locked) return false + return keyboard.recallHistory(direction) + }, canSubmit: () => !gate.current.locked && !gate.current.machineBusy, submit: (accelerated) => { const g = gate.current diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 393c88944c..75e471df19 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -10,7 +10,8 @@ */ import type { Context } from '@deepseek-ai/cordis' import type { InboxState } from '@deepseek-ai/dsh-agent/types' -import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionEventLikeEntry, SessionEventSource, SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionSeq } from '@deepseek-ai/dsh-session/types' import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore, } from '@deepseek-ai/dsh-client-store' @@ -55,6 +56,8 @@ export interface SessionInputDeps { popup?: (() => PopupDismissFace | undefined) | undefined /** Agent Inbox projection; its next-turn list is overlaid onto InputState.queue. */ inbox?: ObservableSnapshot | undefined + /** Loaded Session event window whose human prompts the arrow keys recall; absent = no recall. */ + events?: SessionEventSource | undefined /** * Steer every still-pending queued message into the running turn, in FIFO * order (the empty-draft accelerated-Enter gesture); absent = unsupported. @@ -131,6 +134,34 @@ function errorText(error: unknown): string { const EMPTY_QUEUE: InboxState['next-turn'] = [] +/** One recallable prompt; a run of consecutive identical prompts folds into one, spanning `oldest`..`newest`. */ +interface LoadedPrompt { + readonly text: string + readonly newest: SessionSeq + oldest: SessionSeq +} + +/** + * The recallable human prompts of a loaded event window, newest first: + * their joined text blocks, skipping prompts without text and folding + * consecutive repeats. + * @param entries - the loaded window, oldest first. + * @returns prompts newest first. + */ +function loadedPrompts(entries: readonly SessionEventLikeEntry[]): readonly LoadedPrompt[] { + const prompts: LoadedPrompt[] = [] + for (let index = entries.length - 1; index >= 0; index -= 1) { + const entry = entries[index] + if (entry?.type !== 'event' || entry.event.type !== 'user/message' || entry.event.data.source.kind !== 'user') continue + const text = entry.event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + if (text.trim() === '') continue + const last = prompts.at(-1) + if (last?.text === text) last.oldest = entry.event.seq + else prompts.push({ text, newest: entry.event.seq, oldest: entry.event.seq }) + } + return prompts +} + /** Unavailable catalogs contain no named text references. */ const EMPTY_LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map() @@ -186,6 +217,14 @@ export class SessionInputShell implements SessionInput { /** The mounted composer's file-picker opener (scoped pick-files event target). */ private filePicker: Parameters[0] | undefined private readonly unsubscribeInbox: (() => void) | undefined + /** + * The log seq of the recalled prompt the draft shows and the draft revision + * that showed it. Neighbours are looked up by seq in the current window on + * every arrow, so prompts appended or loaded while browsing do not shift + * the position. Any later content change, including an undo, leaves the + * revisions unequal and ends browsing. + */ + private recallPosition: { readonly seq: SessionSeq; readonly rev: number } | undefined constructor(private readonly deps: SessionInputDeps) { this.draftEditor = new DraftEditorRuntime({ @@ -232,6 +271,7 @@ export class SessionInputShell implements SessionInput { */ setDraft(text: DraftInput): void { const draft = resolveDraftInput(text) + this.recallPosition = undefined this.cancelCommandRestore() if (draft.references.length === 0 && (draft.quotes?.length ?? 0) === 0) this.draftEditor.setDraft(draft.text) else this.draftEditor.restoreDraft(draft.text, draft.references, draft.quotes, { remove: this.deps.quoteRemoveLabel?.() ?? '' }) @@ -493,6 +533,36 @@ export class SessionInputShell implements SessionInput { // update listener re-tracks at the settled caret on its own. } + /** + * Step through the human prompts in the loaded Session history as plain + * text. Browsing starts from an empty draft and continues only while the + * draft is the unedited prompt it last showed. Inside an editor update (a + * key command), the replacement runs in a microtask after that update. + * @param direction - history direction. + * @returns whether an adjacent prompt exists and the replacement is scheduled. + */ + recallHistory(direction: 'older' | 'newer'): boolean { + const phase = this.core.state.phase + if (this.disposed || (phase !== 'plain' && phase !== 'claimed')) return false + const prompts = loadedPrompts(this.deps.events?.getSnapshot().entries ?? []) + // -1 is the empty draft before the newest prompt. + let index = -1 + const position = this.recallPosition?.rev === this.rev ? this.recallPosition : undefined + if (position !== undefined) index = prompts.findIndex(prompt => prompt.oldest <= position.seq && position.seq <= prompt.newest) + else if (this.projection.clipboardText !== '') return false + if (position !== undefined && index < 0) return false + index += direction === 'older' ? 1 : -1 + if (index < -1 || index >= prompts.length) return false + const target = index < 0 ? undefined : prompts[index] + this.draftEditor.afterUpdate(() => { + // An undoable edit: undo returns to the draft shown before the step. + this.cancelCommandRestore() + this.draftEditor.setDraft(target?.text ?? '', true) + this.recallPosition = target === undefined ? undefined : { seq: target.newest, rev: this.rev } + }) + return true + } + /** Dismiss the popupSelect shell (any interaction outside the box). */ dismissPopup(): void { this.deps.popup?.()?.dismiss() diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index ad18048d26..397a90b7a4 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -178,6 +178,7 @@ export class InputHub implements SessionInputResolver { inputTriggers: () => this.controller(actx), popup: () => this.popup(actx), inbox: session.projections.faceOf('inbox') as ObservableSnapshot, + events: binding.eventSource, defaultSink: (text, attachmentIds, mode, signal, accept) => this.sink(session, text, attachmentIds, mode, signal, accept), quoteRemoveLabel: () => this.t('quote.remove'), session: () => session.getSnapshot(), diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index 06e4ccd5cb..b99aaef353 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -610,7 +610,7 @@ describe('Conversation inject API', () => { text.select(0, 2) }, { discrete: true }) const off = registerComposerKeymap(editor, { - arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit: () => {}, pasteText: (text) => { composer.keyboard!.paste(text) }, intakeFiles: (files, directories) => { expect(composer.addFiles?.(files, directories)).toBeNull() }, }) diff --git a/packages/client/ui-conversation/tests/composer-history.client.spec.ts b/packages/client/ui-conversation/tests/composer-history.client.spec.ts new file mode 100644 index 0000000000..9df661774a --- /dev/null +++ b/packages/client/ui-conversation/tests/composer-history.client.spec.ts @@ -0,0 +1,428 @@ +// @vitest-environment jsdom +/** Prompt recall from the loaded Session history through the real input shell and the composer keymap. */ +import { setImmediate } from 'node:timers/promises' +import { Context } from '@deepseek-ai/cordis' +import { MutableSessionEventSource } from '@deepseek-ai/dsh-api-session-controller/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm' +import { SessionSeq } from '@deepseek-ai/dsh-session/types' +import { fireEvent } from '@testing-library/react' +import { + $createLineBreakNode, $createParagraphNode, $createTextNode, $getRoot, CLEAR_HISTORY_COMMAND, createEditor, KEY_ARROW_UP_COMMAND, + UNDO_COMMAND, +} from 'lexical' +import { registerPlainText } from '@lexical/plain-text' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { CommandClaim, InputTriggerController, SubmitOutcome } from '../src/client/contract/input.ts' +import { registerComposerKeymap } from '../src/client/input/editor/keymap.ts' +import { installDraftKeymap } from '../src/client/input/editor/view-binding.ts' +import { SessionInputShell, type SessionInputDeps } from '../src/client/input/facade.ts' + +/** A loaded event window; `prompt` appends one durable user message, newest last. */ +function history() { + const events = new MutableSessionEventSource() + // Starts above zero so a test can prepend an older page. + let seq = 10 + const message = (content: readonly ContentBlock[], source: MessageSource = { kind: 'user' }): void => { + events.append({ type: 'event', event: { + type: 'user/message', seq: SessionSeq(seq++), time: 0, surfaceOp: 'append', + data: createUserMessage({ content: [...content], source }), + } }) + } + return { events, message, prompt: (text: string) => { message([{ type: 'text', text }]) } } +} + +function makeShell(overrides: Partial = {}): SessionInputShell { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const shell = new SessionInputShell({ + actx: ctx, + defaultSink: () => Promise.resolve({ kind: 'success' }), + commandAttachments: { serialize: () => Promise.resolve([]), release: () => {}, unsupportedNotice: token => token }, + ...overrides, + }) + onTestFinished(() => { shell.dispose() }) + return shell +} + +function withPrompts(...prompts: readonly string[]) { + const h = history() + for (const text of prompts) h.prompt(text) + return { ...h, shell: makeShell({ events: h.events }) } +} + +function triggers(claim: CommandClaim): InputTriggerController { + return { + lexicon: createSnapshotStore(new Map()), + launcher: createSnapshotStore(null), + track: () => {}, + arbitrate: () => 'pass', + onSpace: () => false, + serializeReference: (_source, ref) => Promise.resolve(ref), + adjudicate: () => Promise.resolve(undefined), + resolveClaim: () => Promise.resolve(claim), + openReference: () => false, + toggleSource: () => {}, + } +} + +async function undo(shell: SessionInputShell): Promise { + shell.editor.dispatchCommand(UNDO_COMMAND, undefined) + await setImmediate() + return shell.snapshot.draft +} + +describe('loaded prompt recall', () => { + it('steps through loaded prompts from an empty draft and returns to it past the newest', () => { + const { shell } = withPrompts('first', 'second') + expect(shell.recallHistory('newer')).toBe(false) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('second') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('first') + expect(shell.recallHistory('older')).toBe(false) + expect(shell.recallHistory('newer')).toBe(true) + expect(shell.snapshot.draft).toBe('second') + expect(shell.recallHistory('newer')).toBe(true) + expect(shell.snapshot.draft).toBe('') + expect(shell.recallHistory('newer')).toBe(false) + }) + + it('recalls nothing without an event window or loaded prompts', () => { + expect(makeShell().recallHistory('older')).toBe(false) + expect(withPrompts().shell.recallHistory('older')).toBe(false) + }) + + it('never replaces typed text', () => { + const { shell } = withPrompts('sent') + shell.setDraft('typed') + expect(shell.recallHistory('older')).toBe(false) + expect(shell.snapshot.draft).toBe('typed') + }) + + it('ends browsing once a recalled prompt is edited', () => { + const { shell } = withPrompts('first', 'second') + expect(shell.recallHistory('older')).toBe(true) + shell.paste(' edited') + expect(shell.recallHistory('older')).toBe(false) + expect(shell.recallHistory('newer')).toBe(false) + expect(shell.snapshot.draft).toBe('second edited') + shell.setDraft('') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('second') + }) + + it('ends browsing when the draft is replaced programmatically', () => { + const { shell } = withPrompts('sent') + expect(shell.recallHistory('older')).toBe(true) + shell.setDraft('replacement') + expect(shell.recallHistory('newer')).toBe(false) + expect(shell.snapshot.draft).toBe('replacement') + }) + + it('undoes each step as an ordinary edit, back to the empty draft', async () => { + const { shell } = withPrompts('first', 'second') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.recallHistory('older')).toBe(true) + shell.paste(' edited') + expect(await undo(shell)).toBe('first') + expect(shell.recallHistory('newer')).toBe(false) + expect(await undo(shell)).toBe('second') + expect(await undo(shell)).toBe('') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('second') + }) + + it('keeps an undo target after a submission cut the history', async () => { + const h = history() + const shell = makeShell({ events: h.events }) + shell.setDraft('sent') + shell.submit() + await setImmediate() + h.prompt('sent') + expect(shell.snapshot.draft).toBe('') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('sent') + expect(await undo(shell)).toBe('') + }) + + it('undoes the first step to the existing empty paragraph after the history was cut', async () => { + const { shell } = withPrompts('sent') + shell.setDraft('draft') + shell.setDraft('') + shell.editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined) + expect(shell.recallHistory('older')).toBe(true) + expect(await undo(shell)).toBe('') + }) + + it('recalls only human prompts with text, as plain text, and folds consecutive repeats', () => { + const h = history() + h.prompt('older') + h.prompt('again') + h.prompt('again') + h.message([{ type: 'text', text: 'injected context' }], { kind: 'retry' } as MessageSource) + h.message([{ type: 'text', text: '' }]) + h.message([{ type: 'text', text: 'see ' }, { type: 'reasoning', text: 'not prompt text ' }, { type: 'text', text: '@src/a.ts' }]) + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('see @src/a.ts') + expect(shell.snapshot.occurrences).toHaveLength(0) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('again') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('older') + expect(shell.recallHistory('older')).toBe(false) + }) + + it('keeps its place when a prompt is appended or an older page loads while browsing', () => { + const h = history() + h.prompt('A') + h.prompt('B') + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('B') + h.prompt('C') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('A') + expect(shell.recallHistory('newer')).toBe(true) + expect(shell.snapshot.draft).toBe('B') + expect(shell.recallHistory('newer')).toBe(true) + expect(shell.snapshot.draft).toBe('C') + h.events.prepend([{ type: 'event', event: { + type: 'user/message', seq: SessionSeq(0), time: 0, surfaceOp: 'append', + data: createUserMessage({ content: [{ type: 'text', text: 'older page' }], source: { kind: 'user' } }), + } }], false) + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('B') + }) + + it('stays on a folded repeat when its newest copy is appended while browsing', () => { + const h = history() + h.prompt('A') + h.prompt('B') + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(true) + h.prompt('B') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('A') + }) + + it('stops browsing when the shown prompt left the window', () => { + const h = history() + h.prompt('A') + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(true) + h.events.replace([], false) + expect(shell.recallHistory('older')).toBe(false) + expect(shell.snapshot.draft).toBe('A') + }) + + it('reads the window as it is when the arrow arrives', () => { + const h = history() + const shell = makeShell({ events: h.events }) + expect(shell.recallHistory('older')).toBe(false) + h.prompt('arrived later') + expect(shell.recallHistory('older')).toBe(true) + expect(shell.snapshot.draft).toBe('arrived later') + }) + + it('replaces a claimed command draft and cancels its pending chip restore', async () => { + const claim: CommandClaim = { name: 'goal', token: '/goal ', submit: () => Promise.resolve({ kind: 'success' }) } + const pending = Promise.withResolvers() + const h = history() + h.prompt('plain') + const shell = makeShell({ events: h.events, inputTriggers: () => ({ ...triggers(claim), resolveClaim: () => pending.promise }) }) + shell.setDraft({ text: '', references: [], command: { token: '/goal ' } }) + expect(shell.recallHistory('older')).toBe(true) + pending.resolve(claim) + await setImmediate() + expect(shell.draftSnapshot).toEqual({ text: 'plain', references: [] }) + expect(shell.snapshot.phase).toBe('plain') + }) + + it('recalls through the key command after its update commits', async () => { + const { shell } = withPrompts('sent') + const root = document.createElement('div') + root.contentEditable = 'true' + document.body.append(root) + onTestFinished(() => { shell.editor.setRootElement(null); root.remove() }) + shell.editor.setRootElement(root) + onTestFinished(registerComposerKeymap(shell.editor, { + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory: direction => shell.recallHistory(direction), + canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, + })) + window.getSelection()?.collapse(root.firstElementChild ?? root, 0) + expect(fireEvent.keyDown(root, { key: 'ArrowUp' })).toBe(false) + await setImmediate() + expect(shell.snapshot.draft).toBe('sent') + }) + + it('refuses while a submission holds the draft and after disposal', async () => { + let release: (outcome: SubmitOutcome) => void = () => {} + const claim: CommandClaim = { + name: 'goal', token: '/goal ', + submit: () => new Promise((resolve) => { release = resolve }), + } + const { shell } = withPrompts('sent') + shell.setDraft('/goal ') + shell.beginCommand(claim, { start: 0, end: 6, draftRev: shell.snapshot.draftRev }) + shell.submit() + expect(shell.snapshot.phase).toBe('submitting') + expect(shell.recallHistory('older')).toBe(false) + release({ kind: 'success' }) + await setImmediate() + shell.dispose() + expect(shell.recallHistory('older')).toBe(false) + }) +}) + +describe('history arrow routing', () => { + function bench(...lines: readonly string[]) { + const editor = createEditor({ namespace: 'history-arrows', onError: (error) => { throw error } }) + const root = document.createElement('div') + root.contentEditable = 'true' + document.body.append(root) + onTestFinished(() => { editor.setRootElement(null); root.remove() }) + editor.setRootElement(root) + onTestFinished(registerPlainText(editor)) + const recallHistory = vi.fn<(direction: 'older' | 'newer') => boolean>(() => true) + const arbitrate = vi.fn((): 'consumed' | 'pass' => 'pass') + onTestFinished(registerComposerKeymap(editor, { + arbitrate, space: () => false, dismissPopup: () => {}, recallHistory, + canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, + })) + editor.update(() => { + for (const line of lines) { + const paragraph = $createParagraphNode() + for (const [index, part] of line.split('\n').entries()) { + if (index > 0) paragraph.append($createLineBreakNode()) + if (part !== '') paragraph.append($createTextNode(part)) + } + $getRoot().append(paragraph) + } + }, { discrete: true }) + /** Collapse the DOM caret at a child offset of one paragraph, or inside that child's text. */ + const caret = (line: number, offset = 0, child?: number): void => { + const block = root.children.item(line) + if (block === null) throw new Error(`missing line ${String(line)}`) + const text = child === undefined ? undefined : block.childNodes.item(child)?.firstChild + if (child !== undefined && (text === undefined || text === null)) throw new Error(`missing text ${String(child)}`) + window.getSelection()?.collapse(text ?? block, offset) + } + const key = (name: 'ArrowUp' | 'ArrowDown', init: KeyboardEventInit = {}): boolean => + fireEvent.keyDown(root, { key: name, ...init }) + return { root, recallHistory, arbitrate, caret, key } + } + + it('recalls on unmodified arrows the menu passes and consumes the key', () => { + const b = bench('draft') + b.caret(0, 5, 0) + expect(b.key('ArrowUp')).toBe(false) + expect(b.recallHistory).toHaveBeenLastCalledWith('older') + expect(b.key('ArrowDown')).toBe(false) + expect(b.recallHistory).toHaveBeenLastCalledWith('newer') + b.recallHistory.mockReturnValue(false) + expect(b.key('ArrowUp')).toBe(true) + }) + + it.each([{ shiftKey: true }, { altKey: true }, { ctrlKey: true }, { metaKey: true }, { isComposing: true }])( + 'leaves %j arrows to the browser', (init) => { + const b = bench('draft') + b.caret(0, 5, 0) + expect(b.key('ArrowUp', init)).toBe(true) + expect(b.recallHistory).not.toHaveBeenCalled() + }, + ) + + it('lets an open menu consume the arrow first', () => { + const b = bench('draft') + b.caret(0, 5, 0) + b.arbitrate.mockReturnValue('consumed') + expect(b.key('ArrowUp')).toBe(false) + expect(b.recallHistory).not.toHaveBeenCalled() + }) + + it('recalls only with a collapsed caret at the draft end', () => { + const b = bench('top', '', 'bottom') + b.caret(0, 0, 0) + expect(b.key('ArrowUp')).toBe(true) + b.caret(1) + expect(b.key('ArrowDown')).toBe(true) + b.caret(2, 3, 0) + expect(b.key('ArrowUp')).toBe(true) + b.caret(2, 0, 0) + window.getSelection()?.extend(window.getSelection()?.anchorNode ?? b.root, 6) + expect(b.key('ArrowUp')).toBe(true) + expect(b.recallHistory).not.toHaveBeenCalled() + b.caret(2, 6, 0) + expect(b.key('ArrowUp')).toBe(false) + expect(b.key('ArrowDown')).toBe(false) + expect(b.recallHistory).toHaveBeenCalledTimes(2) + }) + + it('treats the end after typed line breaks as the draft end', () => { + const b = bench('a\n\nb') + // Children: text a,
,
, text b. + b.caret(0, 2) + expect(b.key('ArrowUp')).toBe(true) + b.caret(0, 1, 3) + expect(b.key('ArrowUp')).toBe(false) + expect(b.recallHistory).toHaveBeenCalledOnce() + }) + + it('treats an empty draft as at its end and a missing or outside selection as not', () => { + const b = bench('') + b.caret(0) + expect(b.key('ArrowUp')).toBe(false) + window.getSelection()?.removeAllRanges() + expect(b.key('ArrowDown')).toBe(true) + const outside = document.createElement('span') + document.body.append(outside) + onTestFinished(() => { outside.remove() }) + window.getSelection()?.collapse(outside, 0) + expect(b.key('ArrowDown')).toBe(true) + expect(b.recallHistory).toHaveBeenCalledOnce() + }) + + it('does not recall without a mounted root to read the caret from', () => { + const b = bench('draft') + b.caret(0, 5, 0) + const editor = createEditor({ namespace: 'detached', onError: (error) => { throw error } }) + const recallHistory = vi.fn(() => true) + onTestFinished(registerComposerKeymap(editor, { + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory, + canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, + })) + editor.update(() => { $getRoot().append($createParagraphNode()) }, { discrete: true }) + expect(editor.dispatchCommand(KEY_ARROW_UP_COMMAND, new KeyboardEvent('keydown', { key: 'ArrowUp' }))).toBe(false) + expect(recallHistory).not.toHaveBeenCalled() + }) + + it.each([ + { locked: true, machineBusy: false, recalls: false }, + { locked: false, machineBusy: true, recalls: false }, + { locked: false, machineBusy: false, recalls: true }, + ])( + 'the view gate passes recall through only when open: %j', ({ recalls, ...gate }) => { + const editor = createEditor({ namespace: 'gated', onError: (error) => { throw error } }) + const root = document.createElement('div') + root.contentEditable = 'true' + document.body.append(root) + onTestFinished(() => { editor.setRootElement(null); root.remove() }) + editor.setRootElement(root) + onTestFinished(registerPlainText(editor)) + const shell = makeShell() + const recallHistory = vi.spyOn(shell, 'recallHistory') + onTestFinished(installDraftKeymap(editor, shell, { + current: { + ...gate, canSteerQueue: false, running: false, steeringAvailable: false, busyEnter: 'queue', + intakeFiles: () => {}, uploadsPending: false, uploadsHeldText: '', showToast: () => {}, canAcceptDrop: false, + }, + })) + window.getSelection()?.collapse(root.firstElementChild ?? root, 0) + expect(fireEvent.keyDown(root, { key: 'ArrowUp' })).toBe(true) + expect(recallHistory).toHaveBeenCalledTimes(recalls ? 1 : 0) + }, + ) +}) diff --git a/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx b/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx index 66008b4c7b..d061bd06f5 100644 --- a/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx +++ b/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx @@ -25,7 +25,7 @@ describe('keymap keydown routing', () => { }) editor.setRootElement(first) const unregister = registerComposerKeymap(editor, { - arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => false, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, }) onTestFinished(unregister) @@ -57,7 +57,7 @@ describe('keymap keydown routing', () => { registerComposerKeymap(editor, { arbitrate: () => 'pass', space: () => false, - dismissPopup: () => {}, + dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit, intakeFiles: () => {}, @@ -88,7 +88,7 @@ describe('keymap keydown routing', () => { const submit = vi.fn() const arbitrate = vi.fn(() => 'pass' as const) onTestFinished(registerComposerKeymap(editor, { - arbitrate, space: () => false, dismissPopup: () => {}, canSubmit: () => true, + arbitrate, space: () => false, dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit, intakeFiles: () => {}, pasteText: () => {}, })) editor.update(() => { @@ -125,7 +125,7 @@ describe('keymap keydown routing', () => { registerComposerKeymap(editor, { arbitrate, space: () => false, - dismissPopup: () => {}, + dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, @@ -164,7 +164,7 @@ describe('keymap keydown routing', () => { editor.setRootElement(root) onTestFinished(registerPlainText(editor)) onTestFinished(registerComposerKeymap(editor, { - arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, canSubmit: () => true, + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, recallHistory: () => false, canSubmit: () => true, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, })) return { editor, root, modify } diff --git a/tsconfig.host.json b/tsconfig.host.json index ba4faed880..0ac34e98ba 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -258,6 +258,7 @@ "apps/web/tests/chat-scroll-contract.e2e.ts", "apps/web/tests/chat-long-interactions.e2e.ts", "apps/web/tests/chat-continuous-conversation.e2e.ts", + "apps/web/tests/composer-history.e2e.ts", "apps/web/tests/composer-tab-geometry.e2e.ts", "apps/web/tests/conversation-view-tabs.e2e.ts", "apps/web/tests/composer-shortcuts.e2e.ts", From 286f2f3a2030bf53403c257a22a4fdde500f2b76 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 12:31:53 +0800 Subject: [PATCH 33/54] Keep requestImageMaxBytes as the pi profile setting --- docs/config-catalog.md | 4 ++-- docs/config-catalog.zh.md | 4 ++-- .../pi-image-resize-defaults/guide.i18n.yaml | 8 ++++---- .../pi-image-resize-defaults/guide.md | 4 ++-- .../pi-image-resize-defaults/guide.zh.md | 4 ++-- packages/llm/llm-pi-ai/README.i18n.yaml | 4 ++-- packages/llm/llm-pi-ai/README.md | 6 +++--- packages/llm/llm-pi-ai/README.zh.md | 6 +++--- packages/llm/llm-pi-ai/src/config.ts | 19 +++++++++++-------- packages/llm/llm-pi-ai/tests/adapter.spec.ts | 6 +++--- packages/llm/llm-pi-ai/tests/config.spec.ts | 18 ++++++++++-------- .../pi-ai-image-limits/runtime.cordis.yml | 2 +- 12 files changed, 45 insertions(+), 40 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 8f68a35c82..c97f4e311c 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2274,7 +2274,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:255`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:257`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2393,7 +2393,7 @@ export interface PiAiProviderProfile { * The effective cap is the smaller of this value and the route's equal share of maxRequestImageBytes. * Omission uses the catalog budget converted to raw bytes, or 1 MiB without catalog metadata. */ - maxImageBytes?: number + requestImageMaxBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ retryPolicy?: RetryPolicyConfig } diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index beb246bc0e..f18ff2b648 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2276,7 +2276,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:255`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:257`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2395,7 +2395,7 @@ export interface PiAiProviderProfile { * The effective cap is the smaller of this value and the route's equal share of maxRequestImageBytes. * Omission uses the catalog budget converted to raw bytes, or 1 MiB without catalog metadata. */ - maxImageBytes?: number + requestImageMaxBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ retryPolicy?: RetryPolicyConfig } diff --git a/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml index 7a0b4a91c3..b08bfbe1b7 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 6bee071887ac3982 zh: ec0176e47b3e64a1 /request-image-byte-limits/change: - en: f0636ed9e57d5081 - zh: ad5c5584f0e8bfe1 + en: 17fdb9e78254c0f4 + zh: 9f31b97bede355ae /request-image-byte-limits/migration: - en: 56bb5f70380e26b8 - zh: c7a62c8709b1bd90 + en: f42239aa9df6c95c + zh: ef4972f9e4f74ee8 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md index 8cce3d905c..e61d9be38f 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.md @@ -10,13 +10,13 @@ English | [中文](guide.zh.md) Model-request images distinguish `maxImageBytes`, a hard encoded-byte limit, from `imageTargetBytes`, a preferred target. The encoder keeps the 85/75/60 quality ladder and reduces dimensions further only when its smallest output exceeds the hard limit. Each reduction starts from the saved source. A limit that cannot fit even a 1×1 image fails with `IMAGE_REQUEST_TOO_LARGE`; oversized bytes are never returned. Stored attachments are unchanged, and request caches regenerate under a new transform version. -pi exposes only hard limits. `maxImageBytes` replaces `requestImageMaxBytes` and overrides the selected model's per-image byte cap. `requestImageBudgetCount` defaults to 20. The effective hard limit is the smaller of that cap and `3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount))`; the internal soft target equals it. Default allocation is 0.75 MiB per image. Width and height follow catalog limits unless `requestImageMaxDimension` overrides both with the same value; unequal local width/height overrides are not supported. +pi exposes only hard limits. `requestImageMaxBytes` keeps its name and now sets a hard cap on the encoded image. `requestImageBudgetCount` defaults to 20. The effective hard limit is the smaller of that cap and `3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount))`; the internal soft target equals it. Default allocation is 0.75 MiB per image. Width and height follow catalog limits unless `requestImageMaxDimension` overrides both with the same value; unequal local width/height overrides are not supported. DeepSeek renames the configurable `imageMaxBytes` soft target to `imageTargetBytes`, retaining its 2 MiB default. Its hard cap is fixed at 32 MiB. CUA's fixed `screenshotTarget.maxBytes` also becomes a hard cap. Request-image targets describe maximum dimensions; actual output can be smaller. Aggregate request limits still apply to actual encoded payloads. ## Migration -1. In pi provider profiles, replace `requestImageMaxBytes` with `maxImageBytes` and review its hard-limit meaning. Set `requestImageBudgetCount` to the desired allocation divisor, independently of the retained-count cap. The aggregate base64 budget must allow at least four bytes per share. For 1 MiB allocations, use a sufficient aggregate budget and divisor, such as 32 MiB and 20 shares, plus `maxImageBytes: 1048576`. +1. In pi provider profiles, review any explicit `requestImageMaxBytes` value. Images that exceed this value after quality adjustment now shrink further. Set `requestImageBudgetCount` to the desired allocation divisor, independently of the retained-count cap. The aggregate base64 budget must allow at least four bytes per share. For 1 MiB allocations, use a sufficient aggregate budget and divisor, such as 32 MiB and 20 shares, plus `requestImageMaxBytes: 1048576`. 2. In DeepSeek `models` and `modelOverrides`, rename `imageMaxBytes` to `imageTargetBytes`. Keep the value at or below 32 MiB. The retired field is rejected with migration guidance. 3. Consumers of `ImageRequestTarget` replace `maxBytes` with `maxImageBytes` and supply `imageTargetBytes` no greater than it. Read the final width and height from `readImageRequest`, including for coordinate mapping. Direct `readRequestImageFile` and `requestImageVariantId` callers must pass resolved resize controls; DeepSeek helper consumers use `resolveRequestImageTargetBytes` and `DEFAULT_REQUEST_IMAGE_TARGET_BYTES`. 4. Attachment-local deployments may tune `requestImageMinShrinkFactor` (default 1.1, greater than one) and `requestImageByteHeadroom` (default 0.95, in `(0, 1]`). Verify actual encoded bytes stay within the hard limit and coordinate mappings match the returned dimensions. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.zh.md index 063787e4df..a9bd1f53e6 100644 --- a/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.5/pi-image-resize-defaults/guide.zh.md @@ -10,13 +10,13 @@ description: "请求图片在编码后执行字节硬上限,DeepSeek 的软目 模型请求图片区分编码字节硬上限 `maxImageBytes` 和软目标 `imageTargetBytes`。编码器保留 85/75/60 质量阶梯,只有最小结果仍超过硬上限时才继续缩小尺寸。每次缩放都从已保存的源图开始。连 1×1 图片也无法满足上限时,以 `IMAGE_REQUEST_TOO_LARGE` 失败,不返回超限字节。存储附件保持不变,请求缓存使用新的变换版本重新生成。 -pi 只暴露硬上限。`maxImageBytes` 替代 `requestImageMaxBytes`,用于覆盖所选模型的单图字节上限。`requestImageBudgetCount` 默认为 20。最终硬上限取该单图上限与 `3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount))` 的较小值,内部软目标等于硬上限。默认每张图分得 0.75 MiB。宽高跟随目录限制,或由 `requestImageMaxDimension` 用同一个值覆盖;不支持分别配置不同的本地宽高上限。 +pi 只暴露硬上限。继续使用 `requestImageMaxBytes`,它现在限制编码后每张图的字节数。`requestImageBudgetCount` 默认为 20。最终硬上限取该单图上限与 `3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount))` 的较小值,内部软目标等于硬上限。默认每张图分得 0.75 MiB。宽高跟随目录限制,或由 `requestImageMaxDimension` 用同一个值覆盖;不支持分别配置不同的本地宽高上限。 DeepSeek 将可配置软目标 `imageMaxBytes` 重命名为 `imageTargetBytes`,默认仍为 2 MiB,硬上限固定为 32 MiB。CUA 的固定截图配置 `screenshotTarget.maxBytes` 也改为硬上限。请求图片目标描述最大尺寸,实际输出可能更小。请求总量限制仍按实际编码载荷执行。 ## 迁移 -1. 在 pi 提供方配置中,将 `requestImageMaxBytes` 改为 `maxImageBytes`,并按硬上限语义检查取值。通过 `requestImageBudgetCount` 配置预算分摊张数,它独立于保留图片数量上限。base64 总预算须为每份预算至少提供 4 个字节。若希望每张分配 1 MiB,应使用足够的总预算及分摊张数,例如 32 MiB、20 份,再设置 `maxImageBytes: 1048576`。 +1. 如果 pi 提供方配置已设置 `requestImageMaxBytes`,请检查现有取值。调低编码质量后仍超过该值的图片会继续缩小尺寸。通过 `requestImageBudgetCount` 配置预算分摊张数,它独立于保留图片数量上限。base64 总预算须为每份预算至少提供 4 个字节。若希望每张分配 1 MiB,应使用足够的总预算及分摊张数,例如 32 MiB、20 份,再设置 `requestImageMaxBytes: 1048576`。 2. 在 DeepSeek 的 `models` 和 `modelOverrides` 中,将 `imageMaxBytes` 改为 `imageTargetBytes`,值不得超过 32 MiB。旧字段会被拒绝,并提示迁移方式。 3. `ImageRequestTarget` 调用方将 `maxBytes` 改为 `maxImageBytes`,并提供不大于硬上限的 `imageTargetBytes`。包括坐标换算在内的调用方,都从 `readImageRequest` 获取最终宽高。直接调用 `readRequestImageFile` 和 `requestImageVariantId` 时须传入已解析的缩放参数;DeepSeek 辅助函数调用方改用 `resolveRequestImageTargetBytes` 和 `DEFAULT_REQUEST_IMAGE_TARGET_BYTES`。 4. 附件本地存储可配置 `requestImageMinShrinkFactor`,默认 1.1,必须大于 1;以及 `requestImageByteHeadroom`,默认 0.95,范围为 `(0, 1]`。检查实际编码字节满足硬上限,坐标映射与返回尺寸一致。 diff --git a/packages/llm/llm-pi-ai/README.i18n.yaml b/packages/llm/llm-pi-ai/README.i18n.yaml index 8b24c83c7c..da1eb9baa7 100644 --- a/packages/llm/llm-pi-ai/README.i18n.yaml +++ b/packages/llm/llm-pi-ai/README.i18n.yaml @@ -21,8 +21,8 @@ en: f3b761c7c7ecb82f zh: e10d999aa348ef86 /deepseek-ai-dsh-llm-pi-ai/use-this-package/configure-provider-routes: - en: 90a1571e9de28c7d - zh: 8a2d445ed31f1bd7 + en: 5f2e3298066947a2 + zh: 0166148523454073 /deepseek-ai-dsh-llm-pi-ai/use-this-package/sign-in-to-a-provider: en: c36f66438638ae08 zh: 066a2fc4cb97c86f diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index 4cae0d5687..8d3ab6cfff 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -47,7 +47,7 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie reasoning: high requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default requestImageMaxDimension: 3000 # override catalog width and height limits - maxImageBytes: 1048576 # hard per-image cap before allocation + requestImageMaxBytes: 1048576 # hard per-image cap before allocation requestImageBudgetCount: 20 # fixed number of equal budget shares maxRequestImageBytes: 20971520 # accumulated base64 payload maxRequestImages: 50 # retained image occurrences @@ -89,14 +89,14 @@ Each profile may set a `retryPolicy`; omission uses normal mode with five retrie | `defaultMaxTokens` | `128,000` | Output-cap fallback for undescribed models | | `requestImagePixelBudget` | `4,194,304` | Total-pixel budget for each deterministic request image | | `requestImageMaxDimension` | catalog width/height limits | Maximum width and height for each request image; an explicit value overrides both catalog limits | -| `maxImageBytes` | catalog base64 cap converted to raw bytes; otherwise `1 MiB` | Hard per-image cap before allocation; an explicit value overrides the catalog cap | +| `requestImageMaxBytes` | catalog base64 cap converted to raw bytes; otherwise `1 MiB` | Hard per-image cap before allocation; an explicit value overrides the catalog cap | | `requestImageBudgetCount` | `20` | Fixed divisor of the aggregate image budget; independent of retained image count | | `maxRequestImageBytes` | `20 MiB` | Aggregate base64 image-payload bound; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED` | | `maxRequestImages` | `50` | Retained request-image count bound; a request whose retained images exceed it fails with `IMAGE_OFFLOAD_REQUIRED`. The default follows Azure OpenAI's 50-image limit; raise it on routes whose provider accepts more images | | `imageOffloadCountQuantum` | `10`, capped at `maxRequestImages` | Oldest images offloaded per count overflow | | `retryPolicy` | normal, 5 retries | Provider-owned retry policy executed by `dsh-llm-retry` | -Request images inherit the selected pi-ai model's `inputLimits.images.resize` width, height, and base64-byte cap. `requestImageMaxDimension` overrides both dimensions with one value; it cannot express unequal width and height overrides. `maxImageBytes` overrides the per-image cap in raw encoded bytes. The effective hard limit is `min(3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount)), maxImageBytes or catalog cap or 1 MiB)`, with the catalog cap converted using `3 × floor(catalogBytes / 4)`. Configuration must allow at least four aggregate base64 bytes per budget share. Defaults allocate 0.75 MiB per image, so 20 images at that limit use at most 20 MiB of base64 payload. Budget shares stay fixed as history grows; `maxRequestImages` separately controls retained occurrences. Missing catalog dimensions leave that axis uncapped, while total pixels remain governed by `requestImagePixelBudget`. +Request images inherit the selected pi-ai model's `inputLimits.images.resize` width, height, and base64-byte cap. `requestImageMaxDimension` overrides both dimensions with one value; it cannot express unequal width and height overrides. `requestImageMaxBytes` overrides the per-image cap in raw encoded bytes. The effective hard limit is `min(3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount)), requestImageMaxBytes or catalog cap or 1 MiB)`, with the catalog cap converted using `3 × floor(catalogBytes / 4)`. Configuration must allow at least four aggregate base64 bytes per budget share. Defaults allocate 0.75 MiB per image, so 20 images at that limit use at most 20 MiB of base64 payload. Budget shares stay fixed as history grows; `maxRequestImages` separately controls retained occurrences. Missing catalog dimensions leave that axis uncapped, while total pixels remain governed by `requestImagePixelBudget`. pi exposes no separate soft-byte target: the shared encoder's `imageTargetBytes` equals its effective `maxImageBytes`. After the quality ladder, images that still exceed the limit are resized and re-encoded until they fit; an impossible limit fails explicitly. Stored attachments stay unchanged. Image descriptors and screenshot coordinates use the final encoded dimensions. Increase `requestImageBudgetCount` for smaller per-image allocations, or decrease it for larger ones; the aggregate cap still applies to actual payloads. diff --git a/packages/llm/llm-pi-ai/README.zh.md b/packages/llm/llm-pi-ai/README.zh.md index f9566acc8f..b75d154548 100644 --- a/packages/llm/llm-pi-ai/README.zh.md +++ b/packages/llm/llm-pi-ai/README.zh.md @@ -47,7 +47,7 @@ kind: "package-reference" reasoning: high requestImagePixelBudget: 4194304 # total pixels; 2048 by 2048 default requestImageMaxDimension: 3000 # override catalog width and height limits - maxImageBytes: 1048576 # hard per-image cap before allocation + requestImageMaxBytes: 1048576 # hard per-image cap before allocation requestImageBudgetCount: 20 # fixed number of equal budget shares maxRequestImageBytes: 20971520 # accumulated base64 payload maxRequestImages: 50 # retained image occurrences @@ -89,14 +89,14 @@ kind: "package-reference" | `defaultMaxTokens` | `128,000` | 未描述模型的输出上限回退 | | `requestImagePixelBudget` | `4,194,304` | 每张确定性请求图片的总像素预算 | | `requestImageMaxDimension` | 目录中的宽高限制 | 每张请求图片的最大宽度和高度;显式配置会覆盖目录中的两个限制 | -| `maxImageBytes` | 目录的 base64 上限换算为原始字节;否则为 `1 MiB` | 分摊前的单图硬上限;显式配置会覆盖目录上限 | +| `requestImageMaxBytes` | 目录的 base64 上限换算为原始字节;否则为 `1 MiB` | 分摊前的单图硬上限;显式配置会覆盖目录上限 | | `requestImageBudgetCount` | `20` | 图片总预算的固定分摊张数,与当前保留图片数量无关 | | `maxRequestImageBytes` | `20 MiB` | base64 图片载荷总上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败 | | `maxRequestImages` | `50` | 保留请求图片数量上限,保留图片超过时请求以 `IMAGE_OFFLOAD_REQUIRED` 失败。默认值取 Azure OpenAI 的 50 张上限;提供方接受更多图片的路由应调高 | | `imageOffloadCountQuantum` | `10`,不超过 `maxRequestImages` | 每次数量超限时省略的最老图片数 | | `retryPolicy` | normal,5 次重试 | 由 `dsh-llm-retry` 执行的提供方自有重试策略 | -请求图片继承所选 pi-ai 模型的 `inputLimits.images.resize` 宽度、高度和 base64 字节上限。`requestImageMaxDimension` 用同一个值覆盖宽高,不能分别配置不同的宽度和高度上限。`maxImageBytes` 按原始编码字节覆盖单图上限。最终硬上限为 `min(3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount)), maxImageBytes 或目录上限或 1 MiB)`,其中目录上限通过 `3 × floor(catalogBytes / 4)` 换算。总预算须为每份预算至少提供 4 个 base64 字节。默认每张图分得 0.75 MiB,20 张达到该上限的图片最多占用 20 MiB base64 载荷。历史增长不会改变分摊张数;`maxRequestImages` 单独控制保留图片数量。目录缺少某个尺寸时,路由不限制该轴,总像素仍由 `requestImagePixelBudget` 控制。 +请求图片继承所选 pi-ai 模型的 `inputLimits.images.resize` 宽度、高度和 base64 字节上限。`requestImageMaxDimension` 用同一个值覆盖宽高,不能分别配置不同的宽度和高度上限。`requestImageMaxBytes` 按原始编码字节覆盖单图上限。最终硬上限为 `min(3 × floor(maxRequestImageBytes / (4 × requestImageBudgetCount)), requestImageMaxBytes 或目录上限或 1 MiB)`,其中目录上限通过 `3 × floor(catalogBytes / 4)` 换算。总预算须为每份预算至少提供 4 个 base64 字节。默认每张图分得 0.75 MiB,20 张达到该上限的图片最多占用 20 MiB base64 载荷。历史增长不会改变分摊张数;`maxRequestImages` 单独控制保留图片数量。目录缺少某个尺寸时,路由不限制该轴,总像素仍由 `requestImagePixelBudget` 控制。 pi 不暴露单独的软字节目标,共享编码器的 `imageTargetBytes` 等于最终 `maxImageBytes`。质量阶梯结束后仍超限的图片会继续缩小尺寸并重新编码,直到满足上限;无法满足的极小上限会明确报错。存储附件保持不变。图片描述和截图坐标使用最终编码尺寸。调大 `requestImageBudgetCount` 会减小每张图的分配额度,调小则增加额度;总预算仍按实际载荷执行。 diff --git a/packages/llm/llm-pi-ai/src/config.ts b/packages/llm/llm-pi-ai/src/config.ts index de09eca4d6..4e02502b31 100644 --- a/packages/llm/llm-pi-ai/src/config.ts +++ b/packages/llm/llm-pi-ai/src/config.ts @@ -206,14 +206,14 @@ export interface PiAiProviderProfile { * The effective cap is the smaller of this value and the route's equal share of maxRequestImageBytes. * Omission uses the catalog budget converted to raw bytes, or 1 MiB without catalog metadata. */ - maxImageBytes?: number + requestImageMaxBytes?: number /** Provider-owned model-request retry policy; omission uses normal mode with five retries. */ retryPolicy?: RetryPolicyConfig } /** Validated profile with its route stamped and every adapter-owned default resolved. */ export interface ResolvedPiAiProviderProfile - extends Omit { + extends Omit { /** Harness route key and the `Models` collection key (the configuration dict key). */ provider: string /** Resolved display name for selectors and configuration surfaces. */ @@ -232,6 +232,8 @@ export interface ResolvedPiAiProviderProfile requestImageBudgetCount: number /** Positive total-pixel request-version budget after defaulting. */ requestImagePixelBudget: number + /** Configured hard per-image cap in raw encoded bytes, before the request budget is shared. */ + maxImageBytes?: number /** Immutable retry policy captured with this provider route. */ retryPolicy: ResolvedRetryPolicy /** @@ -381,7 +383,7 @@ const profile = z.object({ requestImageBudgetCount: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_REQUEST_IMAGE_BUDGET_COUNT), requestImagePixelBudget: z.number().step(1).min(1).default(DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET), requestImageMaxDimension: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), - maxImageBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), + requestImageMaxBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER), retryPolicy: RetryPolicySchema, }) @@ -456,10 +458,10 @@ export function resolveProfiles( for (const [provider, source] of entries) { rejectRemovedFields(provider, source) if ('imageTargetBytes' in source) { - throw new Error('llm-pi-ai: imageTargetBytes is not configurable; pi uses its effective maxImageBytes as the target') + throw new Error('llm-pi-ai: imageTargetBytes is not configurable; pi uses the effective per-image cap as the target') } - if ('requestImageMaxBytes' in source) { - throw new Error('llm-pi-ai: replace requestImageMaxBytes with maxImageBytes; the new value is a hard per-image cap') + if ('maxImageBytes' in source) { + throw new Error(`llm-pi-ai: provider "${provider}" must use requestImageMaxBytes to set the per-image cap; maxImageBytes is internal`) } if (provider.length === 0) throw new Error('llm-pi-ai: provider names must be non-empty') if (source.baseURL !== undefined && source.baseURL.length === 0) { @@ -500,7 +502,7 @@ export function resolveProfiles( if (!Number.isSafeInteger(requestImagePixelBudget) || requestImagePixelBudget <= 0) { throw new Error(`llm-pi-ai: provider "${provider}" requestImagePixelBudget must be a positive safe integer`) } - for (const field of ['requestImageMaxDimension', 'maxImageBytes'] as const) { + for (const field of ['requestImageMaxDimension', 'requestImageMaxBytes'] as const) { const value = source[field] if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) { throw new Error(`llm-pi-ai: provider "${provider}" ${field} must be a positive safe integer`) @@ -547,9 +549,10 @@ export function resolveProfiles( if (validation === 'strict' || !(error instanceof PiAiCatalogError)) throw error catalogError ??= error.message } - const { apiKeyEnv, retryPolicy, models: _models, displayName: _displayName, ...rest } = source + const { apiKeyEnv, retryPolicy, models: _models, displayName: _displayName, requestImageMaxBytes, ...rest } = source resolved.set(provider, { ...rest, + ...requestImageMaxBytes === undefined ? {} : { maxImageBytes: requestImageMaxBytes }, provider, displayName, ...apiKeyEnv === undefined ? {} : { apiKeyEnv: credentialRef(apiKeyEnv) }, diff --git a/packages/llm/llm-pi-ai/tests/adapter.spec.ts b/packages/llm/llm-pi-ai/tests/adapter.spec.ts index 5ad7e16e97..66638a1ef9 100644 --- a/packages/llm/llm-pi-ai/tests/adapter.spec.ts +++ b/packages/llm/llm-pi-ai/tests/adapter.spec.ts @@ -1255,7 +1255,7 @@ it.each([ }) it('resolves the exact pi-ai image budget for screenshot coordinates', () => { - const adapter = adapterOf({ deepseek: { apiKeyEnv: 'PI_TEST_KEY', requestImagePixelBudget: 10_000, maxImageBytes: 50_000 } }) + const adapter = adapterOf({ deepseek: { apiKeyEnv: 'PI_TEST_KEY', requestImagePixelBudget: 10_000, requestImageMaxBytes: 50_000 } }) expect(adapter.imageRequestTarget('deepseek', 'deepseek-flash', { ...IMAGE_REF, width: 1000, height: 1000 })) .toEqual({ width: 100, height: 100, maxImageBytes: 50_000, imageTargetBytes: 50_000 }) expect(() => adapter.imageRequestTarget('missing', 'deepseek-flash', IMAGE_REF)).toThrow('does not own provider') @@ -1265,7 +1265,7 @@ it('resolves the exact pi-ai image budget for screenshot coordinates', () => { it.each([ [{}, { width: 627, height: 2000, maxImageBytes: 786_432, imageTargetBytes: 786_432 }], [{ - requestImageMaxDimension: 3000, maxImageBytes: 500_000, + requestImageMaxDimension: 3000, requestImageMaxBytes: 500_000, }, { width: 940, height: 3000, maxImageBytes: 500_000, imageTargetBytes: 500_000, }], @@ -1290,7 +1290,7 @@ it.each([ const ref = { ...IMAGE_REF, width: 1146, height: 3657 } expect(adapter.imageRequestTarget('anthropic', 'claude-sonnet-4-5', ref)).toEqual(expected) const prepared = await adapter.prepareCall('anthropic', 'claude-sonnet-4-5') - providers = { anthropic: { ...providers['anthropic'], requestImageMaxDimension: 777, maxImageBytes: 333 } } + providers = { anthropic: { ...providers['anthropic'], requestImageMaxDimension: 777, requestImageMaxBytes: 333 } } expect(adapter.imageRequestTarget('anthropic', 'claude-sonnet-4-5', ref)).toMatchObject({ height: 777, maxImageBytes: 333, imageTargetBytes: 333, }) diff --git a/packages/llm/llm-pi-ai/tests/config.spec.ts b/packages/llm/llm-pi-ai/tests/config.spec.ts index 1753f88e81..5fec34efa2 100644 --- a/packages/llm/llm-pi-ai/tests/config.spec.ts +++ b/packages/llm/llm-pi-ai/tests/config.spec.ts @@ -92,13 +92,13 @@ describe('request image policy bounds', () => { expect(profile.requestImageMaxDimension).toBeUndefined() expect(profile.maxImageBytes).toBeUndefined() expect(profile.requestImageBudgetCount).toBe(20) - const explicit = routeWith({ requestImageMaxDimension: 3000, maxImageBytes: 2000000 })() as Options + const explicit = routeWith({ requestImageMaxDimension: 3000, requestImageMaxBytes: 2000000 })() as Options expect(resolveProfiles(explicit.providers).get('acme-gateway')).toMatchObject({ requestImageMaxDimension: 3000, maxImageBytes: 2000000, }) }) - it.each(['requestImageMaxDimension', 'maxImageBytes', 'requestImageBudgetCount'])( + it.each(['requestImageMaxDimension', 'requestImageMaxBytes', 'requestImageBudgetCount'])( 'rejects invalid %s at the configuration parser', (field) => { for (const value of [0, -1, 1.5, Infinity, Number.MAX_SAFE_INTEGER + 1]) { expect(routeWith({ [field]: value })).toThrow() @@ -114,8 +114,8 @@ describe('request image policy bounds', () => { ['requestImageMaxDimension', 0, /requestImageMaxDimension must be a positive safe integer/], ['requestImageMaxDimension', 1.5, /requestImageMaxDimension must be a positive safe integer/], ['requestImageMaxDimension', Number.MAX_SAFE_INTEGER + 1, /requestImageMaxDimension must be a positive safe integer/], - ['maxImageBytes', 0, /maxImageBytes must be a positive safe integer/], - ['maxImageBytes', 1.5, /maxImageBytes must be a positive safe integer/], + ['requestImageMaxBytes', 0, /requestImageMaxBytes must be a positive safe integer/], + ['requestImageMaxBytes', 1.5, /requestImageMaxBytes must be a positive safe integer/], ] as const)('rejects %s=%s at service resolution', (field, value, message) => { const programmatic = { providers: { @@ -143,10 +143,12 @@ it('rejects an aggregate budget without room for one base64 group per allocated .toThrow(/maxRequestImageBytes/) }) -it('rejects the retired soft-byte configuration key instead of ignoring it', () => { - expect(() => { assertServiceable(routeWith({ requestImageMaxBytes: 1024 })() as Options) }) - .toThrow(/replace requestImageMaxBytes with maxImageBytes/) -}) +it.each([{ maxImageBytes: 1024 }, { requestImageMaxBytes: 1024, maxImageBytes: 1024 }])( + 'rejects the internal byte-cap name in a provider profile: %j', (fields) => { + expect(() => { assertServiceable(routeWith(fields)() as Options) }) + .toThrow(/provider "acme-gateway" must use requestImageMaxBytes.*maxImageBytes is internal/) + }, +) it('refuses a separate pi soft target at the configuration boundary', () => { diff --git a/snapshots/session/pi-ai-image-limits/runtime.cordis.yml b/snapshots/session/pi-ai-image-limits/runtime.cordis.yml index 8b67ac9889..ee224e4bb7 100644 --- a/snapshots/session/pi-ai-image-limits/runtime.cordis.yml +++ b/snapshots/session/pi-ai-image-limits/runtime.cordis.yml @@ -7,7 +7,7 @@ api: anthropic-messages baseURL: https://image-override.invalid requestImageMaxDimension: 3000 - maxImageBytes: 4096 + requestImageMaxBytes: 4096 models: - id: vision input: [text, image] From 4e4856598fd719d8fd2412cd9d70caf9f1ee2b41 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 20 Nov 2026 12:35:01 +0800 Subject: [PATCH 34/54] Refresh the pi image limits session against master --- snapshots/session/pi-ai-image-limits/session.v4.jsonl | 2 +- snapshots/session/pi-ai-image-limits/tool-schemas.expected.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/snapshots/session/pi-ai-image-limits/session.v4.jsonl b/snapshots/session/pi-ai-image-limits/session.v4.jsonl index b558c5d16f..a837764682 100644 --- a/snapshots/session/pi-ai-image-limits/session.v4.jsonl +++ b/snapshots/session/pi-ai-image-limits/session.v4.jsonl @@ -6,7 +6,7 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} -{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"},{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt","sections":[{"name":"harness:identity","order":-1000,"state":"active","contentIndex":0},{"name":"deployment:persona-prefix","order":0,"state":"active","contentIndex":1},{"name":"tool:bash","order":1000,"state":"active","contentIndex":2},{"name":"tool:read","order":1100,"state":"active","contentIndex":3},{"name":"tool:write","order":1200,"state":"active","contentIndex":4},{"name":"tool:edit","order":1300,"state":"active","contentIndex":5},{"name":"tool:apply_patch","order":1350,"state":"active","contentIndex":6},{"name":"tool:glob","order":1400,"state":"active","contentIndex":7},{"name":"tool:grep","order":1500,"state":"active","contentIndex":8},{"name":"tool:jobs","order":1600,"state":"active","contentIndex":9},{"name":"tool:web_search","order":2000,"state":"active","contentIndex":10},{"name":"tool:web_fetch","order":2100,"state":"active","contentIndex":11},{"name":"tool:goal","order":2400,"state":"active","contentIndex":12},{"name":"tool:workflow","order":2600,"state":"active","contentIndex":13},{"name":"tool:subagent","order":2800,"state":"active","contentIndex":14}]},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Call snapshot_image_limits, then reply with the single word DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} diff --git a/snapshots/session/pi-ai-image-limits/tool-schemas.expected.json b/snapshots/session/pi-ai-image-limits/tool-schemas.expected.json index 38a3c9cc25..0f5efd8fe7 100644 --- a/snapshots/session/pi-ai-image-limits/tool-schemas.expected.json +++ b/snapshots/session/pi-ai-image-limits/tool-schemas.expected.json @@ -241,7 +241,7 @@ }, { "name": "list_agents", - "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", + "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Shared capacity reports running/limit; do not spawn more agents when capacity is limited. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", "parameters": { "type": "object", "properties": {} From f5dc990da844bfcad6828142be9ff7e70229e78c Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:03:57 +0800 Subject: [PATCH 35/54] ci: split coverage across two file shards and merge on a small report job (#8868) * ci: split coverage across two file shards and merge on a small report job Coverage runs as a three-lane matrix: two instrumented file shards that deal path-sorted test files in snake order (DSH_COVERAGE_SHARD) and the uninstrumented heavy suites. Each shard uploads its blobs, file list, and durations; node-24-coverage-report re-lists the inventory, checks the shards partition it, merges the blobs with thresholds on a 2-vCPU runner, and alone saves the duration history. Only the report job joins all-checks-passed. * ci: run the coverage heavy suites on the first shard and split shards by file size The exempt heavy suites finished in about a minute on a dedicated 16-vCPU runner, so they join shard 1 with the coverage lane's usual worker split. Shards now deal files largest first by byte size instead of by path order, so the heaviest suites no longer land on one shard. The coordinator repeats each failed partition and its Vitest FAIL lines after all partitions finish, and run-gates.spec clears DSH_COVERAGE_SHARD inherited from the CI shard. * ci: give the coverage merge a 4 GB heap on the small report runner Merging both shards' blobs exhausted Node's default heap of about 2 GB on the 2-vCPU report runner (run 44664262449). * ci: merge coverage shards on an 8-vCPU runner The merge took 154s on the 2-vCPU report runner against ~30s on the former 16-vCPU lane (run 44667701311). * ci: address review on the coverage shards - Shards record their checkout root, and the merge rewrites that prefix in blobs from another checkout so one source file never merges as two. - Shard blob uploads overwrite on a re-run of the same workflow run. - The coverage report lane joins the runner-temp and compile-cache lane lists in ci-workflow.spec. - The failover runbook states the self-hosted shard and exempt workers. * ci: address the second coverage-shard review and leftover lane cleanup - The cross-checkout blob rewrite spec builds roots and paths with join(), so it holds on Windows, where the rewrite prefix ends in a backslash. - The failover runbook names the current coverage, build, consumer, and web snapshot checks instead of the former single-job names. - node-24-build and node-24-consumers drop env variables that none of their gates read. --- .../2026-07-26-ci-failover-runbook.i18n.yaml | 12 +- .../process/2026-07-26-ci-failover-runbook.md | 6 +- .../2026-07-26-ci-failover-runbook.zh.md | 6 +- .github/workflows/ci.yml | 116 +++++- package.json | 2 + scripts/ci-workflow.spec.ts | 80 +++- scripts/coverage-partitions.spec.ts | 185 +++++++++ scripts/coverage-partitions.ts | 382 ++++++++++++++++-- scripts/merge-coverage-shards.ts | 26 ++ scripts/run-coverage-partitions.ts | 6 +- scripts/run-gates.spec.ts | 32 ++ scripts/run-gates.ts | 73 +++- 12 files changed, 848 insertions(+), 78 deletions(-) create mode 100644 scripts/merge-coverage-shards.ts diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml index 3215401d0a..2b557568b7 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml @@ -6,11 +6,11 @@ en: 677b522817e84e2f zh: f8518a7033b0fd54 /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/problem: - en: bcdd24f3c39d593c - zh: 3e576d09c8c3bfd4 + en: 52c1c7d73dea8807 + zh: 8ce9142d06cb4be6 /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision: - en: 23fc560e2c12be5e - zh: 89071bd1735823ff + en: 072960364d4be488 + zh: 861a856b7a5a5bf0 /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision/release-rehearsals-share-the-linux-switch: en: 01e74068e0a96375 zh: aa811861ce30cb47 @@ -21,8 +21,8 @@ en: f395af725d1deaf1 zh: 896cedbb36c13758 /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/decision/switch-any-repository-writer-1-minute-no-merge: - en: 2e3829fd72d6b1b0 - zh: 563f0abade7974f9 + en: f5ec9b53f6fd483a + zh: f6a22f29bf13e66e /agent-note-ci-failover-runbook-hosted-pools-in-house-pool/capacity-during-failover: en: 3dffe12ecf2356c2 zh: 7e2385fcabab1398 diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md index 360a39a640..df7ccd68e6 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md @@ -6,11 +6,11 @@ English | [中文](2026-07-26-ci-failover-runbook.zh.md) ## Problem -The three required Linux worker jobs in [CI](../../../../.github/workflows/ci.yml) (`node 24 / static`, `node 24 / coverage`, `node 24 / snapshots and artifacts`) run on the hosted enterprise 32-core pools; the required verdict job that aggregates them (`all checks passed`) runs on standard `ubuntu-latest`; the [native Windows jobs](2026-08-08-native-windows-pull-request-ci.md) in [CI Windows](../../../../.github/workflows/ci-windows.yml) run on the hosted `dsh-windows-2025-16core` larger runner. When the enterprise pools degrade — jobs queue indefinitely or the enterprise labels vanish — every open pull request becomes unmergeable, and the ordinary recovery of merging a fix is itself deadlocked behind the very required checks that cannot run. **Scope: two independent switches, one per platform.** `DSH_CI_FAILOVER_LINUX` recovers an enterprise Linux-pool outage (the three required Linux workers plus the `all checks passed`, `windows checks passed`, and `python checks passed` verdicts); `DSH_CI_FAILOVER_WINDOWS` recovers a hosted Windows-pool outage (the native Windows jobs). A Linux-pool outage need not retarget Windows jobs and vice versa. The [Node compatibility jobs](../../../../.github/workflows/ci.yml) also follow the Linux switch with isolated setup; the verdict's `node-24-bench`, `python-sdk`, and `python-runtime` dependencies stay on standard hosted runners, as does CI Python's `python-runtime`; in a broader GitHub-hosted capacity failure that also takes out the standard pools, those dependencies still block the verdicts that require them. An outage therefore needs a switch any responder with repository write access can throw without merging anything. +The required Linux worker jobs in [CI](../../../../.github/workflows/ci.yml) (`node 24 / static`, `node 24 / coverage 1/2` and `2/2`, `node 24 / coverage report`, `node 24 / build`, `node 24 / snapshots and artifacts`, `node 24 / web snapshots 1/2` and `2/2`) run on the hosted enterprise pools; the required verdict job that aggregates them (`all checks passed`) runs on standard `ubuntu-latest`; the [native Windows jobs](2026-08-08-native-windows-pull-request-ci.md) in [CI Windows](../../../../.github/workflows/ci-windows.yml) run on the hosted `dsh-windows-2025-16core` larger runner. When the enterprise pools degrade — jobs queue indefinitely or the enterprise labels vanish — every open pull request becomes unmergeable, and the ordinary recovery of merging a fix is itself deadlocked behind the very required checks that cannot run. **Scope: two independent switches, one per platform.** `DSH_CI_FAILOVER_LINUX` recovers an enterprise Linux-pool outage (the required Linux workers plus the `all checks passed`, `windows checks passed`, and `python checks passed` verdicts); `DSH_CI_FAILOVER_WINDOWS` recovers a hosted Windows-pool outage (the native Windows jobs). A Linux-pool outage need not retarget Windows jobs and vice versa. The [Node compatibility jobs](../../../../.github/workflows/ci.yml) also follow the Linux switch with isolated setup; the verdict's `node-24-bench`, `python-sdk`, and `python-runtime` dependencies stay on standard hosted runners, as does CI Python's `python-runtime`; in a broader GitHub-hosted capacity failure that also takes out the standard pools, those dependencies still block the verdicts that require them. An outage therefore needs a switch any responder with repository write access can throw without merging anything. ## Decision -The primary Linux jobs (`node-24`, `node-24-coverage`, `node-24-build`, `node-24-consumers`, which restores the `node-24-build` output, and both entries of the `node-24-web-snapshot` shard matrix), the two `node-compat` matrix entries, and the `all-checks-passed`, `windows-checks-passed`, and `python-checks-passed` verdicts resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; the `blacksmith` value routes the participating jobs per the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); unset or any other value retains the workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain the `ubuntu-latest` fallback under unset and non-special values; the blacksmith branch carries none of those predicates. Under the `selfhosted` value, Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The three verdict jobs follow the Linux switch so they do not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes. +The primary Linux jobs (`node-24`, both `node-24-coverage` shard matrix entries and the `node-24-coverage-report` job that merges them, `node-24-build`, `node-24-consumers`, which restores the `node-24-build` output, and both entries of the `node-24-web-snapshot` shard matrix), the two `node-compat` matrix entries, and the `all-checks-passed`, `windows-checks-passed`, and `python-checks-passed` verdicts resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; the `blacksmith` value routes the participating jobs per the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); unset or any other value retains the workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain the `ubuntu-latest` fallback under unset and non-special values; the blacksmith branch carries none of those predicates. Under the `selfhosted` value, Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The three verdict jobs follow the Linux switch so they do not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes. The [superseded-CI cancellation policy](../../../../.github/workflows/ci.yml) governs master pushes and manual runs in the same workflow/ref group, including standby drills. Rapid master updates can starve a drill before it reaches a verdict. Use the latest completed standby verdict and check its age and commit before treating it as readiness evidence; a cancelled or merely scheduled run is not proof of readiness. @@ -32,7 +32,7 @@ The two switches are independent: flip only the one whose platform is degraded. 1. Repository **Settings → Secrets and variables → Actions → Variables → New repository variable**: name `DSH_CI_FAILOVER_LINUX` (Linux pool outage) or `DSH_CI_FAILOVER_WINDOWS` (Windows pool outage), value `selfhosted`. 2. Retrigger the required jobs so they re-resolve their pool. Jobs already **queued** for the hosted labels do not retarget and cannot be re-run in place, so for the documented indefinite-queue outage, cancel the stuck run and re-run all jobs, or push a new commit; "Re-run failed jobs" only helps once a job has actually failed rather than queued. -3. That is the entire switch. Under the `selfhosted` Linux failover value the workflow also drops `DSH_SNAPSHOT_MAX_CONCURRENCY` to 12 for the shared VM and skips the hosted-path pnpm cache restores because the VM's persistent store serves warm installs. Self-hosted coverage uses four single-worker instrumented partitions and two exempt workers; isolated hosted runners derive worker defaults from available CPUs. The Windows switch selects the native Windows pool and retains explicit worker limits on shared self-hosted runners. +3. That is the entire switch. Under the `selfhosted` Linux failover value the workflow also drops `DSH_SNAPSHOT_MAX_CONCURRENCY` to 12 for the shared VM and skips the hosted-path pnpm cache restores because the VM's persistent store serves warm installs. Self-hosted coverage runs two shard lanes of four single-worker instrumented partitions each, and the first shard also runs the exempt suites with two workers; isolated hosted runners derive worker defaults from available CPUs. The Windows switch selects the native Windows pool and retains explicit worker limits on shared self-hosted runners. **Dependabot exception.** Both switches' `selfhosted` legs deliberately exclude `dependabot[bot]`: under self-hosted failover, Dependabot PRs stay queued for the hosted pool rather than executing dependency-supplied code on the persistent VMs. A Dependabot PR that remains queued during an outage is expected behavior, not a failed switch; it completes when the hosted pool recovers. The `blacksmith` value's branches carry no such exclusion, because Blacksmith runners are ephemeral (see the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md)). diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md index c89acf64ea..d17a434556 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md @@ -6,11 +6,11 @@ Status: implemented ## 问题 -[CI](../../../../.github/workflows/ci.yml) 中三个必需的 Linux 工作作业(`node 24 / static`、`node 24 / coverage`、`node 24 / snapshots and artifacts`)运行在托管的企业级 32 核池上;聚合它们的必需判定作业(`all checks passed`)运行在标准 `ubuntu-latest` 上;[原生 Windows 作业](2026-08-08-native-windows-pull-request-ci.zh.md)(位于 [CI Windows](../../../../.github/workflows/ci-windows.yml))运行在托管的 `dsh-windows-2025-16core` 大型运行器上。当企业池发生故障——作业无限排队或企业标签消失——所有开启的拉取请求都无法合并,而"合并一个修复"这一常规恢复手段本身正被那些无法运行的必需检查死锁。**适用范围:两个独立开关,每个平台一个。**`DSH_CI_FAILOVER_LINUX` 恢复企业级 Linux 池故障(三个必需的 Linux 工作作业加 `all checks passed`、`windows checks passed` 与 `python checks passed` 判定作业);`DSH_CI_FAILOVER_WINDOWS` 恢复托管 Windows 池故障(原生 Windows 作业)。Linux 池故障无需重定向 Windows 作业,反之亦然。[Node 兼容性作业](../../../../.github/workflows/ci.yml)也通过隔离设置跟随 Linux 开关;判定作业的 `node-24-bench`、`python-sdk` 和 `python-runtime` 依赖仍留在标准托管运行器上,CI Python 的 `python-runtime` 也是如此;若更大范围的 GitHub 托管容量故障连标准池一并击倒,这些依赖仍会阻塞要求它们的判定。因此故障需要一个任何具备仓库写权限的响应者都能在不合并任何代码的情况下触发的开关。 +[CI](../../../../.github/workflows/ci.yml) 中必需的 Linux 工作作业(`node 24 / static`、`node 24 / coverage 1/2` 与 `2/2`、`node 24 / coverage report`、`node 24 / build`、`node 24 / snapshots and artifacts`、`node 24 / web snapshots 1/2` 与 `2/2`)运行在托管的企业级池上;聚合它们的必需判定作业(`all checks passed`)运行在标准 `ubuntu-latest` 上;[原生 Windows 作业](2026-08-08-native-windows-pull-request-ci.zh.md)(位于 [CI Windows](../../../../.github/workflows/ci-windows.yml))运行在托管的 `dsh-windows-2025-16core` 大型运行器上。当企业池发生故障——作业无限排队或企业标签消失——所有开启的拉取请求都无法合并,而"合并一个修复"这一常规恢复手段本身正被那些无法运行的必需检查死锁。**适用范围:两个独立开关,每个平台一个。**`DSH_CI_FAILOVER_LINUX` 恢复企业级 Linux 池故障(必需的 Linux 工作作业加 `all checks passed`、`windows checks passed` 与 `python checks passed` 判定作业);`DSH_CI_FAILOVER_WINDOWS` 恢复托管 Windows 池故障(原生 Windows 作业)。Linux 池故障无需重定向 Windows 作业,反之亦然。[Node 兼容性作业](../../../../.github/workflows/ci.yml)也通过隔离设置跟随 Linux 开关;判定作业的 `node-24-bench`、`python-sdk` 和 `python-runtime` 依赖仍留在标准托管运行器上,CI Python 的 `python-runtime` 也是如此;若更大范围的 GitHub 托管容量故障连标准池一并击倒,这些依赖仍会阻塞要求它们的判定。因此故障需要一个任何具备仓库写权限的响应者都能在不合并任何代码的情况下触发的开关。 ## 决策 -主要 Linux 作业(`node-24`、`node-24-coverage`、`node-24-build`、恢复 `node-24-build` 产物的 `node-24-consumers`,以及 `node-24-web-snapshot` 分片矩阵的两个条目)、两个 `node-compat` 矩阵条目,以及 `all-checks-passed`、`windows-checks-passed`、`python-checks-passed` 三个判定作业通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;`blacksmith` 取值按 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md) 路由参与切换的作业;未设置或任何其它值保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并在未设置与非特殊值下保留 `ubuntu-latest` 回退;blacksmith 分支不带上述任何条件。在 `selfhosted` 取值下,Linux 故障切换会限制快照并发,并跳过托管软件包缓存恢复。三个判定作业跟随 Linux 开关,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。 +主要 Linux 作业(`node-24`、`node-24-coverage` 分片矩阵的两个条目及合并它们的 `node-24-coverage-report`、`node-24-build`、恢复 `node-24-build` 产物的 `node-24-consumers`,以及 `node-24-web-snapshot` 分片矩阵的两个条目)、两个 `node-compat` 矩阵条目,以及 `all-checks-passed`、`windows-checks-passed`、`python-checks-passed` 三个判定作业通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;`blacksmith` 取值按 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md) 路由参与切换的作业;未设置或任何其它值保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并在未设置与非特殊值下保留 `ubuntu-latest` 回退;blacksmith 分支不带上述任何条件。在 `selfhosted` 取值下,Linux 故障切换会限制快照并发,并跳过托管软件包缓存恢复。三个判定作业跟随 Linux 开关,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。 [被取代 CI 的取消策略](../../../../.github/workflows/ci.yml) 管理同一工作流/引用组内的 master 推送和手动运行,包括热备演练。master 快速更新可能让演练因反复被取消而始终无法得出结论。判断就绪状态时,使用最近一次已完成的热备结论,并核对其时间和提交;已取消或仅被调度的运行不构成就绪证据。 @@ -32,7 +32,7 @@ Status: implemented 1. 仓库 **Settings → Secrets and variables → Actions → Variables → New repository variable**:名称 `DSH_CI_FAILOVER_LINUX`(Linux 池故障)或 `DSH_CI_FAILOVER_WINDOWS`(Windows 池故障),值 `selfhosted`。 2. 重新触发必需作业,使其重新解析运行器池。已经为托管标签**排队**的作业不会重定向,也无法原地 re-run,因此对于本手册所述的无限排队故障,应取消卡住的运行并 re-run all jobs,或推送一个新提交;“Re-run failed jobs”只有在作业真正失败(而非仍在排队)时才有用。 -3. 切换到此完成。在 `selfhosted` 的 Linux 故障切换取值下,工作流还会把 `DSH_SNAPSHOT_MAX_CONCURRENCY` 降为 12,以限制共享虚拟机上的争抢,并跳过托管路径的 pnpm 缓存恢复,因为虚拟机的持久 store 会直接提供热安装。自托管覆盖率使用 4 个单 worker 插桩分区与 2 个豁免 worker;独占的托管运行器根据可用 CPU 计算默认 worker 数。Windows 开关选择原生 Windows 运行器池,并在共享的自托管运行器上保留显式 worker 限制。 +3. 切换到此完成。在 `selfhosted` 的 Linux 故障切换取值下,工作流还会把 `DSH_SNAPSHOT_MAX_CONCURRENCY` 降为 12,以限制共享虚拟机上的争抢,并跳过托管路径的 pnpm 缓存恢复,因为虚拟机的持久 store 会直接提供热安装。自托管覆盖率分两条分片车道,每条 4 个单 worker 插桩分区,第一片另用 2 个 worker 运行豁免套件;独占的托管运行器根据可用 CPU 计算默认 worker 数。Windows 开关选择原生 Windows 运行器池,并在共享的自托管运行器上保留显式 worker 限制。 **Dependabot 例外。**两个开关的 `selfhosted` 腿都刻意排除 `dependabot[bot]`:自托管故障切换期间,Dependabot 拉取请求继续在托管池排队,而不是把依赖项提供的代码放到持久化虚拟机上执行。故障期间 Dependabot PR 持续排队是预期行为而非切换失败;托管池恢复后它会自行完成。`blacksmith` 取值下的分支不带此类排除,因为 Blacksmith 运行器是临时的(见 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md))。 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 146937a1bc..cba2a805fd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,8 +57,10 @@ jobs: # Enterprise jobs isolate coverage, static analysis, and the build-backed - # tail. The build job owns the only Linux artifact build; the consumer job - # and the two web snapshot shards restore its output instead of rebuilding. + # tail. Coverage runs two file shards on separate runners and merges them on + # one small report runner. The build job + # owns the only Linux artifact build; the consumer job and the two web + # snapshot shards restore its output instead of rebuilding. # # FAILOVER (Linux): each Linux enterprise job resolves its pool through the # DSH_CI_FAILOVER_LINUX repository variable. Unset (normal), the expressions @@ -149,8 +151,16 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'dsh-ubuntu-24-04-16core' }} - name: node 24 / coverage + # Two instrumented file shards run on separate runners; the first also + # runs the uninstrumented heavy suites. node-24-coverage-report merges the + # shard blobs and owns the thresholds and the duration history. + strategy: + fail-fast: false + matrix: + shard: [1, 2] + name: node 24 / coverage ${{ matrix.shard }}/2 env: + DSH_COVERAGE_SHARD: ${{ matrix.shard }}/2 # Shared hosts expose host CPUs, not an isolated allocation. DSH_COVERAGE_MAX_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }} DSH_COVERAGE_PARTITIONS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '4' || '' }} @@ -248,8 +258,92 @@ jobs: path: ~/.cache/dsh-ci/bubblewrap key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }} - - name: Run exhaustive coverage - run: pnpm run check:ci:coverage + - name: Run coverage shard + run: pnpm run check:ci:coverage-shard + + - name: Upload coverage shard blobs + uses: actions/upload-artifact@v7.0.1 + with: + name: coverage-blobs-${{ matrix.shard }} + path: coverage/shard/ + # A re-run of this shard replaces the previous attempt's output. + overwrite: true + if-no-files-found: error + include-hidden-files: true + retention-days: 30 + + # Merging blobs and checking thresholds runs after both coverage shards + # succeed. The merge converts every shard's V8 coverage to per-file reports + # and needs several GB of heap: a 2-vCPU runner took 154s against ~30s on the + # former 16-vCPU lane (run 44667701311), so this job uses an 8-vCPU runner. + # A failed shard skips this job, and the skipped result fails all-checks-passed. + node-24-coverage-report: + needs: node-24-coverage + if: github.event_name == 'pull_request' + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-8vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'dsh-ubuntu-24-04-8core' }} + name: node 24 / coverage report + steps: + # Runner cleanup owns tool caches and fixtures, including cancelled runs. + - name: Use runner-owned temporary storage + run: | + echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV" + + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + + # Redirect the Node compile cache (enabled by pnpm and TypeScript) off + # the root partition's /tmp before the first pnpm call in this lane. + - name: Redirect Node compile cache to runner temp + run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV" + + - uses: pnpm/action-setup@v5.0.0 + with: + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} + + - uses: actions/setup-node@v7.0.0 + with: + node-version: ${{ env.PRIMARY_NODE_VERSION }} + + - name: Configure pnpm store path + id: pnpm-store + run: | + store_root="$HOME/.local/share/pnpm/store" + echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV" + store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent) + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + # Self-hosted runners reuse the shared persistent pnpm store. + # Hosted runners restore the remote cache into their ephemeral store. + - uses: actions/cache/restore@v6.1.0 + if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]' + with: + path: ${{ steps.pnpm-store.outputs.path }} + key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm- + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Download coverage shard blobs + uses: actions/download-artifact@v8.0.1 + with: + pattern: coverage-blobs-* + path: ${{ runner.temp }}/coverage-shards + + # Node sizes its default heap from host memory; merging the whole + # inventory exceeded the ~2 GB default of a 2-vCPU runner (run + # 44664262449), so the merge states its heap instead of inheriting one. + - name: Merge coverage shards and check thresholds + env: + NODE_OPTIONS: --max-old-space-size=4096 + run: pnpm run test:coverage:merge-shards "$RUNNER_TEMP/coverage-shards" - name: Save coverage duration history if: ${{ !cancelled() }} @@ -402,10 +496,7 @@ jobs: env: # Shared hosts expose host CPUs, not an isolated allocation. DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '10' || '' }} - DSH_OXLINT_THREADS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} DSH_PUBLINT_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} - DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '' }} - DSH_NODE_COMPAT_SKIP_TYPECHECK: '1' # A failing gate aborts its running siblings. DSH_GATE_FAIL_FAST: '1' steps: @@ -512,9 +603,6 @@ jobs: env: # Shared hosts expose host CPUs, not an isolated allocation. DSH_GATE_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '10' || '' }} - DSH_OXLINT_THREADS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} - DSH_PUBLINT_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '8' || '' }} - DSH_WEB_SNAPSHOT_WORKERS: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '6' || '' }} DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '' }} DSH_NODE_COMPAT_SKIP_TYPECHECK: '1' # A failing gate aborts its running siblings. @@ -925,7 +1013,9 @@ jobs: # Single stable required check for branch protection: require "all checks # passed" instead of enumerating matrix legs whose names change as lanes and # node versions evolve. Every blocking job in THIS workflow must be listed in - # `needs`. `needs` cannot cross workflow files: native Windows jobs report + # `needs` or be needed by a listed job: a failed node-24-coverage shard skips + # node-24-coverage-report, and a skipped need fails this verdict. `needs` + # cannot cross workflow files: native Windows jobs report # the separate "windows checks passed" verdict from ci-windows.yml, Python # jobs report "python checks passed" from ci-python.yml, and Wine plus the # master-only runtime targets live in ci-master.yml. @@ -948,7 +1038,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [publisher-isolated, node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-build, node-24-consumers, node-24-web-snapshot, node-compat] + needs: [publisher-isolated, node-24, node-24-coverage-report, node-24-lint, node-24-bench, node-24-build, node-24-consumers, node-24-web-snapshot, node-compat] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/package.json b/package.json index e433b1d4fd..aa2aa84244 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "test:coverage": "pnpm run build:native-system && vitest run --coverage", "build:native-system": "tsx native/system/scripts/build.ts --host-addon-only", "test:coverage:partitioned": "tsx scripts/run-coverage-partitions.ts", + "test:coverage:merge-shards": "tsx scripts/merge-coverage-shards.ts", "test:e2e": "vitest run --config vitest.e2e.config.ts", "test:bench": "npm run build:bench && npm run build:web && npm run test:bench:built", "test:bench:built": "tsx scripts/run-bench-suite.ts", @@ -92,6 +93,7 @@ "check:ci:static": "tsx scripts/run-gates.ts ci-static", "check:ci:lint:contracts-ready": "tsx scripts/run-gates.ts ci-lint-contracts-ready", "check:ci:coverage": "tsx scripts/run-gates.ts ci-coverage", + "check:ci:coverage-shard": "tsx scripts/run-gates.ts ci-coverage-shard", "check:ci:unit": "tsx scripts/run-gates.ts ci-unit", "check:ci:bench": "tsx scripts/run-gates.ts ci-bench", "check:ci:snapshot": "tsx scripts/run-gates.ts ci-snapshot", diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index 3b7cb0a347..0649ad7179 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -15,7 +15,7 @@ const runnerPrivatePnpmDestination = /^\$\{\{ runner\.temp \}\}\/setup-pnpm-\$\{ const nativeWindowsPnpmDestination = '${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}' describe('CI workflow', () => { - it('keeps at most fourteen worker jobs active across PR workflows while Python runtime targets follow the SDK suite', () => { + it('keeps at most fifteen worker jobs active across PR workflows while Python runtime targets follow the SDK suite', () => { const ci = loadWorkflow('.github/workflows/ci.yml') const ciWindows = loadWorkflow('.github/workflows/ci-windows.yml') const ciPython = loadWorkflow('.github/workflows/ci-python.yml') @@ -45,8 +45,21 @@ describe('CI workflow', () => { expect(webSnapshot.strategy).toEqual({ 'fail-fast': false, matrix: { shard: [1, 2] } }) const webSnapshotShards = isRecord(webSnapshot.strategy) && isRecord(webSnapshot.strategy.matrix) && Array.isArray(webSnapshot.strategy.matrix.shard) ? webSnapshot.strategy.matrix.shard.length : 0 + // Coverage runs two instrumented file shards as one matrix; its report job + // starts only after both finish. + const coverage = workflowJob(ci, 'node-24-coverage') + expect(coverage.strategy).toEqual({ 'fail-fast': false, matrix: { shard: [1, 2] } }) + expect(coverage.name).toBe('node 24 / coverage ${{ matrix.shard }}/2') + const coverageLanes = isRecord(coverage.strategy) && isRecord(coverage.strategy.matrix) + && Array.isArray(coverage.strategy.matrix.shard) ? coverage.strategy.matrix.shard.length : 0 + expect(coverageLanes).toBe(2) + expect(workflowJob(ci, 'node-24-coverage-report').needs).toBe('node-24-coverage') + // The merge is CPU- and heap-bound; it runs on 8-vCPU pools. + const reportRunner = String(workflowJob(ci, 'node-24-coverage-report')['runs-on']) + expect(reportRunner).toContain("'blacksmith-8vcpu-ubuntu-2404'") + expect(reportRunner).toContain("'dsh-ubuntu-24-04-8core'") const ordinaryJobs = Object.entries(ci.jobs) - .filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated', 'node-24-web-snapshot'].includes(name)) + .filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated', 'node-24-web-snapshot', 'node-24-coverage', 'node-24-coverage-report'].includes(name)) for (const [name, job] of ordinaryJobs) { if (!isRecord(job)) throw new TypeError(`${name} must define a job`) expect(job).not.toHaveProperty('strategy') @@ -100,12 +113,13 @@ describe('CI workflow', () => { // The lint lane owns its own runner, so it raises the ceiling by one; the // self-hosted failover pool is still admitted only up to its own limit. // The build job finishes before its downstream jobs start, so the - // static count overstates the peak by one. - const linuxActive = ordinaryJobs.length + webSnapshotShards + // static count overstates the peak by one. Coverage counts its two + // shards; the coverage report starts after them and is not counted. + const linuxActive = ordinaryJobs.length + webSnapshotShards + coverageLanes const beforeSdk = linuxActive + compatibilityLimit + windowsActive + 1 const afterSdk = linuxActive + compatibilityLimit + windowsActive + Math.max(1, targets.split(',').length) - expect(beforeSdk).toBeLessThanOrEqual(14) - expect(afterSdk).toBeLessThanOrEqual(14) + expect(beforeSdk).toBeLessThanOrEqual(15) + expect(afterSdk).toBeLessThanOrEqual(15) }) it('keeps required PR verdicts covering runtime and publisher jobs', () => { @@ -125,13 +139,29 @@ describe('CI workflow', () => { expect(verdict.needs.every(id => typeof id === 'string' && id in jobs)).toBe(true) blocking.push(...(verdict.needs as string[])) } + // A job the verdict does not list must be needed by one it lists: a failed + // coverage shard skips its report job, and the verdict fails on a skip. + const ci = loadWorkflow('.github/workflows/ci.yml') + if (!isRecord(ci.jobs)) throw new TypeError('ci.yml must define jobs') + const covered = new Set() + const visit = (id: string): void => { + if (covered.has(id)) return + covered.add(id) + const needs = workflowJob(ci, id).needs + for (const need of Array.isArray(needs) ? needs : typeof needs === 'string' ? [needs] : []) { + if (typeof need === 'string') visit(need) + } + } + for (const id of workflowJob(ci, 'all-checks-passed').needs as string[]) visit(id) + expect(Object.keys(ci.jobs).filter(id => id !== 'all-checks-passed' && !covered.has(id))).toEqual([]) + expect(blocking).not.toContain('node-24-coverage') // Every blocking lane must contribute to a branch-protection verdict. expect(blocking.sort()).toEqual([ 'node-24', 'node-24-bench', 'node-24-build', 'node-24-consumers', - 'node-24-coverage', + 'node-24-coverage-report', 'node-24-lint', 'node-24-web-snapshot', 'node-compat', @@ -301,8 +331,39 @@ describe('CI workflow', () => { expect(wine.steps).toContainEqual(expect.objectContaining({ name: 'Shut down wineserver', if: 'always()' })) }) + it('restores Linux coverage timings on the shards and saves the merged timings only from the report job', () => { + const ci = loadWorkflow('.github/workflows/ci.yml') + const prefix = "coverage-times-Linux-${{ runner.environment }}-${{ vars.DSH_CI_FAILOVER_LINUX || 'enterprise' }}-" + const key = prefix + '${{ github.run_id }}-${{ github.run_attempt }}' + const stepsOf = (jobName: string): Record[] => { + const job = workflowJob(ci, jobName) + if (!Array.isArray(job.steps)) throw new TypeError(`${jobName} must define steps`) + return job.steps.filter(isRecord) + } + const lanes = stepsOf('node-24-coverage') + const restore = lanes.findIndex(step => step.name === 'Restore coverage duration history') + expect(restore).toBeGreaterThan(lanes.findIndex(step => step.uses === 'actions/checkout@v7.0.1')) + expect(lanes.findIndex(step => step.run === 'pnpm run check:ci:coverage-shard')).toBeGreaterThan(restore) + expect(lanes[restore]).toMatchObject({ + uses: 'actions/cache/restore@v6.1.0', + with: { path: '.coverage-times.json', key, 'restore-keys': `${prefix}\n` }, + }) + expect(lanes.filter(step => isRecord(step.with) && step.with.path === '.coverage-times.json' && step.uses === 'actions/cache/save@v6.1.0')).toEqual([]) + const report = stepsOf('node-24-coverage-report') + const merge = report.findIndex(step => step.run === 'pnpm run test:coverage:merge-shards "$RUNNER_TEMP/coverage-shards"') + expect(report[merge]).toMatchObject({ env: { NODE_OPTIONS: '--max-old-space-size=4096' } }) + expect(lanes.find(step => step.name === 'Upload coverage shard blobs')).toMatchObject({ with: { overwrite: true } }) + const save = report.findIndex(step => step.name === 'Save coverage duration history') + expect(merge).toBeGreaterThan(report.findIndex(step => step.uses === 'actions/download-artifact@v8.0.1')) + expect(save).toBeGreaterThan(merge) + expect(report[save]).toMatchObject({ + uses: 'actions/cache/save@v6.1.0', + if: '${{ !cancelled() }}', + with: { path: '.coverage-times.json', key }, + }) + }) + it.each([ - ['node-24-coverage', 'ci.yml', 'Linux', 'LINUX', 'pnpm run check:ci:coverage'], ['windows-coverage', 'ci-windows.yml', 'Windows', 'WINDOWS', 'pnpm run check:ci:coverage'], ])('reuses %s coverage timings only within its platform and runner pool', (jobName, file, platform, variable, command) => { const job = workflowJob(loadWorkflow('.github/workflows/' + file), jobName) @@ -357,7 +418,7 @@ describe('CI workflow', () => { } }) - it.each(['node-24', 'node-24-coverage', 'node-24-build', 'node-24-consumers', 'node-24-web-snapshot'])( + it.each(['node-24', 'node-24-coverage', 'node-24-coverage-report', 'node-24-build', 'node-24-consumers', 'node-24-web-snapshot'])( '%s keeps tool and fixture temporary files under runner cleanup', (jobName) => { const job = workflowJob(loadWorkflow('.github/workflows/ci.yml'), jobName) @@ -936,6 +997,7 @@ describe('CI workflow', () => { const redirectLanes = [ [prWorkflow, 'node-24'], [prWorkflow, 'node-24-coverage'], + [prWorkflow, 'node-24-coverage-report'], [prWorkflow, 'node-24-build'], [prWorkflow, 'node-24-consumers'], [prWorkflow, 'node-24-web-snapshot'], diff --git a/scripts/coverage-partitions.spec.ts b/scripts/coverage-partitions.spec.ts index 2e5ebdb705..8241e0c775 100644 --- a/scripts/coverage-partitions.spec.ts +++ b/scripts/coverage-partitions.spec.ts @@ -9,8 +9,13 @@ import { COVERAGE_PARTITIONS_ENV, COVERAGE_TEST_TIMEOUT_ENV, CoveragePartitionCoordinator, + COVERAGE_SHARD_DIRECTORY, assignWeightedPartitions, collectPartitionDurations, + FailedTestCollector, + mergeCoverageShards, + parseCoverageShard, + selectCoverageShardFiles, coverageTestTimeoutOptions, forwardedCoverageArgs, parseCoveragePartitionCount, @@ -775,3 +780,183 @@ describe('coverage partition coordinator', () => { await expect(access(marker)).resolves.toBeUndefined() }) }) + +describe('coverage file shards', () => { + // An absolute checkout root on any platform, distinct from every temporary root. + const otherCheckout = join(tmpdir(), 'dsh-coverage-other-checkout') + + it.each([ + [undefined, undefined], + ['', undefined], + ['1/2', { index: 1, count: 2 }], + ['2/2', { index: 2, count: 2 }], + ])('parses %j', (raw, expected) => { + expect(parseCoverageShard(raw)).toEqual(expected) + }) + + it.each(['3/2', '0/2', '1/0', 'a/b', '1'])('rejects %j', (raw) => { + expect(() => parseCoverageShard(raw)).toThrow(/DSH_COVERAGE_SHARD must be \//) + }) + + const sizes = new Map([['a.spec.ts', 90], ['b.spec.ts', 60], ['c.spec.ts', 50], ['d.spec.ts', 30], ['e.spec.ts', 20], ['f.spec.ts', 20]]) + const sizeOf = (file: string): number => sizes.get(file) ?? 0 + const inventory = [...sizes.keys()] + + it('deals files largest first to the lighter shard, independent of input order', () => { + expect(selectCoverageShardFiles(inventory, { index: 1, count: 2 }, sizeOf)).toEqual(['a.spec.ts', 'd.spec.ts', 'f.spec.ts']) + expect(selectCoverageShardFiles(inventory, { index: 2, count: 2 }, sizeOf)).toEqual(['b.spec.ts', 'c.spec.ts', 'e.spec.ts']) + expect(selectCoverageShardFiles([...inventory].reverse(), { index: 1, count: 2 }, sizeOf)) + .toEqual(selectCoverageShardFiles(inventory, { index: 1, count: 2 }, sizeOf)) + }) + + it.each([2, 3])('assigns every file to exactly one of %i shards', (count) => { + const shards = Array.from({ length: count }, (_, index) => selectCoverageShardFiles(inventory, { index: index + 1, count }, sizeOf)) + expect(shards.flat().sort()).toEqual([...inventory].sort()) + }) + + it('collects Vitest failure lines across split chunks and color codes', () => { + const collector = new FailedTestCollector() + collector.add('stdout', ' ✓ passes\n \u001b[31m×\u001b[39m breaks the con') + collector.add('stdout', 'tract 12ms\n') + collector.add('stderr', ' FAIL |thread-safe| a.spec.ts > suite > breaks the contract\nAssertionError: x\n FAIL b.spec.ts') + + expect(collector.lines()).toEqual([ + '× breaks the contract 12ms', + 'FAIL |thread-safe| a.spec.ts > suite > breaks the contract', + 'FAIL b.spec.ts', + ]) + }) + + it('writes the shard manifest, blobs, and durations instead of merging', async () => { + const root = await temporaryRoot() + // Byte sizes 40, 30, 20, 10 deal a and d to shard 1, b and c to shard 2. + for (const [file, size] of [['a.spec.ts', 40], ['b.spec.ts', 30], ['c.spec.ts', 20], ['d.spec.ts', 10]] as const) { + await writeFile(join(root, file), 'x'.repeat(size)) + } + const commands: CoverageCommand[] = [] + const coordinator = new CoveragePartitionCoordinator({ + root, + partitions: 2, + pnpmEntrypoint: '/pnpm.cjs', + files: ['a.spec.ts', 'b.spec.ts', 'c.spec.ts', 'd.spec.ts'], + shard: { index: 2, count: 2 }, + runCommand: successfulCommandRecorder(commands), + }) + + await expect(coordinator.run()).resolves.toBe(0) + + expect(commands.map(command => command.label)).toEqual(['partition 1/2', 'partition 2/2']) + const directory = join(root, COVERAGE_SHARD_DIRECTORY) + const manifest = JSON.parse(await readFile(join(directory, 'shard.json'), 'utf8')) as { shard: string; files: string[]; blobs: string[] } + expect(manifest).toEqual({ + shard: '2/2', + root, + files: ['b.spec.ts', 'c.spec.ts'], + blobs: ['shard-2-partition-1.json', 'shard-2-partition-2.json'], + }) + for (const blob of manifest.blobs) await expect(access(join(directory, 'blobs', blob))).resolves.toBeUndefined() + const times = JSON.parse(await readFile(join(directory, 'times.json'), 'utf8')) as Array<{ file: string }> + expect(times.map(entry => entry.file).sort()).toEqual(['b.spec.ts', 'c.spec.ts']) + }) + + /** Write one shard output directory as the report job downloads it. */ + async function writeShardOutput( + input: string, + index: number, + files: readonly string[], + root: string, + blobs = [`shard-${index}-partition-1.json`], + ): Promise { + const directory = join(input, `coverage-blobs-${index}`) + await mkdir(join(directory, 'blobs'), { recursive: true }) + for (const blob of blobs) await writeFile(join(directory, 'blobs', blob), JSON.stringify([join(root, 'packages', 'a', 'src', 'index.ts')])) + await writeFile(join(directory, 'shard.json'), JSON.stringify({ shard: `${index}/2`, root, files, blobs })) + await writeFile(join(directory, 'times.json'), JSON.stringify(files.map(file => ({ file, duration: 7 })))) + } + + async function mergeFixture(first: readonly string[], second: readonly string[]) { + const root = await temporaryRoot() + const input = await temporaryRoot() + await writeShardOutput(input, 1, first, root) + await writeShardOutput(input, 2, second, otherCheckout) + const commands: CoverageCommand[] = [] + const merge = () => mergeCoverageShards({ + root, + pnpmEntrypoint: '/pnpm.cjs', + inputDirectory: input, + inventory: ['a.spec.ts', 'b.spec.ts', 'c.spec.ts'], + runCommand: vi.fn(async (command: CoverageCommand) => { + commands.push(command) + return passed + }), + }) + return { root, input, commands, merge } + } + + it('merges every shard blob once and records the shard durations', async () => { + const { root, commands, merge } = await mergeFixture(['a.spec.ts', 'c.spec.ts'], ['b.spec.ts']) + + await expect(merge()).resolves.toBe(0) + + expect(commands).toHaveLength(1) + expect(commands[0]!.label).toBe('merged coverage report') + expect(commands[0]!.args).toContain('--merge-reports=coverage/.merge/blobs') + expect([...readFileDurations(root).keys()].sort()).toEqual(['a.spec.ts', 'b.spec.ts', 'c.spec.ts']) + }) + + it('rewrites the blob paths of a shard that ran in another checkout to this checkout', async () => { + const root = await temporaryRoot() + const input = await temporaryRoot() + await writeShardOutput(input, 1, ['a.spec.ts', 'c.spec.ts'], root) + await writeShardOutput(input, 2, ['b.spec.ts'], otherCheckout) + const merged: string[] = [] + await expect(mergeCoverageShards({ + root, + pnpmEntrypoint: '/pnpm.cjs', + inputDirectory: input, + inventory: ['a.spec.ts', 'b.spec.ts', 'c.spec.ts'], + runCommand: vi.fn(async () => { + for (const blob of ['shard-1-partition-1.json', 'shard-2-partition-1.json']) { + merged.push(...JSON.parse(await readFile(join(root, 'coverage/.merge/blobs', blob), 'utf8')) as string[]) + } + return passed + }), + })).resolves.toBe(0) + + expect(merged).toEqual([join(root, 'packages', 'a', 'src', 'index.ts'), join(root, 'packages', 'a', 'src', 'index.ts')]) + }) + + it.each([ + ['overlapping', ['a.spec.ts', 'b.spec.ts'], ['b.spec.ts', 'c.spec.ts']], + ['incomplete', ['a.spec.ts'], ['b.spec.ts']], + ['unexpected', ['a.spec.ts', 'c.spec.ts'], ['b.spec.ts', 'z.spec.ts']], + ])('refuses %s shard file lists before merging', async (_case, first, second) => { + const { commands, merge } = await mergeFixture(first, second) + + await expect(merge()).rejects.toThrow(/must partition the instrumented inventory/) + expect(commands).toEqual([]) + }) + + it('refuses a listed blob that the shard did not upload', async () => { + const { input, commands, merge } = await mergeFixture(['a.spec.ts', 'c.spec.ts'], ['b.spec.ts']) + await rm(join(input, 'coverage-blobs-2', 'blobs', 'shard-2-partition-1.json')) + + await expect(merge()).rejects.toThrow(/blob shard-2-partition-1.json is missing or empty/) + expect(commands).toEqual([]) + }) + + it('refuses a missing shard', async () => { + const { input, commands, merge } = await mergeFixture(['a.spec.ts', 'c.spec.ts'], ['b.spec.ts']) + await rm(join(input, 'coverage-blobs-2'), { recursive: true }) + + await expect(merge()).rejects.toThrow(/expected shards 1..n of one count/) + expect(commands).toEqual([]) + }) + + it('refuses shard input inside the coverage directory it replaces', async () => { + const root = await temporaryRoot() + await expect(mergeCoverageShards({ + root, pnpmEntrypoint: '/pnpm.cjs', inputDirectory: join(root, 'coverage', 'shards'), inventory: [], + })).rejects.toThrow(/must lie outside/) + }) +}) diff --git a/scripts/coverage-partitions.ts b/scripts/coverage-partitions.ts index b0cccc5338..35c13d6e41 100644 --- a/scripts/coverage-partitions.ts +++ b/scripts/coverage-partitions.ts @@ -1,12 +1,13 @@ /** * Coordinate single-worker Vitest coverage partitions and one merged report. * Separate processes preserve worker isolation; only the complete merged - * inventory can enforce per-file coverage thresholds. + * inventory can enforce per-file coverage thresholds. CI splits the inventory + * into file shards on separate runners and merges their blobs on one report job. */ import { spawn } from 'node:child_process' -import { globSync, readFileSync, writeFileSync } from 'node:fs' -import { lstat, mkdir, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises' -import { join, relative, sep } from 'node:path' +import { globSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { copyFile, lstat, mkdir, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises' +import { basename, isAbsolute, join, relative, sep } from 'node:path' import type { TestUserConfig } from 'vitest/config' import { coverageExemptHeavySuites } from './coverage-exempt.ts' import { pnpmInvocation } from './pnpm-invocation.ts' @@ -20,6 +21,79 @@ export const COVERAGE_PARTITION_MODE_ENV = 'DSH_COVERAGE_PARTITION_MODE' /** Environment variable carrying a lane's per-test, hook, and `expect.poll` budget in milliseconds. */ export const COVERAGE_TEST_TIMEOUT_ENV = 'DSH_COVERAGE_TEST_TIMEOUT_MS' +/** + * Environment variable selecting one file shard of the instrumented inventory, + * as `/`. A shard run writes {@link COVERAGE_SHARD_DIRECTORY} + * and leaves merging and thresholds to {@link mergeCoverageShards}. + */ +export const COVERAGE_SHARD_ENV = 'DSH_COVERAGE_SHARD' + +/** Root-relative directory where a shard run writes its manifest, blobs, and durations. */ +export const COVERAGE_SHARD_DIRECTORY = 'coverage/shard' + +/** One selected file shard: 1-based `index` of `count`. */ +export interface CoverageShard { + index: number + count: number +} + +/** + * Parse an optional coverage file shard. + * @param raw - the `DSH_COVERAGE_SHARD` value. + * @returns the shard, or undefined when unset or empty. + * @throws when the value is not `/` with 1 <= index <= count. + */ +export function parseCoverageShard(raw: string | undefined): CoverageShard | undefined { + if (raw === undefined || raw === '') return undefined + const match = /^([1-9]\d*)\/([1-9]\d*)$/.exec(raw) + if (match === null || Number(match[1]) > Number(match[2])) { + throw new Error(`${COVERAGE_SHARD_ENV} must be / with 1 <= index <= count, got ${JSON.stringify(raw)}.`) + } + return { index: Number(match[1]), count: Number(match[2]) } +} + +/** + * Select one shard's files by byte size: files are taken largest first (ties by + * repository-relative path) and each goes to the shard with the smallest total + * size so far (ties to the lower index). Byte size stands in for test cost; the + * split reads only the checkout, so every shard computes the same assignment. + * @param files - the instrumented inventory. + * @param shard - the shard to keep. + * @param sizeOf - byte size of one repository-relative file. + * @returns the shard's files in path order. + */ +export function selectCoverageShardFiles( + files: readonly string[], + shard: CoverageShard, + sizeOf: (file: string) => number, +): string[] { + const loads = Array.from({ length: shard.count }, () => 0) + const selected: string[] = [] + const ordered = [...files].map(file => ({ file, size: sizeOf(file) })) + .sort((left, right) => right.size - left.size || (left.file < right.file ? -1 : left.file > right.file ? 1 : 0)) + for (const { file, size } of ordered) { + let owner = 0 + for (let index = 1; index < loads.length; index++) { + if ((loads[index] ?? 0) < (loads[owner] ?? 0)) owner = index + } + loads[owner] = (loads[owner] ?? 0) + size + if (owner === shard.index - 1) selected.push(file) + } + return selected.sort() +} + +/** Manifest a shard run writes beside its blobs, read back by {@link mergeCoverageShards}. */ +export interface CoverageShardManifest { + /** The shard as `/`. */ + shard: string + /** Absolute checkout root of the shard run, the prefix of every path its blobs record. */ + root: string + /** Test files the shard ran, in path order. */ + files: string[] + /** Blob file names under the shard's `blobs/` directory. */ + blobs: string[] +} + /** * Reporter that canonicalizes a partition's coverage locations before its blob * is serialized (see scripts/coverage-canonical-locations.ts). Root-relative in @@ -55,6 +129,8 @@ export interface CoverageCommandResult { error?: string /** Bounded combined stdout/stderr tail repeated when the command fails. */ outputTail?: string + /** Vitest `FAIL` and `×` lines from the whole output, bounded, repeated in the run summary. */ + failedTests?: string[] } /** Execute one coordinator command with inherited output. */ @@ -78,6 +154,8 @@ export interface CoveragePartitionCoordinatorOptions { weights?: ReadonlyMap /** Project ownership paired with `files`; collected from `vitest list` when absent. */ projectOf?: ReadonlyMap + /** File shard to run; its manifest, blobs, and durations replace the merge and thresholds. */ + shard?: CoverageShard } /** Parse an optional coverage partition count. */ @@ -151,6 +229,11 @@ const UNKNOWN_FILE_WEIGHT = 1 */ const FILE_TIMES_NAME = '.coverage-times.json' +/** File names inside a shard directory. */ +const SHARD_MANIFEST_NAME = 'shard.json' +const SHARD_TIMES_NAME = 'times.json' +const SHARD_BLOBS_NAME = 'blobs' + /** * The instrumented inventory: every file plus the Vitest project it belongs * to (`thread-safe` or `process-bound`). Preserving the per-project split @@ -467,8 +550,10 @@ export class CoveragePartitionCoordinator { private readonly files: readonly string[] private readonly weights: ReadonlyMap | undefined private projectOf = new Map() + private readonly shard: CoverageShard | undefined private readonly temporaryRoot: string private readonly blobsRoot: string + private readonly blobPrefix: string /** Create a coordinator from validated process-independent inputs. */ public constructor(options: CoveragePartitionCoordinatorOptions) { @@ -483,17 +568,23 @@ export class CoveragePartitionCoordinator { this.files = options.files ?? [] this.weights = options.weights this.projectOf = new Map(options.projectOf ?? []) + this.shard = options.shard this.temporaryRoot = join(this.root, 'coverage', '.partitioned') - this.blobsRoot = join(this.temporaryRoot, 'blobs') + // Shard blobs carry the shard index so the report job can merge every + // shard's blobs from one directory. + this.blobsRoot = this.shard === undefined ? join(this.temporaryRoot, 'blobs') : join(this.root, COVERAGE_SHARD_DIRECTORY, SHARD_BLOBS_NAME) + this.blobPrefix = this.shard === undefined ? '' : `shard-${this.shard.index}-` } /** * Run every partition and verify its test-file inventory before one merged threshold check. + * A shard run instead writes its manifest, blobs, and durations under `coverage/shard/`. * Failed runs retain inventories, partition configs, and test reports in coverage/.partitioned. * @returns zero only when every partition and the merge command succeed. */ public async run(): Promise { await removeOwnedTree(join(this.root, 'coverage')) + await mkdir(this.temporaryRoot, { recursive: true }) await mkdir(this.blobsRoot, { recursive: true }) let succeeded = false @@ -513,6 +604,14 @@ export class CoveragePartitionCoordinator { } return result })) + reportFailedPartitions(commands, results) + if (this.shard !== undefined) { + await this.assertCompleteBlobSet(commands) + await this.assertCompleteTestFiles(assignments) + await this.writeShardOutput(this.shard, assignments, commands) + succeeded = !results.some(commandFailed) + return succeeded ? 0 : 1 + } // Persist durations before blob validation: a missing blob aborts the // run, but the completed partitions' timings are still worth keeping. this.persistDurations(this.partitions) @@ -555,6 +654,25 @@ export class CoveragePartitionCoordinator { writeFileDurations(this.root, collectPartitionDurations(reportFiles), currentFiles) } + /** Write the shard manifest and measured durations beside the shard's blobs. */ + private async writeShardOutput( + shard: CoverageShard, + assignments: readonly (readonly string[])[], + commands: readonly CoverageCommand[], + ): Promise { + const directory = join(this.root, COVERAGE_SHARD_DIRECTORY) + const manifest: CoverageShardManifest = { + shard: `${shard.index}/${shard.count}`, + root: this.root, + files: assignments.flat().sort(), + blobs: commands.map(command => basename(command.blobPath ?? '')).sort(), + } + const reportFiles = assignments.map((_, index) => join(this.temporaryRoot, `partition-${index + 1}.times.json`)) + await writeFile(join(directory, SHARD_MANIFEST_NAME), `${JSON.stringify(manifest, null, 1)}\n`, 'utf8') + const durations = [...collectPartitionDurations(reportFiles)].map(([file, duration]) => ({ file, duration })) + await writeFile(join(directory, SHARD_TIMES_NAME), `${JSON.stringify(durations, null, 1)}\n`, 'utf8') + } + /** * Distribute the instrumented inventory across partitions by recorded * duration, heaviest partition first so the longest child starts earliest @@ -578,6 +696,9 @@ export class CoveragePartitionCoordinator { this.projectOf = inventory.projectOf weights = readFileDurations(this.root) } + if (this.shard !== undefined) { + files = selectCoverageShardFiles(files, this.shard, file => statSync(join(this.root, file)).size) + } const buckets = assignWeightedPartitions(files, weights, this.partitions) buckets.sort((left, right) => partitionWeight(right, weights) - partitionWeight(left, weights)) return buckets @@ -599,7 +720,7 @@ export class CoveragePartitionCoordinator { } private partitionCommand(index: number, configPath: string): CoverageCommand { - const blobPath = join(this.blobsRoot, `partition-${index}.json`) + const blobPath = join(this.blobsRoot, `${this.blobPrefix}partition-${index}.json`) const reportsDirectory = join(this.temporaryRoot, `coverage-${index}`) const timingReportPath = join(this.temporaryRoot, `partition-${index}.times.json`) const invocation = pnpmInvocation([ @@ -632,21 +753,7 @@ export class CoveragePartitionCoordinator { } private mergeCommand(): CoverageCommand { - const invocation = pnpmInvocation([ - 'exec', - 'vitest', - `--merge-reports=${this.relativePath(this.blobsRoot)}`, - '--coverage', - ], { npm_execpath: this.pnpmEntrypoint }) - return { - label: 'merged coverage report', - ...invocation, - env: { - [COVERAGE_PARTITIONS_ENV]: undefined, - [COVERAGE_PARTITION_MODE_ENV]: undefined, - }, - cwd: this.root, - } + return mergeReportsCommand(this.root, this.pnpmEntrypoint, this.blobsRoot) } private relativePath(path: string): string { @@ -691,10 +798,167 @@ export class CoveragePartitionCoordinator { } } +/** Construction inputs for {@link mergeCoverageShards}. */ +export interface CoverageShardMergeOptions { + /** Repository root that owns coverage output. */ + root: string + /** pnpm JavaScript or executable entrypoint from `npm_execpath`. */ + pnpmEntrypoint: string + /** Directory outside `coverage/` whose immediate subdirectories each hold one shard's `coverage/shard/` output. */ + inputDirectory: string + /** Child executor, injectable for tests. */ + runCommand?: CoverageCommandRunner + /** Instrumented inventory; collected from the workspace when absent. */ + inventory?: readonly string[] +} + +/** One shard's validated output directory. */ +interface ShardOutput { + directory: string + shard: CoverageShard + root: string + files: string[] + blobs: string[] +} + +/** + * Merge the blobs of every file shard into one report with thresholds. Before + * merging, the shard file lists must be disjoint, their union must equal the + * re-listed instrumented inventory, and every listed blob must be present; + * the shards' measured durations replace `.coverage-times.json`. + * @param options - the repository, shard outputs, and optional injected executor and inventory. + * @returns zero only when the merged report and its thresholds pass. + * @throws when a shard output is malformed or the shards do not cover the inventory exactly once. + */ +export async function mergeCoverageShards(options: CoverageShardMergeOptions): Promise { + const coverageRoot = join(options.root, 'coverage') + const input = relative(coverageRoot, options.inputDirectory) + if (input === '' || (!input.startsWith('..') && !isAbsolute(input))) { + throw new Error(`coverage shard merge: input ${options.inputDirectory} must lie outside ${coverageRoot}, which the merge replaces.`) + } + await removeOwnedTree(coverageRoot) + const mergeRoot = join(coverageRoot, '.merge') + const blobsRoot = join(mergeRoot, SHARD_BLOBS_NAME) + await mkdir(blobsRoot, { recursive: true }) + const shards = await readShardOutputs(options.inputDirectory) + const inventory = options.inventory + ?? (await collectInstrumentedFiles(options.root, options.pnpmEntrypoint, join(mergeRoot, 'inventory.json'))).files + assertShardsCoverInventory(shards, inventory) + const blobNames = new Set() + for (const output of shards) { + for (const blob of output.blobs) { + if (blobNames.has(blob)) throw new Error(`coverage shard merge: blob ${blob} appears in more than one shard.`) + blobNames.add(blob) + await copyShardBlob(join(output.directory, SHARD_BLOBS_NAME, blob), join(blobsRoot, blob), output.root, options.root) + } + } + writeFileDurations(options.root, collectPartitionDurations(shards.map(output => join(output.directory, SHARD_TIMES_NAME))), inventory) + const command = mergeReportsCommand(options.root, options.pnpmEntrypoint, blobsRoot) + console.log(`coverage-partitions: start ${command.label} of ${shards.length} shards`) + const result = await (options.runCommand ?? runCoverageCommand)(command) + if (commandFailed(result)) { + console.error(`coverage-partitions: FAIL ${command.label} (${commandFailureReason(result)})`) + return 1 + } + await removeOwnedTree(mergeRoot) + return 0 +} + +/** + * Copy one shard blob into the merge directory. A blob records absolute source + * paths under its shard's checkout, and the merge keys coverage by those + * paths, so a shard whose checkout differs from this one has its root prefix + * rewritten in the serialized JSON strings to the merging checkout. + */ +async function copyShardBlob(source: string, target: string, shardRoot: string, mergeRoot: string): Promise { + if (shardRoot === mergeRoot) { + await copyFile(source, target) + return + } + const quoted = (path: string): string => JSON.stringify(`${path}${sep}`).slice(1, -1) + const content = await readFile(source, 'utf8') + await writeFile(target, content.split(quoted(shardRoot)).join(quoted(mergeRoot)), 'utf8') +} + +/** Read and validate every shard directory, requiring shards 1..count exactly once. */ +async function readShardOutputs(inputDirectory: string): Promise { + const entries = (await readdir(inputDirectory, { withFileTypes: true })).filter(entry => entry.isDirectory()) + const outputs = await Promise.all(entries.map(async (entry) => { + const directory = join(inputDirectory, entry.name) + const manifest: unknown = JSON.parse(await readFile(join(directory, SHARD_MANIFEST_NAME), 'utf8')) + if (manifest === null || typeof manifest !== 'object' || !('shard' in manifest) || typeof manifest.shard !== 'string' + || !('root' in manifest) || typeof manifest.root !== 'string' || !isAbsolute(manifest.root) + || !('files' in manifest) || !isStringArray(manifest.files) + || !('blobs' in manifest) || !isStringArray(manifest.blobs) || manifest.blobs.length === 0) { + throw new Error(`coverage shard merge: ${directory} needs a ${SHARD_MANIFEST_NAME} with shard, absolute root, files, and at least one blob.`) + } + const shard = parseCoverageShard(manifest.shard) + if (shard === undefined) throw new Error(`coverage shard merge: ${directory} names no shard.`) + for (const blob of manifest.blobs) { + const path = join(directory, SHARD_BLOBS_NAME, blob) + const metadata = basename(blob) === blob ? await lstatIfPresent(path) : undefined + if (metadata === undefined || !metadata.isFile() || metadata.size === 0) { + throw new Error(`coverage shard merge: shard ${manifest.shard} blob ${blob} is missing or empty at ${path}.`) + } + } + return { directory, shard, root: manifest.root, files: manifest.files, blobs: manifest.blobs } + })) + const count = outputs[0]?.shard.count + const indices = outputs.map(output => output.shard.index).sort((left, right) => left - right) + if (count === undefined || outputs.some(output => output.shard.count !== count) + || indices.length !== count || indices.some((index, position) => index !== position + 1)) { + throw new Error(`coverage shard merge: expected shards 1..n of one count under ${inputDirectory}, got ${JSON.stringify(outputs.map(output => `${output.shard.index}/${output.shard.count}`))}.`) + } + return outputs +} + +/** Require disjoint shard file lists whose union is exactly the instrumented inventory. */ +function assertShardsCoverInventory(shards: readonly ShardOutput[], inventory: readonly string[]): void { + const owner = new Map() + const overlapping: string[] = [] + for (const output of shards) { + for (const file of output.files) { + if (owner.has(file)) overlapping.push(file) + else owner.set(file, output.shard.index) + } + } + const expected = new Set(inventory) + const missing = inventory.filter(file => !owner.has(file)) + const unexpected = [...owner.keys()].filter(file => !expected.has(file)) + if (overlapping.length > 0 || missing.length > 0 || unexpected.length > 0) { + const sample = (files: readonly string[]): string => `${files.length} ${JSON.stringify(files.slice(0, 20))}` + throw new Error(`coverage shard merge: shard file lists must partition the instrumented inventory; overlapping ${sample(overlapping)}; missing ${sample(missing)}; unexpected ${sample(unexpected)}.`) + } +} + +function isStringArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every(item => typeof item === 'string') +} + +/** The single `vitest --merge-reports` command that applies thresholds to a blob directory. */ +function mergeReportsCommand(root: string, pnpmEntrypoint: string, blobsRoot: string): CoverageCommand { + const invocation = pnpmInvocation([ + 'exec', + 'vitest', + `--merge-reports=${relative(root, blobsRoot).split(sep).join('/')}`, + '--coverage', + ], { npm_execpath: pnpmEntrypoint }) + return { + label: 'merged coverage report', + ...invocation, + env: { + [COVERAGE_PARTITIONS_ENV]: undefined, + [COVERAGE_PARTITION_MODE_ENV]: undefined, + }, + cwd: root, + } +} + /** Spawn one pnpm-backed command without a platform shell. */ function runCoverageCommand(command: CoverageCommand): Promise { return new Promise((resolveCommand) => { let outputTail = '' + const failures = new FailedTestCollector() const env = { ...process.env } for (const [name, value] of Object.entries(command.env)) { if (value === undefined) Reflect.deleteProperty(env, name) @@ -710,20 +974,84 @@ function runCoverageCommand(command: CoverageCommand): Promise { process.stdout.write(chunk) outputTail = appendOutputTail(outputTail, chunk) + failures.add('stdout', chunk) }) child.stderr.on('data', (chunk: string) => { process.stderr.write(chunk) outputTail = appendOutputTail(outputTail, chunk) + failures.add('stderr', chunk) }) child.once('error', (error: Error) => { - resolveCommand({ exitCode: null, signalCode: null, error: error.message, outputTail }) + resolveCommand({ exitCode: null, signalCode: null, error: error.message, outputTail, failedTests: failures.lines() }) }) child.once('close', (exitCode, signalCode) => { - resolveCommand({ exitCode, signalCode, outputTail }) + resolveCommand({ exitCode, signalCode, outputTail, failedTests: failures.lines() }) }) }) } +/** ANSI color sequences Vitest writes around status markers. */ +const ANSI_COLOR = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g') + +/** Maximum failed-test lines one command keeps for the run summary. */ +const FAILED_TEST_LINE_LIMIT = 50 + +/** + * Collect Vitest failure lines (`FAIL > ` and `× `) across + * output chunks, which can split a line, so a failure stays visible after a + * long interleaved log. + */ +export class FailedTestCollector { + private readonly partial = new Map() + private readonly found: string[] = [] + + /** + * Add one output chunk. + * @param stream - the chunk's stream; partial lines are joined per stream. + * @param chunk - decoded output. + */ + public add(stream: string, chunk: string): void { + const text = (this.partial.get(stream) ?? '') + chunk + const lines = text.split('\n') + this.partial.set(stream, lines.pop() ?? '') + for (const line of lines) this.consider(line) + } + + /** @returns the collected lines, including a trailing unterminated line. */ + public lines(): string[] { + for (const [stream, rest] of this.partial) { + this.consider(rest) + this.partial.set(stream, '') + } + return [...this.found] + } + + private consider(line: string): void { + const plain = line.replace(ANSI_COLOR, '').trim() + if (!/^(FAIL|×)\s/.test(plain) || this.found.length >= FAILED_TEST_LINE_LIMIT) return + if (!this.found.includes(plain)) this.found.push(plain) + } +} + +/** + * Repeat each failed partition and its failed tests after every partition has + * finished, so the cause is at the end of an interleaved multi-partition log. + */ +function reportFailedPartitions(commands: readonly CoverageCommand[], results: readonly CoverageCommandResult[]): void { + const failed = commands.flatMap((command, index) => { + const result = results[index] + return result !== undefined && commandFailed(result) ? [{ command, result }] : [] + }) + if (failed.length === 0) return + console.error(`coverage-partitions: ${String(failed.length)} of ${String(commands.length)} partition(s) failed:`) + for (const { command, result } of failed) { + console.error(` ${command.label} (${commandFailureReason(result)})`) + const tests = result.failedTests ?? [] + if (tests.length === 0) console.error(' no Vitest FAIL line; see the output tail above') + for (const test of tests) console.error(` ${test}`) + } +} + function appendOutputTail(previous: string, chunk: string): string { const combined = previous + chunk return combined.length <= 65_536 ? combined : combined.slice(-65_536) @@ -742,11 +1070,15 @@ function commandFailureReason(result: CoverageCommandResult): string { return facts.join(', ') || 'no exit code or signal' } -async function removeOwnedTree(path: string): Promise { - const metadata = await lstat(path).catch((error: unknown) => { +async function lstatIfPresent(path: string): Promise> | undefined> { + return await lstat(path).catch((error: unknown) => { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined throw error }) +} + +async function removeOwnedTree(path: string): Promise { + const metadata = await lstatIfPresent(path) if (metadata === undefined) return if (metadata.isSymbolicLink() || !metadata.isDirectory()) { await unlink(path) diff --git a/scripts/merge-coverage-shards.ts b/scripts/merge-coverage-shards.ts new file mode 100644 index 0000000000..7001bc0b10 --- /dev/null +++ b/scripts/merge-coverage-shards.ts @@ -0,0 +1,26 @@ +/** + * CLI entry that merges downloaded coverage shard outputs into one thresholded + * report. The single argument names a directory outside `coverage/` whose + * subdirectories each hold one shard's `coverage/shard/` output. + */ +import { resolve } from 'node:path' +import { COVERAGE_EXEMPT_ENV } from './coverage-exempt.ts' +import { forwardedCoverageArgs, mergeCoverageShards } from './coverage-partitions.ts' + +const [inputDirectory, ...extra] = forwardedCoverageArgs(process.argv.slice(2)) +if (inputDirectory === undefined || extra.length > 0) { + throw new Error('usage: pnpm run test:coverage:merge-shards ') +} +const pnpmEntrypoint = process.env.npm_execpath +if (pnpmEntrypoint === undefined || pnpmEntrypoint === '') { + throw new Error('coverage shard merge must be invoked through a pnpm package script.') +} +// The shards ran with the exempt heavy suites excluded; the inventory +// listing and the merged report read the same configuration. +process.env[COVERAGE_EXEMPT_ENV] = '1' + +process.exitCode = await mergeCoverageShards({ + root: resolve(import.meta.dirname, '..'), + pnpmEntrypoint, + inputDirectory: resolve(inputDirectory), +}) diff --git a/scripts/run-coverage-partitions.ts b/scripts/run-coverage-partitions.ts index 4b2293c148..027efc78a6 100644 --- a/scripts/run-coverage-partitions.ts +++ b/scripts/run-coverage-partitions.ts @@ -1,10 +1,12 @@ -/** CLI entry for partitioned Vitest coverage. */ +/** CLI entry for partitioned Vitest coverage, optionally limited to one `DSH_COVERAGE_SHARD` file shard. */ import { resolve } from 'node:path' import { COVERAGE_PARTITIONS_ENV, + COVERAGE_SHARD_ENV, CoveragePartitionCoordinator, forwardedCoverageArgs, parseCoveragePartitionCount, + parseCoverageShard, } from './coverage-partitions.ts' const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV]) @@ -16,10 +18,12 @@ if (pnpmEntrypoint === undefined || pnpmEntrypoint === '') { throw new Error('partitioned coverage must be invoked through a pnpm package script.') } +const shard = parseCoverageShard(process.env[COVERAGE_SHARD_ENV]) const coordinator = new CoveragePartitionCoordinator({ root: resolve(import.meta.dirname, '..'), partitions, pnpmEntrypoint, vitestArgs: forwardedCoverageArgs(process.argv.slice(2)), + ...shard === undefined ? {} : { shard }, }) process.exitCode = await coordinator.run() diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index 4ac9318145..80736e7bfd 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -25,6 +25,7 @@ import { // DSH_COVERAGE_PARTITIONS to every child). beforeEach(() => { vi.stubEnv('DSH_WEB_SNAPSHOT_WORKERS', undefined) + vi.stubEnv('DSH_COVERAGE_SHARD', undefined) vi.stubEnv('DSH_COVERAGE_MAX_WORKERS', undefined) vi.stubEnv('DSH_COVERAGE_PARTITIONS', undefined) vi.stubEnv('DSH_CLI_HELP_CONCURRENCY', undefined) @@ -757,6 +758,37 @@ describe('gate graph validation', () => { }) }) + it.each([ + ['1/2', true], + ['2/2', false], + ] as const)('runs coverage file shard %s with the exempt heavy suites only on the first shard', (shard, ownsExempt) => { + const subject = withEnv('DSH_COVERAGE_SHARD', shard, () => withEnv('DSH_COVERAGE_PARTITIONS', '4', () => + withPnpmEntrypoint(() => gatesForMode('ci-coverage-shard')))) + + expect(subject.map(item => [item.id, item.needs ?? []])).toEqual([ + ['native-system', []], + ['coverage', ['native-system']], + ...ownsExempt ? [['coverage-exempt-heavy', ['native-system']]] : [], + ]) + expect(subject[1]).toMatchObject({ + args: ['/private/pnpm.cjs', 'run', 'test:coverage:partitioned'], + env: { DSH_COVERAGE_EXEMPT_HEAVY: '1' }, + }) + }) + + it('refuses a coverage shard lane without a shard', () => { + expect(() => withEnv('DSH_COVERAGE_PARTITIONS', '4', () => + withPnpmEntrypoint(() => gatesForMode('ci-coverage-shard')))) + .toThrow('ci-coverage-shard requires DSH_COVERAGE_SHARD') + }) + + it('leaves the exempt share of the coverage budget only on the first shard', () => { + expect(ciWorkerEnvironment('ci-coverage-shard', { DSH_COVERAGE_MAX_WORKERS: '6', DSH_COVERAGE_SHARD: '1/2' }, 16)) + .toHaveProperty('DSH_COVERAGE_PARTITIONS', '4') + expect(ciWorkerEnvironment('ci-coverage-shard', { DSH_COVERAGE_MAX_WORKERS: '6', DSH_COVERAGE_SHARD: '2/2' }, 16)) + .toHaveProperty('DSH_COVERAGE_PARTITIONS', '6') + }) + it('rejects an invalid coverage partition count before starting a gate', () => { expect(() => withEnv('DSH_COVERAGE_PARTITIONS', '1', () => withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')))) diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index 9a3fe3e627..79992b49d6 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -11,7 +11,7 @@ import { resolve } from 'node:path' import { performance } from 'node:perf_hooks' import { CLIENT_BUILD_PROFILE_SELECTOR } from './client-build-environment.ts' import { COVERAGE_EXEMPT_ENV, coverageExemptHeavySuites } from './coverage-exempt.ts' -import { COVERAGE_PARTITIONS_ENV, parseCoveragePartitionCount } from './coverage-partitions.ts' +import { COVERAGE_PARTITIONS_ENV, COVERAGE_SHARD_ENV, parseCoveragePartitionCount, parseCoverageShard } from './coverage-partitions.ts' import { LOCAL_TEST_PARALLELISM_CAP, defaultParallelism, describeDefaultParallelism } from './parallelism.ts' import { pnpmInvocation } from './pnpm-invocation.ts' @@ -22,6 +22,7 @@ export type Mode = | 'ci-static' | 'ci-lint-contracts-ready' | 'ci-coverage' + | 'ci-coverage-shard' | 'ci-unit' | 'ci-bench' | 'ci-snapshot' @@ -165,6 +166,7 @@ function parseMode(raw: string | undefined): Mode { case 'ci-static': case 'ci-lint-contracts-ready': case 'ci-coverage': + case 'ci-coverage-shard': case 'ci-unit': case 'ci-bench': case 'ci-snapshot': @@ -185,7 +187,7 @@ function parseMode(raw: string | undefined): Mode { return raw default: throw new Error( - `run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | ci-unit | ci-bench | ci-snapshot | ci-artifacts | ci-consumers | ci-build | ci-consumers-prebuilt | ci-web-snapshot-prebuilt | ci-windows-blocking | ci-windows-complete | ci-windows-observational-ready | node-compat | check-all | hygiene | doc-sync | doc-quick | i18n, got ${JSON.stringify(raw)}.`, + `run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | ci-coverage-shard | ci-unit | ci-bench | ci-snapshot | ci-artifacts | ci-consumers | ci-build | ci-consumers-prebuilt | ci-web-snapshot-prebuilt | ci-windows-blocking | ci-windows-complete | ci-windows-observational-ready | node-compat | check-all | hygiene | doc-sync | doc-quick | i18n, got ${JSON.stringify(raw)}.`, ) } } @@ -256,7 +258,10 @@ export function ciWorkerEnvironment( if (!Number.isSafeInteger(total) || total < 1) { throw new Error(`run-gates: DSH_COVERAGE_MAX_WORKERS must be a positive integer, got ${JSON.stringify(coverageBudget)}.`) } - const instrumented = Math.max(1, total - Math.max(1, Math.floor(total / 3))) + // Only the first coverage shard runs the exempt sibling; the others give + // their partitions the whole budget. + const ownsExempt = mode !== 'ci-coverage-shard' || parseCoverageShard(env[COVERAGE_SHARD_ENV])?.index === 1 + const instrumented = ownsExempt ? Math.max(1, total - Math.max(1, Math.floor(total / 3))) : total if (instrumented > 1) setDefault(COVERAGE_PARTITIONS_ENV, instrumented) return additions } @@ -330,6 +335,8 @@ export function gatesForMode(selected: Mode): Gate[] { ] case 'ci-coverage': return coverageGates() + case 'ci-coverage-shard': + return coverageShardGates() case 'ci-unit': return ciUnitGates() case 'ci-bench': @@ -824,25 +831,55 @@ function coverageGates(platform: NodeJS.Platform = process.platform): Gate[] { label: 'test:coverage', env: { [COVERAGE_EXEMPT_ENV]: '1' }, }) - : pnpmScript('coverage', 'test:coverage:partitioned', { - label: 'test:coverage', - displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`, - env: { [COVERAGE_EXEMPT_ENV]: '1' }, - streamOutput: true, - }) + : partitionedCoverageGate(partitions) return [ pnpmScript('native-system', 'build:native-system'), ...electron, { ...instrumented, needs: ['native-system', ...electron.map(gate => gate.id)] }, - pnpmExec('coverage-exempt-heavy', [ - 'vitest', - 'run', - ...coverageExemptHeavySuites.map(suite => suite.filter), - ...workers.exempt, - ], { - label: 'test:coverage-exempt-heavy', - needs: ['native-system'], - }), + coverageExemptHeavyGate(workers.exempt), + ] +} + +function partitionedCoverageGate(partitions: number): Gate { + return pnpmScript('coverage', 'test:coverage:partitioned', { + label: 'test:coverage', + displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`, + env: { [COVERAGE_EXEMPT_ENV]: '1' }, + streamOutput: true, + }) +} + +function coverageExemptHeavyGate(workerArgs: readonly string[]): Gate { + return pnpmExec('coverage-exempt-heavy', [ + 'vitest', + 'run', + ...coverageExemptHeavySuites.map(suite => suite.filter), + ...workerArgs, + ], { + label: 'test:coverage-exempt-heavy', + needs: ['native-system'], + }) +} + +// One CI file shard of the instrumented inventory (DSH_COVERAGE_SHARD); the +// coordinator writes coverage/shard/ and the report job merges and applies +// thresholds. The first shard also runs the uninstrumented heavy suites with +// the coverage lane's usual worker split. Sharding needs the partition +// coordinator, so a missing count is a misconfiguration rather than a +// whole-inventory fallback. +function coverageShardGates(): Gate[] { + const shard = parseCoverageShard(process.env[COVERAGE_SHARD_ENV]) + if (shard === undefined) { + throw new Error(`run-gates: ci-coverage-shard requires ${COVERAGE_SHARD_ENV}.`) + } + const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV]) + if (partitions === undefined) { + throw new Error(`run-gates: ci-coverage-shard requires ${COVERAGE_PARTITIONS_ENV} or a coverage worker budget of at least 2.`) + } + return [ + pnpmScript('native-system', 'build:native-system'), + { ...partitionedCoverageGate(partitions), needs: ['native-system'] }, + ...shard.index === 1 ? [coverageExemptHeavyGate(coverageWorkerArgs().exempt)] : [], ] } From b5161a15794c6abf1d2609d9584b0de6cabead26 Mon Sep 17 00:00:00 2001 From: Shigma Date: Fri, 20 Nov 2026 03:18:28 +0800 Subject: [PATCH 36/54] fix(ui): keep model menu open when pressing non-focusable content --- .../src/client/ModelSelect.tsx | 13 +++++++++-- .../tests/model-menu-pane.client.spec.tsx | 2 ++ .../tests/model-select.client.spec.tsx | 22 +++++++++++++++++-- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index 6cd67bdcc4..67a40e15fe 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -482,8 +482,17 @@ export function ModelSelect( onKeyDown={onRootKeyDown} onBlur={onBlur} onMouseDown={(event) => { - // WebKit blurs a focused row before click unless the button's mousedown keeps focus. - if (event.target instanceof Element && event.target.closest('button') !== null) event.preventDefault() + // WebKit blurs a focused row before click unless the button's mousedown + // keeps focus. Pressing non-focusable card content (a provider heading, + // padding, status text) would move focus to the body and close the card + // through onBlur; a detail pane keeps the default so its prose stays + // selectable. + const { target } = event + if (target instanceof Element && ( + target.closest('button') !== null + || (pane.kind !== 'detail' && menuRef.current?.contains(target) === true + && target.closest('input, textarea, select, [contenteditable]') === null) + )) event.preventDefault() }} > + return <>{extraOption} } if (name === 'conversation.input.model.pane') { const controls = owner as object as OwnerOf<'conversation.input.model.pane'> @@ -88,6 +88,23 @@ it.each([false, true])('closes a detail pane on Tab without changing its setting expect(change).not.toHaveBeenCalled() }) +it('keeps the default press on focusable plugin options that are not buttons', () => { + const { trigger } = setup(true, <> +
Tabbable option
+ Fixture link + Plain option text + ) + const tabbable = screen.getByTestId('tabbable') + // true = default kept, so the browser can move focus to the control. + expect(fireEvent.mouseDown(screen.getByText('Tabbable option'))).toBe(true) + expect(fireEvent.mouseDown(screen.getByRole('link', { name: 'Fixture link' }))).toBe(true) + // Non-focusable option content still keeps the current focus. + expect(fireEvent.mouseDown(screen.getByText('Plain option text'))).toBe(false) + act(() => { tabbable.focus() }) + expect(document.activeElement).toBe(tabbable) + expect(trigger.getAttribute('aria-expanded')).toBe('true') +}) + it('keeps the baseline model-save lock on both summary and detail controls', () => { const { directory } = setup() act(() => { directory.update((state) => { state.pending = { provider: 'fixture', model: 'fixture' } }) }) diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index e8a3f81c05..4f2efdabab 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -1664,14 +1664,14 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.label\', () => ctx.slots.register(\n { name: \'conversation.input.model.label\' },\n ({ provider, model }) => React.createElement(\'span\', { title: provider.name }, model.name),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:80', + source: 'packages/client/ui-model-selection/src/client/slots.ts:84', }, { key: 'conversation.input.model.options', kind: 'list', scope: 'session', summary: 'Session options appended after model and reasoning controls in the root menu.', - doc: 'Session options appended after model and reasoning controls in the root menu.', + doc: 'Session options appended after model and reasoning controls in the root menu.\nRender each interactive entry as a `button` with role `menuitem`, `menuitemradio`, or `switch`:\nArrow keys and Tab reach only those rows.', registerOptions: [ { name: 'id', @@ -1729,7 +1729,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.options\', () => ctx.slots.register(\n { name: \'conversation.input.model.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:50', + source: 'packages/client/ui-model-selection/src/client/slots.ts:54', }, { key: 'conversation.input.model.pane', @@ -1779,7 +1779,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model.pane\', () => ctx.slots.register(\n { name: \'conversation.input.model.pane\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-model-selection/src/client/slots.ts:60', + source: 'packages/client/ui-model-selection/src/client/slots.ts:64', }, { key: 'conversation.input.overlay', From c0a05ff31e4817491a728dba312bed13d3d076f8 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:46:59 +0800 Subject: [PATCH 46/54] ci: rebuild the benchmark native addon when the restored one does not load node-24-build can run on the self-hosted pool while the benchmarks stay on hosted Linux; the phase jobs now load the restored Node-API addon and rebuild it on their runner if it fails. The report spec cleans its directories with onTestFinished, which also removes a clone the duplication gate reported. --- .github/workflows/ci.yml | 14 ++++++++++++++ scripts/ci-workflow.spec.ts | 7 ++++++- scripts/render-benchmark-report.spec.ts | 10 +++------- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2cb64bc1e2..c3c7cc71e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -490,6 +490,20 @@ jobs: zstd -dc -T0 "$archive" | tar -xmf - test -f apps/cli/lib/bin.js && test -f apps/web/dist/index.html && test -f .dsh-build/client-build-environment.json + # node-24-build can run on another pool (vm-backup under self-hosted + # failover) while the benchmarks stay on hosted Linux, so the restored + # Node-API addon is loaded here and rebuilt on this runner if it fails. + - name: Rebuild the native addon if the restored one does not load + run: | + addon=native/system/packages/linux-x64/bin/glibc/system.node + if node -e 'process.dlopen({ exports: {} }, process.argv[1])' "$addon"; then + echo "Restored native addon loads on this runner." + else + echo "::notice::Restored native addon does not load on this runner; rebuilding it." + pnpm run build:native-system + node -e 'process.dlopen({ exports: {} }, process.argv[1])' "$addon" + fi + - name: Install benchmark browser and hosted dependencies run: pnpm --filter @deepseek-ai/dsh-benchmarks exec playwright install --with-deps chromium diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index 5c9cae1b98..2af2c236be 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -866,7 +866,12 @@ describe('CI workflow', () => { expect(steps[index('Download build output')]).toMatchObject({ uses: 'actions/download-artifact@v8.0.1', with: { name: 'build-output' } }) expect(index('Download build output')).toBeGreaterThan(index('Install (immutable)')) expect(index('Unpack build output')).toBeGreaterThan(index('Download build output')) - expect(index('Run performance benchmarks')).toBeGreaterThan(index('Unpack build output')) + // A restored addon from another runner pool that does not load is rebuilt here. + const addon = index('Rebuild the native addon if the restored one does not load') + expect(addon).toBeGreaterThan(index('Unpack build output')) + expect(index('Run performance benchmarks')).toBeGreaterThan(addon) + expect(String(steps[addon]?.run)).toContain('process.dlopen({ exports: {} }, process.argv[1])') + expect(String(steps[addon]?.run)).toContain('pnpm run build:native-system') expect(String(steps[index('Unpack build output')]?.run)).toContain('tar -xmf -') }) diff --git a/scripts/render-benchmark-report.spec.ts b/scripts/render-benchmark-report.spec.ts index 767b8559fa..c589471be1 100644 --- a/scripts/render-benchmark-report.spec.ts +++ b/scripts/render-benchmark-report.spec.ts @@ -1,17 +1,13 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' +import { describe, expect, it, onTestFinished } from 'vitest' import { mergeReportDirectories, renderMergedReport } from '../benchmarks/support/scaling-report.ts' -const roots: string[] = [] -afterEach(async () => { - for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true }) -}) - +/** A private directory removed when the current test finishes. */ async function temporaryRoot(): Promise { const root = await mkdtemp(join(tmpdir(), 'dsh-benchmark-report-')) - roots.push(root) + onTestFinished(() => rm(root, { recursive: true, force: true })) return root } From f5b4ef4cc951599c309216f092ff5569ab02837f Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:50:49 +0800 Subject: [PATCH 47/54] test(web): sample fold gaps after animation frame writes Observe the rendered root anew each frame so an earlier test callback cannot count a gap corrected later in that frame. Keep the existing size/frame limits and check consecutive equal bad frames with a deterministic Chromium control. Refs #6336. --- ...26-10-13-chat-single-fold-motion.i18n.yaml | 4 +- .../2026-10-13-chat-single-fold-motion.md | 2 +- .../2026-10-13-chat-single-fold-motion.zh.md | 2 +- apps/web/tests/fold-blank-matrix.e2e.ts | 67 +++++++++++++++++-- 4 files changed, 65 insertions(+), 10 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml index de7db438b5..8a6b2ca486 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.i18n.yaml @@ -21,8 +21,8 @@ en: ca6a5c372bb3cad1 zh: 1cd5028269b58c65 /agent-note-one-fold-motion-for-collapsing-on-the-next-message/testing: - en: 0423a607ee0589b5 - zh: 61df892a01c5aa43 + en: 6928ea8cc28112e5 + zh: e9d69605558ea102 /agent-note-one-fold-motion-for-collapsing-on-the-next-message/alternatives-considered: en: d8e1ea66e293cd93 zh: 0aaa9e693f441673 diff --git a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md index ebb4ab4087..e862c255ee 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md +++ b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.md @@ -73,7 +73,7 @@ Let `start` be the scrollTop when the batch begins, `above` the height of closin ## Testing -[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) covers 19 main-Session cases and 8 right-Sidebar child cases across reader position (bottom, middle of the body, top of the body, inside the steps, previous Turn), input source (composer, Turn failing before its message is recorded, another tab, queued delivery, steer, parent message, several Turns folding at once), body length, and Standard and "On completion" controls. The layout gap is the tallest band between the scrollport top and the composer that no visible row's box covers: at most 120 px once settled, and over that for at most one animation frame. It counts boxes, so a closing row that has faded but not finished shrinking still covers its space. Tail cases assert the floor landing; reader-content-still cases assert that the reader's anchor row moves at most 2 px on screen. Short-body cases assert only that no room remains after the reply arrives. +[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) covers 19 main-Session cases and 8 right-Sidebar child cases across reader position (bottom, middle of the body, top of the body, inside the steps, previous Turn), input source (composer, Turn failing before its message is recorded, another tab, queued delivery, steer, parent message, several Turns folding at once), body length, and Standard and "On completion" controls. The layout gap is the tallest band between the scrollport top and the composer that no visible row's box covers: at most 120 px once settled, and over that for at most one animation frame. The probe reads the layout after the animation callbacks for each rendering opportunity, before paint. Identical gaps on consecutive frames count separately. It counts boxes, so a closing row that has faded but not finished shrinking still covers its space. Tail cases assert the floor landing; reader-content-still cases assert that the reader's anchor row moves at most 2 px on screen. Short-body cases assert only that no room remains after the reply arrives. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md index 88d8dc6893..5a7712989a 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md @@ -73,7 +73,7 @@ Status: implemented ## Testing -[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) 覆盖主会话 19 例与右侧栏子会话 8 例,维度包括读者位置(底部、正文中段、正文开头、步骤中间、上一轮)、输入来源(输入框、回合在写入消息前失败、另一个标签页、排队投递、steer、父消息、一次折叠多轮)、正文长短,以及 Standard 与「完成时收起」对照。布局空洞指视口顶部到输入框之间没有任何可见行的盒子覆盖的最大连续高度:落定后不超过 120 px,动画中至多 1 帧超过。它按盒子计算,已经淡出但尚未收完的收起行仍算作覆盖。「到底部」的用例断言落到底部;「内容不动」的用例断言读者锚定行的屏幕位置变化不超过 2 px。正文很短的用例只断言回复到达后不再留空。 +[fold-blank-matrix.e2e.ts](../../../../apps/web/tests/fold-blank-matrix.e2e.ts) 覆盖主会话 19 例与右侧栏子会话 8 例,维度包括读者位置(底部、正文中段、正文开头、步骤中间、上一轮)、输入来源(输入框、回合在写入消息前失败、另一个标签页、排队投递、steer、父消息、一次折叠多轮)、正文长短,以及 Standard 与「完成时收起」对照。布局空洞指视口顶部到输入框之间没有任何可见行的盒子覆盖的最大连续高度:落定后不超过 120 px,动画中至多 1 帧超过。探针在每次渲染机会的动画回调全部结束、绘制之前读取布局;相邻两帧的空洞即使相同,也分别计数。它按盒子计算,已经淡出但尚未收完的收起行仍算作覆盖。「到底部」的用例断言落到底部;「内容不动」的用例断言读者锚定行的屏幕位置变化不超过 2 px。正文很短的用例只断言回复到达后不再留空。 ## Alternatives considered diff --git a/apps/web/tests/fold-blank-matrix.e2e.ts b/apps/web/tests/fold-blank-matrix.e2e.ts index 688205f072..3665dcf823 100644 --- a/apps/web/tests/fold-blank-matrix.e2e.ts +++ b/apps/web/tests/fold-blank-matrix.e2e.ts @@ -349,12 +349,22 @@ async function startTrace(page: Page, root: string): Promise { if (read === undefined) throw new Error('fold measurement is not installed') const samples: Geometry[] = [] let frame = 0 + let pending = false + const observer = new ResizeObserver(() => { + if (!pending) return + pending = false + // A scrollport or its composer can remount between rendering opportunities. + if (document.querySelector(selector)?.querySelector('[data-composer-seat]')) samples.push(read(selector)) + }) const tick = (): void => { - // A scrollport can remount between frames; that frame contributes no sample. - try { samples.push(read(selector)) } catch (_remounting) { /* skip this frame */ } + // A fresh observation is delivered after *all* rAF writers, before paint, even when the root box is unchanged. + // Reading here instead can count a gap that the fold's later callback closes in the very same frame. + pending = true + observer.unobserve(document.documentElement) + observer.observe(document.documentElement) frame = requestAnimationFrame(tick) } - window.foldProbe = { samples, stop: () => { cancelAnimationFrame(frame) } } + window.foldProbe = { samples, stop: () => { cancelAnimationFrame(frame); observer.disconnect() } } frame = requestAnimationFrame(tick) }, root) } @@ -848,12 +858,13 @@ describe.skipIf(MODE === 'record')('web e2e: blank area after next-message foldi try { world = await openWorld(browser, scenario, replayDir) const { afterFold, afterTurn, samples, anchors } = await run(world, scenario) - const transient = samples.filter(sample => sample.maxGap > BLANK_LIMIT) + const transient = samples.flatMap((sample, frame) => sample.maxGap > BLANK_LIMIT + ? [{ frame, gap: Math.round(sample.maxGap), at: Math.round(sample.gapAt), collapsing: sample.collapsing }] : []) const summary = { id: scenario.id, landing: scenario.landing, before: samples[0] === undefined ? null : rounded(samples[0]), afterFold: rounded(afterFold), afterTurn: rounded(afterTurn), anchors, peakGap: Math.round(Math.max(0, ...samples.map(sample => sample.maxGap))), - framesOverLimit: transient.length, frames: samples.length, + framesOverLimit: transient.length, firstOverLimit: transient.slice(0, TRANSIENT_FRAMES + 1), frames: samples.length, peakSpacer: Math.round(Math.max(0, ...samples.map(sample => sample.spacer))), } const evidence = async (): Promise => { @@ -864,7 +875,10 @@ describe.skipIf(MODE === 'record')('web e2e: blank area after next-message foldi // Per-frame evidence is written for failures, or for every case with FOLDMX_EVIDENCE=1. if (process.env.FOLDMX_EVIDENCE === '1') await evidence() else onTestFailed(evidence) - if (scenario.origin === 'parent-message' || scenario.origin === 'steer') { + expect(samples.length, 'post-layout frame samples').toBeGreaterThan(0) + if (scenario.anchorFolds) { + expect.soft(samples.some(sample => sample.collapsing), 'sampled a closing row during the reader fold').toBe(true) + } else if (scenario.origin === 'parent-message' || scenario.origin === 'steer') { expect.soft(samples.some(sample => sample.collapsing), 'a control case folds nothing').toBe(false) } if (scenario.roomUntilReply !== true) { @@ -898,6 +912,47 @@ describe.skipIf(MODE === 'record')('web e2e: blank area after next-message foldi export {} describe('web e2e: fold blank measurement', () => { + it('counts gaps left by the frame writers, including consecutive frames with the same gap', async () => { + const browser = await chromium.launch() + try { + const page = await browser.newPage() + await page.setContent(`
+
+
+
+
`) + await page.evaluate(installMeasure) + // Register an early writer before the probe and a late writer after it, all on the browser's frame clock. + const drive = await page.evaluateHandle(() => { + const row = document.querySelector('[data-chat-flow-key="b"]')! + let active = false + let earlyFrame = 0 + const early = (): void => { + if (active) row.style.marginTop = '240px' + earlyFrame = requestAnimationFrame(early) + } + earlyFrame = requestAnimationFrame(early) + return () => new Promise((done) => { + active = true + const gaps = [0, 180, 180, 0] + let index = 0 + const late = (): void => { + row.style.marginTop = `${gaps[index++]}px` + if (index < gaps.length) requestAnimationFrame(late) + else { cancelAnimationFrame(earlyFrame); requestAnimationFrame(() => { done() }) } + } + requestAnimationFrame(late) + }) + }) + await startTrace(page, '#viewport') + await drive.evaluate(start => start()) + const samples = await stopTrace(page) + expect(samples.filter(sample => sample.maxGap > BLANK_LIMIT).map(sample => sample.maxGap)).toEqual([180, 180]) + } finally { + await browser.close() + } + }) + it('skips a band between fully transparent rows and counts a band beside a visible row', async () => { const browser = await chromium.launch() try { From beaa489423e8bf82bc546fb674c215a4b9e7eaea Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 20 Nov 2026 16:02:31 +0800 Subject: [PATCH 48/54] test(voice-input): give the manual-source readiness wait the spawn budget "pins a manual source to one preparation" waited for `ready` with vi.waitFor's default 1,000 ms after starting a real worker subprocess. On a loaded coverage runner that start took longer (the file ran 28 s against 11 s on the passing run), so the case failed twice in a row on this branch with `expected 'loading' to be 'ready'`. The wait now takes the 10,000 ms budget that this file's other readiness waits after a subprocess start already use. --- .../experimental/speech-to-text-sensevoice/tests/worker.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/experimental/speech-to-text-sensevoice/tests/worker.spec.ts b/packages/experimental/speech-to-text-sensevoice/tests/worker.spec.ts index 5ee007e489..9ed82e975b 100644 --- a/packages/experimental/speech-to-text-sensevoice/tests/worker.spec.ts +++ b/packages/experimental/speech-to-text-sensevoice/tests/worker.spec.ts @@ -67,7 +67,7 @@ it('pins a manual source to one preparation without changing deployment defaults const { worker } = await fixture() expect(worker.downloadSources).toEqual(['https://huggingface.co', 'https://hf-mirror.com']) worker.prepare({ downloadSource: 'https://hf-mirror.com' }) - await vi.waitFor(() => { expect(worker.snapshot().phase).toBe('ready') }) + await vi.waitFor(() => { expect(worker.snapshot().phase).toBe('ready') }, { timeout: 10000 }) expect(prepareRuntime).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ modelOrigin: 'https://hf-mirror.com' }), expect.any(AbortSignal), expect.any(Function)) }) From 374237f4d08f07c1c0020db7efa50e4b7e1b42ed Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:16:47 +0800 Subject: [PATCH 49/54] test(benchmarks): measure peak elements restyled during sidebar drag Report the per-pass element histogram, the broadest pass and its duration, and the longest in-gesture frame gap. Guard the fixed 720px column against a single oversized pass independently of its cumulative restyle budget. Refs #8856. --- ...-20-rightbar-drag-restyle-budget.i18n.yaml | 4 +- ...2026-11-20-rightbar-drag-restyle-budget.md | 2 + ...6-11-20-rightbar-drag-restyle-budget.zh.md | 2 + .../rightbar-drag-browser/README.i18n.yaml | 4 +- benchmarks/rightbar-drag-browser/README.md | 3 +- benchmarks/rightbar-drag-browser/README.zh.md | 3 +- .../rightbar-drag.bench.ts | 96 ++++++++++++++++--- 7 files changed, 96 insertions(+), 18 deletions(-) diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml index b091330ead..104fe53627 100644 --- a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.i18n.yaml @@ -12,8 +12,8 @@ en: 83d40f59669f4d33 zh: 1e8de8d1b7e62861 /agent-note-right-sidebar-drag-restyle-budget/calibration: - en: dc1b35868c5ea353 - zh: 546aca16b16ca98b + en: 843539a8446bbe65 + zh: 806c97cb8fecdb61 /agent-note-right-sidebar-drag-restyle-budget/alternatives-considered: en: 721cbfb3276fcb5b zh: 9557ee132f77f5a6 diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md index dcc55127af..502a331260 100644 --- a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md @@ -30,6 +30,8 @@ In the 120-turn Chromium trace, 40 `Layout` events per direction ran inside scri At 2560px with 120 turns and a 720px rendered column, the required benchmark traces the full drag against built Web artifacts, including the press and release. Before the fix, widening restyled 18,239 / 18,428 = 0.98974, failing the 0.10 budget. A diagnostic trace attributed 14,911 restyled elements to a single reserve-room flip. After the fix, widening restyled 380 / 18,428 = 0.02062 and narrowing restyled 379 / 18,428 = 0.02057. The Sidebar moved 80px each way, the column stayed at 720px, and the probe switched in both directions. The budget allows 1,842 restyles: nearly five times either passing count, but less than 40 updates of 82 elements even without the single large recalculation. +The fixed-column peak has an absolute budget of 512 elements in any one completed `UpdateLayoutTree` event. In a 120-turn local widening trace, 40 passes visited one element each, 40 visited three each, two visited four each, and one visited 212 (380 total). Restoring only inheritance of the dock probe's room value into the message flow in the same browser workload left the small buckets unchanged but replaced the 212-element peak with 14,911. The budget leaves more than twice the healthy peak without growing with the size of unrelated page content. A separate control with 600 total visits passes the cumulative budget either way: 200 passes of three pass the peak budget, one pass of 600 fails it. + ## Alternatives considered - Budget frame gaps or style milliseconds. Rejected for the gate: they need browser-runner calibration that does not exist yet, and they also include the transcript reflow at each new column width, which a resize legitimately pays. They remain diagnostics. diff --git a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md index 39d852ed5c..9b6ec141d5 100644 --- a/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md +++ b/.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md @@ -30,6 +30,8 @@ Status: implemented 在 2560px 视口中完整加载 120 轮、正文实际列宽固定为 720px 时,必需基准使用构建后的 Web 产物,追踪包含按下和松开鼠标的整个拖动过程。修复前,加宽方向的重算比值为 18,239 / 18,428 = 0.98974,超过 0.10 的预算。诊断追踪显示,仅一次预留状态翻转就重算了 14,911 个元素。修复后,加宽方向为 380 / 18,428 = 0.02062,缩窄方向为 379 / 18,428 = 0.02057。两个方向的侧栏都移动了 80px,正文列保持 720px,探针均发生翻转。预算允许重算 1,842 个元素,接近两个实测值的五倍;即使没有那次大幅重算,每步重算 82 个元素、连续 40 步也会超限。 +正文列固定时,单个完整 `UpdateLayoutTree` 事件最多可重算 512 个元素。在本地 120 轮的加宽追踪中,40 次各重算 1 个元素,40 次各重算 3 个,2 次各重算 4 个,1 次重算 212 个(累计 380 个)。在相同浏览器负载中,只恢复消息流对停靠探针空间标记的继承,小规模重算的分布不变,峰值却从 212 变为 14,911。预算为健康峰值留出两倍以上余量,且不随页面上无关内容的增多而放宽。另一组对照的累计计数同为 600,两者均满足累计预算:分成 200 次、每次 3 个满足峰值预算,集中在一次重算 600 个则失败。 + ## 备选方案 - 为帧间隔或样式毫秒数设预算。门禁不采用:它们需要尚不存在的浏览器 runner 校准,而且还包含按每个新列宽重排正文的成本,这是缩放本应付出的。它们保留为诊断输出。 diff --git a/benchmarks/rightbar-drag-browser/README.i18n.yaml b/benchmarks/rightbar-drag-browser/README.i18n.yaml index 0c75dcd69d..d7a6028a8d 100644 --- a/benchmarks/rightbar-drag-browser/README.i18n.yaml +++ b/benchmarks/rightbar-drag-browser/README.i18n.yaml @@ -9,5 +9,5 @@ en: 0dce8b92617ea78b zh: 22ce9ccc29acda36 /right-sidebar-drag-browser-benchmark/measurements: - en: ece05c9d313f7906 - zh: 0c54ddf5bb75b162 + en: a46b806f1f9ae765 + zh: f4a81542a960a55c diff --git a/benchmarks/rightbar-drag-browser/README.md b/benchmarks/rightbar-drag-browser/README.md index 97b7ec9248..678d9fbea0 100644 --- a/benchmarks/rightbar-drag-browser/README.md +++ b/benchmarks/rightbar-drag-browser/README.md @@ -16,8 +16,9 @@ Each Chromium trace spans one trusted drag through two animation frames after re - **Fixed column:** The first sample also opens the same 120 turns in a separate page with fresh storage, a 2560×1000 viewport and a saved 720px content width. After the opening slide settles, the visible Sidebar must reach each of 40 steps of 2px, from 1152px to 1232px and back. Every delivered transcript column width must be 720px. The Session panel's reserve-room value at its dock probe must switch from 1px to 0px and back. - **Restyles:** Sum the elements reported by each style recalculation and divide by the page's element count. For the changing column, the upper median per direction must not exceed 1 (one page's worth). For the fixed column, each direction must not exceed 0.10. +- **Individual style passes:** Every sample prints `restylePassesByElementCount`: a bucket such as `"3": 40` means 40 complete Chromium `UpdateLayoutTree` events each reported three restyled elements. These are element visits, not distinct DOM nodes across a drag or invalidation reasons. `peakStyledElements` is the largest count in one event; `peakCountPassMs` is the duration of that event (the longer duration wins a tie). Each fixed-column direction must keep every pass at or below 512 elements, even if the cumulative ratio passes. - **Layouts:** Each changing-column drag must produce at least one `Layout` event. `layoutCount` includes them all; `scriptNestedLayoutCount` counts each layout fully enclosed by a script event on the same process and thread, including animation frame callbacks. This subset must not exceed 20 per drag (half the mouse steps). Nesting is a proxy for synchronous layout, not evidence that every nested layout is unnecessary; browser reflow outside script does not consume the budget. -Frame gaps and style and layout durations are diagnostics only. Neither budget scales with CPU speed. +The p95 and longest animation-frame gaps (`frameP95Ms`, `maxFrameGapMs`) span the gesture through the two frames after release, excluding trace startup and decoding. Frame gaps and style and layout durations are diagnostics only; the work-count budgets do not scale with CPU speed. The fixture contains mixed-language prose, lists, 12 code fences, 8 tables, reasoning, and 24 tool results. No model, tool, external network, recorded Session, or private Harness home supplies its content. The [decision record](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.md) owns the workload choice, calibration, alternatives, and exclusions. diff --git a/benchmarks/rightbar-drag-browser/README.zh.md b/benchmarks/rightbar-drag-browser/README.zh.md index cf0a9633bd..22763db2df 100644 --- a/benchmarks/rightbar-drag-browser/README.zh.md +++ b/benchmarks/rightbar-drag-browser/README.zh.md @@ -16,8 +16,9 @@ - **列宽固定:** 第一个样本还在单独页面中打开相同的 120 轮记录;该页面使用独立存储,视口为 2560×1000,预存的正文宽度为 720px。侧栏展开动画结束后,从 1152px 到 1232px 再拖回,每个方向 40 步,每步 2px,可见侧栏必须逐步到达目标宽度。每次观察到的正文列宽都必须是 720px。会话面板的停靠探针上,标记预留空间是否足够的值必须从 1px 变为 0px,再变回 1px。 - **样式重算:** 各次样式重算报告的元素数之和除以页面元素数。列宽变化时,每个方向的上中位数不得超过 1(即一整个页面的元素数)。列宽固定时,每个方向的比值不得超过 0.10。 +- **单次样式重算:** 每个样本都输出 `restylePassesByElementCount`。例如 `"3": 40` 表示 Chromium 有 40 个完整的 `UpdateLayoutTree` 事件各自重算了 3 个元素。这不是整段拖动去重后的 DOM 节点数,也不是失效原因条数。`peakStyledElements` 是单个事件的最大元素数;`peakCountPassMs` 是该事件的耗时(元素数并列时取较长者)。正文固定时,加宽和缩窄的每次重算都不得超过 512 个元素,即使累计比值合格也一样。 - **布局:** 列宽变化时,每次拖动必须产生至少一个 `Layout` 事件。`layoutCount` 统计所有布局;`scriptNestedLayoutCount` 只统计起止时间均落在同一进程、同一线程的脚本事件内的布局,每次布局只计一次,动画帧回调也算脚本事件。每次拖动此项不得超过 20(鼠标步数的一半)。嵌套关系是判断同步布局的间接指标,并不说明每次嵌套布局都多余;脚本以外的浏览器重排不占用该预算。 -帧间隔、样式重算耗时和布局耗时仅作诊断。两项预算都不随 CPU 速度缩放。 +帧间隔的 p95 和最大值(`frameP95Ms`、`maxFrameGapMs`)覆盖手势至松开后两个动画帧,不包含追踪启动和解析。帧间隔、样式重算耗时和布局耗时仅作诊断;工作量预算不随 CPU 速度缩放。 夹具包含中英混排的正文、列表、12 个代码块、8 个表格、推理内容和 24 个工具结果。内容不来自任何模型、工具、外部网络、录制会话或私有 Harness home。[决策记录](../../.agents/notes/implemented/testing/2026-11-20-rightbar-drag-restyle-budget.zh.md)负责说明负载选择、校准、备选方案和排除项。 diff --git a/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts index f5ed1431a4..51257d0c99 100644 --- a/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts +++ b/benchmarks/rightbar-drag-browser/rightbar-drag.bench.ts @@ -14,6 +14,8 @@ const FIXED_COLUMN_PX = 720 const FIXED_PANEL_START_PX = 1152 const FIXED_STEP_PX = 2 const FIXED_RESTYLE_BUDGET = 0.1 +/** One fixed-column style pass, independent of the cumulative page-ratio budget. */ +const FIXED_PEAK_ELEMENT_BUDGET = 512 const STEPS = 40 const STEP_PX = 8 const STEP_GAP_MS = 8 @@ -40,6 +42,11 @@ interface TraceEvent { interface TraceSummary { styledElements: number + /** Element count → number of completed UpdateLayoutTree events reporting that count. */ + restylePassesByElementCount: Record + peakStyledElements: number + /** Duration of the pass with the highest element count; the longer pass wins ties. */ + peakCountPassMs: number styleMs: number layoutMs: number layoutCount: number @@ -49,6 +56,7 @@ interface TraceSummary { interface DragSample extends TraceSummary { restyleRatio: number frameP95Ms: number + maxFrameGapMs: number columnWidthBefore: number columnWidth: number } @@ -57,6 +65,10 @@ function expectRestylesWithinBudget(ratio: number, budget = RESTYLE_BUDGET): voi expect(ratio).toBeLessThanOrEqual(budget) } +function expectFixedPeakWithinBudget(count: number): void { + expect(count, 'most elements restyled in one fixed-column UpdateLayoutTree event').toBeLessThanOrEqual(FIXED_PEAK_ELEMENT_BUDGET) +} + function median(values: number[]): number { return values.toSorted((a, b) => a - b)[Math.floor(values.length / 2)]! } @@ -71,8 +83,25 @@ function summarizeTrace(buffer: Buffer): TraceSummary { expect(scripts.length, 'drag trace must contain script events').toBeGreaterThan(0) const end = (event: TraceEvent): number => event.ts + (event.dur ?? 0) const ms = (list: TraceEvent[]): number => list.reduce((total, event) => total + (event.dur ?? 0), 0) / 1000 + const restylePassesByElementCount: Record = {} + let styledElements = 0 + let peakStyledElements = 0 + let peakCountPassMs = 0 + for (const event of styles) { + const count = event.args?.elementCount + if (count === undefined || !Number.isSafeInteger(count) || count < 0) { + throw new Error('Chromium UpdateLayoutTree is missing a valid elementCount') + } + const passMs = (event.dur ?? 0) / 1000 + restylePassesByElementCount[count] = (restylePassesByElementCount[count] ?? 0) + 1 + styledElements += count + if (count > peakStyledElements || (count === peakStyledElements && passMs > peakCountPassMs)) { + peakStyledElements = count + peakCountPassMs = passMs + } + } return { - styledElements: styles.reduce((total, event) => total + (event.args?.elementCount ?? 0), 0), + styledElements, restylePassesByElementCount, peakStyledElements, peakCountPassMs, styleMs: ms(styles), layoutMs: ms(layouts), layoutCount: layouts.length, @@ -120,7 +149,8 @@ async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: n const y = box.y + box.height / 2 const readColumnWidth = (): Promise => page.locator('[data-chat-flow]').first().evaluate(element => element.getBoundingClientRect().width) const columnWidthBefore = await readColumnWidth() - await page.evaluate(() => { + await browser.startTracing(page, { categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'] }) + await page.evaluate(() => new Promise((resolve) => { const probe = { frames: [] as number[], running: true } ;(window as FrameProbe).benchmarkFrames = probe const tick = (time: number): void => { @@ -128,9 +158,8 @@ async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: n probe.frames.push(time) requestAnimationFrame(tick) } - requestAnimationFrame(tick) - }) - await browser.startTracing(page, { categories: ['devtools.timeline', 'disabled-by-default-devtools.timeline'] }) + requestAnimationFrame((time) => { tick(time); resolve() }) + })) await page.mouse.move(x, y) await page.mouse.down() for (let step = 1; step <= STEPS; step++) { @@ -144,18 +173,20 @@ async function drag(browser: Browser, page: Page, direction: 1 | -1, elements: n } await page.mouse.up() // Two animation frames let the release reach style and layout before the trace closes. - await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))) + const frames = await page.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => { + const probe = (window as FrameProbe).benchmarkFrames! + probe.running = false + resolve(probe.frames) + })) + })) const trace = summarizeTrace(await browser.stopTracing()) - const frames = await page.evaluate(() => { - const probe = (window as FrameProbe).benchmarkFrames! - probe.running = false - return probe.frames - }) const gaps = frames.slice(1).map((time, index) => time - frames[index]!).sort((a, b) => a - b) return { ...trace, restyleRatio: trace.styledElements / elements, frameP95Ms: gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * 0.95))] ?? 0, + maxFrameGapMs: gaps.at(-1) ?? 0, columnWidthBefore, columnWidth: await readColumnWidth(), } @@ -203,13 +234,18 @@ async function measureFixedColumn(browser: Browser, url: string): Promise const { panel, column } = (window as FixedWidthProbe).benchmarkWidths return { panelWidth: panel, columnWidths: [...column] } }) - console.log(JSON.stringify({ benchmark: 'rightbar-drag-browser/fixed-column', direction, elements, budget: FIXED_RESTYLE_BUDGET, panelStart, ...geometry, reserveBefore, reserveAfter, ...result })) + console.log(JSON.stringify({ + benchmark: 'rightbar-drag-browser/fixed-column', direction, elements, + budget: FIXED_RESTYLE_BUDGET, peakElementBudget: FIXED_PEAK_ELEMENT_BUDGET, + panelStart, ...geometry, reserveBefore, reserveAfter, ...result, + })) panelStart += direction * STEPS * FIXED_STEP_PX expect(geometry.panelWidth).toBe(panelStart) expect(geometry.columnWidths).toEqual([FIXED_COLUMN_PX]) expect([result.columnWidthBefore, result.columnWidth]).toEqual([FIXED_COLUMN_PX, FIXED_COLUMN_PX]) expect([reserveBefore, reserveAfter]).toEqual(direction === 1 ? ['1px', '0px'] : ['0px', '1px']) expect(result.styledElements).toBeGreaterThan(0) + expectFixedPeakWithinBudget(result.peakStyledElements) expectRestylesWithinBudget(result.restyleRatio, FIXED_RESTYLE_BUDGET) } expect(consoleWatch.pageErrors).toEqual([]) @@ -233,6 +269,41 @@ it('rejects the fixed-column drag that restyled the transcript when reserve room for (const restyled of [380, 379]) expectRestylesWithinBudget(restyled / elements, FIXED_RESTYLE_BUDGET) }) +/** A Chromium trace fragment with completed style passes and a separate invalidation notification. */ +function restyleTrace(passes: readonly (readonly [number | undefined, number])[]): TraceSummary { + const span = { pid: 1, tid: 1, ph: 'X' } + const events = [ + { ...span, ts: 0, name: 'FunctionCall', dur: 1 }, + { ...span, ts: 0, ph: 'I', name: 'ScheduleStyleInvalidationTracking', args: { elementCount: 99_999 } }, + ...passes.map(([elementCount, dur], index) => ({ + ...span, ts: (index + 1) * 10_000, name: 'UpdateLayoutTree', dur, args: { elementCount }, + })), + ] + return summarizeTrace(Buffer.from(JSON.stringify({ traceEvents: events }))) +} + +it('reports the breadth of each style pass and the duration of the broadest pass, not the slowest pass', () => { + expect(restyleTrace([[3, 9_000], [14_911, 1_200], [3, 500], [14_911, 2_300], [0, 100]])).toMatchObject({ + styledElements: 29_828, + restylePassesByElementCount: { 0: 1, 3: 2, 14911: 2 }, + peakStyledElements: 14_911, + peakCountPassMs: 2.3, + }) + expect(() => restyleTrace([[undefined, 100]])).toThrow('elementCount') +}) + +it('distinguishes one oversized style pass from the same total work spread over small passes', () => { + const elements = 18_428 + const distributed = restyleTrace(Array.from({ length: 200 }, () => [3, 100] as const)) + const spike = restyleTrace([[600, 100]]) + for (const result of [distributed, spike]) { + expect(result.styledElements).toBe(600) + expectRestylesWithinBudget(result.styledElements / elements, FIXED_RESTYLE_BUDGET) + } + expectFixedPeakWithinBudget(distributed.peakStyledElements) + expect(() => expectFixedPeakWithinBudget(spike.peakStyledElements)).toThrow() +}) + it('counts each layout enclosed by script on the same thread once, including frame callbacks', () => { const event = (name: string, ts: number, dur: number, pid = 1, tid = 1): TraceEvent => ({ name, ph: 'X', ts, dur, pid, tid }) const events = [ @@ -267,6 +338,7 @@ it(`bounds restyles and script-nested layouts while the right Sidebar is dragged expect(Math.max(result.columnWidthBefore, result.columnWidth)).toBeLessThan(CONTENT_WIDTH_FLOOR_PX) if (key === 'widen') expect(result.columnWidth).toBeLessThan(result.columnWidthBefore) else expect(result.columnWidth).toBeGreaterThan(result.columnWidthBefore) + expect(result.styledElements).toBeGreaterThan(0) expect(result.layoutCount).toBeGreaterThan(0) expect(result.scriptNestedLayoutCount).toBeLessThanOrEqual(SCRIPT_NESTED_LAYOUT_BUDGET) samples[key].push(result) From 159b3edfebfd8b6d6d8725bcdeb7d73d54fce05d Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 20 Nov 2026 16:26:45 +0800 Subject: [PATCH 50/54] test(web): add plugin_manager to the scoped PTC round system prompt The persistent-in-memory PTC round snapshot from master uses the Desktop ptc preset, which now provides plugin_manager when the Host supplies an editable profile. --- .../system-prompt.expected.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/snapshots/web/ptc-round-scoped/system-prompt.expected.md b/snapshots/web/ptc-round-scoped/system-prompt.expected.md index f24e11c14e..0240fc97ca 100644 --- a/snapshots/web/ptc-round-scoped/system-prompt.expected.md +++ b/snapshots/web/ptc-round-scoped/system-prompt.expected.md @@ -160,6 +160,27 @@ interface ToolArgsMap { /** Exact model id; requires provider. */ model?: string; } & Record; + /** List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. The application field of a change result is authoritative: applied means the change is in effect and needs no restart; any other value carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one. */ + plugin_manager: { + /** Management operation. */ + action: "list_plugins" | "list_bundles" | "set_plugin" | "set_bundle" | "install_bundle" | "remove_bundle" | "list_version_exemptions" | "set_version_exemption"; + /** Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle. */ + target?: string; + /** Required for set operations; defaults to true for installation. For set_version_exemption, true grants and false revokes. */ + enabled?: boolean; + /** For set_version_exemption: exact DSH version from list_version_exemptions. Target must be the manifest package-name@version, not an alias or version range. */ + runtimeVersion?: string; + /** For granting an exemption: true only after warning the user about possible crashes and data loss and receiving explicit permission for this exact plugin/runtime pair. General installation permission is not enough. */ + acceptRisk?: boolean; + /** For install_bundle: pass names from pendingBuilds only after the user explicitly approves running their install scripts in the conversation. This grants persistent permission for this profile. */ + approvedBuilds?: string[]; + /** For install_bundle: the npm registry URL asked first, when the user names one; otherwise the configured registry is asked, and its configured fallbacks while a registry is unreachable. */ + registry?: string; + /** Zero-based list offset; defaults to 0. */ + offset?: number; + /** List page size, from 1 to 100; defaults to 25. */ + limit?: number; + } & Record; /** Declare existing files as final deliverables for the user. Hosts may show presented files only after your turn ends, so call it once the files are final. If the user needs to review files earlier, such as before a tool call that waits for their answer, link them in your message instead. Use it when the user needs a separate file, especially Office documents, spreadsheets, and slide decks; prefer your final response when that suffices. The user opens the current files; their contents are not copied. */ present: { /** Usually the 1-2 most important deliverables; at most 4 per call. */ @@ -455,6 +476,7 @@ interface ToolOutputMap { })[]; }; list_subagent_models: string; + plugin_manager: string; present: { turn: number; files: { From 03fef310626678183405ab64ed963d984abf7eb5 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Fri, 20 Nov 2026 16:38:00 +0800 Subject: [PATCH 51/54] =?UTF-8?q?fix(action-cards):=20=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E4=B8=8D=E5=90=8C=E8=BD=AE=E6=AC=A1=E4=B8=AD=E5=90=84=E8=87=AA?= =?UTF-8?q?=E5=8F=AF=E6=93=8D=E4=BD=9C=E7=9A=84=E6=8F=90=E6=A1=88=20(#8900?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(action-cards): keep proposals available across turns * test(action-cards): consolidate replay and lifecycle regressions * fix(action-cards): guide revised creation plans and drop derived decision wording A changed plan now gets a new card whose answer says the earlier card stays available until dismissed. Card body docs describe decisions as recorded only. --- .../web/tests/creation-recommendations.e2e.ts | 32 +++++++----- docs/subsystems/boot.md | 2 +- docs/subsystems/boot.zh.md | 2 +- .../independent-action-cards/guide.i18n.yaml | 16 ++++++ .../independent-action-cards/guide.md | 18 +++++++ .../independent-action-cards/guide.zh.md | 18 +++++++ .../action-cards/README.i18n.yaml | 16 +++--- packages/experimental/action-cards/README.md | 14 +++-- .../experimental/action-cards/README.zh.md | 14 +++-- .../experimental/action-cards/src/index.ts | 11 ++-- .../action-cards/src/projection.ts | 13 ++--- .../experimental/action-cards/src/types.ts | 6 +-- .../action-cards/tests/act.spec.ts | 4 +- .../action-cards/tests/projection.spec.ts | 51 ++++++++++++------- .../client-ui-action-cards/README.i18n.yaml | 4 +- .../client-ui-action-cards/README.md | 2 +- .../client-ui-action-cards/README.zh.md | 2 +- .../src/client/Card.tsx | 6 +-- .../src/client/locales.ts | 16 +++--- .../src/client/registry.ts | 2 +- .../tests/card.client.spec.tsx | 2 +- .../README.i18n.yaml | 4 +- .../README.md | 2 +- .../README.zh.md | 2 +- .../src/client/Card.tsx | 2 +- .../src/client/locales.ts | 11 ++-- .../tests/card.client.spec.tsx | 4 +- .../src/client/Card.tsx | 2 +- .../src/client/locales.ts | 8 --- .../tests/card.client.spec.tsx | 1 - .../creation-recommendations/README.i18n.yaml | 8 +-- .../creation-recommendations/README.md | 4 +- .../creation-recommendations/README.zh.md | 4 +- .../skills/personalized-pages.md | 2 +- .../tests/__snapshots__/creation.spec.ts.snap | 2 +- .../tests/status-context.spec.ts | 37 ++++---------- .../plugin-recommendations/README.i18n.yaml | 4 +- .../plugin-recommendations/README.md | 2 +- .../plugin-recommendations/README.zh.md | 2 +- .../tests/recommendations.spec.ts | 9 ++-- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../creation-recommendations/session.v4.jsonl | 20 +++++--- 42 files changed, 203 insertions(+), 180 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.zh.md diff --git a/apps/web/tests/creation-recommendations.e2e.ts b/apps/web/tests/creation-recommendations.e2e.ts index eeb92882e1..006a9e49b2 100644 --- a/apps/web/tests/creation-recommendations.e2e.ts +++ b/apps/web/tests/creation-recommendations.e2e.ts @@ -27,19 +27,23 @@ describe('creation recommendation after an explicit wish', () => { }) afterAll(async () => { await browser?.close(); await scaffold?.close() }) - it('shows one card below the answer, lets the user change location, and restores a dismissal', async () => { + it('keeps the creation controls after a documentation example and restores only the chosen dismissal', async () => { const tripwire = watchConsole(page) await page.setViewportSize({ width: 620, height: 900 }) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await connectFreshWorkspace(page, scaffold.workspaceCwd) const input = page.locator('[data-composer-input]').first() - const settled = scaffold.whenTurnSettled() - await input.fill(fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]!) - await input.press('Enter') - await settled - const card = page.locator('[data-action-card]') + const prompts = fixtureUserPrompts(await readFile(fixture, 'utf8')) + async function sendTurn(prompt: string) { + const settled = scaffold.whenTurnSettled() + await input.fill(prompt) + await input.press('Enter') + await settled + } + await sendTurn(prompts[0]!) + const creationSelector = '[data-action="create_personalized_page"]' + const card = page.locator(creationSelector) await card.waitFor({ state: 'visible' }) - expect(await card.count()).toBe(1) expect(await page.locator('[data-turn-tail] [data-action-card]').count()).toBe(1) const answer = page.getByText('I can create a persistent counter with increment and reset controls. Choose its location below.', { exact: true }) const answerBox = await answer.boundingBox() @@ -107,6 +111,11 @@ describe('creation recommendation after an explicit wish', () => { expect(await custom.count()).toBe(0) await compareOrRefreshGolden(join(directory, 'options.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await sendTurn(prompts[1]!) + const dismissExample = page.locator('[data-action="my_example"]').getByRole('button', { name: 'Not now', exact: true }) + await dismissExample.waitFor() + expect(await page.locator('[data-action-card]').count()).toBe(2) + expect(await card.getByRole('button', { name: 'Create', exact: true }).isEnabled()).toBe(true) await card.getByRole('button', { name: 'Not now', exact: true }).click() await card.getByRole('status').getByText('Dismissed', { exact: true }).waitFor() const warnings = tripwire.warnings.length @@ -116,14 +125,11 @@ describe('creation recommendation after an explicit wish', () => { expect(await card.getByRole('button', { name: 'Create', exact: true }).count()).toBe(0) expect(await card.getByRole('button', { name: 'Show more', exact: true }).isVisible()).toBe(true) expect((await scaffold.ctx.pluginManager.listBundles()).some(bundle => bundle.name.startsWith('@dsh-local/view-'))).toBe(false) - await compareOrRefreshGolden(join(directory, 'dismissed.expected.md'), await captureStableAria(page, '[data-action-card]', scaffold.workspaceCwd), scaffold.mode) - const statusSettled = scaffold.whenTurnSettled() - await input.fill(fixtureUserPrompts(await readFile(fixture, 'utf8'))[1]!) - await input.press('Enter') - await statusSettled + await compareOrRefreshGolden(join(directory, 'dismissed.expected.md'), await captureStableAria(page, creationSelector, scaffold.workspaceCwd), scaffold.mode) + await sendTurn(prompts[2]!) await page.getByText('The counter proposal was dismissed. Creation never started.', { exact: true }).waitFor() - expect(await card.count()).toBe(1) expect(await card.getByRole('button', { name: 'Create', exact: true }).count()).toBe(0) + expect(await dismissExample.isEnabled()).toBe(true) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) if (scaffold.mode === 'replay') await assertFixtureInventory(directory, [ diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 704ce4467b..e5feb9ed76 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -88,7 +88,7 @@ register
(kind: ActionCardKind
): () => void * Record a card decision in the Session log; the next model request reports it. * @param agent - agent whose Session owns the card. * @param decision - the card's new state. - * @throws when no kind ever registered the decision's action with this service, or its phase is one the projection derives. + * @throws when no kind ever registered the decision's action with this service. */ record(agent: Agent, decision: ActionCardDecision): void diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index e441de34b8..cd0f3fee21 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -88,7 +88,7 @@ register
(kind: ActionCardKind
): () => void * Record a card decision in the Session log; the next model request reports it. * @param agent - agent whose Session owns the card. * @param decision - the card's new state. - * @throws when no kind ever registered the decision's action with this service, or its phase is one the projection derives. + * @throws when no kind ever registered the decision's action with this service. */ record(agent: Agent, decision: ActionCardDecision): void diff --git a/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.i18n.yaml new file mode 100644 index 0000000000..36676d0a23 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/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.5/independent-action-cards/guide.md +/: + en: c226e668bcaa1303 + zh: b24fa291f2ac9165 +/action-cards-stay-available-across-turns: + en: 1cea03e62b94a3e2 + zh: 6137ad5e581e0283 +/action-cards-stay-available-across-turns/change: + en: 7c55dcb05dc0749a + zh: fa96d17567d8cffb +/action-cards-stay-available-across-turns/migration: + en: e261b9075be87be0 + zh: f2b147aa33c16a97 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.md new file mode 100644 index 0000000000..3e74952d8c --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Earlier action cards stay available when a later turn offers another card." +--- + +# Action cards stay available across turns + +English | [中文](guide.zh.md) + +## Change + +A later proposal used to mark earlier unstarted cards as `replaced`. When you reopen a Session, those cards offer their actions again. Each card keeps its own recorded decisions, including dismissals and work already started. Each turn still admits only its first valid `action-card` block. + +## Migration + +1. Reopen a conversation containing two proposals from different turns. The Host rebuilds the `actionCards` projection from the Session log when it encounters a version 3 checkpoint. Session files need no edits. +2. Check that each untouched proposal offers its controls. Choose **Not now** on any proposal you no longer want. +3. If your plugin reads `ActionCardView.decisions`, use the decision for the proposal’s `cardId`. An absent decision means the card is unstarted. Remove handling for the former shared `replaced` phase. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.zh.md new file mode 100644 index 0000000000..acdef53adc --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/independent-action-cards/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "后续轮次出现新的 Action 卡片时,早先的卡片仍可操作。" +--- + +# Action 卡片在后续轮次仍可操作 + +[English](guide.md) | 中文 + +## 变更 + +过去,新提案会把早先尚未开始的卡片标记为 `replaced`。重新打开会话后,这些卡片会再次提供操作。每张卡片都保留自己的决定记录,包括已忽略的提案和已开始的任务。每轮仍只接纳第一个合法的 `action-card` 代码块。 + +## 迁移 + +1. 打开一个在不同轮次收到过两张提案卡片的会话。Host 遇到版本 3 的检查点时会从会话日志重建 `actionCards` 投影,无需编辑会话文件。 +2. 确认每张尚未操作的卡片都有相应的控件。对不再需要的提案选择**暂不需要**。 +3. 如果插件读取 `ActionCardView.decisions`,请按提案的 `cardId` 读取决定。没有决定记录表示卡片尚未开始,可以删除对原有共享阶段 `replaced` 的处理。 diff --git a/packages/experimental/action-cards/README.i18n.yaml b/packages/experimental/action-cards/README.i18n.yaml index 3a8a4ee2e5..8262560581 100644 --- a/packages/experimental/action-cards/README.i18n.yaml +++ b/packages/experimental/action-cards/README.i18n.yaml @@ -18,14 +18,14 @@ en: 697aac17308c991b zh: 0e338bb18457aabc /deepseek-ai-dsh-action-cards/use-this-package/register-a-card-kind: - en: ec2c7e23b17e2d3e - zh: f6e104e7ce68c3ac + en: 2003c7c13914bb55 + zh: 296c1bf9ad1bd1fc /deepseek-ai-dsh-action-cards/use-this-package/card-rules: - en: 1720908663123d8e - zh: abc24f2874f21e59 + en: 0ba291cab3c4c773 + zh: 0ad5b6f8ec91d375 /deepseek-ai-dsh-action-cards/understand-the-implementation: - en: 2553967d926b491d - zh: 8d7edff4d39aff5e + en: 41a46e1f7647b09d + zh: 215f9b5823201daf /deepseek-ai-dsh-action-cards/further-exploration: en: b5d6fde7329f67a7 zh: db2839d22fc577c4 @@ -60,8 +60,8 @@ en: 58785543e2428dba zh: 4b082f77b3b2f482 /deepseek-ai-dsh-action-cards/known-limitations-and-deferred-work: - en: a59763d767870671 - zh: a5fce29a79e17d0f + en: 2377288074636c31 + zh: 4c0342c146ad6533 /deepseek-ai-dsh-action-cards/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: bd8a8936229e035e diff --git a/packages/experimental/action-cards/README.md b/packages/experimental/action-cards/README.md index cc4afeca09..c3527952fc 100644 --- a/packages/experimental/action-cards/README.md +++ b/packages/experimental/action-cards/README.md @@ -29,15 +29,15 @@ The [Personalized recommendations](../personalized-recommendations/README.md) bu ### Register a card kind -A kind package injects `actionCards` and calls `ctx.actionCards.register(kind)` from its own plugin; unloading that plugin removes the kind, and actions on its cards are then refused as unavailable, except that Not now still dismisses an unstarted card. Its own skill tells the model when to offer the card and what the block holds. The kind names its action, a zod schema for the card's `details`, the user actions it accepts and the shared checks each needs (`global` Remote access, `writes` refused in a read-only Session), the recorded phases that still offer dismissal, optional status guidance, the decision data fields the status notice reports, an optional `reconcile` that updates the card's recorded decision from state outside the Session before every action, and the handler for every action except `dismiss`. The handler records each new decision with `ctx.actionCards.record()`, which refuses an action no kind registered and the derived `replaced` phase, and returns `accepted`, `settled` with the decision in effect, `refused` or `unconfirmed`. +A kind package injects `actionCards` and calls `ctx.actionCards.register(kind)` from its own plugin; unloading that plugin removes the kind, and actions on its cards are then refused as unavailable, except that Not now still dismisses an unstarted card. Its own skill tells the model when to offer the card and what the block holds. The kind names its action, a zod schema for the card's `details`, the user actions it accepts and the shared checks each needs (`global` Remote access, `writes` refused in a read-only Session), the recorded phases that still offer dismissal, optional status guidance, the decision data fields the status notice reports, an optional `reconcile` that updates the card's recorded decision from state outside the Session before every action, and the handler for every action except `dismiss`. The handler records each new decision with `ctx.actionCards.record()`, which refuses an action no kind registered, and returns `accepted`, `settled` with the decision in effect, `refused` or `unconfirmed`. ### Card rules - A card is a fenced block whose language is `action-card` and whose content is one JSON object with `action`, `title`, `brief` and an object `details`. A block counts when its fence follows at most three spaces, or at most three spaces and a list item marker; a block in a block quote, one indented four or more spaces and one inside another fenced block offer no card. The first such block of a turn that parses becomes the card, named by the id of the assistant message that holds it. Later blocks of that turn, blocks in reasoning, blocks in an interrupted answer, blocks with a blank title or brief, and every block of a subagent Session create no card, and nothing reports this to the model. -- Admission does not check the kind: a card whose action no kind registered, or whose `details` fail the kind schema, still appears, replaces every unstarted earlier card, and refuses every action except Not now as unavailable. -- A newer card of any kind replaces every unstarted earlier card. Replacement is derived from the log and never recorded. +- Admission does not check the kind: a card whose action no kind registered, or whose `details` fail the kind schema, still appears and refuses every action except Not now as unavailable. +- Cards from different turns remain available independently. Each card takes its state from decisions recorded for its own id. - Events a forked Session inherits create no cards. -- Before every action, including Not now, the kind's `reconcile` updates the card from state outside the Session. Not now is then recorded for an unstarted card and for the phases the kind lists; dismissed and replaced cards accept no further action. Without its registered kind, Not now still dismisses an unstarted card, and every other action is refused as unavailable. +- Before every action, including Not now, the kind's `reconcile` updates the card from state outside the Session. Not now is then recorded for an unstarted card and for the phases the kind lists; dismissed cards accept no further action. Without its registered kind, Not now still dismisses an unstarted card, and every other action is refused as unavailable. - Concurrent actions on one card share one operation. Actions require the exact live Agent for the card's Session, whose `origin` must not be `subagent`. ----- @@ -48,9 +48,9 @@ A kind package injects `actionCards` and calls `ctx.actionCards.register(kind)`
Implementation internals — click to expand -The package default-exports the `actionCards` Remote service and registers no tool. The logged answer is the durable proposal: the `actionCards` Session projection (state version 3) reads the text blocks of each `assistant/message` with [`src/fence.ts`](src/fence.ts), which finds fenced blocks at the top level and in list items by the CommonMark fence rules and matches their language the way the Chat client dispatches fences, and admits the first valid block of the turn. It also records decisions from `plugin:action-cards/decision`, and keeps unreported decisions until a status notice whose `through` covers them enters the log. The header's `origin` marks a subagent Session, whose projection admits nothing. Its Client view `{ proposals, decisions }` is excluded from Session summaries. +The package default-exports the `actionCards` Remote service and registers no tool. The logged answer is the durable proposal: the `actionCards` Session projection (state version 4) reads the text blocks of each `assistant/message` with [`src/fence.ts`](src/fence.ts), which finds fenced blocks at the top level and in list items by the CommonMark fence rules and matches their language the way the Chat client dispatches fences, and admits the first valid block of the turn. It also records decisions from `plugin:action-cards/decision`, and keeps unreported decisions until a status notice whose `through` covers them enters the log. The header's `origin` marks a subagent Session, whose projection admits nothing. Its Client view `{ proposals, decisions }` is excluded from Session summaries. -The Remote `act(sessionId, cardId, verb, payload?)` checks the owner, the live root and the card; Not now continues without a registered kind, while other verbs need the kind, the verb and Remote access. It then shares one operation per card. The kind's `reconcile` runs first and the live root is checked again; a dismissed or replaced card then settles unchanged, Not now is recorded, a writing verb is refused in a read-only Session, and every other verb goes to the kind handler under the Agent's initiator. `record()` also accepts an action whose kind has unregistered, because Cordis disposes a plugin's effects concurrently and an unloading kind still records the outcome of work it started. An `agent/pre-step` listener adds the status notice after later listeners prepared the step. +The Remote `act(sessionId, cardId, verb, payload?)` checks the owner, the live root and the card; Not now continues without a registered kind, while other verbs need the kind, the verb and Remote access. It then shares one operation per card. The kind's `reconcile` runs first and the live root is checked again; a dismissed card then settles unchanged, Not now is recorded, a writing verb is refused in a read-only Session, and every other verb goes to the kind handler under the Agent's initiator. `record()` also accepts an action whose kind has unregistered, because Cordis disposes a plugin's effects concurrently and an unloading kind still records the outcome of work it started. An `agent/pre-step` listener adds the status notice after later listeners prepared the step. | Source | Contents | |---|---| @@ -116,9 +116,7 @@ The notice is appended after the request's other new context and never rewrites - The model learns nothing about a block that creates no card: a malformed block, a second block of the turn or a subagent's block shows nothing, while the answer may already invite the user to the card. - The Host finds blocks line by line and reads only the literal language `action-card`, while the Chat client hides every `action-card` block it renders. A block in a block quote, one indented four or more spaces in a nested list item, or one whose language is written with an escape or a character reference, is hidden and offers no card; a block inside an HTML block or a `$$` or `\[ … \]` math block offers a card while its text stays visible. The skills ask for one top-level block at the end of the answer. - Sessions recorded with the removed `propose_action` tool show no card for those calls, and decision records that name a card `callId` are skipped. -- A card that fails its kind schema or names no registered kind still replaces an unstarted earlier card, which then offers no action. - Cards are offered in the main conversation only. A subagent Session, including a Creator child's, admits no card, because only a live root can act on one. -- Only one card is offered per turn across all kinds. A later card of any kind replaces every unstarted earlier card, so a second kind's card replaces an unstarted card of the first. - Refusal reasons of user actions are plain strings by design: the service defines `closing`, `not-live-root`, `unknown`, `unavailable`, `access-denied` and `read-only`, each kind adds its own, and a browser body names the reasons it knows and treats others as unavailable. - Each kind validates `details` on both sides, with its Host schema before each action and with its browser body's own schema, so the two schemas change together. diff --git a/packages/experimental/action-cards/README.zh.md b/packages/experimental/action-cards/README.zh.md index 6074c46855..76e3a9ccff 100644 --- a/packages/experimental/action-cards/README.zh.md +++ b/packages/experimental/action-cards/README.zh.md @@ -29,15 +29,15 @@ kind: "package-reference" ### 注册卡片种类 -种类所在的包注入 `actionCards`,并在自己的插件中调用 `ctx.actionCards.register(kind)`;该插件卸载时种类随之移除,此后对其卡片的操作会以 unavailable 拒绝,只有“暂不需要”仍可忽略尚未开始的卡片。种类自己的 Skill 告诉模型何时提供卡片以及代码块里写什么。种类需要给出:动作名、卡片 `details` 的 zod 校验、接受的用户操作及各自需要的共享检查(`global` 表示需要全局 Remote 权限,`writes` 表示只读会话中拒绝)、仍可忽略卡片的已记录阶段、可选的状态说明、状态通知要报告的决定数据字段、可选的 `reconcile`(每次操作前根据会话之外的状态更新卡片的已记录决定),以及处理 `dismiss` 以外所有操作的处理器。处理器用 `ctx.actionCards.record()` 记录每个新决定(该方法拒绝没有种类注册过的动作和推导得出的 `replaced` 阶段),并返回 `accepted`、带当前决定的 `settled`、`refused` 或 `unconfirmed`。 +种类所在的包注入 `actionCards`,并在自己的插件中调用 `ctx.actionCards.register(kind)`;该插件卸载时种类随之移除,此后对其卡片的操作会以 unavailable 拒绝,只有“暂不需要”仍可忽略尚未开始的卡片。种类自己的 Skill 告诉模型何时提供卡片以及代码块里写什么。种类需要给出:动作名、卡片 `details` 的 zod 校验、接受的用户操作及各自需要的共享检查(`global` 表示需要全局 Remote 权限,`writes` 表示只读会话中拒绝)、仍可忽略卡片的已记录阶段、可选的状态说明、状态通知要报告的决定数据字段、可选的 `reconcile`(每次操作前根据会话之外的状态更新卡片的已记录决定),以及处理 `dismiss` 以外所有操作的处理器。处理器用 `ctx.actionCards.record()` 记录每个新决定(该方法拒绝没有种类注册过的动作),并返回 `accepted`、带当前决定的 `settled`、`refused` 或 `unconfirmed`。 ### 卡片规则 - 卡片是语言为 `action-card` 的围栏代码块,内容是一个 JSON 对象,包含 `action`、`title`、`brief` 和对象类型的 `details`。围栏前最多有 3 个空格,或最多 3 个空格加一个列表项标记的代码块才算数;引用块里的、缩进 4 格及以上的,以及其他围栏代码块里的代码块不提供卡片。一轮中第一个能解析的这种代码块成为卡片,以所在助手消息的 id 作为卡片 id。同一轮之后的代码块、思考内容里的代码块、被打断的回答里的代码块、标题或说明为空的代码块,以及 subagent 会话里的所有代码块都不会产生卡片,也不会告知模型。 -- 收下卡片时不检查种类:动作没有种类注册、或 `details` 未通过种类校验的卡片照样出现,并替换此前所有尚未开始的卡片,除“暂不需要”外的操作一律以 unavailable 拒绝。 -- 任何种类的新卡片都会替换此前所有尚未开始的卡片。替换从日志推导,从不单独记录。 +- 收下卡片时不检查种类:动作没有种类注册、或 `details` 未通过种类校验的卡片照样出现,除“暂不需要”外的操作一律以 unavailable 拒绝。 +- 不同轮次的卡片各自可用,每张卡片的状态由其自身 ID 对应的决定记录确定。 - fork 出的会话从父会话继承的事件不会产生卡片。 -- 每次操作(包括“暂不需要”)之前,种类的 `reconcile` 先根据会话之外的状态更新卡片。之后,对尚未开始的卡片,以及处于种类列出阶段的卡片,“暂不需要”会被记录;已忽略、已替换的卡片不再接受任何操作。卡片的种类未注册时,“暂不需要”仍可忽略尚未开始的卡片,其他操作一律以 unavailable 拒绝。 +- 每次操作(包括“暂不需要”)之前,种类的 `reconcile` 先根据会话之外的状态更新卡片。之后,对尚未开始的卡片,以及处于种类列出阶段的卡片,“暂不需要”会被记录;已忽略的卡片不再接受任何操作。卡片的种类未注册时,“暂不需要”仍可忽略尚未开始的卡片,其他操作一律以 unavailable 拒绝。 - 同一张卡片上的并发操作共用一次处理。操作要求调用者是卡片所在 Session 的精确在线 Agent 实例,且 `origin` 不是 `subagent`。 ----- @@ -48,9 +48,9 @@ kind: "package-reference"
实现细节——点击展开 -本包默认导出 `actionCards` Remote 服务,不注册任何工具。日志里的回答就是持久的提议:`actionCards` 会话投影(状态版本 3)用 [`src/fence.ts`](src/fence.ts) 读取每条 `assistant/message` 的文字块,按 CommonMark 的围栏规则找出顶层和列表项里的围栏代码块,并按 Chat 客户端分派代码块的方式匹配语言,收下本轮第一个合格的代码块。投影还从 `plugin:action-cards/decision` 读取决定,并保留尚未报告的决定,直到 `through` 覆盖它们的状态通知写入日志。会话头的 `origin` 标出 subagent 会话,其投影不收任何卡片。投影的客户端视图 `{ proposals, decisions }` 不进入会话摘要。 +本包默认导出 `actionCards` Remote 服务,不注册任何工具。日志里的回答就是持久的提议:`actionCards` 会话投影(状态版本 4)用 [`src/fence.ts`](src/fence.ts) 读取每条 `assistant/message` 的文字块,按 CommonMark 的围栏规则找出顶层和列表项里的围栏代码块,并按 Chat 客户端分派代码块的方式匹配语言,收下本轮第一个合格的代码块。投影还从 `plugin:action-cards/decision` 读取决定,并保留尚未报告的决定,直到 `through` 覆盖它们的状态通知写入日志。会话头的 `origin` 标出 subagent 会话,其投影不收任何卡片。投影的客户端视图 `{ proposals, decisions }` 不进入会话摘要。 -Remote `act(sessionId, cardId, verb, payload?)` 先检查服务所有者、在线根 Agent 和卡片;“暂不需要”在种类未注册时也继续处理,其他操作还需要种类、操作和 Remote 权限。然后同一张卡片共用一次处理。种类的 `reconcile` 先运行,之后再次检查在线根 Agent;已忽略或已替换的卡片原样返回,“暂不需要”被记录,写入类操作在只读会话中被拒绝,其余操作在该 Agent 的发起方作用域内交给种类处理器。`record()` 也接受种类已注销的动作,因为 Cordis 并发释放插件的各个 effect,卸载中的种类仍要记录已开始工作的结果。一个 `agent/pre-step` 监听器在后续监听器准备好本步之后追加状态通知。 +Remote `act(sessionId, cardId, verb, payload?)` 先检查服务所有者、在线根 Agent 和卡片;“暂不需要”在种类未注册时也继续处理,其他操作还需要种类、操作和 Remote 权限。然后同一张卡片共用一次处理。种类的 `reconcile` 先运行,之后再次检查在线根 Agent;已忽略的卡片原样返回,“暂不需要”被记录,写入类操作在只读会话中被拒绝,其余操作在该 Agent 的发起方作用域内交给种类处理器。`record()` 也接受种类已注销的动作,因为 Cordis 并发释放插件的各个 effect,卸载中的种类仍要记录已开始工作的结果。一个 `agent/pre-step` 监听器在后续监听器准备好本步之后追加状态通知。 | 源码 | 内容 | |---|---| @@ -116,9 +116,7 @@ Latest status of action cards from user actions and background work. These are s - 代码块没有产生卡片时模型不会知道:格式错误的代码块、同一轮的第二个代码块或 subagent 的代码块都不显示任何东西,而回答里可能已经邀请用户点卡片。 - Host 逐行查找代码块,只认字面上就是 `action-card` 的语言,而 Chat 客户端会隐藏它渲染出的每一个 `action-card` 代码块。引用块里的代码块、嵌套列表项里缩进 4 格及以上的代码块、语言用转义或字符引用写成的代码块会被隐藏,但不提供卡片;HTML 块或 `$$`、`\[ … \]` 数学块里的代码块会提供卡片,但其文字仍然可见。各 Skill 要求在回答末尾写一个顶层代码块。 - 用已移除的 `propose_action` 工具录下的会话,这些调用不再显示卡片;用 `callId` 指代卡片的决定记录会被跳过。 -- 未通过种类校验或动作没有注册的卡片仍会替换此前尚未开始的卡片,被替换的卡片不再提供任何操作。 - 卡片只在主对话中提供。subagent 会话(包括 Creator 子 Agent 的会话)不收任何卡片,因为只有在线的根 Agent 才能对卡片进行操作。 -- 所有种类合计每轮只展示一张卡片。任何种类的新卡片都会替换此前所有尚未开始的卡片,因此第二个种类的卡片会替换第一个种类尚未开始的卡片。 - 用户操作的拒绝原因有意设计为普通字符串:服务定义 `closing`、`not-live-root`、`unknown`、`unavailable`、`access-denied` 和 `read-only`,各种类可以添加自己的原因,浏览器端正文为已知原因显示文案,其余按 unavailable 处理。 - 每个种类在两端各自校验 `details`:Host 端的 schema 在每次操作前校验,浏览器端正文用自己的 schema 校验,因此两个 schema 要一起修改。 diff --git a/packages/experimental/action-cards/src/index.ts b/packages/experimental/action-cards/src/index.ts index 4a318b5ea4..b8fa134182 100644 --- a/packages/experimental/action-cards/src/index.ts +++ b/packages/experimental/action-cards/src/index.ts @@ -19,10 +19,6 @@ declare module '@deepseek-ai/cordis' { /** The user action every card offers; the shared service records it. */ const DISMISS = 'dismiss' -/** Phases the projection derives from the log; no decision may record them. */ -const DERIVED_PHASES: readonly string[] = ['replaced'] -/** Phases after which no user action changes the card. */ -const FINAL_PHASES: readonly string[] = ['dismissed', ...DERIVED_PHASES] const STATUS_PREAMBLE = 'Latest status of action cards from user actions and background work. ' + 'These are status facts, not a request to start or retry work. Use these receipts instead of the earlier proposal when describing progress.' @@ -223,13 +219,12 @@ export class ActionCards extends TypertRemoteService { * Record a card decision in the Session log; the next model request reports it. * @param agent - agent whose Session owns the card. * @param decision - the card's new state. - * @throws when no kind ever registered the decision's action with this service, or its phase is one the projection derives. + * @throws when no kind ever registered the decision's action with this service. */ record(agent: Agent, decision: ActionCardDecision): void { if (!this.kinds.has(decision.action) && !this.retired.has(decision.action)) { throw new Error(`action-cards: cannot record a decision for unregistered action "${decision.action}"`) } - if (DERIVED_PHASES.includes(decision.phase)) throw new Error(`action-cards: phase "${decision.phase}" is derived from the log and cannot be recorded`) this.append(agent, decision) } @@ -299,7 +294,7 @@ export class ActionCards extends TypertRemoteService { if (refusal !== undefined) return refusal const decision = ownEntry(this.projection.stateOf(agent.session).view.decisions, proposal.cardId) // Without its kind no recorded phase is known to be open, and the kind may return to act on it. - if (decision !== undefined && (FINAL_PHASES.includes(decision.phase) || kind?.openPhases.includes(decision.phase) !== true)) { + if (decision !== undefined && (decision.phase === 'dismissed' || kind?.openPhases.includes(decision.phase) !== true)) { return { status: 'settled', decision } } const data = kind?.dismissal(proposal, payload) @@ -315,7 +310,7 @@ export class ActionCards extends TypertRemoteService { const refusal = await this.reconciled(agent, kind, proposal, verb) if (refusal !== undefined) return refusal const decision = ownEntry(this.projection.stateOf(agent.session).view.decisions, proposal.cardId) - if (decision !== undefined && FINAL_PHASES.includes(decision.phase)) return { status: 'settled', decision } + if (decision?.phase === 'dismissed') return { status: 'settled', decision } if (policy.writes === true && this.ctx.get('sandboxPolicy')?.resolve({ session: agent.session }).mode === 'read-only') return refused('read-only') return await kind.act(agent, proposal, verb, payload) } diff --git a/packages/experimental/action-cards/src/projection.ts b/packages/experimental/action-cards/src/projection.ts index 601375ab9d..7ed0aca450 100644 --- a/packages/experimental/action-cards/src/projection.ts +++ b/packages/experimental/action-cards/src/projection.ts @@ -84,11 +84,11 @@ function cardFieldsOf(message: AssistantMessage): CardFields | undefined { /** * Full-Session fold. The first valid `action-card` block in a turn's answer text becomes the card, named by the id of - * its assistant message. Later blocks of that turn create no card, and a newer card replaces every unstarted earlier - * card. Interrupted answers, subagent Sessions and events inherited by a forked Session create no proposals. + * its assistant message. Later blocks of that turn create no card. Interrupted answers, subagent Sessions and events inherited + * by a forked Session create no proposals. */ export const actionCardProjection: ActionCardProjectionDefinition = { - key: 'actionCards', stateVersion: 3, stateSchema, + key: 'actionCards', stateVersion: 4, stateSchema, init: (header, inheritedEventCount) => ({ inheritedEventCount, offers: header.origin !== 'subagent', view: { proposals: {}, decisions: {} }, admittedTurn: null, pendingStatus: {}, }), @@ -106,13 +106,8 @@ export const actionCardProjection: ActionCardProjectionDefinition = { const fields = cardFieldsOf(message) if (fields === undefined) return state const cardId = brandString(message.id) - const decisions = { ...state.view.decisions } - // A newer card supersedes every unstarted card; the model made that choice, so no status is reported. - for (const earlier of Object.values(state.view.proposals)) { - if (decisions[earlier.cardId] === undefined) decisions[earlier.cardId] = { cardId: earlier.cardId, action: earlier.action, phase: 'replaced' } - } const proposals = { ...state.view.proposals, [cardId]: { cardId, turn, ...fields } } - return { ...state, admittedTurn: turn, view: { proposals, decisions } } + return { ...state, admittedTurn: turn, view: { ...state.view, proposals } } } default: { const record = pluginRecordOf(event) diff --git a/packages/experimental/action-cards/src/types.ts b/packages/experimental/action-cards/src/types.ts index 02434d235e..366d770f29 100644 --- a/packages/experimental/action-cards/src/types.ts +++ b/packages/experimental/action-cards/src/types.ts @@ -28,11 +28,7 @@ export interface ActionCardProposal { readonly details: ActionCardFields } -/** - * Latest state of one card. Kinds define their own phases; `dismissed` is shared. - * `replaced` (a later proposal superseded an unstarted card) is derived from the - * log and never recorded. - */ +/** Latest recorded decision of one card. Kinds define their own phases alongside the shared `dismissed` phase. */ export interface ActionCardDecision { readonly cardId: ActionCardId readonly action: string diff --git a/packages/experimental/action-cards/tests/act.spec.ts b/packages/experimental/action-cards/tests/act.spec.ts index 8a72eb3fa1..ef0139b582 100644 --- a/packages/experimental/action-cards/tests/act.spec.ts +++ b/packages/experimental/action-cards/tests/act.spec.ts @@ -137,13 +137,11 @@ it('refuses the action when reconciliation fails or the root closes meanwhile', expect(f.act).not.toHaveBeenCalled() }) -it('refuses to record decisions of actions no kind registered or of phases the projection derives', async () => { +it('refuses to record decisions of actions no kind registered', async () => { const f = await fixture() const cardId = f.offer() expect(() => { f.ctx.actionCards.record(f.agent, { cardId, action: 'other_action', phase: 'done' }) }) .toThrow('action-cards: cannot record a decision for unregistered action "other_action"') - expect(() => { f.ctx.actionCards.record(f.agent, { cardId, action: ACTION, phase: 'replaced' }) }) - .toThrow('action-cards: phase "replaced" is derived from the log and cannot be recorded') expect(f.view().decisions).toEqual({}) // An unloading kind still records the outcome of work it had started. await f.kindFiber.dispose() diff --git a/packages/experimental/action-cards/tests/projection.spec.ts b/packages/experimental/action-cards/tests/projection.spec.ts index 137b5d6b10..b58ce44792 100644 --- a/packages/experimental/action-cards/tests/projection.spec.ts +++ b/packages/experimental/action-cards/tests/projection.spec.ts @@ -7,6 +7,7 @@ import { import type { PluginRecordMap } from '@deepseek-ai/dsh-session/types' import { actionCardProjection, type ActionCardState } from '../src/projection.ts' import type { ActionCardId } from '../src/types.ts' +import { ACTION, fixture, proposal } from './fixture.ts' const projection = actionCardProjection const args = { action: 'test_action', title: 'Counter', brief: 'Keep count visible', details: { value: 'a' } } @@ -50,9 +51,9 @@ const notice = (through: number): SessionEvent<'user/message'> => ({ type: 'user data: createUserMessage({ content: [{ type: 'text', text: 'status' }], source: { kind: 'action-cards', through: SessionSeq(through), form: 'notice', summary: 'status' } }) }) -it('admits the first valid action-card block of an answer as a card named by the answer message id', () => { +it('admits only the first valid block across the answers of a turn, named by its message id', () => { const offered = answer(`Here is an option.\n\n${block()}\n`) - expect(fold([turn(1), offered]).view.proposals).toEqual({ [idOf(offered)]: { cardId: idOf(offered), turn: 1, ...args } }) + expect(fold([offered, answer(block())]).view.proposals).toEqual({ [idOf(offered)]: { cardId: idOf(offered), turn: 1, ...args } }) const second = answer(`${block('{broken')}\n${block({ ...args, title: ' ' })}\n${block({ ...args, title: ' Second ' })}\n${block()}`) expect(fold([second]).view.proposals[idOf(second)]?.title).toBe('Second') const split = answer([{ type: 'text', text: 'No card yet.' }, { type: 'text', text: block({ ...args, title: 'Later block' }) }]) @@ -71,23 +72,35 @@ it('admits the first valid action-card block of an answer as a card named by the expect(fold([reasoning]).view.proposals).toEqual({}) }) -it('keeps the first card of a turn across steps, and replaces only unstarted earlier cards', () => { - const firstAnswer = answer(block()) - const first = fold([turn(1), firstAnswer]) - const a = idOf(firstAnswer) - expect(fold([answer(block({ ...args, title: 'Late' }))], first)).toEqual(first) - const nextAnswer = answer(block(args), 2) - const next = fold([turn(2), nextAnswer], first) - expect(Object.keys(next.view.proposals)).toEqual([a, idOf(nextAnswer)]) - expect(next.view.decisions).toEqual({ [a]: { cardId: a, action: 'test_action', phase: 'replaced' } }) - const started = fold(records({ cardId: a, action: 'test_action', phase: 'creating' }), first) - const laterAnswer = answer(block(args), 2) - const afterStart = fold([turn(2), laterAnswer], started) - expect(afterStart.view.decisions[a]?.phase).toBe('creating') - expect(afterStart.view.decisions[idOf(laterAnswer)]).toBeUndefined() - // Replacement crosses kinds: a card of another action replaces the unstarted one too. - const otherAnswer = answer(block({ ...args, action: 'other_action' }), 2) - expect(fold([turn(2), otherAnswer], first).view.decisions).toEqual({ [a]: { cardId: a, action: 'test_action', phase: 'replaced' } }) +it('replays v3 replacements from the log and restores a current checkpoint with its suffix', async () => { + const f = await fixture() + const { session } = f.agent + const registry = f.ctx.sessionProjections + const open = f.offer() + const started = f.offer(proposal, f.agent, 2) + const creating = { cardId: started, action: ACTION, phase: 'creating' } + f.ctx.actionCards.record(f.agent, creating) + const dismissed = f.offer(proposal, f.agent, 3) + const dismissal = { cardId: dismissed, action: ACTION, phase: 'dismissed' } + f.ctx.actionCards.record(f.agent, dismissal) + const prefix = registry.checkpoint(session) + const row = prefix['actionCards']! + const legacy = projection.stateSchema.parse(row.val) + legacy.view.decisions[open] = { cardId: open, action: ACTION, phase: 'replaced' } + const stale = { ...prefix, actionCards: { ...row, ver: 3, val: legacy } } + const example = f.offer({ ...proposal, action: 'my_example' }, f.agent, 4) + const events = session.snapshotEvents() + const restore = (checkpoint: typeof prefix, offset: number) => registry.restore( + checkpoint, events.slice(offset), SessionLogOffset(offset), session.header, session.inheritedEventCount, + ) + const full = restore({}, 0) + expect(registry.restoreFloor(stale)).toBe(0) + expect(restore(stale, 0)).toEqual(full) + expect(restore(prefix, row.seq + 1)).toEqual(full) + const recovered = projection.stateSchema.parse(full.checkpoint['actionCards']!.val) + expect(Object.keys(recovered.view.proposals)).toEqual([open, started, dismissed, example]) + expect(recovered.view.decisions).toEqual({ [started]: creating, [dismissed]: dismissal }) + expect(Object.keys(recovered.pendingStatus)).toEqual([started, dismissed]) }) it('creates no card from an interrupted answer or in a subagent Session', () => { diff --git a/packages/experimental/client-ui-action-cards/README.i18n.yaml b/packages/experimental/client-ui-action-cards/README.i18n.yaml index 6fe8a12d5c..1f730149a7 100644 --- a/packages/experimental/client-ui-action-cards/README.i18n.yaml +++ b/packages/experimental/client-ui-action-cards/README.i18n.yaml @@ -18,8 +18,8 @@ en: 717a53d2170d253b zh: 4e52852690601371 /deepseek-ai-dsh-client-ui-action-cards/use-this-package/register-a-card-body: - en: f46356cea53e8c72 - zh: 76f7ee328445a5d4 + en: 924cf85fcb2804fe + zh: 6cc87fb92ffa31a3 /deepseek-ai-dsh-client-ui-action-cards/understand-the-implementation: en: 180ee8add4b750a4 zh: 8ad116b65ccd532a diff --git a/packages/experimental/client-ui-action-cards/README.md b/packages/experimental/client-ui-action-cards/README.md index 95a992a982..bfc60eaba8 100644 --- a/packages/experimental/client-ui-action-cards/README.md +++ b/packages/experimental/client-ui-action-cards/README.md @@ -29,7 +29,7 @@ Enable the [Personalized recommendations](../personalized-recommendations/README ### Register a card body -A kind's browser plugin injects `actionCards` and registers its body inside its own `ctx.effect`: `ctx.actionCards.register({ action, locale, Body })` returns the disposer. The frame renders `Body` for cards of that action with the card, its recorded or derived decision, the Session id, the frame's title and folded brief as `summary`, the frame's dismiss-only content as `fallback`, the frame's fold component as `Folded`, an `act(verb, payload?)` bound to the card, and a translator `t` for the body's own locale namespace. The body places `summary` in its own layout, renders `fallback` instead when its schema rejects the card's `details`, and owns its header, controls, status and footer. A second body for the same action is a registration error. +A kind's browser plugin injects `actionCards` and registers its body inside its own `ctx.effect`: `ctx.actionCards.register({ action, locale, Body })` returns the disposer. The frame renders `Body` for cards of that action with the card, its latest recorded decision, the Session id, the frame's title and folded brief as `summary`, the frame's dismiss-only content as `fallback`, the frame's fold component as `Folded`, an `act(verb, payload?)` bound to the card, and a translator `t` for the body's own locale namespace. The body places `summary` in its own layout, renders `fallback` instead when its schema rejects the card's `details`, and owns its header, controls, status and footer. A second body for the same action is a registration error. ----- diff --git a/packages/experimental/client-ui-action-cards/README.zh.md b/packages/experimental/client-ui-action-cards/README.zh.md index c7274c97fa..8d35060b55 100644 --- a/packages/experimental/client-ui-action-cards/README.zh.md +++ b/packages/experimental/client-ui-action-cards/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" ### 注册卡片正文 -种类的浏览器插件注入 `actionCards`,并在自己的 `ctx.effect` 中注册正文:`ctx.actionCards.register({ action, locale, Body })` 返回注销函数。框架为该动作的卡片渲染 `Body`,并传入:卡片、已记录或推导出的决定、会话 id、框架渲染的标题与折叠说明 `summary`、只提供“暂不需要”的后备内容 `fallback`、框架的折叠组件 `Folded`、绑定到该卡片的 `act(verb, payload?)`,以及正文自己语言命名空间的翻译函数 `t`。正文把 `summary` 放进自己的布局,卡片的 `details` 未通过自己的校验时改为渲染 `fallback`,并负责自己的标题栏、控件、状态和底部操作。为同一动作注册第二个正文属于注册错误。 +种类的浏览器插件注入 `actionCards`,并在自己的 `ctx.effect` 中注册正文:`ctx.actionCards.register({ action, locale, Body })` 返回注销函数。框架为该动作的卡片渲染 `Body`,并传入:卡片、最新的已记录决定、会话 id、框架渲染的标题与折叠说明 `summary`、只提供“暂不需要”的后备内容 `fallback`、框架的折叠组件 `Folded`、绑定到该卡片的 `act(verb, payload?)`,以及正文自己语言命名空间的翻译函数 `t`。正文把 `summary` 放进自己的布局,卡片的 `details` 未通过自己的校验时改为渲染 `fallback`,并负责自己的标题栏、控件、状态和底部操作。为同一动作注册第二个正文属于注册错误。 ----- diff --git a/packages/experimental/client-ui-action-cards/src/client/Card.tsx b/packages/experimental/client-ui-action-cards/src/client/Card.tsx index 29c9d3d09e..4983207dc8 100644 --- a/packages/experimental/client-ui-action-cards/src/client/Card.tsx +++ b/packages/experimental/client-ui-action-cards/src/client/Card.tsx @@ -126,9 +126,6 @@ export function ActionCard({ proposal, decision, sessionId, act, bind, useBodies } -/** Phases the fallback can name; other kind phases leave only the summary. */ -const NAMED_PHASES: Readonly> = { dismissed: 'dismissed', replaced: 'replaced' } - /** Title, brief and Not now for a card whose kind registered no body in this browser or whose body rejects its `details`. */ function FallbackBody({ summary, decision, act, t }: { summary: ReactNode @@ -137,7 +134,6 @@ function FallbackBody({ summary, decision, act, t }: { } & PropsLocale<'actionCards'>) { const [pending, setPending] = useState(false) const [error, setError] = useState() - const phase = decision === undefined || !Object.hasOwn(NAMED_PHASES, decision.phase) ? undefined : NAMED_PHASES[decision.phase] const dismiss = async () => { setPending(true) setError(undefined) @@ -152,7 +148,7 @@ function FallbackBody({ summary, decision, act, t }: { } return
{summary} - {phase !== undefined &&

{t(phase)}

} + {decision?.phase === 'dismissed' &&

{t('dismissed')}

} {error !== undefined &&

{t(error)}

} {decision === undefined &&