mirror of
https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-11-10 20:57:49 +08:00
Merge master into fix/image-drag-plugin-ownership
This commit is contained in:
@@ -9,8 +9,8 @@
|
||||
en: e7c3b5d7702714fe
|
||||
zh: 268f162b553b37d1
|
||||
/agent-note-generic-file-upload/decision:
|
||||
en: 31c7ad96c6ab82c8
|
||||
zh: 806922fc8fcd1242
|
||||
en: 1769950d73d30dca
|
||||
zh: bf296b920ea9b997
|
||||
/agent-note-generic-file-upload/alternatives-considered:
|
||||
en: 23f386b05e4e79ef
|
||||
zh: 0756c4fa30e8d0eb
|
||||
@@ -21,5 +21,5 @@
|
||||
en: 3a50ac370d51cda9
|
||||
zh: d490f58922f8795b
|
||||
/agent-note-generic-file-upload/related:
|
||||
en: 7579c49eefdb8488
|
||||
zh: 68ad384fd9d2f8f9
|
||||
en: 14e8659b89dc08a8
|
||||
zh: dec5baa11f168e91
|
||||
|
||||
@@ -14,7 +14,7 @@ The command plane had already established a whole-envelope rule for images: a co
|
||||
|
||||
Files and images use separate storage schemes and one ordered message attachment list. Images keep their normalized-attachment pipeline unchanged. Other picked files enter one FIFO background-upload queue and are stored byte-for-byte with no type or size limits, then staged in-process for the same Session. Equal bytes have one canonical object under `DSH_HOME/attachments/v1/file-objects/<digest-prefix>/<digest>`; each read-only model-facing path at `DSH_HOME/attachments/v1/files/<digest-prefix>/<digest>/<name>` is a hard link, so different display names do not duplicate content. The configurable queue defaults to two active transfers. The independent dual-face `file-upload` Cordis package owns transfer and staging. Its Client `fileUpload` service accepts the owning Session identity together with a `Blob`, exact bytes, or a one-shot `ReadableStream<Uint8Array>`; it uses that identity to assemble the raw route request or invoke the generated Remote directly. Its Host `fileUploads` service owns the streaming route, encoded Remote fallback, command receipt resolver, and receipt tables keyed by the receiving Agent's Session object. Encoded admission and attachment-error recognition go through `ctx.attachments`, whose provider owns byte storage. Session Controller registers the resolver for cold ordinary Agents and consumes receipts during prompt admission; Session objects do not expose file transfer. Served Web pages hand each active body to a dedicated upload Worker: Blob bodies use XMLHttpRequest for total-aware byte progress, while streams transfer ownership and feed Fetch incrementally. Worker-hosted pages transfer the body through their page-owned Fetch carrier to the Host Worker, which reads bounded chunks. The page thread never reads, base64-encodes, or JSON-serializes generic file bytes. The authenticated Host route opts into Connection's streaming request mode, so the bridge dispatches before consuming the body and the local store hashes and writes bounded chunks to a private staging object. Completion atomically publishes the content-addressed object; cancellation or failure removes the staging file. Upload operations and draft state belong to the resident conversation root, so navigation to another Session does not stop the transfer; returning to the original Session shows the same card and progress. Removing the file card skips its queued transfer or aborts its active transfer. The sent message carries a structured `FileBlock` (`{ name, bytes, attachmentId }`) inside `user/message`; no new session event type exists. Request assembly in `LlmRuntime` projects every file block, including nested tool-result occurrences, to one deterministic handle naming the file and its saved read-only path. The handle tells a main agent to include that path when delegating file work and to report when the child's execution environment cannot see it. No provider receives file bytes; the model reads the stored copy with existing file tools on demand.
|
||||
|
||||
Default mode, active Plan Mode, and an active goal share ordinary queue, follow-up, and steer attachment admission. `/goal` create and edit and `/plan` entry accept the same ordered image and file batches; attachment-bearing control subcommands reject before changing state. Command submissions cite completed staged-file receipts, so generic file bytes are not read or copied again. Session Controller resolves every file receipt to a durable reference before `ctx.attachments.admitPromptContent()` receives the complete ordered content list; attachment admission persists images and passes file references unchanged. The Host rejects upload completion after the original Agent is disposed and deduplicates prompt retries already identified by `rpcId`. Prompt receipts remain available through failure recovery, then retire after the accepted queue or history occurrence is observed; command-only receipts remain until Session disposal. Submission echoes register through `beginSubmission` before serialization, carry mixed attachments through `pendingSubmissions`, correlate by `rpcId`, retire once after queue or history observation, and keep drafts on failure. Before submission, the composer presents the ordered batch in one non-wrapping horizontal rail: images use 64 by 64 pixel thumbnails and generic files use 240 by 64 pixel cards with a 16 pixel radius, blue document glyph, filename plus extension and size, and a hover or keyboard removal action. QueueDock uses the same order with compact thumbnails and file cards. After submission, Chat presents the ordered batch in one right-aligned wrapping attachment flow. A lone image retains the large gallery presentation; a message with multiple attachments uses 64 by 64 pixel image tiles and 240 by 64 pixel file cards, so files and images share each row until the available width forces a wrap. Trajectory keeps the user-message preview compact and adds a localized generic-file count. Paperclip, drag, and paste classify by MIME; send waits for every file upload. Continuable subagent composers disable attachment intake, and the Host rejects any file block received for a child session.
|
||||
Default mode, active Plan Mode, and an active goal share ordinary queue, follow-up, and steer attachment admission. `/goal` create and edit and `/plan` entry accept the same ordered image and file batches; attachment-bearing control subcommands reject before changing state. Command submissions cite completed staged-file receipts, so generic file bytes are not read or copied again. Session Controller resolves every file receipt to a durable reference before `ctx.attachments.admitPromptContent()` receives the complete ordered content list; attachment admission persists images and passes file references unchanged. The Host rejects upload completion after the original Agent is disposed and deduplicates prompt retries already identified by `rpcId`. Prompt receipts remain available through failure recovery, then retire after the accepted queue or history occurrence is observed; command-only receipts remain until Session disposal. Submission echoes register through `beginSubmission` before serialization, carry mixed attachments through `pendingSubmissions`, correlate by `rpcId`, retire once after queue or history observation, and keep drafts on failure. Before submission, the composer presents the ordered batch in one non-wrapping horizontal rail: images use 64 by 64 pixel thumbnails and generic files use 240 by 64 pixel cards with a 16 pixel radius, blue document glyph, filename plus extension and size, and a hover or keyboard removal action. QueueDock uses the same order with compact thumbnails and file cards. After submission, Chat presents the ordered batch in one right-aligned wrapping attachment flow. A lone image retains the large gallery presentation; a message with multiple attachments uses 64 by 64 pixel image tiles and 240 by 64 pixel file cards, so files and images share each row until the available width forces a wrap. Trajectory keeps the user-message preview compact and adds a localized generic-file count. Paperclip, drag, and paste classify by MIME; send waits for every upload. Continuable subagent composers disable attachment intake, and the Host rejects any file block received for a child session.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -54,3 +54,5 @@ Unit and integration coverage pins verbatim and streamed storage, name sanitizat
|
||||
The [Trajectory reference](../../../../packages/client/ui-trajectory/README.md) documents ledger counts and inspector attachment layouts.
|
||||
|
||||
The [input echo admission reference](../../../../packages/api/session-controller/README.md) owns placement-specific retirement and delayed Inbox suppression for submissions with or without attachments.
|
||||
|
||||
The [composer image upload on add](2026-10-21-composer-image-upload-on-add.md) note extends this background-upload queue to the images of an ordinary Session's draft.
|
||||
|
||||
@@ -14,7 +14,7 @@ Status: implemented
|
||||
|
||||
文件与图片使用不同存储方案,并进入同一个有序消息附件列表。图片的规范化附件流水线保持不变。其他被选中的文件进入同一个先进先出的后台上传队列,按字节原样保存且不设类型与大小限制,再在本进程内按同一 Session 暂存。相同字节在 `DSH_HOME/attachments/v1/file-objects/<digest-prefix>/<digest>` 下只有一个规范对象;每条模型可见的只读路径 `DSH_HOME/attachments/v1/files/<digest-prefix>/<digest>/<name>` 都是硬链接,因此不同显示名称不会复制内容。该队列可以配置,默认同时运行两项传输。独立的双端 `file-upload` Cordis 包拥有传输与暂存。其 Client `fileUpload` 服务同时接收所属 Session 标识与 `Blob`、精确字节或只能使用一次的 `ReadableStream<Uint8Array>`;它使用该标识组装原始路由请求,或直接调用生成的 Remote。其 Host `fileUploads` 服务拥有流式路由、编码 Remote 兜底、命令凭证解析器,以及以接收方 Agent 的 Session 对象为键的凭证表。编码准入和附件错误识别通过 `ctx.attachments` 完成,字节存储由附件提供方拥有。Session Controller 注册用于休眠普通 Agent 的解析器,并在 prompt 准入时消费凭证;Session 对象不公开文件传输。普通 Web 页面把每个活动请求体交给专用上传 Worker:Blob 请求体通过 XMLHttpRequest 发送并报告包含总量的字节进度,stream 则转移所有权并增量传入 Fetch。Worker-hosted 页面通过页面自有 Fetch 载体把请求体转交给 Host Worker,后者读取有界分片。页面线程不读取通用文件字节,也不做 base64 编码或 JSON 序列化。经过认证的 Host 路由显式使用 Connection 的流式请求模式,因此 bridge 会在消费请求体前分发,本地存储则把有界分片写入私有暂存对象并同时计算摘要。接收完成后,内容寻址对象以原子方式发布;取消或失败会移除暂存文件。上传任务和草稿状态属于常驻的 conversation 根,因此切到另一条 Session 不会停止传输,返回原 Session 时仍显示同一张文件卡和当前进度。移除文件卡会跳过排队中的传输或中止正在运行的传输。发送的消息在 `user/message` 里携带结构化的 `FileBlock`(`{ name, bytes, attachmentId }`),不新增会话事件类型。`LlmRuntime` 的请求组装把每个文件块,包括嵌套工具结果中的文件块,投影成确定性 handle 文本,指出文件与其只读保存路径。handle 会要求主 agent 委派文件任务时附上该路径,并在子级执行环境看不到路径时明确报告。提供方不会收到文件字节,模型在需要时用现有文件工具读取存储副本。
|
||||
|
||||
默认模式、激活的 Plan Mode 与 active goal 共用普通 queue、follow-up 和 steer 的附件准入。`/goal` create 和 edit 以及 `/plan` 进入接受同一套有序图片与文件批量;携带附件的控制子命令会在状态变更前拒绝。命令提交引用已完成暂存的文件凭证,不会再次读取或复制通用文件字节。Session Controller 先把每个文件凭证解析为持久引用,再由 `ctx.attachments.admitPromptContent()` 接收完整有序内容列表;附件准入会持久化图片,并让文件引用原样通过。原 Agent 已销毁时,Host 会拒绝发布上传完成凭证,并按 `rpcId` 去重已经存在的 prompt 重试。prompt 凭证在失败恢复期间保持可用,已接受的 queue 或历史 occurrence 被观察后才退休;只被命令使用的凭证保留到 Session 销毁。提交回显在序列化前经 `beginSubmission` 注册,通过 `pendingSubmissions` 携带混合附件,以 `rpcId` 关联,在 queue 或历史观察后只退休一次,并在失败时保留草稿。发送前,composer 把有序附件放进同一条不换行的横向附件栏:图片使用 64 乘 64 像素缩略图,通用文件使用 240 乘 64 像素卡片,带 16 像素圆角、蓝色文档图标、文件名加扩展名与大小,以及悬停或键盘操作时可用的移除按钮。QueueDock 使用相同顺序以及紧凑的缩略图和文件卡。发送后,Chat 把有序附件放进同一个右对齐、可换行的附件区域。只有一张图片时保留图片画廊的大图样式;一条消息含有多个附件时,图片使用 64 乘 64 像素缩略图,文件使用 240 乘 64 像素卡片,文件与图片在可用宽度内共用一行,空间不足时再换行。Trajectory 保持紧凑的用户消息预览,并增加本地化的通用文件数量。回形针、拖拽和粘贴按 MIME 分类;发送会等待每个文件上传完成。continuable 子代理 composer 禁用附件入口,Host 会拒绝收到的任何子会话文件块。
|
||||
默认模式、激活的 Plan Mode 与 active goal 共用普通 queue、follow-up 和 steer 的附件准入。`/goal` create 和 edit 以及 `/plan` 进入接受同一套有序图片与文件批量;携带附件的控制子命令会在状态变更前拒绝。命令提交引用已完成暂存的文件凭证,不会再次读取或复制通用文件字节。Session Controller 先把每个文件凭证解析为持久引用,再由 `ctx.attachments.admitPromptContent()` 接收完整有序内容列表;附件准入会持久化图片,并让文件引用原样通过。原 Agent 已销毁时,Host 会拒绝发布上传完成凭证,并按 `rpcId` 去重已经存在的 prompt 重试。prompt 凭证在失败恢复期间保持可用,已接受的 queue 或历史 occurrence 被观察后才退休;只被命令使用的凭证保留到 Session 销毁。提交回显在序列化前经 `beginSubmission` 注册,通过 `pendingSubmissions` 携带混合附件,以 `rpcId` 关联,在 queue 或历史观察后只退休一次,并在失败时保留草稿。发送前,composer 把有序附件放进同一条不换行的横向附件栏:图片使用 64 乘 64 像素缩略图,通用文件使用 240 乘 64 像素卡片,带 16 像素圆角、蓝色文档图标、文件名加扩展名与大小,以及悬停或键盘操作时可用的移除按钮。QueueDock 使用相同顺序以及紧凑的缩略图和文件卡。发送后,Chat 把有序附件放进同一个右对齐、可换行的附件区域。只有一张图片时保留图片画廊的大图样式;一条消息含有多个附件时,图片使用 64 乘 64 像素缩略图,文件使用 240 乘 64 像素卡片,文件与图片在可用宽度内共用一行,空间不足时再换行。Trajectory 保持紧凑的用户消息预览,并增加本地化的通用文件数量。回形针、拖拽和粘贴按 MIME 分类;发送会等待每项上传完成。continuable 子代理 composer 禁用附件入口,Host 会拒绝收到的任何子会话文件块。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
@@ -54,3 +54,5 @@ Status: implemented
|
||||
[Trajectory 参考](../../../../packages/client/ui-trajectory/README.zh.md)说明列表计数与详情面板附件布局。
|
||||
|
||||
[输入回显入档参考](../../../../packages/api/session-controller/README.zh.md)负责有无附件提交的按展示归属回收和迟到 Inbox 排除。
|
||||
|
||||
[输入框在加入时上传图片](2026-10-21-composer-image-upload-on-add.zh.md) 记录把这条后台上传队列扩展到普通 Session 草稿里的图片。
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Bilingual-pair consistency record for 2026-10-21-composer-image-upload-on-add.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-21-composer-image-upload-on-add.md
|
||||
/agent-note-composer-image-upload-on-add:
|
||||
en: 996b39b53086b9ac
|
||||
zh: c81fade50ac895ec
|
||||
/agent-note-composer-image-upload-on-add/problem:
|
||||
en: b184ade2bd353f50
|
||||
zh: 00b97c91df54b310
|
||||
/agent-note-composer-image-upload-on-add/decision:
|
||||
en: eada67e3c3d50f47
|
||||
zh: 5fb4f3a5e774e47e
|
||||
/agent-note-composer-image-upload-on-add/alternatives-considered:
|
||||
en: afa82b9bce9015f6
|
||||
zh: d088b92c2cb6c622
|
||||
/agent-note-composer-image-upload-on-add/consequences:
|
||||
en: 08d1bcb970beb40e
|
||||
zh: f42db4052618c289
|
||||
/agent-note-composer-image-upload-on-add/testing:
|
||||
en: f2d2c59272ffcf70
|
||||
zh: 46c933fd2aeb87ea
|
||||
/agent-note-composer-image-upload-on-add/related:
|
||||
en: 6eac98f60c3b99f9
|
||||
zh: c1e318e74f44fbb4
|
||||
@@ -0,0 +1,36 @@
|
||||
# Agent Note: Composer image upload on add
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-10-21-composer-image-upload-on-add.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The Web composer kept image drafts in the browser and base64-encoded each image into `session/prompt` at send time, so the Host received, validated, normalized, and stored image bytes inside prompt admission. Generic files already uploaded when picked ([generic file upload](2026-08-26-generic-file-upload.md)). An image message therefore carried up to the per-message image byte limit in one RPC body, and its send time grew with image size; a composer that waits for the Host to accept a message before clearing it would hold the draft for that whole transfer.
|
||||
|
||||
## Decision
|
||||
|
||||
An ordinary Session's composer uploads each image draft as soon as it is added, through the same FIFO background-upload queue, Worker carriers, progress, retry, and cancellation that generic files use. The raw upload route takes a `mediaType` query parameter for an image upload; the Host reads at most the smaller of the deployment's per-image and per-message image byte limits, then validates, normalizes, and stores the image with `ctx.attachments.saveImages` exactly as prompt admission would, and stages the normalized image under a receipt for that Session. The prompt cites the receipt in an ordinary file part, so `session/prompt` keeps its wire types; prompt admission resolves the receipt to the stored image, applies the model's image-input check to the prompt, and counts stored images toward `maxImagesPerMessage` and `maxMessageImageBytes` together with encoded ones, each stored image by the bytes of its upload. Send waits until every image draft has a receipt, and a failed image upload turns its thumbnail into a retry control. Commands accept only file receipts, so command submissions keep encoding images inline. A continuable subagent's composer keeps inline images because the Host stages uploads only for ordinary Sessions; SDK and other wire callers may still send encoded images.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **A dedicated image-receipt prompt part.** Rejected: the receipt already names what was staged, so a second part kind would widen the `session/prompt` wire union, its generated catalogs, and every consumer that switches on parts without changing what the Host admits.
|
||||
- **A separate image upload route or Remote method.** Rejected: one route with an explicit `mediaType` parameter reuses Session addressing, carrier selection, progress, and the failure envelope; the exact-bytes Remote fallback has no image caller.
|
||||
- **Upload images but normalize them at send.** Rejected: normalization is the expensive part of image admission, so deferring it would keep the send-time cost this change removes.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Sending an image message transfers only references, and the normalization cost moves to the moment the image is added.
|
||||
- Per-image refusals such as an undecodable or oversized image surface when the image is added: the thumbnail names the refusal instead of offering a retry, and Enter repeats it. The model's image-input check and the per-message image count and byte limits still apply at send.
|
||||
- Commands accept only file receipts, so a command submission that carries an image waits for the image upload like a message and then encodes the image inline: the image is stored a second time, and its unused receipt lasts until its Session ends.
|
||||
- Removing an image while it uploads cancels the upload, and a cancelled upload receives no receipt; an image whose storage had already begun, or whose upload had finished, stays under `DSH_HOME`, which never deletes attachments. On a remote Host the bytes reach the server as soon as the user adds the image.
|
||||
- Staged image receipts share the generic files' in-memory lifetime: a Host restart between adding and sending surfaces `FILE_NOT_STAGED`, and the user adds the image again.
|
||||
- Image drafts, like file drafts, are not restored after a page reload or after their Session's client scope is released.
|
||||
|
||||
## Testing
|
||||
|
||||
Host coverage pins image staging through the raw route, the per-image byte bound that stops reading, unsupported types, subagent refusal, command refusal of image receipts, receipt resolution into the admitted image, the image-input check for an uploaded image, the per-message byte limit across receipts, and withheld receipts for uploads cancelled after their last chunk or during storage. Attachment admission coverage pins stored-image pass-through and the combined image count and byte limits. Client coverage pins image upload start, retry, cancellation, the send gate, receipt citation without re-encoding, inline images for drafts without an upload, the rail's progress, retry, and refusal states, and the Enter explanation of a held send.
|
||||
|
||||
## Related
|
||||
|
||||
The [generic file upload](2026-08-26-generic-file-upload.md) note owns the background-upload queue, carriers, staging lifetime, and file storage that image uploads reuse.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Agent Note: 输入框在加入时上传图片
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-10-21-composer-image-upload-on-add.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
Web 输入框把图片草稿留在浏览器里,发送时才把每张图片 base64 编码进 `session/prompt`,Host 在 prompt 准入时才接收、校验、规整并存储图片字节。通用文件早已在选中时上传([通用文件上传](2026-08-26-generic-file-upload.zh.md))。因此一条图片消息要在一个 RPC 请求体里携带最多达到单条消息图片字节上限的数据,发送耗时随图片大小增长;如果输入框要等 Host 接纳消息后才清空,草稿就要在整个传输期间一直保留。
|
||||
|
||||
## 决定
|
||||
|
||||
普通 Session 的输入框在图片草稿加入时就上传它,复用通用文件的先进先出后台上传队列、Worker 载体、进度、重试与取消。原始上传路由用 `mediaType` 查询参数表示图片上传;Host 最多读取部署配置的单张图片与单条消息图片字节上限中较小的一个,然后按 prompt 准入的同样方式用 `ctx.attachments.saveImages` 校验、规整并存储图片,再以该 Session 的凭证暂存规整后的图片。prompt 在普通文件部分引用该凭证,因此 `session/prompt` 的线上类型不变;prompt 准入把凭证解析为已存储的图片,对这条 prompt 执行模型的图片输入检查,并把已存储图片与编码图片一起计入 `maxImagesPerMessage` 和 `maxMessageImageBytes`,已存储图片按其上传的字节数计入。发送会等到每个图片草稿都取得凭证;图片上传失败时,缩略图变成重试控件。命令只接受文件凭证,所以命令提交仍以内联方式编码图片。continuable 子代理的输入框继续内联图片,因为 Host 只为普通 Session 暂存上传;SDK 和其他线上调用方仍可发送编码图片。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
- **专用的图片凭证 prompt 部分。** 已否决:凭证本身已经指明暂存的内容,新增一种部分类型会扩大 `session/prompt` 线上联合类型、它的生成目录以及每个按部分类型分支的消费方,却不改变 Host 准入的内容。
|
||||
- **单独的图片上传路由或 Remote 方法。** 已否决:一条带显式 `mediaType` 参数的路由复用了 Session 寻址、载体选择、进度和失败信封;精确字节的 Remote 兜底没有图片调用方。
|
||||
- **加入时上传、发送时再规整。** 已否决:规整是图片准入中开销最大的部分,推迟它会保留这次改动要消除的发送耗时。
|
||||
|
||||
## 后果
|
||||
|
||||
- 发送图片消息只传引用,规整开销移到图片加入的时刻。
|
||||
- 无法解码、超过单张上限等逐张拒绝在图片加入时出现:缩略图说明拒绝原因而不提供重试,按 Enter 也会提示同样的原因。模型的图片输入检查以及单条消息的图片数量与总字节上限仍在发送时执行。
|
||||
- 命令只接受文件凭证,所以带图片的命令提交也要像消息一样等图片上传完成,再以内联方式编码图片:同一张图会再存储一次,未被引用的凭证一直留到 Session 结束。
|
||||
- 图片上传中移除会取消上传,取消的上传不会取得凭证;已开始存储或已上传完成的图片仍留在 `DSH_HOME` 下,附件存储从不删除。Host 在远端时,用户一加入图片,字节就到达服务器。
|
||||
- 暂存的图片凭证与通用文件同样只存在内存里:在加入与发送之间重启 Host 会得到 `FILE_NOT_STAGED`,用户需要重新加入图片。
|
||||
- 与文件草稿一样,图片草稿在页面刷新后或其 Session 的客户端作用域释放后不会恢复。
|
||||
|
||||
## 测试
|
||||
|
||||
Host 侧覆盖经原始路由暂存图片、单张字节上限一超出即停止读取、不支持的类型、子代理拒绝、命令拒绝图片凭证、凭证解析为准入后的图片、已上传图片的图片输入检查、多个凭证合计的单条消息字节上限,以及在最后一个分块之后或存储期间取消的上传不签发凭证。附件准入覆盖已存储图片原样通过,以及合并后的图片数量与总字节上限。客户端覆盖图片上传的开始、重试、取消、发送闸门、发送时引用凭证而不重新编码、没有上传的草稿以内联方式发送图片,附件栏的进度、重试与拒绝状态,以及发送被挡住时按 Enter 的说明。
|
||||
|
||||
## 相关记录
|
||||
|
||||
[通用文件上传](2026-08-26-generic-file-upload.zh.md) 记录负责图片上传所复用的后台上传队列、载体、暂存生命周期与文件存储。
|
||||
@@ -179,6 +179,7 @@ interface FixtureWindow extends Window {
|
||||
__DSH_BOOT__?: WebBootGraph
|
||||
__ModuleLoader__?: ClientModuleLoaderTarget
|
||||
__DSH_TRANSPORT__?: { readonly rpc: RemoteMock['rpc'] }
|
||||
__DSH_FILE_UPLOAD__?: { readonly fetch: AssembledRemote['fileUpload'] }
|
||||
}
|
||||
|
||||
class ResizeObserverStub {
|
||||
@@ -253,6 +254,7 @@ export function installAssembledBootEnv(): void {
|
||||
delete win.__DSH_BOOT__
|
||||
delete win.__ModuleLoader__
|
||||
delete win.__DSH_TRANSPORT__
|
||||
delete win.__DSH_FILE_UPLOAD__
|
||||
document.body.innerHTML = ''
|
||||
document.head.querySelectorAll('style[data-plugin]').forEach((style) => { style.remove() })
|
||||
document.title = ''
|
||||
@@ -281,6 +283,7 @@ export function mountAssembledApp(options: AssembledBootOptions = {}): Assembled
|
||||
const remote = createAssembledRemote(options.remote)
|
||||
mountedRemote = remote.mock
|
||||
win.__DSH_TRANSPORT__ = { rpc: remote.mock.rpc }
|
||||
win.__DSH_FILE_UPLOAD__ = { fetch: remote.fileUpload }
|
||||
history.replaceState(null, '', '/')
|
||||
const root = document.createElement('div')
|
||||
root.id = 'root'
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* Fixture Sessions have no retained Host terminals to restore.
|
||||
*/
|
||||
|
||||
import { Buffer } from 'node:buffer'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { join } from 'node:path'
|
||||
@@ -106,6 +107,8 @@ export interface AssembledRemoteOptions {
|
||||
|
||||
export interface AssembledRemote {
|
||||
readonly mock: RemoteMock
|
||||
/** Page-owned upload carrier: stages an image upload as the Host would and answers its receipt. */
|
||||
readonly fileUpload: (input: string | URL, init: RequestInit) => Promise<Response>
|
||||
}
|
||||
|
||||
const fixtureSource = readFileSync(
|
||||
@@ -132,6 +135,7 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass
|
||||
return [sessionId, next] as const
|
||||
}))
|
||||
const attachments = new Map<string, unknown>([['fixture:image', structuredClone(fixture.attachment)]])
|
||||
const stagedImages = new Map<string, Record<string, unknown>>()
|
||||
const blankSessionProjections = fixture.control.value.projections['fx-gamma']
|
||||
if (blankSessionProjections === undefined) {
|
||||
throw new Error('assembled fixture: blank Session projections missing')
|
||||
@@ -312,6 +316,10 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass
|
||||
const summary = sessions.find(candidate => candidate.sessionId === sessionId)
|
||||
if (summary === undefined) throw new Error(`assembled fixture: no Session ${sessionId}`)
|
||||
const content = recordArray(request, 'content').map((part) => {
|
||||
if (isRecord(part) && part.type === 'file') {
|
||||
const image = stagedImages.get(recordString(part, 'receiptId'))
|
||||
return image === undefined ? part : { type: 'image', attachment: image }
|
||||
}
|
||||
if (!isRecord(part) || part.type !== 'image') return part
|
||||
const attachmentId = `assembled:${randomUUID()}`
|
||||
const data = recordString(part, 'data')
|
||||
@@ -364,7 +372,28 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass
|
||||
})
|
||||
})
|
||||
|
||||
return { mock }
|
||||
const fileUpload = async (input: string | URL, init: RequestInit): Promise<Response> => {
|
||||
const url = new URL(String(input), 'http://assembled.test/')
|
||||
const mediaType = url.searchParams.get('mediaType')
|
||||
if (!url.pathname.endsWith('/api/session/uploadFileBinary') || mediaType === null || !(init.body instanceof Blob)) {
|
||||
throw new Error(`assembled fixture: unexpected upload ${url.pathname}${url.search}`)
|
||||
}
|
||||
const bytes = new Uint8Array(await init.body.arrayBuffer())
|
||||
const name = url.searchParams.get('name')
|
||||
const image = {
|
||||
attachmentId: `assembled:${randomUUID()}`,
|
||||
mediaType,
|
||||
bytes: bytes.byteLength,
|
||||
width: 160,
|
||||
height: 90,
|
||||
...name === null ? {} : { name },
|
||||
}
|
||||
attachments.set(image.attachmentId, ok({ attachment: image, data: Buffer.from(bytes).toString('base64') }))
|
||||
const receiptId = `assembled-receipt:${randomUUID()}`
|
||||
stagedImages.set(receiptId, image)
|
||||
return new Response(JSON.stringify({ ok: true, value: { receiptId, image } }), { status: 200 })
|
||||
}
|
||||
return { mock, fileUpload }
|
||||
}
|
||||
|
||||
function eventOf(
|
||||
|
||||
@@ -179,7 +179,8 @@ describe('web e2e: Markdown image rendering', () => {
|
||||
await writeFile(join(scaffold.workspaceCwd, 'corrupt.png'), 'invalid image')
|
||||
const oversized = await open(join(scaffold.workspaceCwd, 'oversized.png'), 'w')
|
||||
try {
|
||||
await oversized.truncate(20 * 1024 * 1024 + 1)
|
||||
// One byte over attachment-local's default maxImageBytes (50 MiB), which also bounds /api/file.
|
||||
await oversized.truncate(50 * 1024 * 1024 + 1)
|
||||
} finally {
|
||||
await oversized.close()
|
||||
}
|
||||
|
||||
@@ -100,6 +100,9 @@ describe('web e2e: queued image submission', () => {
|
||||
await page.locator('[data-composer-input][contenteditable="true"]').first().waitFor({ timeout: 10_000 })
|
||||
await pasteImage(page, await readFile(PNG))
|
||||
await page.getByRole('img', { name: 'queued.png' }).waitFor({ timeout: 10_000 })
|
||||
// The image uploads as soon as it is added, and Send waits for its receipt.
|
||||
await page.locator('button[aria-busy="false"]', { has: page.getByRole('img', { name: 'queued.png' }) })
|
||||
.waitFor({ timeout: 10_000 })
|
||||
const releasePrompt = Promise.withResolvers<undefined>()
|
||||
const releaseImage = Promise.withResolvers<undefined>()
|
||||
let cleanupPromise: Promise<void> | undefined
|
||||
|
||||
@@ -356,14 +356,14 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-attachment-local`
|
||||
|
||||
- `source`: [`packages/attachment/attachment-local/src/index.ts:61`](../packages/attachment/attachment-local/src/index.ts)
|
||||
- `source`: [`packages/attachment/attachment-local/src/index.ts:65`](../packages/attachment/attachment-local/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Local attachment backend configuration. */
|
||||
export interface Config {
|
||||
/** Explicit harness home; omitted follows `DSH_HOME`, then `~/.dsh`. */
|
||||
dshHome?: string
|
||||
/** Maximum encoded bytes accepted for one submitted image. Default: 20 MiB. */
|
||||
/** Maximum encoded bytes accepted for one submitted image. Default: 50 MiB. */
|
||||
maxImageBytes?: number
|
||||
/** Maximum image count accepted in one submitted message. Default: 20. */
|
||||
maxImagesPerMessage?: number
|
||||
@@ -371,7 +371,7 @@ export interface Config {
|
||||
maxMessageImageBytes?: number
|
||||
/** Maximum intrinsic width multiplied by height accepted for one submitted image. Default: 64,000,000. */
|
||||
maxImagePixels?: number
|
||||
/** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 8192px. */
|
||||
/** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 65,535px. */
|
||||
maxImageDimension?: number
|
||||
/** Total-pixel budget of the stored provider-independent normalized image. */
|
||||
normalizedImageMaxPixels?: number
|
||||
|
||||
@@ -358,14 +358,14 @@ export interface Config {
|
||||
|
||||
## `@deepseek-ai/dsh-attachment-local`
|
||||
|
||||
- `source`: [`packages/attachment/attachment-local/src/index.ts:61`](../packages/attachment/attachment-local/src/index.ts)
|
||||
- `source`: [`packages/attachment/attachment-local/src/index.ts:65`](../packages/attachment/attachment-local/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Local attachment backend configuration. */
|
||||
export interface Config {
|
||||
/** Explicit harness home; omitted follows `DSH_HOME`, then `~/.dsh`. */
|
||||
dshHome?: string
|
||||
/** Maximum encoded bytes accepted for one submitted image. Default: 20 MiB. */
|
||||
/** Maximum encoded bytes accepted for one submitted image. Default: 50 MiB. */
|
||||
maxImageBytes?: number
|
||||
/** Maximum image count accepted in one submitted message. Default: 20. */
|
||||
maxImagesPerMessage?: number
|
||||
@@ -373,7 +373,7 @@ export interface Config {
|
||||
maxMessageImageBytes?: number
|
||||
/** Maximum intrinsic width multiplied by height accepted for one submitted image. Default: 64,000,000. */
|
||||
maxImagePixels?: number
|
||||
/** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 8192px. */
|
||||
/** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 65,535px. */
|
||||
maxImageDimension?: number
|
||||
/** Total-pixel budget of the stored provider-independent normalized image. */
|
||||
normalizedImageMaxPixels?: number
|
||||
|
||||
@@ -24,8 +24,8 @@
|
||||
en: 1b527d85759324f9
|
||||
zh: 54aa40db2705b95c
|
||||
/fiber/the-fiber-class/fiber-config:
|
||||
en: ee804c03c39e7806
|
||||
zh: 4353ba7817ec61ec
|
||||
en: 1efe137a7ef0e599
|
||||
zh: bb4b9818fb48f4e9
|
||||
/fiber/the-fiber-class/fiber-state:
|
||||
en: 999ad29dfc29661b
|
||||
zh: 20245d11c338e3f1
|
||||
@@ -50,15 +50,24 @@
|
||||
/fiber/the-fiber-class/fiber-geteffects:
|
||||
en: 4d739a9c186fd9c2
|
||||
zh: f80fd3b87e79b004
|
||||
/fiber/the-fiber-class/fiber-rawconfig:
|
||||
en: 898aab51825bd8c3
|
||||
zh: b9ab6339574002df
|
||||
/fiber/the-fiber-class/fiber-effectiveconfig:
|
||||
en: 93ac680251e7023f
|
||||
zh: 8ea7d7de5db39b8e
|
||||
/fiber/the-fiber-class/fiber-resolveconfig-config:
|
||||
en: d7319852e2a1c3a9
|
||||
zh: 3300fac049227006
|
||||
/fiber/the-fiber-class/fiber-await:
|
||||
en: 1d6258cbea61cd18
|
||||
zh: 2f10dda8918dadc5
|
||||
en: c9a6544cacdbc28e
|
||||
zh: 636bf93efad95bc9
|
||||
/fiber/the-fiber-class/fiber-restart:
|
||||
en: 62d68dedb20b4fa9
|
||||
zh: 5a735ae0ff1266f4
|
||||
en: 6ffc1baba98d689f
|
||||
zh: 7e13bc92225c7e0a
|
||||
/fiber/the-fiber-class/fiber-update-config-nosave:
|
||||
en: b57ce0f6260c2cb8
|
||||
zh: 3bfb6c5bc252a2c2
|
||||
en: 5c176a6e67073e92
|
||||
zh: ee07edc8dbf7c1f3
|
||||
/fiber/effect:
|
||||
en: 007d5b214e8a8610
|
||||
zh: d74c26fbb1b8aeb6
|
||||
|
||||
@@ -80,11 +80,11 @@ The context this fiber's plugin runs in (extends the parent context).
|
||||
### fiber.config
|
||||
|
||||
```ts cordis-catalog
|
||||
/** The validated plugin config (updated by `update()`). */
|
||||
/** The validated plugin config (updated by `update()`); read through {@link effectiveConfig}. */
|
||||
public config: any
|
||||
```
|
||||
|
||||
The validated plugin config (updated by `update()`).
|
||||
The validated plugin config (updated by `update()`); read through effectiveConfig.
|
||||
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L190)
|
||||
|
||||
@@ -209,6 +209,53 @@ Return metadata for currently registered effects.
|
||||
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L568)
|
||||
|
||||
### fiber.rawConfig
|
||||
|
||||
```ts cordis-catalog
|
||||
/** Raw input retained for the next activation, without evaluating expressions or validating it. */
|
||||
get rawConfig(): unknown
|
||||
```
|
||||
|
||||
Raw input retained for the next activation, without evaluating expressions or validating it.
|
||||
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L642)
|
||||
|
||||
### fiber.effectiveConfig
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* The config object published by the existing activation/update lifecycle, without cloning or re-parsing.
|
||||
* It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`.
|
||||
*/
|
||||
get effectiveConfig(): unknown
|
||||
```
|
||||
|
||||
The config object published by the existing activation/update lifecycle, without cloning or re-parsing. It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`.
|
||||
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L655)
|
||||
|
||||
### fiber.resolveConfig(config)
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema.
|
||||
* Does not publish the result, replace raw input, or commit running volatile references.
|
||||
* Required injections must be available when a hook uses them.
|
||||
* @param config Raw candidate input.
|
||||
* @returns The candidate's resolved config, retaining the schema's result identity.
|
||||
* @throws {ValidationError} when the runtime schema rejects the candidate; hook errors propagate.
|
||||
*/
|
||||
resolveConfig(config: unknown): unknown
|
||||
```
|
||||
|
||||
Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema. Does not publish the result, replace raw input, or commit running volatile references. Required injections must be available when a hook uses them.
|
||||
|
||||
- `config` — Raw candidate input.
|
||||
|
||||
**Returns** The candidate's resolved config, retaining the schema's result identity.
|
||||
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L667)
|
||||
|
||||
### fiber.await()
|
||||
|
||||
```ts cordis-catalog
|
||||
@@ -225,7 +272,7 @@ Wait for current lifecycle work and rethrow startup errors.
|
||||
|
||||
**Returns** this fiber, once it has settled into a stable state.
|
||||
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L704)
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L731)
|
||||
|
||||
### fiber.restart()
|
||||
|
||||
@@ -243,7 +290,7 @@ Dispose and immediately reload this plugin with its current config.
|
||||
|
||||
**Returns** a promise resolving once the reload settled.
|
||||
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L718)
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L745)
|
||||
|
||||
### fiber.update(config, noSave?)
|
||||
|
||||
@@ -271,7 +318,7 @@ Runs the `internal/update` waterfall first, so update hooks (and HMR) can veto o
|
||||
|
||||
**Returns** nothing; the restart runs behind the `internal/update` waterfall.
|
||||
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L736)
|
||||
[Source](../../vendor/cordis/src/fiber.ts#L764)
|
||||
|
||||
## Effect
|
||||
|
||||
|
||||
@@ -82,11 +82,11 @@ public readonly ctx: Context
|
||||
### fiber.config
|
||||
|
||||
```ts cordis-catalog
|
||||
/** The validated plugin config (updated by `update()`). */
|
||||
/** The validated plugin config (updated by `update()`); read through {@link effectiveConfig}. */
|
||||
public config: any
|
||||
```
|
||||
|
||||
经过校验的插件配置(由 `update()` 更新)。
|
||||
经过校验的插件配置(由 `update()` 更新);通过 `effectiveConfig` 读取。
|
||||
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L190)
|
||||
|
||||
@@ -211,6 +211,53 @@ getEffects()
|
||||
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L568)
|
||||
|
||||
### fiber.rawConfig
|
||||
|
||||
```ts cordis-catalog
|
||||
/** Raw input retained for the next activation, without evaluating expressions or validating it. */
|
||||
get rawConfig(): unknown
|
||||
```
|
||||
|
||||
保留供下次激活使用的原始输入,不执行表达式求值或验证。
|
||||
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L642)
|
||||
|
||||
### fiber.effectiveConfig
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* The config object published by the existing activation/update lifecycle, without cloning or re-parsing.
|
||||
* It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`.
|
||||
*/
|
||||
get effectiveConfig(): unknown
|
||||
```
|
||||
|
||||
既有激活/更新生命周期发布的配置对象,不克隆或重新解析。首次解析前为 undefined,卸载后仍可读取;需要运行实例的调用方应检查 `state`。
|
||||
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L655)
|
||||
|
||||
### fiber.resolveConfig(config)
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema.
|
||||
* Does not publish the result, replace raw input, or commit running volatile references.
|
||||
* Required injections must be available when a hook uses them.
|
||||
* @param config Raw candidate input.
|
||||
* @returns The candidate's resolved config, retaining the schema's result identity.
|
||||
* @throws {ValidationError} when the runtime schema rejects the candidate; hook errors propagate.
|
||||
*/
|
||||
resolveConfig(config: unknown): unknown
|
||||
```
|
||||
|
||||
通过此 fiber 的 `internal/config` 钩子和运行时 schema 对候选值求值并验证。此操作不发布结果、不替换原始输入,也不提交运行中的 volatile 引用。钩子访问的注入服务必须已经可用。
|
||||
|
||||
- `config`:原始候选输入。
|
||||
|
||||
**返回**候选配置的解析结果,保留 schema 返回对象的身份。
|
||||
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L667)
|
||||
|
||||
### fiber.await()
|
||||
|
||||
```ts cordis-catalog
|
||||
@@ -227,7 +274,7 @@ async await()
|
||||
|
||||
**返回**:进入稳定状态后的此 fiber。
|
||||
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L704)
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L731)
|
||||
|
||||
### fiber.restart()
|
||||
|
||||
@@ -245,7 +292,7 @@ dispose 此插件,并立即使用其当前配置重新加载。
|
||||
|
||||
**返回**一个在重新加载完成后兑现的 promise。
|
||||
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L718)
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L745)
|
||||
|
||||
### fiber.update(config, noSave?)
|
||||
|
||||
@@ -273,7 +320,7 @@ update(config: any, noSave = false)
|
||||
|
||||
**返回**无返回值;重启由 `internal/update` waterfall 执行。
|
||||
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L736)
|
||||
[源码](../../vendor/cordis/src/fiber.ts#L764)
|
||||
|
||||
## Effect
|
||||
|
||||
|
||||
@@ -21,11 +21,11 @@ This matrix shows which packages dispatch each harness-owned event and which pac
|
||||
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
|
||||
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
|
||||
| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:599`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:579`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:606`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:585`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:592`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:600`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:580`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:586`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:593`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:54`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
|
||||
| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` |
|
||||
| `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - |
|
||||
@@ -99,7 +99,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac
|
||||
| Event string | Dispatchers | Listeners |
|
||||
| --- | --- | --- |
|
||||
| `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic) |
|
||||
| `internal/config` | [`config-editor`](../packages/boot/config-editor) (`waterfall`) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) |
|
||||
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) |
|
||||
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
|
||||
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` |
|
||||
| `internal/service` | - | `gateway` |
|
||||
|
||||
@@ -23,11 +23,11 @@
|
||||
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
|
||||
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
|
||||
| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:599`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:579`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:606`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:585`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:592`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:600`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:580`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:586`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:593`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:54`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
|
||||
| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` |
|
||||
| `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - |
|
||||
@@ -101,7 +101,7 @@
|
||||
| Event string | Dispatchers | Listeners |
|
||||
| --- | --- | --- |
|
||||
| `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic) |
|
||||
| `internal/config` | [`config-editor`](../packages/boot/config-editor) (`waterfall`) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) |
|
||||
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) |
|
||||
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
|
||||
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` |
|
||||
| `internal/service` | - | `gateway` |
|
||||
|
||||
@@ -1347,8 +1347,8 @@
|
||||
en: 2786fef560851bb4
|
||||
zh: 5d787475356b2606
|
||||
/session-persistence-event-catalog/resolved-persistence-types/string:
|
||||
en: 967168de7dce17f6
|
||||
zh: c43778dcbfea301e
|
||||
en: a9d7dc010ada133d
|
||||
zh: 9bd682adee72d04e
|
||||
/session-persistence-event-catalog/resolved-persistence-types/string~2:
|
||||
en: 0089620bf4638263
|
||||
zh: 1922bef1713094bb
|
||||
@@ -1833,8 +1833,8 @@
|
||||
en: c59d020828d8211f
|
||||
zh: 154a30cb69e79489
|
||||
/session-persistence-event-catalog/resolved-persistence-types/kind-user:
|
||||
en: 43f0c6042d410afd
|
||||
zh: a0b68de4e5d220bd
|
||||
en: 81620af099525ee9
|
||||
zh: 812db2fdf9e5d309
|
||||
/session-persistence-event-catalog/resolved-persistence-types/kind-user-approval:
|
||||
en: a52d2dfbaf844127
|
||||
zh: 4c5306ca40f20873
|
||||
|
||||
@@ -5583,7 +5583,7 @@ Array of `number`.
|
||||
|
||||
SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b`
|
||||
|
||||
Sources: [`packages/api/session-controller/src/types.ts:379`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts)
|
||||
Sources: [`packages/api/session-controller/src/types.ts:380`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts)
|
||||
|
||||
`string`
|
||||
|
||||
@@ -7554,7 +7554,7 @@ Sources: [`packages/core/tools/src/index.ts:18`](../packages/core/tools/src/inde
|
||||
|
||||
SHA-256: `6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def`
|
||||
|
||||
Sources: [`packages/api/session-controller/src/types.ts:388`](../packages/api/session-controller/src/types.ts)
|
||||
Sources: [`packages/api/session-controller/src/types.ts:389`](../packages/api/session-controller/src/types.ts)
|
||||
|
||||
| Property | Presence | Type |
|
||||
|---|---|---|
|
||||
|
||||
@@ -5585,7 +5585,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78`
|
||||
|
||||
SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b`
|
||||
|
||||
来源:[`packages/api/session-controller/src/types.ts:379`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts)
|
||||
来源:[`packages/api/session-controller/src/types.ts:380`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts)
|
||||
|
||||
`string`
|
||||
|
||||
@@ -7556,7 +7556,7 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543`
|
||||
|
||||
SHA-256: `6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def`
|
||||
|
||||
来源:[`packages/api/session-controller/src/types.ts:388`](../packages/api/session-controller/src/types.ts)
|
||||
来源:[`packages/api/session-controller/src/types.ts:389`](../packages/api/session-controller/src/types.ts)
|
||||
|
||||
| 属性 | 存在性 | 类型 |
|
||||
|---|---|---|
|
||||
|
||||
Generated
+2
-2
@@ -253,7 +253,7 @@
|
||||
{"digest":"4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731","names":["packages/llm/llm/src/message.ts#ToolResultMessage"],"sources":["packages/llm/llm/src/message.ts:173"]},
|
||||
{"digest":"4b7ddaf3710b88ff9b8df66304f5f97bf03688fd19730eedc2e9535203c820ea","names":[],"sources":[]},
|
||||
{"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:194"]},
|
||||
{"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/agent-team/src/types.ts#TeamId","packages/experimental/agent-team/src/types.ts#TeamMessageId","packages/experimental/agent-team/src/types.ts#TeamTaskId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:379","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/agent-team/src/types.ts:21","packages/experimental/agent-team/src/types.ts:33","packages/experimental/agent-team/src/types.ts:9","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/workflow/workflow/src/types.ts:13"]},
|
||||
{"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/agent-team/src/types.ts#TeamId","packages/experimental/agent-team/src/types.ts#TeamMessageId","packages/experimental/agent-team/src/types.ts#TeamTaskId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:380","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/agent-team/src/types.ts:21","packages/experimental/agent-team/src/types.ts:33","packages/experimental/agent-team/src/types.ts:9","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/workflow/workflow/src/types.ts:13"]},
|
||||
{"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]},
|
||||
{"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]},
|
||||
{"digest":"4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c","names":["packages/llm/llm/src/types.ts#TextBlock"],"sources":["packages/llm/llm/src/types.ts:62","packages/web/web-search-deepseek/src/provider.ts:66"]},
|
||||
@@ -335,7 +335,7 @@
|
||||
{"digest":"6ccb6bc423fb3952458abf9c1b1c3284208b7e660344b612cc55da773d61afe4","names":[],"sources":[]},
|
||||
{"digest":"6cda0d6d3b4336d83998fe580628426df81c2afbab5d768b8813b56d569120e8","names":[],"sources":[]},
|
||||
{"digest":"6cf082d0fb6034dea61636787ff0ddf43b6e59aad71e644435a479bc9b83ad65","names":[],"sources":[]},
|
||||
{"digest":"6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def","names":[],"sources":["packages/api/session-controller/src/types.ts:388"]},
|
||||
{"digest":"6dacb1584f2bfbe209dc6b6f578d51da6d55595f64d0e63c727c98f359278def","names":[],"sources":["packages/api/session-controller/src/types.ts:389"]},
|
||||
{"digest":"6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406","names":[],"sources":["packages/preset/agent-preset-registry/src/session.ts:31"]},
|
||||
{"digest":"6ea608bdc8a7a63d3d23b84c49721325094db88d136482e43a820945295eee3e","names":[],"sources":[]},
|
||||
{"digest":"6ebcc2dbec9f2dabca9f668ae6d39e877899b180740570f453409db339221df3","names":[],"sources":[]},
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
en: 564dfcaaca384e23
|
||||
zh: 5d215635919b5bc4
|
||||
/durable-attachments/identity-and-verified-metadata:
|
||||
en: 3ddfd5100061dc6a
|
||||
zh: 3eedb90c8813d015
|
||||
en: 96378c208b220c6f
|
||||
zh: 7af93f6a79520732
|
||||
/durable-attachments/commit-and-verified-read-payloads:
|
||||
en: 01c9eb5d67e3c7c3
|
||||
zh: abf32dddcca5fce1
|
||||
en: f79753272bb0ec70
|
||||
zh: 61830c41021f9274
|
||||
|
||||
@@ -56,7 +56,7 @@ interface ImageAttachmentLimits {
|
||||
}
|
||||
```
|
||||
|
||||
The local backend admits at most 20 images and 200 MiB of encoded source data per message. One source may use up to 20 MiB, 64,000,000 pixels, and 8192 pixels on either side. These source limits precede the independent normalization stage, which limits the long edge to 2048 pixels and encoded data to 4 MiB by default.
|
||||
The local backend admits at most 20 images and 200 MiB of encoded source data per message. One source may use up to 50 MiB, 64,000,000 pixels, and 65,535 pixels on either side. These source limits precede the independent normalization stage, which limits the long edge to 2048 pixels and encoded data to 4 MiB by default.
|
||||
|
||||
The reference records intrinsic dimensions and encoded length so clients can lay out history without decoding first, while every authoritative read still re-checks digest, media signature, dimensions, and metadata against the object.
|
||||
|
||||
@@ -80,10 +80,16 @@ type PromptContentPart =
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Host prompt content whose file receipts are resolved and whose image bytes await admission. */
|
||||
/**
|
||||
* Host prompt content whose upload receipts are resolved. An image part
|
||||
* carries encoded bytes awaiting admission, or references an image this
|
||||
* service already stored for an upload the same Session staged, with
|
||||
* `encodedBytes` holding the byte length of that upload.
|
||||
*/
|
||||
type AttachmentAdmissionPart =
|
||||
| PromptContentPart
|
||||
| { readonly type: 'file'; readonly attachment: FileAttachmentRef }
|
||||
| { readonly type: 'image'; readonly attachment: ImageAttachmentRef; readonly encodedBytes: number }
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
@@ -167,7 +173,7 @@ interface RequestImageAttachment {
|
||||
}
|
||||
```
|
||||
|
||||
`saveImage()` prepares and atomically commits a provider-independent normalized attachment before returning its `ImageAttachmentRef`. `saveImages()` prepares every validated attachment once before publishing the batch, so validation rejection leaves no partial objects and publication does not repeat decoding or quality selection. `admitPromptContent()` accepts the complete ordered Host prompt after file receipt resolution, replaces base64 image uploads with durable references, and passes durable file references unchanged. `admitEncodedImages()` supports other wire entries and delegates count, aggregate-byte, and ordered batch admission to `saveImages()`. `admitEncodedFile()` gives encoded protocol adapters the same service-owned canonical-base64 admission, and `isAttachmentError()` lets those adapters recognize stable attachment failures without importing implementation helpers. `readImage()` verifies a normalized attachment from an authorized session path. `imageHostPath()` exposes only the provider-owned host object location; it does not decide whether the current tool execution world can read it. `readImageRequest()` derives and caches one deterministic request version at an exact route-chosen target size and encoded-byte target. That version contains encoded bytes and metadata but no execution-world path. New entries are fully decoded before publication, while cache hits use a bounded metadata probe. Callers use `Promise.all` over the singular method when they need an ordered batch. The local implementation lazily encodes preferred candidates, singleflights equal request identities, lets each waiter cancel independently, stops shared work when no waiter remains, and bounds all transforms with its instance-level limiter, which defaults to two simultaneous transformations. The service is retention-neutral: resumed and forked sessions may share objects, so reference-aware garbage collection is deferred rather than tied to one session's deletion.
|
||||
`saveImage()` prepares and atomically commits a provider-independent normalized attachment before returning its `ImageAttachmentRef`. `saveImages()` prepares every validated attachment once before publishing the batch, so validation rejection leaves no partial objects and publication does not repeat decoding or quality selection. `admitPromptContent()` accepts the complete ordered Host prompt after upload receipt resolution, replaces base64 image uploads with durable references, passes durable file references and already stored images unchanged, and counts every image toward the per-message image count and aggregate byte limits, a stored image by the bytes of its upload. `admitEncodedImages()` supports other wire entries and delegates count, aggregate-byte, and ordered batch admission to `saveImages()`. `admitEncodedFile()` gives encoded protocol adapters the same service-owned canonical-base64 admission, and `isAttachmentError()` lets those adapters recognize stable attachment failures without importing implementation helpers. `readImage()` verifies a normalized attachment from an authorized session path. `imageHostPath()` exposes only the provider-owned host object location; it does not decide whether the current tool execution world can read it. `readImageRequest()` derives and caches one deterministic request version at an exact route-chosen target size and encoded-byte target. That version contains encoded bytes and metadata but no execution-world path. New entries are fully decoded before publication, while cache hits use a bounded metadata probe. Callers use `Promise.all` over the singular method when they need an ordered batch. The local implementation lazily encodes preferred candidates, singleflights equal request identities, lets each waiter cancel independently, stops shared work when no waiter remains, and bounds all transforms with its instance-level limiter, which defaults to two simultaneous transformations. The service is retention-neutral: resumed and forked sessions may share objects, so reference-aware garbage collection is deferred rather than tied to one session's deletion.
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
@@ -200,9 +206,12 @@ abstract validateImage(input: SaveImageAttachment): Promise<void>
|
||||
async saveImages(inputs: readonly SaveImageAttachment[]): Promise<readonly ImageAttachmentRef[]>
|
||||
|
||||
/**
|
||||
* Admit one Host prompt and replace each uploaded image with its durable reference.
|
||||
* Text and durable file references pass through unchanged. A prompt without image parts performs no storage operation.
|
||||
* @param content - prompt parts in message order after file receipt resolution.
|
||||
* Admit one Host prompt and replace each encoded image with its durable reference.
|
||||
* Text, durable file references, and already stored images pass through unchanged.
|
||||
* Every image part counts toward `maxImagesPerMessage` and `maxMessageImageBytes`;
|
||||
* a stored image counts the bytes of the upload that stored it. Refused content
|
||||
* starts no writes. A prompt without encoded images performs no storage operation.
|
||||
* @param content - prompt parts in message order after upload receipt resolution.
|
||||
* @returns admitted prompt parts in the same order as `content`.
|
||||
* @throws AttachmentError when the image batch is refused.
|
||||
*/
|
||||
@@ -320,7 +329,7 @@ registerAgentResolver(resolve: AgentResolver): () => void
|
||||
* @param signal - caller cancellation before storage begins.
|
||||
* @returns the staged receipt and durable file reference.
|
||||
*/
|
||||
@Remote('upload') upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise<FileUploadValue>
|
||||
@Remote('upload') async upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise<FileUploadValue>
|
||||
|
||||
/**
|
||||
* Persist raw chunks for one Session without aggregating the upload.
|
||||
@@ -329,13 +338,27 @@ registerAgentResolver(resolve: AgentResolver): () => void
|
||||
*/
|
||||
async uploadStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable<Uint8Array> readonly signal?: AbortSignal readonly name?: string }): Promise<FileUploadValue>
|
||||
|
||||
/**
|
||||
* Persist one prompt image for a Session: read at most the smaller of the
|
||||
* deployment's per-image and per-message byte limits, then validate,
|
||||
* normalize, and store the image the way prompt admission does, so a later
|
||||
* prompt cites it by receipt.
|
||||
* Cancellation before storage begins stores nothing; a cancelled upload
|
||||
* never receives a receipt, although an image whose storage already began
|
||||
* stays in the content-addressed store.
|
||||
* @param request - Session identity, ordered bytes, the declared media type that this deployment
|
||||
* must accept, cancellation, and optional display name.
|
||||
* @returns the staged receipt and durable normalized image reference.
|
||||
*/
|
||||
async uploadImageStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable<Uint8Array> readonly mediaType: string readonly signal?: AbortSignal readonly name?: string }): Promise<ImageUploadValue>
|
||||
|
||||
/**
|
||||
* Resolve one staged receipt for the receiving Agent's exact Session.
|
||||
* @param agent - receiving Agent.
|
||||
* @param receiptId - opaque receipt minted for one completed upload.
|
||||
* @returns durable file reference, or `undefined` for an unknown or foreign receipt.
|
||||
* @returns the staged file or image, or `undefined` for an unknown or foreign receipt.
|
||||
*/
|
||||
resolve(agent: Agent, receiptId: FileUploadReceiptId): FileAttachmentRef | undefined
|
||||
resolve(agent: Agent, receiptId: FileUploadReceiptId): StagedAttachment | undefined
|
||||
|
||||
/**
|
||||
* Bind receipts while one prompt enters an Agent inbox.
|
||||
|
||||
@@ -56,7 +56,7 @@ interface ImageAttachmentLimits {
|
||||
}
|
||||
```
|
||||
|
||||
本地后端每条消息最多准入 20 张图片,源图编码数据总量不超过 200 MiB。单张源图不得超过 20 MiB、64,000,000 像素和单边 8192 像素。这些源文件限制先于独立的规范化阶段执行;该阶段默认把长边限制为 2048 像素,把编码数据限制为 4 MiB。
|
||||
本地后端每条消息最多准入 20 张图片,源图编码数据总量不超过 200 MiB。单张源图不得超过 50 MiB、64,000,000 像素和单边 65,535 像素。这些源文件限制先于独立的规范化阶段执行;该阶段默认把长边限制为 2048 像素,把编码数据限制为 4 MiB。
|
||||
|
||||
引用记录固有尺寸和编码长度,使客户端无需先解码即可排布历史记录;每次权威读取仍会根据对象重新校验摘要、媒体签名、尺寸和元数据。
|
||||
|
||||
@@ -80,10 +80,16 @@ type PromptContentPart =
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
/** Host prompt content whose file receipts are resolved and whose image bytes await admission. */
|
||||
/**
|
||||
* Host prompt content whose upload receipts are resolved. An image part
|
||||
* carries encoded bytes awaiting admission, or references an image this
|
||||
* service already stored for an upload the same Session staged, with
|
||||
* `encodedBytes` holding the byte length of that upload.
|
||||
*/
|
||||
type AttachmentAdmissionPart =
|
||||
| PromptContentPart
|
||||
| { readonly type: 'file'; readonly attachment: FileAttachmentRef }
|
||||
| { readonly type: 'image'; readonly attachment: ImageAttachmentRef; readonly encodedBytes: number }
|
||||
```
|
||||
|
||||
```ts type-equiv
|
||||
@@ -167,7 +173,7 @@ interface RequestImageAttachment {
|
||||
}
|
||||
```
|
||||
|
||||
`saveImage()` 准备并原子提交提供方无关的规范化附件,然后直接返回 `ImageAttachmentRef`。`saveImages()` 在发布批次前为每个成员各准备一次经过验证的附件,因此校验拒绝不会留下部分对象,发布也不会重复解码或选择质量。`admitPromptContent()` 在文件凭证解析后接收完整且有序的 Host prompt,把 base64 图片上传替换为持久引用,并让持久文件引用原样通过。`admitEncodedImages()` 支持其他 wire 入口,把张数、聚合字节和有序批量准入交给 `saveImages()`。`admitEncodedFile()` 让编码协议适配器使用服务拥有的规范 base64 准入,`isAttachmentError()` 让这些适配器无需导入实现辅助函数即可识别稳定的附件错误。`readImage()` 校验来自已授权会话路径的规范化附件。`imageHostPath()` 只公开提供方所持对象的宿主位置,不判断当前工具执行环境能否读取它。`readImageRequest()` 按确切的路由目标尺寸和编码字节目标派生并缓存确定性请求版本。该版本包含编码字节和元数据,不包含执行环境路径。新条目在发布前完整解码,缓存命中只做有界元数据探测。调用方需要有序批次时,对单数方法使用 `Promise.all`。本地实现按需编码首选候选、合并相同请求身份的并发任务、允许每个等待方单独取消、没有等待方时停止共享任务,并通过实例级限流器限制全部变换,默认同时执行两项。该服务不规定保留策略:恢复和 fork 后的会话可能共享对象,因此基于引用的垃圾回收会延期实现,不与单个会话的删除绑定。
|
||||
`saveImage()` 准备并原子提交提供方无关的规范化附件,然后直接返回 `ImageAttachmentRef`。`saveImages()` 在发布批次前为每个成员各准备一次经过验证的附件,因此校验拒绝不会留下部分对象,发布也不会重复解码或选择质量。`admitPromptContent()` 在上传凭证解析后接收完整且有序的 Host prompt,把 base64 图片上传替换为持久引用,让持久文件引用和已存储的图片原样通过,并把每张图片计入单条消息的图片数量与总字节上限,已存储的图片按其上传的字节数计入。`admitEncodedImages()` 支持其他 wire 入口,把张数、聚合字节和有序批量准入交给 `saveImages()`。`admitEncodedFile()` 让编码协议适配器使用服务拥有的规范 base64 准入,`isAttachmentError()` 让这些适配器无需导入实现辅助函数即可识别稳定的附件错误。`readImage()` 校验来自已授权会话路径的规范化附件。`imageHostPath()` 只公开提供方所持对象的宿主位置,不判断当前工具执行环境能否读取它。`readImageRequest()` 按确切的路由目标尺寸和编码字节目标派生并缓存确定性请求版本。该版本包含编码字节和元数据,不包含执行环境路径。新条目在发布前完整解码,缓存命中只做有界元数据探测。调用方需要有序批次时,对单数方法使用 `Promise.all`。本地实现按需编码首选候选、合并相同请求身份的并发任务、允许每个等待方单独取消、没有等待方时停止共享任务,并通过实例级限流器限制全部变换,默认同时执行两项。该服务不规定保留策略:恢复和 fork 后的会话可能共享对象,因此基于引用的垃圾回收会延期实现,不与单个会话的删除绑定。
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
@@ -200,9 +206,12 @@ abstract validateImage(input: SaveImageAttachment): Promise<void>
|
||||
async saveImages(inputs: readonly SaveImageAttachment[]): Promise<readonly ImageAttachmentRef[]>
|
||||
|
||||
/**
|
||||
* Admit one Host prompt and replace each uploaded image with its durable reference.
|
||||
* Text and durable file references pass through unchanged. A prompt without image parts performs no storage operation.
|
||||
* @param content - prompt parts in message order after file receipt resolution.
|
||||
* Admit one Host prompt and replace each encoded image with its durable reference.
|
||||
* Text, durable file references, and already stored images pass through unchanged.
|
||||
* Every image part counts toward `maxImagesPerMessage` and `maxMessageImageBytes`;
|
||||
* a stored image counts the bytes of the upload that stored it. Refused content
|
||||
* starts no writes. A prompt without encoded images performs no storage operation.
|
||||
* @param content - prompt parts in message order after upload receipt resolution.
|
||||
* @returns admitted prompt parts in the same order as `content`.
|
||||
* @throws AttachmentError when the image batch is refused.
|
||||
*/
|
||||
@@ -320,7 +329,7 @@ registerAgentResolver(resolve: AgentResolver): () => void
|
||||
* @param signal - caller cancellation before storage begins.
|
||||
* @returns the staged receipt and durable file reference.
|
||||
*/
|
||||
@Remote('upload') upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise<FileUploadValue>
|
||||
@Remote('upload') async upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise<FileUploadValue>
|
||||
|
||||
/**
|
||||
* Persist raw chunks for one Session without aggregating the upload.
|
||||
@@ -329,13 +338,27 @@ registerAgentResolver(resolve: AgentResolver): () => void
|
||||
*/
|
||||
async uploadStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable<Uint8Array> readonly signal?: AbortSignal readonly name?: string }): Promise<FileUploadValue>
|
||||
|
||||
/**
|
||||
* Persist one prompt image for a Session: read at most the smaller of the
|
||||
* deployment's per-image and per-message byte limits, then validate,
|
||||
* normalize, and store the image the way prompt admission does, so a later
|
||||
* prompt cites it by receipt.
|
||||
* Cancellation before storage begins stores nothing; a cancelled upload
|
||||
* never receives a receipt, although an image whose storage already began
|
||||
* stays in the content-addressed store.
|
||||
* @param request - Session identity, ordered bytes, the declared media type that this deployment
|
||||
* must accept, cancellation, and optional display name.
|
||||
* @returns the staged receipt and durable normalized image reference.
|
||||
*/
|
||||
async uploadImageStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable<Uint8Array> readonly mediaType: string readonly signal?: AbortSignal readonly name?: string }): Promise<ImageUploadValue>
|
||||
|
||||
/**
|
||||
* Resolve one staged receipt for the receiving Agent's exact Session.
|
||||
* @param agent - receiving Agent.
|
||||
* @param receiptId - opaque receipt minted for one completed upload.
|
||||
* @returns durable file reference, or `undefined` for an unknown or foreign receipt.
|
||||
* @returns the staged file or image, or `undefined` for an unknown or foreign receipt.
|
||||
*/
|
||||
resolve(agent: Agent, receiptId: FileUploadReceiptId): FileAttachmentRef | undefined
|
||||
resolve(agent: Agent, receiptId: FileUploadReceiptId): StagedAttachment | undefined
|
||||
|
||||
/**
|
||||
* Bind receipts while one prompt enters an Agent inbox.
|
||||
|
||||
@@ -15,14 +15,14 @@
|
||||
en: 1fdf707322fb6996
|
||||
zh: 0204f7e9d4aa3cce
|
||||
/session-controller/use-this-package:
|
||||
en: 8fcfa14545bd9d1c
|
||||
zh: c10c2bba792699ef
|
||||
en: aabd5be911e477f5
|
||||
zh: 2f7fdb44bc8777bc
|
||||
/session-controller/client-references:
|
||||
en: 41bdda1ac32df558
|
||||
zh: aa5d0e325924066b
|
||||
/session-controller/session-media-references:
|
||||
en: 49a3d0e8e92017d3
|
||||
zh: 91302aa3dd6e9378
|
||||
en: 25e40cb508265c01
|
||||
zh: c8ce39a94997af00
|
||||
/session-controller/configuration:
|
||||
en: c92590fbaf75e45e
|
||||
zh: fcac67017bb0e3ab
|
||||
|
||||
@@ -33,7 +33,7 @@ History pages and follow opening snapshots carry one `{ type: 'event', event: Se
|
||||
|
||||
The Client journal validates current Session event envelopes before publishing follow snapshots, live entries, or history pages. It reuses the browser-safe Session validators for required surface markers, exact replacement endpoints, earlier unique source seqs, embedded Assistant provider metadata, request-header omissions, and tool-error consistency. Invalid records fail without field stripping or normalization; range membership and source existence remain durable-log checks on the Host.
|
||||
|
||||
Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values.
|
||||
Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. A receipt names a staged file or a staged image, and an image receipt subjects the prompt to the same image-input check as an encoded image. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values.
|
||||
|
||||
Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) grants a role listing the action ([Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)). The controller injects `remoteAccess` and registers the `session` resource kind with the default field `sessionId` through `typert.resources`. `session/page` and `session/follow` declare a `session` reader in `@Remote({ resources })` that reads `request.address.sessionId` for an ordinary Session address and `request.address.childSessionId` for a subagent address; whether access to the parent Session covers its children is the policy's rule. `session/projections` reads the Session resource from `request.sessionId`, so a reconnecting reader reloads only the projections of Sessions it may read. `session/list`, `session/search`, and `session/control` read no resource, so their calls touch the `global` resource and need a `global` role; for a non-owner caller, `session/list` returns only the rows, `session/search` only the hits, and `session/control` only the baseline projections and projection frames, whose Session `ctx.remoteAccess.allows()` admits for the same action, so that action also belongs to a `session` role; owner results are unfiltered. `session/prompt` builds the durable `user-rpc` message source in its Remote method and records `principal` only for a non-owner caller, read through `principalOf(this.ctx.invocation)`; a source without `principal` belongs to the owner.
|
||||
|
||||
@@ -86,7 +86,7 @@ References keep local Session data, scoped Contexts, and history streams alive,
|
||||
<a id="session-media-references"></a>
|
||||
## Session media references
|
||||
|
||||
`SessionMediaReferences` mounts `GET|HEAD /api/file?path=<absolute path>` on the authenticated `connection.fetch` channel when `connection`, `fs`, and `attachments` are composed. It reads ordinary files through `ctx.fs`, including temporary paths outside registered workspaces and files in remote providers. Neither directory containment nor MIME categories restrict access; `mime-types` supplies the response type, with `application/octet-stream` for unknown extensions. GET reuses `readBytes` for preflight and ongoing byte limits; HEAD reads metadata only. All files use `ctx.attachments.imageLimits.maxImageBytes` (normally 20 MiB); exceeding this limit returns 413. Responses contain the complete file, ignore Range, and carry `private, no-store`, `nosniff`, and a sandbox CSP so directly opened HTML/SVG cannot execute with the API origin. The Client rewrite lives in `ui-chat` (`AssistantMarkdown`); audio/video responses are available, while Markdown audio/video player nodes remain separate work.
|
||||
`SessionMediaReferences` mounts `GET|HEAD /api/file?path=<absolute path>` on the authenticated `connection.fetch` channel when `connection`, `fs`, and `attachments` are composed. It reads ordinary files through `ctx.fs`, including temporary paths outside registered workspaces and files in remote providers. Neither directory containment nor MIME categories restrict access; `mime-types` supplies the response type, with `application/octet-stream` for unknown extensions. GET reuses `readBytes` for preflight and ongoing byte limits; HEAD reads metadata only. All files use `ctx.attachments.imageLimits.maxImageBytes` (normally 50 MiB); exceeding this limit returns 413. Responses contain the complete file, ignore Range, and carry `private, no-store`, `nosniff`, and a sandbox CSP so directly opened HTML/SVG cannot execute with the API origin. The Client rewrite lives in `ui-chat` (`AssistantMarkdown`); audio/video responses are available, while Markdown audio/video player nodes remain separate work.
|
||||
|
||||
GUI model selection requires the exact provider/model pair in the available catalog; unavailable choices reject with `session/model-unavailable`. Prompt admission retains the saved route without a catalog availability gate, so request execution reports missing credentials or unavailable models. `initializeDefaultModel()` saves the first available account model after login when no other provider has a configured API key; credential checks use configured references independently of model availability. A provider with no available models rejects initialization with `session/provider-models-unavailable`. Availability never substitutes another model or rewrites a Session selection.
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ kind: "package-reference"
|
||||
|
||||
Client journal 在发布 follow 快照、live entry 或历史页之前验证当前 Session 事件 envelope。它复用浏览器安全的 Session validator,检查必需的 surface marker、精确的 replacement endpoint、更早且唯一的 source seq、内嵌 Assistant 提供方元数据、request header 可选字段的省略规则以及工具错误一致性。无效 record 直接失败,不删除字段或归一化;范围成员与来源存在性仍由 Host 的持久日志检查。
|
||||
|
||||
每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。
|
||||
每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。凭证指向一个暂存文件或一张暂存图片;图片凭证与编码图片一样要经过图片输入检查。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。
|
||||
|
||||
每个 Remote 端点都受访问控制:principal 不是 owner 的 Peer 只有在本次调用访问的每个资源上,该 principal kind 在 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 都有某个 binding 授予列出该 action 的 role 时,才能调用该端点([Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md))。控制器注入 `remoteAccess`,并经 `typert.resources` 以默认字段 `sessionId` 登记 `session` 资源种类。`session/page` 与 `session/follow` 在 `@Remote({ resources })` 中声明 `session` 读取函数:对普通 Session 地址读 `request.address.sessionId`,对 subagent 地址读 `request.address.childSessionId`;父会话的访问权是否覆盖其子会话由 policy 决定。`session/projections` 从 `request.sessionId` 读取会话资源,因此重连的读者只会重新读取它可读的会话的 projections。`session/list`、`session/search` 与 `session/control` 不读取资源,其调用访问 `global` 资源,需要 `global` role;对非 owner 调用方,`session/list` 只返回其 Session 被 `ctx.remoteAccess.allows()` 按同一 action 允许的行,`session/search` 只返回这类 Session 的命中,`session/control` 也只返回这类 Session 的 baseline projection 与 projection 帧,因此该 action 也要列在 `session` role 中;owner 的结果不过滤。`session/prompt` 在其 Remote 方法内构造持久的 `user-rpc` 消息 source,且只为非 owner 调用方记录经 `principalOf(this.ctx.invocation)` 读取的 `principal`;不带 `principal` 的 source 属于 owner。
|
||||
|
||||
@@ -86,7 +86,7 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以
|
||||
<a id="session-media-references"></a>
|
||||
## 会话媒体引用
|
||||
|
||||
当 `connection`、`fs` 与 `attachments` 均被组合时,`SessionMediaReferences` 在鉴权 `connection.fetch` 通道上挂载 `GET|HEAD /api/file?path=<绝对路径>`。它通过 `ctx.fs` 读取普通文件,包括已注册工作区之外的临时路径与远程提供方中的文件。目录包含关系与 MIME 类别均不限制访问;`mime-types` 提供响应类型,未知扩展名使用 `application/octet-stream`。GET 复用 `readBytes` 执行读取前及读取中的字节限制;HEAD 只读取元数据。所有文件均使用 `ctx.attachments.imageLimits.maxImageBytes`(通常为 20 MiB);超过此上限返回 413。响应包含完整文件,忽略 Range,并携带 `private, no-store`、`nosniff` 与沙箱 CSP,使直接打开的 HTML/SVG 无法以 API 源身份执行脚本。客户端重写位于 `ui-chat`(`AssistantMarkdown`);音视频文件响应已可用,Markdown 音视频播放器节点仍是独立工作。
|
||||
当 `connection`、`fs` 与 `attachments` 均被组合时,`SessionMediaReferences` 在鉴权 `connection.fetch` 通道上挂载 `GET|HEAD /api/file?path=<绝对路径>`。它通过 `ctx.fs` 读取普通文件,包括已注册工作区之外的临时路径与远程提供方中的文件。目录包含关系与 MIME 类别均不限制访问;`mime-types` 提供响应类型,未知扩展名使用 `application/octet-stream`。GET 复用 `readBytes` 执行读取前及读取中的字节限制;HEAD 只读取元数据。所有文件均使用 `ctx.attachments.imageLimits.maxImageBytes`(通常为 50 MiB);超过此上限返回 413。响应包含完整文件,忽略 Range,并携带 `private, no-store`、`nosniff` 与沙箱 CSP,使直接打开的 HTML/SVG 无法以 API 源身份执行脚本。客户端重写位于 `ui-chat`(`AssistantMarkdown`);音视频文件响应已可用,Markdown 音视频播放器节点仍是独立工作。
|
||||
|
||||
GUI 模型选择要求确切提供方/模型对出现在可用目录中;不可用的选择以 `session/model-unavailable` 拒绝。提示词准入保留已保存的路由,不按目录可用性阻断发送,由请求执行报告凭据缺失或模型不可用。`initializeDefaultModel()` 在账号登录后、其他提供方均未配置 API key 时,将第一个可用账号模型保存为默认模型;凭据检查使用已配置的引用,不依赖模型是否可用。提供方没有可用模型时,初始化以 `session/provider-models-unavailable` 拒绝。可用性变化不会替换模型或改写会话选择。
|
||||
|
||||
|
||||
@@ -7,9 +7,9 @@ import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { Agent, ModelSelection as AgentModelSelection } from '@deepseek-ai/dsh-agent'
|
||||
import { AttachmentError } from '@deepseek-ai/dsh-attachment'
|
||||
import type {
|
||||
AttachmentAdmissionPart, FileAttachmentRef, ImageAttachmentRef,
|
||||
AttachmentAdmissionPart, ImageAttachmentRef,
|
||||
} from '@deepseek-ai/dsh-attachment'
|
||||
import type { FileUploadReceiptId } from '@deepseek-ai/dsh-client-file-upload/types'
|
||||
import type { FileUploadReceiptId, StagedAttachment } from '@deepseek-ai/dsh-client-file-upload/types'
|
||||
import type {} from '@deepseek-ai/dsh-client-file-upload'
|
||||
import {
|
||||
ReasoningEffortId, assistantStreamChunks, createUserMessage, freezeMessage,
|
||||
@@ -313,7 +313,12 @@ export class SessionCommandController {
|
||||
async prompt(request: SessionPromptRequest, source: MessageSource): Promise<SessionPromptValue> {
|
||||
const agent = await this.resolveAgent(request.sessionId)
|
||||
if (hasPromptRequest(agent, request.requestId)) return { accepted: true }
|
||||
const hasImage = request.content.some(part => part.type === 'image')
|
||||
const admission = resolvePromptFileReceipts(
|
||||
request.content,
|
||||
receiptId => this.ctx.fileUploads.resolve(agent, receiptId),
|
||||
)
|
||||
// Encoded images and image upload receipts both make an image prompt.
|
||||
const hasImage = admission.content.some(part => part.type === 'image')
|
||||
const admit = async (): Promise<SessionPromptValue> => {
|
||||
try {
|
||||
if (hasImage) {
|
||||
@@ -329,10 +334,6 @@ export class SessionCommandController {
|
||||
}
|
||||
}
|
||||
}
|
||||
const admission = resolvePromptFileReceipts(
|
||||
request.content,
|
||||
receiptId => this.ctx.fileUploads.resolve(agent, receiptId),
|
||||
)
|
||||
const content = await this.ctx.attachments.admitPromptContent(admission.content)
|
||||
const message: UserMessage = createUserMessage({ content, source })
|
||||
if (this.ctx.agents.get(agent.id) !== agent) {
|
||||
@@ -556,14 +557,15 @@ export class SessionCommandController {
|
||||
}
|
||||
}
|
||||
|
||||
/** Replace each file part with the file or image its staged receipt names. */
|
||||
function resolvePromptFileReceipts(
|
||||
content: SessionPromptRequest['content'],
|
||||
stagedFile: (receiptId: FileUploadReceiptId) => FileAttachmentRef | undefined,
|
||||
staged: (receiptId: FileUploadReceiptId) => StagedAttachment | undefined,
|
||||
): { readonly content: AttachmentAdmissionPart[]; readonly receiptIds: readonly FileUploadReceiptId[] } {
|
||||
const receiptIds = new Set<FileUploadReceiptId>()
|
||||
const resolved = content.map((part): AttachmentAdmissionPart => {
|
||||
if (part.type !== 'file') return part
|
||||
const attachment = stagedFile(part.receiptId)
|
||||
const attachment = staged(part.receiptId)
|
||||
if (attachment === undefined) {
|
||||
throw new RemoteError(
|
||||
'session/attachment-invalid',
|
||||
@@ -572,7 +574,7 @@ function resolvePromptFileReceipts(
|
||||
)
|
||||
}
|
||||
receiptIds.add(part.receiptId)
|
||||
return { type: 'file', attachment }
|
||||
return attachment
|
||||
})
|
||||
return { content: resolved, receiptIds: [...receiptIds] }
|
||||
}
|
||||
|
||||
@@ -71,7 +71,8 @@ export type SessionProjectionValues = Partial<SessionProjectionMap>
|
||||
/**
|
||||
* Browser-submitted prompt content; the Host promotes image bytes to durable
|
||||
* references. File parts carry the opaque receipt returned by a preceding
|
||||
* `uploadFile` call on the same Session.
|
||||
* upload on the same Session; the receipt of an image upload enters the
|
||||
* message as that image.
|
||||
*/
|
||||
export type PromptContentPart =
|
||||
| { readonly type: 'text'; readonly text: string }
|
||||
|
||||
@@ -6,7 +6,8 @@ import { createInboxStub } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import AttachmentStore, { AttachmentId } from '@deepseek-ai/dsh-attachment'
|
||||
import type {
|
||||
FileAttachmentRef, ImageAttachmentRef, SaveFileAttachment, SaveFileStreamAttachment,
|
||||
FileAttachmentRef, ImageAttachmentLimits, ImageAttachmentRef, SaveFileAttachment, SaveFileStreamAttachment,
|
||||
SaveImageAttachment,
|
||||
} from '@deepseek-ai/dsh-attachment'
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
import type { MessageSource, UserMessage } from '@deepseek-ai/dsh-llm'
|
||||
@@ -21,8 +22,28 @@ import { SessionCommandController } from '../src/commands.ts'
|
||||
import type { SessionRequestId } from '../src/types.ts'
|
||||
|
||||
const SESSION = SessionId('upload-session')
|
||||
const IMAGE_LIMITS: ImageAttachmentLimits = {
|
||||
maxImageBytes: 4,
|
||||
maxImagesPerMessage: 2,
|
||||
maxMessageImageBytes: 8,
|
||||
maxImagePixels: 64,
|
||||
maxImageDimension: 8,
|
||||
mediaTypes: ['image/png'],
|
||||
}
|
||||
const STAGED_IMAGE: ImageAttachmentRef = {
|
||||
attachmentId: AttachmentId(`sha256:${'12'.repeat(32)}`),
|
||||
mediaType: 'image/png',
|
||||
bytes: 3,
|
||||
width: 1,
|
||||
height: 1,
|
||||
name: 'shot.png',
|
||||
}
|
||||
|
||||
async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
async function* chunks(...parts: readonly number[][]): AsyncIterable<Uint8Array> {
|
||||
for (const part of parts) yield Uint8Array.from(part)
|
||||
}
|
||||
|
||||
async function uploadHarness(origin?: 'subagent', imageLimits: ImageAttachmentLimits = IMAGE_LIMITS): Promise<{
|
||||
ctx: Context
|
||||
controller: SessionCommandController
|
||||
uploads: FileUploads
|
||||
@@ -31,6 +52,7 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
saveFile: ReturnType<typeof vi.fn>
|
||||
saveFileStream: ReturnType<typeof vi.fn>
|
||||
saveImages: ReturnType<typeof vi.fn>
|
||||
resolveModelInfo: ReturnType<typeof vi.fn>
|
||||
disposeAgent: () => Promise<void>
|
||||
uploadRoute: (request: Request) => Promise<Response>
|
||||
}> {
|
||||
@@ -79,10 +101,10 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
bytes,
|
||||
}
|
||||
})
|
||||
const saveImages = vi.fn((): Promise<readonly ImageAttachmentRef[]> =>
|
||||
const saveImages = vi.fn((_inputs: readonly SaveImageAttachment[]): Promise<readonly ImageAttachmentRef[]> =>
|
||||
Promise.reject(new Error('fixture did not expect image persistence')))
|
||||
ctx.provide('attachments', Object.setPrototypeOf(
|
||||
{ saveFile, saveFileStream, saveImages },
|
||||
{ saveFile, saveFileStream, saveImages, imageLimits },
|
||||
AttachmentStore.prototype,
|
||||
) as never)
|
||||
let uploadRoute: ((request: Request) => Promise<Response>) | undefined
|
||||
@@ -94,10 +116,16 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
},
|
||||
},
|
||||
} as never)
|
||||
const resolveModelInfo = vi.fn((): Promise<{
|
||||
readonly provider: string
|
||||
readonly id: string
|
||||
readonly name: string
|
||||
readonly inputModalities?: readonly string[]
|
||||
}> => Promise.resolve({ provider: 'fixture', id: 'fixture-model', name: 'Fixture' }))
|
||||
ctx.provide('llm', {
|
||||
listModels: async () => [{ id: 'fixture-model', name: 'Model' }],
|
||||
listProviders: () => [{ id: 'fixture', name: 'Fixture' }],
|
||||
resolveModelInfo: () => Promise.resolve({ provider: 'fixture', id: 'fixture-model', name: 'Fixture' }),
|
||||
resolveModelInfo,
|
||||
} as never)
|
||||
const agents = new ApiSessionAgentController(ctx)
|
||||
vi.spyOn(agents, 'resolveAgent').mockResolvedValue({ agent })
|
||||
@@ -112,6 +140,7 @@ async function uploadHarness(origin?: 'subagent'): Promise<{
|
||||
saveFile,
|
||||
saveFileStream,
|
||||
saveImages,
|
||||
resolveModelInfo,
|
||||
disposeAgent,
|
||||
uploadRoute,
|
||||
}
|
||||
@@ -142,7 +171,7 @@ describe('Session file uploads', () => {
|
||||
expect(saveFile).toHaveBeenCalledTimes(1)
|
||||
expect(receipt.file.name).toBe('notes.pdf')
|
||||
expect(receipt.file.bytes).toBe(3)
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file })
|
||||
expect(uploads.resolve(agent, 'missing' as FileUploadReceiptId)).toBeUndefined()
|
||||
const commandHandler = vi.fn((_invocation: unknown) => ({ kind: 'success' as const }))
|
||||
ctx.commands.register({
|
||||
@@ -203,6 +232,116 @@ describe('Session file uploads', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('stages an uploaded image and admits its receipt as that image, which commands do not accept', async () => {
|
||||
const { ctx, controller, uploads, agent, followup, saveImages } = await uploadHarness()
|
||||
saveImages.mockResolvedValueOnce([STAGED_IMAGE])
|
||||
const receipt = await uploads.uploadImageStream({
|
||||
sessionId: SESSION, data: chunks([1, 2], [3, 4]), mediaType: 'image/png', name: 'shot.png',
|
||||
})
|
||||
expect(saveImages).toHaveBeenCalledWith([{ data: Uint8Array.of(1, 2, 3, 4), mediaType: 'image/png', name: 'shot.png' }])
|
||||
expect(receipt.image).toEqual(STAGED_IMAGE)
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'image', attachment: STAGED_IMAGE, encodedBytes: 4 })
|
||||
const commandHandler = vi.fn((_invocation: unknown) => ({ kind: 'success' as const }))
|
||||
ctx.commands.register({
|
||||
name: 'files', description: 'Use staged files', input: { hint: '<task>', attachments: true },
|
||||
handler: commandHandler,
|
||||
})
|
||||
await ctx.commands.execute(
|
||||
agent,
|
||||
'/files inspect',
|
||||
[{ type: 'file', receiptId: receipt.receiptId }],
|
||||
new AbortController().signal,
|
||||
)
|
||||
expect(commandHandler).not.toHaveBeenCalled()
|
||||
await controller.prompt(promptRequest([
|
||||
{ type: 'file', receiptId: receipt.receiptId },
|
||||
{ type: 'text', text: 'look' },
|
||||
]), USER_SOURCE)
|
||||
expect((followup.mock.calls[0]?.[0] as UserMessage).content).toEqual([
|
||||
{ type: 'image', attachment: STAGED_IMAGE },
|
||||
{ type: 'text', text: 'look' },
|
||||
])
|
||||
expect(saveImages).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('refuses an uploaded image for a model without image input', async () => {
|
||||
const { controller, uploads, followup, saveImages, resolveModelInfo } = await uploadHarness()
|
||||
saveImages.mockResolvedValueOnce([STAGED_IMAGE])
|
||||
const receipt = await uploads.uploadImageStream({ sessionId: SESSION, data: chunks([1]), mediaType: 'image/png' })
|
||||
resolveModelInfo.mockResolvedValue({ provider: 'fixture', id: 'fixture-model', name: 'Fixture', inputModalities: ['text'] })
|
||||
await expect(controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE))
|
||||
.rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'MODEL_DOES_NOT_SUPPORT_IMAGES' } })
|
||||
expect(followup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses image receipts whose uploads together exceed the message image-byte limit', async () => {
|
||||
const { controller, uploads, followup, saveImages } = await uploadHarness(undefined, {
|
||||
...IMAGE_LIMITS, maxMessageImageBytes: 5,
|
||||
})
|
||||
saveImages.mockResolvedValue([STAGED_IMAGE])
|
||||
const first = await uploads.uploadImageStream({ sessionId: SESSION, data: chunks([1, 2, 3]), mediaType: 'image/png' })
|
||||
const second = await uploads.uploadImageStream({ sessionId: SESSION, data: chunks([4, 5, 6]), mediaType: 'image/png' })
|
||||
await expect(controller.prompt(promptRequest([
|
||||
{ type: 'file', receiptId: first.receiptId },
|
||||
{ type: 'file', receiptId: second.receiptId },
|
||||
]), USER_SOURCE)).rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'IMAGES_TOO_LARGE' } })
|
||||
expect(followup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('issues no receipt for an image upload cancelled after its last chunk or during storage', async () => {
|
||||
const { uploads, saveImages } = await uploadHarness()
|
||||
const afterBody = new AbortController()
|
||||
await expect(uploads.uploadImageStream({
|
||||
sessionId: SESSION,
|
||||
data: (async function* (): AsyncIterable<Uint8Array> {
|
||||
yield Uint8Array.of(1, 2, 3)
|
||||
afterBody.abort()
|
||||
})(),
|
||||
mediaType: 'image/png',
|
||||
signal: afterBody.signal,
|
||||
})).rejects.toThrow('failed to store file upload: AbortError')
|
||||
expect(saveImages).not.toHaveBeenCalled()
|
||||
const duringStorage = new AbortController()
|
||||
const stored = Promise.withResolvers<readonly ImageAttachmentRef[]>()
|
||||
saveImages.mockReturnValueOnce(stored.promise)
|
||||
const uploading = uploads.uploadImageStream({
|
||||
sessionId: SESSION, data: chunks([1, 2, 3]), mediaType: 'image/png', signal: duringStorage.signal,
|
||||
})
|
||||
await vi.waitFor(() => { expect(saveImages).toHaveBeenCalledOnce() })
|
||||
duringStorage.abort()
|
||||
stored.resolve([STAGED_IMAGE])
|
||||
// The image whose storage began stays stored; only its receipt is withheld.
|
||||
await expect(uploading).rejects.toThrow('failed to store file upload: AbortError')
|
||||
})
|
||||
|
||||
it('refuses an image past the per-image byte limit without reading further, and an unaccepted type', async () => {
|
||||
const { uploads, saveImages } = await uploadHarness()
|
||||
const overLimit = (async function* (): AsyncIterable<Uint8Array> {
|
||||
yield Uint8Array.of(1, 2, 3)
|
||||
yield Uint8Array.of(4, 5)
|
||||
throw new Error('read past the limit')
|
||||
})()
|
||||
await expect(uploads.uploadImageStream({ sessionId: SESSION, data: overLimit, mediaType: 'image/png' }))
|
||||
.rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'IMAGE_TOO_LARGE' } })
|
||||
await expect(uploads.uploadImageStream({ sessionId: SESSION, data: chunks([1]), mediaType: 'image/bmp' }))
|
||||
.rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'UNSUPPORTED_IMAGE_TYPE' } })
|
||||
expect(saveImages).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stops reading an image at the message byte limit when it is below the per-image limit', async () => {
|
||||
const { uploads, saveImages } = await uploadHarness(undefined, {
|
||||
...IMAGE_LIMITS, maxImageBytes: 8, maxMessageImageBytes: 3,
|
||||
})
|
||||
const overLimit = (async function* (): AsyncIterable<Uint8Array> {
|
||||
yield Uint8Array.of(1, 2)
|
||||
yield Uint8Array.of(3, 4)
|
||||
throw new Error('read past the limit')
|
||||
})()
|
||||
await expect(uploads.uploadImageStream({ sessionId: SESSION, data: overLimit, mediaType: 'image/png' }))
|
||||
.rejects.toMatchObject({ code: 'session/attachment-invalid', details: { reason: 'IMAGE_TOO_LARGE' } })
|
||||
expect(saveImages).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the stream name optional and maps storage failures through the same error vocabulary', async () => {
|
||||
const { uploads, saveFileStream } = await uploadHarness()
|
||||
const stream = (async function* (): AsyncIterable<Uint8Array> {})()
|
||||
@@ -320,6 +459,9 @@ describe('Session file uploads', () => {
|
||||
details: { reason: 'SUBAGENT_FILE_UNSUPPORTED' },
|
||||
})
|
||||
expect(child.saveFile).not.toHaveBeenCalled()
|
||||
await expect(child.uploads.uploadImageStream({ sessionId: SESSION, data: chunks([1]), mediaType: 'image/png' }))
|
||||
.rejects.toMatchObject({ code: 'subagent/attachment-invalid', details: { reason: 'SUBAGENT_FILE_UNSUPPORTED' } })
|
||||
expect(child.saveImages).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('isolates receipts by Session object even when Session ids match', async () => {
|
||||
@@ -335,7 +477,7 @@ describe('Session file uploads', () => {
|
||||
expect(() => owner.uploads.bindPrompt(other.agent, [receipt.receiptId], 'other-prompt'))
|
||||
.toThrow(expect.objectContaining({ code: 'session/attachment-invalid', details: { reason: 'FILE_NOT_STAGED' } }))
|
||||
owner.uploads.retirePrompt(other.agent, 'owner-prompt')
|
||||
expect(owner.uploads.resolve(owner.agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
expect(owner.uploads.resolve(owner.agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file })
|
||||
owner.uploads.retirePrompt(owner.agent, 'owner-prompt')
|
||||
expect(owner.uploads.resolve(owner.agent, receipt.receiptId)).toBeUndefined()
|
||||
})
|
||||
@@ -345,9 +487,9 @@ describe('Session file uploads', () => {
|
||||
uploads.retirePrompt(agent, 'not-staged')
|
||||
const receipt = await uploads.upload(agent, { data: 'AAAA' }, new AbortController().signal)
|
||||
await controller.prompt(promptRequest([{ type: 'file', receiptId: receipt.receiptId }]), USER_SOURCE)
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file })
|
||||
uploads.retirePrompt(agent, 'other-request')
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file })
|
||||
uploads.retirePrompt(agent, 'req-1')
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toBeUndefined()
|
||||
})
|
||||
@@ -364,7 +506,7 @@ describe('Session file uploads', () => {
|
||||
content: [{ type: 'text', text: 'extension event' }],
|
||||
source: { kind: 'user', rpcId: 1 } as never,
|
||||
}), { surfaceOp: 'append' })
|
||||
expect(first.uploads.resolve(first.agent, observed.receiptId)).toEqual(observed.file)
|
||||
expect(first.uploads.resolve(first.agent, observed.receiptId)).toEqual({ type: 'file', attachment: observed.file })
|
||||
first.agent.session.append('user/message', createUserMessage({
|
||||
content: [{ type: 'text', text: 'observed' }],
|
||||
source: { kind: 'user', rpcId: 'req-1' as SessionRequestId },
|
||||
@@ -466,7 +608,7 @@ describe('Session file uploads', () => {
|
||||
{ type: 'file', receiptId: receipt.receiptId },
|
||||
]), USER_SOURCE)).rejects.toMatchObject({ code: 'session/agent-busy' })
|
||||
uploads.retirePrompt(agent, 'req-1')
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual(receipt.file)
|
||||
expect(uploads.resolve(agent, receipt.receiptId)).toEqual({ type: 'file', attachment: receipt.file })
|
||||
})
|
||||
|
||||
it('retires a prompt-bound receipt when its queued occurrence is removed', async () => {
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 912a19be4b59ff8a
|
||||
zh: 9c14694cf2ebbaf2
|
||||
/deepseek-ai-dsh-attachment-local/use-this-package/minimal-configuration:
|
||||
en: b34e09c3236f81f1
|
||||
zh: c541b5dc22c8f307
|
||||
en: 9597c3d9779cb93d
|
||||
zh: 900baa94138cc7de
|
||||
/deepseek-ai-dsh-attachment-local/use-this-package/where-your-images-are-stored-and-how-long-they-last:
|
||||
en: 4ee90b8f74baa38c
|
||||
zh: 9c577709ec55eb82
|
||||
@@ -36,8 +36,8 @@
|
||||
en: dcd9857653645420
|
||||
zh: a27259a09f17465d
|
||||
/deepseek-ai-dsh-attachment-local/understand-the-implementation/write-and-read-paths:
|
||||
en: 609ccc784a87b770
|
||||
zh: bc702582cf2b3316
|
||||
en: 62ea104a00a7fdb8
|
||||
zh: b08575274ca244b4
|
||||
/deepseek-ai-dsh-attachment-local/understand-the-implementation/source-map:
|
||||
en: 05af85aa85934d01
|
||||
zh: 1c89e80d496dc0a3
|
||||
|
||||
@@ -38,11 +38,11 @@ Mount the plugin with no required configuration. The defaults below define what
|
||||
| Field | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `dshHome` | resolved | Explicit harness home; omitted follows `$DSH_HOME`, then `~/.dsh` |
|
||||
| `maxImageBytes` | `20 MiB` | Maximum encoded source bytes accepted for one image |
|
||||
| `maxImageBytes` | `50 MiB` | Maximum encoded source bytes accepted for one image |
|
||||
| `maxImagesPerMessage` | `20` | Maximum image count accepted in one submitted message |
|
||||
| `maxMessageImageBytes` | `200 MiB` | Maximum aggregate encoded source bytes in one submitted message |
|
||||
| `maxImagePixels` | `64,000,000` | Maximum source width multiplied by height |
|
||||
| `maxImageDimension` | `8192` | Maximum source width or height |
|
||||
| `maxImageDimension` | `65,535` | Maximum source width or height; the default leaves admission to `maxImagePixels`, and normalization downscales long sides |
|
||||
| `normalizedImageMaxPixels` | `2048 × 2048` | Total-pixel budget of the stored normalized image |
|
||||
| `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 |
|
||||
@@ -83,7 +83,7 @@ This section explains the durability and verification design behind the storage,
|
||||
|
||||
Objects land at `<DSH_HOME>/attachments/v1/objects/<sha256-prefix>/<sha256>`; equal bytes deduplicate to one object and one `sha256:` id. Before the first write, the process syncs every ancestor directory of the home down to the filesystem root once, so a directory another process created but has not yet synced is never mistaken for a safe boundary. Writes then stage bytes in `v1/tmp`, sync the temporary file, publish with an atomic exclusive hard link, and sync the publication directories — on Windows, filesystem metadata journaling owns entry durability. Once the save resolves, the reported reference is durable.
|
||||
|
||||
Admission accepts up to 20 images and 200 MiB of source bytes per message; one source may use up to 20 MiB, 64 million pixels, and 8192 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.
|
||||
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 `<DSH_HOME>/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.
|
||||
|
||||
|
||||
@@ -38,11 +38,11 @@ kind: "package-reference"
|
||||
| 字段 | 默认值 | 含义 |
|
||||
|---|---|---|
|
||||
| `dshHome` | 自动解析 | 显式 harness home;省略时依次跟随 `$DSH_HOME` 与 `~/.dsh` |
|
||||
| `maxImageBytes` | `20 MiB` | 单张图片接受的最大编码源字节数 |
|
||||
| `maxImageBytes` | `50 MiB` | 单张图片接受的最大编码源字节数 |
|
||||
| `maxImagesPerMessage` | `20` | 单条提交消息接受的最大图片数量 |
|
||||
| `maxMessageImageBytes` | `200 MiB` | 单条提交消息接受的最大编码源图字节总数 |
|
||||
| `maxImagePixels` | `64,000,000` | 源图宽度与高度乘积的最大值 |
|
||||
| `maxImageDimension` | `8192` | 源图接受的最大宽度或高度 |
|
||||
| `maxImageDimension` | `65,535` | 源图接受的最大宽度或高度;默认值让 `maxImagePixels` 单独把关,长边由规范化缩小 |
|
||||
| `normalizedImageMaxPixels` | `2048 × 2048` | 已存规范化图片的总像素预算 |
|
||||
| `normalizedImageMaxDimension` | `8192` | 应用总像素预算后的最大长边 |
|
||||
| `normalizedImageMaxBytes` | `4 MiB` | 编码字节目标;没有候选满足时保留质量阶梯中的最小输出 |
|
||||
@@ -83,7 +83,7 @@ kind: "package-reference"
|
||||
|
||||
对象存放在 `<DSH_HOME>/attachments/v1/objects/<sha256-prefix>/<sha256>`;相同字节会去重为同一个对象和同一个 `sha256:` 标识符。首次写入前,进程会把 home 的每个祖先目录逐级同步到文件系统根目录,因此绝不会把另一个进程已创建但尚未同步的目录误认为安全边界。随后,写入过程把字节暂存到 `v1/tmp`、同步临时文件、以原子且排他的硬链接发布,并同步发布目录——在 Windows 上,文件系统元数据日志负责目录项持久性。保存操作完成后,返回的引用已具备持久性。
|
||||
|
||||
准入允许每条消息最多 20 张图片与 200 MiB 源字节;单个源图最多 20 MiB、6400 万像素与单边 8192 像素。系统应用方向、移除元数据与色彩配置,并把规范化结果限制在 2048×2048 总像素预算、8192 像素长边和 4 MiB 编码字节目标内,因此,即使宽高比极端,图片也会保留短边分辨率。已经满足限制的干净、单帧、8-bit sRGB/sRGBA PNG、JPEG 或 WebP 会逐字节直通;GIF、动画、元数据、方向、16-bit PNG 与不兼容色彩空间会触发转换。
|
||||
准入允许每条消息最多 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` 解析的 `<DSH_HOME>/cache/attachments/request-images/`;显式 `dshHome` 设置同时适用于缓存与持久存储。在两次请求之间清空此缓存会保留持久附件,后续读取会重新生成请求版本。`readImageRequest` 在不放大的前提下缩放到路由选定的目标尺寸,缩放只按长边给定,短边由编码器按路由预测的方式推出,随后通过相同的 alpha 路由与质量阶梯应用独立编码字节目标。缓存身份包含附件 id、变换版本、目标尺寸、字节目标与固定编码参数;缓存字节会先通过文件头探测格式、8-bit sRGB/sRGBA、尺寸与 alpha 信息,不匹配时重新生成。并发调用方共享一次变换与缓存写入,且只在没有等待方时由取消停止共享工作。`imageHostPath` 派生规范化对象的宿主路径,挂载的文件系统可以把该路径映射进执行世界,而不会写入持久历史。
|
||||
|
||||
|
||||
@@ -31,15 +31,19 @@ export type { PreparedImageFile } from './store.ts'
|
||||
export { readRequestImageFile, requestImageVariantId } from './request-image.ts'
|
||||
|
||||
/** Default maximum encoded bytes for one submitted image; oversized sources are refused, not shrunk. */
|
||||
export const DEFAULT_MAX_IMAGE_BYTES = 20 * 1024 * 1024
|
||||
export const DEFAULT_MAX_IMAGE_BYTES = 50 * 1024 * 1024
|
||||
/** Default maximum images in one prompt. */
|
||||
export const DEFAULT_MAX_IMAGES_PER_MESSAGE = 20
|
||||
/** Default maximum aggregate image bytes in one prompt. */
|
||||
export const DEFAULT_MAX_MESSAGE_IMAGE_BYTES = 200 * 1024 * 1024
|
||||
/** Default maximum intrinsic pixels for one submitted image. */
|
||||
export const DEFAULT_MAX_IMAGE_PIXELS = 64_000_000
|
||||
/** Default per-side pixel cap for one submitted image. */
|
||||
export const DEFAULT_MAX_IMAGE_DIMENSION = 8192
|
||||
/**
|
||||
* Default per-side pixel cap for one submitted image: the largest side a JPEG
|
||||
* can carry. Normalization downscales a long side, so by default the
|
||||
* decoded-pixel limit alone bounds admission.
|
||||
*/
|
||||
export const DEFAULT_MAX_IMAGE_DIMENSION = 65_535
|
||||
/**
|
||||
* Default total-pixel budget of the stored normalized image. A larger source
|
||||
* is admitted and downscaled proportionally, so admission bounds what rides
|
||||
@@ -61,7 +65,7 @@ export const MAX_IMAGE_COMPRESSION_CONCURRENCY = 8
|
||||
export interface Config {
|
||||
/** Explicit harness home; omitted follows `DSH_HOME`, then `~/.dsh`. */
|
||||
dshHome?: string
|
||||
/** Maximum encoded bytes accepted for one submitted image. Default: 20 MiB. */
|
||||
/** Maximum encoded bytes accepted for one submitted image. Default: 50 MiB. */
|
||||
maxImageBytes?: number
|
||||
/** Maximum image count accepted in one submitted message. Default: 20. */
|
||||
maxImagesPerMessage?: number
|
||||
@@ -69,7 +73,7 @@ export interface Config {
|
||||
maxMessageImageBytes?: number
|
||||
/** Maximum intrinsic width multiplied by height accepted for one submitted image. Default: 64,000,000. */
|
||||
maxImagePixels?: number
|
||||
/** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 8192px. */
|
||||
/** Maximum intrinsic width and maximum intrinsic height accepted for one submitted image. Default: 65,535px. */
|
||||
maxImageDimension?: number
|
||||
/** Total-pixel budget of the stored provider-independent normalized image. */
|
||||
normalizedImageMaxPixels?: number
|
||||
|
||||
@@ -21,11 +21,11 @@ import LocalAttachmentStore, {
|
||||
describe('local attachment service', () => {
|
||||
it('resolves every omitted admission limit explicitly', () => {
|
||||
const service = new LocalAttachmentStore(new Context(), {})
|
||||
expect(DEFAULT_MAX_IMAGE_BYTES).toBe(20 * 1024 * 1024)
|
||||
expect(DEFAULT_MAX_IMAGE_BYTES).toBe(50 * 1024 * 1024)
|
||||
expect(DEFAULT_MAX_IMAGES_PER_MESSAGE).toBe(20)
|
||||
expect(DEFAULT_MAX_MESSAGE_IMAGE_BYTES).toBe(200 * 1024 * 1024)
|
||||
expect(DEFAULT_MAX_IMAGE_PIXELS).toBe(64_000_000)
|
||||
expect(DEFAULT_MAX_IMAGE_DIMENSION).toBe(8192)
|
||||
expect(DEFAULT_MAX_IMAGE_DIMENSION).toBe(65_535)
|
||||
expect(service.imageLimits).toEqual({
|
||||
maxImageBytes: DEFAULT_MAX_IMAGE_BYTES,
|
||||
maxImagesPerMessage: DEFAULT_MAX_IMAGES_PER_MESSAGE,
|
||||
|
||||
@@ -39,8 +39,8 @@
|
||||
en: af7deef72fd2fa93
|
||||
zh: f217d52ce3971135
|
||||
/deepseek-ai-dsh-attachment/understand-the-implementation/service-operations:
|
||||
en: 4a35cdba790c3b8b
|
||||
zh: 08d4a18bbad4b182
|
||||
en: b94d13fe133d8ce6
|
||||
zh: dd4064d20d510afc
|
||||
/deepseek-ai-dsh-attachment/understand-the-implementation/source-map:
|
||||
en: 4fb4c96184c38169
|
||||
zh: 015b06e4bfff4fcd
|
||||
|
||||
@@ -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 references to `ctx.attachments.admitPromptContent()`; the method persists images and passes file references unchanged. 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 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
|
||||
|
||||
|
||||
@@ -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)。
|
||||
|
||||
### 源码地图
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/** Durable attachment storage seam (`ctx.attachments`). @module @deepseek-ai/dsh-attachment */
|
||||
|
||||
import { Buffer } from 'node:buffer'
|
||||
import { Context, Service } from '@deepseek-ai/cordis'
|
||||
import { admitEncodedFile as admitFileInput, admitEncodedImages } from './admission.ts'
|
||||
import { AttachmentError, isAttachmentError as matchesAttachmentError } from './error.ts'
|
||||
@@ -11,6 +12,7 @@ import type {
|
||||
ImageAttachmentLimits,
|
||||
ImageAttachmentRef,
|
||||
ImageRequestTarget,
|
||||
PromptContentPart,
|
||||
RequestImageAttachment,
|
||||
SaveFileAttachment,
|
||||
SaveFileStreamAttachment,
|
||||
@@ -49,6 +51,28 @@ declare module '@deepseek-ai/cordis' {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether one admission part still carries encoded image bytes. */
|
||||
function isEncodedImage(part: AttachmentAdmissionPart): part is Extract<PromptContentPart, { readonly type: 'image' }> {
|
||||
return part.type === 'image' && !('attachment' in part)
|
||||
}
|
||||
|
||||
/** Whether one admission part references an image an earlier upload stored. */
|
||||
function isStoredImage(
|
||||
part: AttachmentAdmissionPart,
|
||||
): part is Extract<AttachmentAdmissionPart, { readonly type: 'image'; readonly encodedBytes: number }> {
|
||||
return part.type === 'image' && 'attachment' in part
|
||||
}
|
||||
|
||||
/** Refuse one message whose images exceed the configured count or aggregate byte limit. */
|
||||
function assertMessageImages(limits: ImageAttachmentLimits, count: number, bytes: number): void {
|
||||
if (count > limits.maxImagesPerMessage) {
|
||||
throw new AttachmentError('Image batch exceeds the configured image-count limit.', 'TOO_MANY_IMAGES')
|
||||
}
|
||||
if (bytes > limits.maxMessageImageBytes) {
|
||||
throw new AttachmentError('Image batch exceeds the configured aggregate image-byte limit.', 'IMAGES_TOO_LARGE')
|
||||
}
|
||||
}
|
||||
|
||||
/** Immutable binary attachment service. Implementations validate bytes before publishing a reference. */
|
||||
export abstract class AttachmentStore extends Service {
|
||||
constructor(ctx: Context) {
|
||||
@@ -75,16 +99,10 @@ export abstract class AttachmentStore extends Service {
|
||||
* @returns durable references in the exact input order.
|
||||
*/
|
||||
protected validateImageBatch(inputs: readonly SaveImageAttachment[]): void {
|
||||
const { maxImagesPerMessage, maxMessageImageBytes, mediaTypes } = this.imageLimits
|
||||
if (inputs.length > maxImagesPerMessage) {
|
||||
throw new AttachmentError('Image batch exceeds the configured image-count limit.', 'TOO_MANY_IMAGES')
|
||||
}
|
||||
const totalBytes = inputs.reduce((sum, input) => sum + input.data.byteLength, 0)
|
||||
if (totalBytes > maxMessageImageBytes) {
|
||||
throw new AttachmentError('Image batch exceeds the configured aggregate image-byte limit.', 'IMAGES_TOO_LARGE')
|
||||
}
|
||||
const limits = this.imageLimits
|
||||
assertMessageImages(limits, inputs.length, inputs.reduce((sum, input) => sum + input.data.byteLength, 0))
|
||||
for (const input of inputs) {
|
||||
if (!mediaTypes.includes(input.mediaType)) {
|
||||
if (!limits.mediaTypes.includes(input.mediaType)) {
|
||||
throw new AttachmentError(`Image type ${input.mediaType} is not accepted by this deployment.`, 'UNSUPPORTED_IMAGE_TYPE')
|
||||
}
|
||||
}
|
||||
@@ -105,25 +123,35 @@ export abstract class AttachmentStore extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* Admit one Host prompt and replace each uploaded image with its durable reference.
|
||||
* Text and durable file references pass through unchanged. A prompt without image parts performs no storage operation.
|
||||
* @param content - prompt parts in message order after file receipt resolution.
|
||||
* Admit one Host prompt and replace each encoded image with its durable reference.
|
||||
* Text, durable file references, and already stored images pass through unchanged.
|
||||
* Every image part counts toward `maxImagesPerMessage` and `maxMessageImageBytes`;
|
||||
* a stored image counts the bytes of the upload that stored it. Refused content
|
||||
* starts no writes. A prompt without encoded images performs no storage operation.
|
||||
* @param content - prompt parts in message order after upload receipt resolution.
|
||||
* @returns admitted prompt parts in the same order as `content`.
|
||||
* @throws AttachmentError when the image batch is refused.
|
||||
*/
|
||||
async admitPromptContent(
|
||||
content: readonly AttachmentAdmissionPart[],
|
||||
): Promise<AdmittedPromptContentPart[]> {
|
||||
if (content.every(part => part.type !== 'image')) {
|
||||
return content.map(part => part.type === 'text'
|
||||
? { type: 'text', text: part.text }
|
||||
: { type: 'file', attachment: part.attachment })
|
||||
const encoded = content.filter(isEncodedImage)
|
||||
const stored = content.filter(isStoredImage)
|
||||
// Each upload passed the limits alone; the encoded batch below checks only itself.
|
||||
if (stored.length > 0) {
|
||||
assertMessageImages(
|
||||
this.imageLimits,
|
||||
encoded.length + stored.length,
|
||||
encoded.reduce((sum, part) => sum + Buffer.byteLength(part.data, 'base64'), 0)
|
||||
+ stored.reduce((sum, part) => sum + part.encodedBytes, 0),
|
||||
)
|
||||
}
|
||||
const refs = await admitEncodedImages(this, content.filter(part => part.type === 'image'))
|
||||
const refs = encoded.length === 0 ? [] : await admitEncodedImages(this, encoded)
|
||||
let next = 0
|
||||
return content.map((part) => {
|
||||
if (part.type === 'text') return { type: 'text', text: part.text }
|
||||
if (part.type === 'file') return { type: 'file', attachment: part.attachment }
|
||||
if ('attachment' in part) return { type: 'image', attachment: part.attachment }
|
||||
return { type: 'image', attachment: refs[next++] as ImageAttachmentRef }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -106,10 +106,16 @@ export type PromptContentPart =
|
||||
readonly name?: string
|
||||
}
|
||||
|
||||
/** Host prompt content whose file receipts are resolved and whose image bytes await admission. */
|
||||
/**
|
||||
* Host prompt content whose upload receipts are resolved. An image part
|
||||
* carries encoded bytes awaiting admission, or references an image this
|
||||
* service already stored for an upload the same Session staged, with
|
||||
* `encodedBytes` holding the byte length of that upload.
|
||||
*/
|
||||
export type AttachmentAdmissionPart =
|
||||
| PromptContentPart
|
||||
| { readonly type: 'file'; readonly attachment: FileAttachmentRef }
|
||||
| { readonly type: 'image'; readonly attachment: ImageAttachmentRef; readonly encodedBytes: number }
|
||||
|
||||
/** Host-admitted prompt content with every attachment represented by its durable reference. */
|
||||
export type AdmittedPromptContentPart =
|
||||
|
||||
@@ -10,6 +10,13 @@ const FILE_REF: FileAttachmentRef = {
|
||||
name: 'notes.md',
|
||||
bytes: 12,
|
||||
}
|
||||
const STORED_REF: ImageAttachmentRef = {
|
||||
attachmentId: 'stored-1' as ImageAttachmentRef['attachmentId'],
|
||||
mediaType: 'image/png',
|
||||
bytes: 8,
|
||||
width: 2,
|
||||
height: 2,
|
||||
}
|
||||
|
||||
/** Delegation double: records the exact saveImages batch and answers ordered refs. */
|
||||
function storeOf() {
|
||||
@@ -138,4 +145,50 @@ describe('AttachmentStore.admitPromptContent', () => {
|
||||
{ type: 'image', attachment: { attachmentId: 'att-2', mediaType: 'image/png', bytes: 1, width: 1, height: 1 } },
|
||||
])
|
||||
})
|
||||
|
||||
it('passes stored images through in part order and stores only the encoded ones', async () => {
|
||||
const { store, mocks } = storeOf()
|
||||
// The stored upload's 4 bytes and the encoded byte fill the budget exactly; the normalized 8 bytes do not count.
|
||||
Object.defineProperty(store, 'imageLimits', { value: { maxImagesPerMessage: 2, maxMessageImageBytes: 5 } })
|
||||
await expect(store.admitPromptContent([
|
||||
{ type: 'image', attachment: STORED_REF, encodedBytes: 4 },
|
||||
{ type: 'text', text: 'between' },
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AQ==' },
|
||||
])).resolves.toEqual([
|
||||
{ type: 'image', attachment: STORED_REF },
|
||||
{ type: 'text', text: 'between' },
|
||||
{ type: 'image', attachment: { attachmentId: 'att-1', mediaType: 'image/png', bytes: 1, width: 1, height: 1 } },
|
||||
])
|
||||
expect(mocks.saveImages).toHaveBeenCalledTimes(1)
|
||||
expect((mocks.saveImages.mock.calls[0]?.[0] as readonly SaveImageAttachment[]).length).toBe(1)
|
||||
})
|
||||
|
||||
it('counts stored images toward the image-count limit before storing anything', async () => {
|
||||
const { store, mocks } = storeOf()
|
||||
Object.defineProperty(store, 'imageLimits', { value: { maxImagesPerMessage: 1, maxMessageImageBytes: 100 } })
|
||||
await expect(store.admitPromptContent([
|
||||
{ type: 'image', attachment: STORED_REF, encodedBytes: 1 },
|
||||
{ type: 'image', mediaType: 'image/png', data: 'AQ==' },
|
||||
])).rejects.toMatchObject({ code: 'TOO_MANY_IMAGES' })
|
||||
await expect(store.admitPromptContent([
|
||||
{ type: 'image', attachment: STORED_REF, encodedBytes: 1 },
|
||||
{ type: 'image', attachment: { ...STORED_REF, attachmentId: 'stored-2' as ImageAttachmentRef['attachmentId'] }, encodedBytes: 1 },
|
||||
])).rejects.toMatchObject({ code: 'TOO_MANY_IMAGES' })
|
||||
expect(mocks.saveImages).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('counts stored upload bytes with encoded bytes toward the message byte limit before storing anything', async () => {
|
||||
const { store, mocks } = storeOf()
|
||||
Object.defineProperty(store, 'imageLimits', { value: { maxImagesPerMessage: 4, maxMessageImageBytes: 5 } })
|
||||
// Two 3-byte uploads each fit alone; together they exceed one message.
|
||||
await expect(store.admitPromptContent([
|
||||
{ type: 'image', attachment: STORED_REF, encodedBytes: 3 },
|
||||
{ type: 'image', attachment: { ...STORED_REF, attachmentId: 'stored-2' as ImageAttachmentRef['attachmentId'] }, encodedBytes: 3 },
|
||||
])).rejects.toMatchObject({ code: 'IMAGES_TOO_LARGE' })
|
||||
await expect(store.admitPromptContent([
|
||||
{ type: 'image', attachment: STORED_REF, encodedBytes: 3 },
|
||||
{ type: 'image', mediaType: 'image/png', data: PNG },
|
||||
])).rejects.toMatchObject({ code: 'IMAGES_TOO_LARGE' })
|
||||
expect(mocks.saveImages).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -246,13 +246,13 @@ describe('best-effort config failure recovery', () => {
|
||||
await ctx.loader.await()
|
||||
const entry = [...ctx.loader.entries()].find(candidate => candidate.options.id === 'webserver')!
|
||||
expect(entry.options.config).toEqual({ value: 'invalid' })
|
||||
expect(entry.fiber?.config).toEqual({ value: 1 })
|
||||
expect(entry.fiber?.effectiveConfig).toEqual({ value: 1 })
|
||||
expect(ctx.get('validatedValue')).toBe(1)
|
||||
|
||||
writeFileSync(join(dir, 'cordis.yml'), config(2))
|
||||
await include.refresh()
|
||||
await ctx.loader.await()
|
||||
expect(entry.fiber?.config).toEqual({ value: 2 })
|
||||
expect(entry.fiber?.effectiveConfig).toEqual({ value: 2 })
|
||||
expect(ctx.get('validatedValue')).toBe(2)
|
||||
} finally {
|
||||
await ctx.fiber.dispose()
|
||||
|
||||
@@ -451,7 +451,7 @@ describe('boot with user patches', () => {
|
||||
try {
|
||||
const noop = [...ctx.loader.entries()].find(entry => entry.options.id === 'noop')
|
||||
// The mounted plugin received the interpolated environment value.
|
||||
expect(noop?.fiber?.config).toEqual({ value: 'user-value' })
|
||||
expect(noop?.fiber?.effectiveConfig).toEqual({ value: 'user-value' })
|
||||
expect([...ctx.loader.entries()].some(entry => entry.options.id === 'user-extra')).toBe(true)
|
||||
} finally {
|
||||
await ctx.fiber.dispose()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
import { Context, FiberState, Service, resolveConfig } from '@deepseek-ai/cordis'
|
||||
import { Context, FiberState, Service } from '@deepseek-ai/cordis'
|
||||
import { entryListSchema, type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
|
||||
import yaml from 'js-yaml'
|
||||
import type { Entry, EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
|
||||
@@ -100,8 +100,7 @@ export class ConfigEditor extends Service {
|
||||
const next = change(current, inherited)
|
||||
const fiber = entry.fiber
|
||||
if (fiber.state !== FiberState.ACTIVE) throw new Error('Configuration plugin is no longer active')
|
||||
const resolved: unknown = fiber.ctx.waterfall(fiber, 'internal/config', next, () => next)
|
||||
resolveConfig(fiber.runtime as NonNullable<typeof fiber.runtime>, resolved)
|
||||
fiber.resolveConfig(next)
|
||||
let before: string
|
||||
try { before = await readFile(path, 'utf8') }
|
||||
catch (error) {
|
||||
|
||||
@@ -646,7 +646,7 @@ class Hmr extends Service {
|
||||
...info, previous,
|
||||
fibers: [...info.runtime?.fibers ?? []].map((fiber) => {
|
||||
const entry = fiber.entry?.fiber?.uid === fiber.uid ? fiber.entry : undefined
|
||||
const config: unknown = entry === undefined ? fiber._config : entry.options.config
|
||||
const config: unknown = entry === undefined ? fiber.rawConfig : entry.options.config
|
||||
return { fiber, entry, config, moduleNamespace: entry?.moduleNamespace }
|
||||
}),
|
||||
}))
|
||||
|
||||
@@ -298,7 +298,7 @@ it('leaves disposed child instances to their replacing parent', async () => {
|
||||
expect(seen).toContain('new:entry')
|
||||
expect(seen).not.toContain('new:child')
|
||||
expect(seen).toContain('new:independent')
|
||||
expect(entry.fiber?._config).toEqual({ value: 'entry' })
|
||||
expect(entry.fiber?.rawConfig).toEqual({ value: 'entry' })
|
||||
})
|
||||
|
||||
it.each(['v1', 'v2'] as const)('invalidates a disabled %s module without activating it', async (version) => {
|
||||
|
||||
@@ -9,17 +9,17 @@
|
||||
en: a6c9f156174554e1
|
||||
zh: cd1a126905ad859b
|
||||
/deepseek-ai-dsh-client-file-upload/summary:
|
||||
en: 430b79a11643da11
|
||||
zh: 5fbab8d425b7f15a
|
||||
en: e53f2cfb8285a578
|
||||
zh: 1930ea2638e59a34
|
||||
/deepseek-ai-dsh-client-file-upload/table-of-contents:
|
||||
en: d152484eb41ac6b4
|
||||
zh: 09388d293f9be9cb
|
||||
/deepseek-ai-dsh-client-file-upload/use-this-package:
|
||||
en: 9d5bbf52599b0d00
|
||||
zh: 7907542ce1e34549
|
||||
en: 7c19ce780c0d1357
|
||||
zh: 2d295b8b872b5f9f
|
||||
/deepseek-ai-dsh-client-file-upload/understand-the-implementation:
|
||||
en: 77937960a540cf51
|
||||
zh: 52c478bd11200975
|
||||
en: 8a03794416a84817
|
||||
zh: 7b2510135b751f97
|
||||
/deepseek-ai-dsh-client-file-upload/further-exploration:
|
||||
en: ac94eb9da9ecc296
|
||||
zh: 25cc3362e2bea330
|
||||
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
This package lets browser features store a `Blob`, exact bytes, or a `ReadableStream<Uint8Array>` for one Session and receive an opaque receipt for a later prompt. Served pages send Blob and stream bodies without aggregating their bytes on the page thread; pages whose Host runs in another execution context supply a Fetch-shaped carrier before Cordis boots. Callers can observe consumed bytes and cancel an active operation. A stream body is consumed once and transfers ownership when it crosses a Worker boundary. Exact bytes use the generated Remote.
|
||||
This package lets browser features store a `Blob`, exact bytes, or a `ReadableStream<Uint8Array>` for one Session and receive an opaque receipt for a later prompt. Served pages send Blob and stream bodies without aggregating their bytes on the page thread; pages whose Host runs in another execution context supply a Fetch-shaped carrier before Cordis boots. Callers can observe consumed bytes and cancel an active operation. A stream body is consumed once and transfers ownership when it crosses a Worker boundary. An image upload stages a normalized prompt image that a later prompt cites by receipt.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -25,7 +25,7 @@ This package lets browser features store a `Blob`, exact bytes, or a `ReadableSt
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
Mount the package before a consumer that injects `fileUpload`, then call `ctx.fileUpload.upload(sessionId, body, name, signal, onProgress)`. The Session identity addresses both the raw route and generated Remote fallback; callers do not assemble either request.
|
||||
Mount the package before a consumer that injects `fileUpload`, then call `ctx.fileUpload.upload(sessionId, body, name, signal, onProgress)`, or `ctx.fileUpload.uploadImage(sessionId, blob, mediaType, name, signal, onProgress)` for a prompt image. The Session identity addresses both the raw route and generated Remote fallback; callers do not assemble either request.
|
||||
|
||||
```yaml
|
||||
- id: file-upload
|
||||
@@ -44,7 +44,7 @@ The package has no Cordis configuration fields. A `Blob` uses XMLHttpRequest ins
|
||||
|
||||
The Client plugin provides `ctx.fileUpload`. Its `upload()` method receives the owning Session identity, assembles the raw route request, and invokes the generated Remote for exact bytes. The provider reads the optional pre-Cordis `__DSH_FILE_UPLOAD__` hook once. Without a hook, each Blob or stream request owns a short-lived Worker and releases it after completion, failure, or cancellation. With the hook, the service sends the body through the page-owned Fetch carrier; the Web Worker runtime transfers stream bodies through its request frame and exposes them to the Host HTTP bridge as backpressured chunks.
|
||||
|
||||
The Host plugin provides `ctx.fileUploads`. It owns the authenticated streaming route, encoded Remote fallback, command receipt resolver, and staged-receipt lifecycle; encoded admission, attachment-error recognition, and byte storage stay behind `ctx.attachments`. Host callers supply an Agent with its runtime-owned context; receipt tables use that Agent's exact Session object as their key. The Session Controller registers the resolver that can resume a cold ordinary Agent and consumes receipts during prompt admission. Prompt delivery holds each receipt binding in a disposable transaction: disposal restores the previous binding until successful delivery commits it, and queue or history observation then retires the committed receipt.
|
||||
The Host plugin provides `ctx.fileUploads`. It owns the authenticated streaming route, encoded Remote fallback, command receipt resolver, and staged-receipt lifecycle; encoded admission, attachment-error recognition, and byte storage stay behind `ctx.attachments`. A raw upload with a `mediaType` query parameter reads at most the smaller of the deployment's per-image and per-message image byte limits and stores the image through `ctx.attachments.saveImages`; its receipt records the upload's byte length and resolves to that image during prompt admission, where those bytes count toward the per-message image byte limit, and commands accept only file receipts. A cancelled image upload receives no receipt: cancellation before storage begins stores nothing, and an image whose storage already began stays stored. Host callers supply an Agent with its runtime-owned context; receipt tables use that Agent's exact Session object as their key. The Session Controller registers the resolver that can resume a cold ordinary Agent and consumes receipts during prompt admission. Prompt delivery holds each receipt binding in a disposable transaction: disposal restores the previous binding until successful delivery commits it, and queue or history observation then retires the committed receipt.
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
|
||||
@@ -9,7 +9,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
本包让浏览器功能为一个 Session 存储 `Blob`、精确字节或 `ReadableStream<Uint8Array>`,并取得供后续 prompt 使用的不透明凭证。普通服务页面发送 Blob 和 stream 请求体时,不会在页面线程聚合全部字节;Host 位于其他执行上下文中的页面会在 Cordis 启动前提供 Fetch 形式的载体。调用方可以观察已消费字节并取消活动操作。stream 请求体只能消费一次,跨 Worker 边界时会转移所有权。精确字节使用生成的 Remote。
|
||||
本包让浏览器功能为一个 Session 存储 `Blob`、精确字节或 `ReadableStream<Uint8Array>`,并取得供后续 prompt 使用的不透明凭证。普通服务页面发送 Blob 和 stream 请求体时,不会在页面线程聚合全部字节;Host 位于其他执行上下文中的页面会在 Cordis 启动前提供 Fetch 形式的载体。调用方可以观察已消费字节并取消活动操作。stream 请求体只能消费一次,跨 Worker 边界时会转移所有权。图片上传会暂存一张规整后的 prompt 图片,供后续 prompt 凭证引用。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -25,7 +25,7 @@ kind: "package-reference"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
在注入 `fileUpload` 的消费方之前挂载本包,再调用 `ctx.fileUpload.upload(sessionId, body, name, signal, onProgress)`。Session 标识同时用于寻址原始路由和生成的 Remote 兜底;调用方不组装这两种请求。
|
||||
在注入 `fileUpload` 的消费方之前挂载本包,再调用 `ctx.fileUpload.upload(sessionId, body, name, signal, onProgress)`;prompt 图片则调用 `ctx.fileUpload.uploadImage(sessionId, blob, mediaType, name, signal, onProgress)`。Session 标识同时用于寻址原始路由和生成的 Remote 兜底;调用方不组装这两种请求。
|
||||
|
||||
```yaml
|
||||
- id: file-upload
|
||||
@@ -44,7 +44,7 @@ kind: "package-reference"
|
||||
|
||||
Client 插件提供 `ctx.fileUpload`。其 `upload()` 方法接收所属 Session 标识,组装原始路由请求,并为精确字节调用生成的 Remote。提供方只读取一次可选的 Cordis 启动前 `__DSH_FILE_UPLOAD__` 钩子。没有该钩子时,每个 Blob 或 stream 请求拥有一个短期 Worker,并在完成、失败或取消后释放。存在该钩子时,服务通过页面自己提供的 Fetch 载体发送请求体;Web Worker runtime 会通过请求帧转移 stream 请求体,再以带背压的分片形式交给 Host HTTP bridge。
|
||||
|
||||
Host 插件提供 `ctx.fileUploads`。它拥有经过认证的流式路由、编码 Remote 兜底、命令凭证解析器与暂存凭证生命周期;编码准入、附件错误识别与字节存储仍由 `ctx.attachments` 提供。Host 调用方传入具有运行时所属上下文的 Agent;凭证表以该 Agent 的准确 Session 对象为键。Session Controller 注册可恢复休眠普通 Agent 的解析器,并在 prompt 准入时消费凭证。Prompt 投递通过可释放事务持有每个凭证绑定。成功投递提交事务前,释放会恢复原绑定;提交后,队列或历史观察会退休该凭证。
|
||||
Host 插件提供 `ctx.fileUploads`。它拥有经过认证的流式路由、编码 Remote 兜底、命令凭证解析器与暂存凭证生命周期;编码准入、附件错误识别与字节存储仍由 `ctx.attachments` 提供。带 `mediaType` 查询参数的原始上传最多读取部署配置的单张图片与单条消息图片字节上限中较小的一个,并通过 `ctx.attachments.saveImages` 存储图片;该凭证记录上传的字节数,在 prompt 准入时解析为这张图片,这些字节计入单条消息的图片总字节上限;命令只接受文件凭证。取消的图片上传不会取得凭证:存储开始前取消不存储任何内容,已开始存储的图片会保留。Host 调用方传入具有运行时所属上下文的 Agent;凭证表以该 Agent 的准确 Session 对象为键。Session Controller 注册可恢复休眠普通 Agent 的解析器,并在 prompt 准入时消费凭证。Prompt 投递通过可释放事务持有每个凭证绑定。成功投递提交事务前,释放会恢复原绑定;提交后,队列或历史观察会退休该凭证。
|
||||
|
||||
| 文件 | 职责 |
|
||||
|---|---|
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ImageMediaType } from '@deepseek-ai/dsh-attachment/types'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { FileUploadValue } from '../types.ts'
|
||||
import type { FileUploadValue, ImageUploadValue } from '../types.ts'
|
||||
|
||||
/** Browser request body accepted by the background file-upload service. */
|
||||
export type FileUploadBody = Blob | ReadableStream<Uint8Array>
|
||||
@@ -30,4 +31,24 @@ export interface FileUploadService {
|
||||
signal?: AbortSignal,
|
||||
onProgress?: (progress: FileUploadProgress) => void,
|
||||
): Promise<RemoteResult<FileUploadValue>>
|
||||
/**
|
||||
* Store one prompt image for a Session through the background carrier. The
|
||||
* Host validates, normalizes, and stores it as prompt admission would, and a
|
||||
* later prompt cites the receipt in a file part.
|
||||
* @param sessionId - Session that owns the staged receipt.
|
||||
* @param data - browser image Blob.
|
||||
* @param mediaType - declared image media type.
|
||||
* @param name - optional display name.
|
||||
* @param signal - optional cancellation for the active upload.
|
||||
* @param onProgress - optional byte-progress observer.
|
||||
* @returns the staged receipt and normalized image reference, or a business error.
|
||||
*/
|
||||
uploadImage(
|
||||
sessionId: SessionId,
|
||||
data: Blob,
|
||||
mediaType: ImageMediaType,
|
||||
name?: string,
|
||||
signal?: AbortSignal,
|
||||
onProgress?: (progress: FileUploadProgress) => void,
|
||||
): Promise<RemoteResult<ImageUploadValue>>
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
/** Background browser upload implementation for Blob and byte-stream bodies. */
|
||||
|
||||
import { Service, type Context } from '@deepseek-ai/cordis'
|
||||
import type { ImageMediaType } from '@deepseek-ai/dsh-attachment/types'
|
||||
import { bytesToBase64 } from '@deepseek-ai/dsh-util-crypto'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { FILE_UPLOAD_ROUTE } from '../protocol.ts'
|
||||
import type {
|
||||
ClientFileUploadHooks, EncodedFileUploadRequest, FileUploadFetch, FileUploadValue,
|
||||
ClientFileUploadHooks, EncodedFileUploadRequest, FileUploadFetch, FileUploadValue, ImageUploadValue,
|
||||
} from '../types.ts'
|
||||
import type { FileUploadBody, FileUploadService } from './contract.ts'
|
||||
|
||||
@@ -198,17 +199,7 @@ export class FileUploadRuntime extends Service implements FileUploadService {
|
||||
if (!(data instanceof Uint8Array)) {
|
||||
const query = new URLSearchParams({ sessionId })
|
||||
if (name !== undefined) query.set('name', name)
|
||||
const response = await this.post({
|
||||
path: `${FILE_UPLOAD_ROUTE}?${query.toString()}`,
|
||||
body: data,
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
...(onProgress === undefined ? {} : { onProgress }),
|
||||
})
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`file upload transport failed with HTTP ${String(response.status)}`)
|
||||
}
|
||||
return parseFileUploadResult(response.body)
|
||||
return parseUploadResult(await this.postRaw(query, data, signal, onProgress), fileUploadValue)
|
||||
}
|
||||
return (this.ctx as FileUploadRemoteContext).remote.fileUploads.upload(
|
||||
sessionId,
|
||||
@@ -219,6 +210,49 @@ export class FileUploadRuntime extends Service implements FileUploadService {
|
||||
signal,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Store one prompt image for a Session.
|
||||
* @param sessionId - Session that owns the staged receipt.
|
||||
* @param data - browser image Blob.
|
||||
* @param mediaType - declared image media type.
|
||||
* @param name - optional display name.
|
||||
* @param signal - optional cancellation for the active upload.
|
||||
* @param onProgress - optional byte-progress observer.
|
||||
* @returns the staged receipt and normalized image reference, or a business error.
|
||||
*/
|
||||
async uploadImage(
|
||||
sessionId: SessionId,
|
||||
data: Blob,
|
||||
mediaType: ImageMediaType,
|
||||
name?: string,
|
||||
signal?: AbortSignal,
|
||||
onProgress?: (progress: { readonly loaded: number; readonly total?: number }) => void,
|
||||
): Promise<RemoteResult<ImageUploadValue>> {
|
||||
const query = new URLSearchParams({ sessionId, mediaType })
|
||||
if (name !== undefined) query.set('name', name)
|
||||
return parseUploadResult(await this.postRaw(query, data, signal, onProgress), imageUploadValue)
|
||||
}
|
||||
|
||||
/** Post one raw body to the upload route; a non-200 status is a transport failure. */
|
||||
private async postRaw(
|
||||
query: URLSearchParams,
|
||||
body: FileUploadBody,
|
||||
signal: AbortSignal | undefined,
|
||||
onProgress: ((progress: { readonly loaded: number; readonly total?: number }) => void) | undefined,
|
||||
): Promise<string> {
|
||||
const response = await this.post({
|
||||
path: `${FILE_UPLOAD_ROUTE}?${query.toString()}`,
|
||||
body,
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
...(onProgress === undefined ? {} : { onProgress }),
|
||||
})
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`file upload transport failed with HTTP ${String(response.status)}`)
|
||||
}
|
||||
return response.body
|
||||
}
|
||||
}
|
||||
|
||||
function customTransport(customFetch: FileUploadFetch): FileUploadTransport {
|
||||
@@ -297,7 +331,7 @@ function workerTransport(): FileUploadTransport {
|
||||
}
|
||||
}
|
||||
|
||||
function parseFileUploadResult(body: string): RemoteResult<FileUploadValue> {
|
||||
function parseUploadResult<T>(body: string, parseValue: (value: unknown) => T): RemoteResult<T> {
|
||||
const value: unknown = JSON.parse(body)
|
||||
if (!isRecord(value) || typeof value.ok !== 'boolean') {
|
||||
throw new TypeError('file upload transport returned an invalid result')
|
||||
@@ -313,26 +347,60 @@ function parseFileUploadResult(body: string): RemoteResult<FileUploadValue> {
|
||||
error: new RemoteError(error.code as never, error.message, error.details as never),
|
||||
}
|
||||
}
|
||||
const result = value.value
|
||||
return { ok: true, value: parseValue(value.value) }
|
||||
}
|
||||
|
||||
function fileUploadValue(result: unknown): FileUploadValue {
|
||||
const file = isRecord(result) ? result.file : undefined
|
||||
if (!isRecord(result) || typeof result.receiptId !== 'string' || !isRecord(file)
|
||||
|| typeof file.attachmentId !== 'string' || typeof file.name !== 'string'
|
||||
|| typeof file.bytes !== 'number' || !Number.isSafeInteger(file.bytes) || file.bytes < 0) {
|
||||
|| typeof file.attachmentId !== 'string' || typeof file.name !== 'string' || !isNonNegativeInteger(file.bytes)) {
|
||||
throw new TypeError('file upload transport returned an invalid receipt')
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
receiptId: result.receiptId as FileUploadValue['receiptId'],
|
||||
file: {
|
||||
attachmentId: file.attachmentId as FileUploadValue['file']['attachmentId'],
|
||||
name: file.name,
|
||||
bytes: file.bytes,
|
||||
},
|
||||
receiptId: result.receiptId as FileUploadValue['receiptId'],
|
||||
file: {
|
||||
attachmentId: file.attachmentId as FileUploadValue['file']['attachmentId'],
|
||||
name: file.name,
|
||||
bytes: file.bytes,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function imageUploadValue(result: unknown): ImageUploadValue {
|
||||
const image = isRecord(result) ? result.image : undefined
|
||||
if (!isRecord(result) || typeof result.receiptId !== 'string' || !isRecord(image)
|
||||
|| typeof image.attachmentId !== 'string' || !isImageMediaType(image.mediaType)
|
||||
|| !isNonNegativeInteger(image.bytes) || !isNonNegativeInteger(image.width) || !isNonNegativeInteger(image.height)
|
||||
|| (image.name !== undefined && typeof image.name !== 'string')
|
||||
|| (image.originalDimensions !== undefined && !isDimensions(image.originalDimensions))) {
|
||||
throw new TypeError('file upload transport returned an invalid image receipt')
|
||||
}
|
||||
return {
|
||||
receiptId: result.receiptId as ImageUploadValue['receiptId'],
|
||||
image: {
|
||||
attachmentId: image.attachmentId as ImageUploadValue['image']['attachmentId'],
|
||||
mediaType: image.mediaType,
|
||||
bytes: image.bytes,
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
...(image.name === undefined ? {} : { name: image.name }),
|
||||
...(image.originalDimensions === undefined ? {} : { originalDimensions: image.originalDimensions }),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function isNonNegativeInteger(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
|
||||
}
|
||||
|
||||
function isImageMediaType(value: unknown): value is ImageMediaType {
|
||||
return value === 'image/png' || value === 'image/jpeg' || value === 'image/webp' || value === 'image/gif'
|
||||
}
|
||||
|
||||
function isDimensions(value: unknown): value is { width: number; height: number } {
|
||||
return isRecord(value) && isNonNegativeInteger(value.width) && isNonNegativeInteger(value.height)
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<PropertyKey, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
@@ -4,17 +4,18 @@ import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { FileUploads } from './index.ts'
|
||||
import type { FileUploadValue } from './types.ts'
|
||||
import type { FileUploadValue, ImageUploadValue } from './types.ts'
|
||||
|
||||
type FileUploadHttpResult =
|
||||
| { readonly ok: true; readonly value: FileUploadValue }
|
||||
| { readonly ok: true; readonly value: FileUploadValue | ImageUploadValue }
|
||||
| {
|
||||
readonly ok: false
|
||||
readonly error: { readonly code: string; readonly message: string; readonly details: object }
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle one authenticated raw-byte upload.
|
||||
* Handle one authenticated raw-byte upload. A `mediaType` query parameter
|
||||
* stages the body as a prompt image; without it the body is stored verbatim.
|
||||
* @param service - Host upload service receiving streamed bytes.
|
||||
* @param request - authenticated HTTP request from Connection.
|
||||
* @returns JSON result using HTTP status 200 after request validation.
|
||||
@@ -33,16 +34,20 @@ export async function handleFileUploadHttp(service: FileUploads, request: Reques
|
||||
return new Response('sessionId is required', { status: 400 })
|
||||
}
|
||||
const name = url.searchParams.get('name') ?? undefined
|
||||
const imageMediaType = url.searchParams.get('mediaType') ?? undefined
|
||||
const upload = {
|
||||
sessionId: brandString<SessionId>(sessionId),
|
||||
data: requestBodyChunks(request.body),
|
||||
signal: request.signal,
|
||||
...(name === undefined ? {} : { name }),
|
||||
}
|
||||
let result: FileUploadHttpResult
|
||||
try {
|
||||
result = {
|
||||
ok: true,
|
||||
value: await service.uploadStream({
|
||||
sessionId: brandString<SessionId>(sessionId),
|
||||
data: requestBodyChunks(request.body),
|
||||
signal: request.signal,
|
||||
...(name === undefined ? {} : { name }),
|
||||
}),
|
||||
value: imageMediaType === undefined
|
||||
? await service.uploadStream(upload)
|
||||
: await service.uploadImageStream({ ...upload, mediaType: imageMediaType }),
|
||||
}
|
||||
} catch (error) {
|
||||
const failure = remoteErrorOf(error)
|
||||
|
||||
@@ -3,26 +3,28 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type { FileAttachmentRef } from '@deepseek-ai/dsh-attachment'
|
||||
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
|
||||
import type {} from '@deepseek-ai/dsh-client-connection'
|
||||
import type { CommandFileReceiptResolver } from '@deepseek-ai/dsh-commands'
|
||||
import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { Remote, RemoteError, remoteErrorOf, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { handleFileUploadHttp } from './http-route.ts'
|
||||
import { FILE_UPLOAD_PATH } from './protocol.ts'
|
||||
import type { EncodedFileUploadRequest, FileUploadReceiptId, FileUploadValue } from './types.ts'
|
||||
import type {
|
||||
EncodedFileUploadRequest, FileUploadReceiptId, FileUploadValue, ImageUploadValue, StagedAttachment,
|
||||
} from './types.ts'
|
||||
|
||||
export type * from './types.ts'
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
/** Host storage and staged-receipt service for browser file uploads. */
|
||||
/** Host storage and staged-receipt service for browser file and image uploads. */
|
||||
fileUploads: FileUploads
|
||||
}
|
||||
}
|
||||
|
||||
interface StagedFileUpload {
|
||||
readonly file: FileAttachmentRef
|
||||
readonly attachment: StagedAttachment
|
||||
/** Prompt that accepted this receipt; absent until successful admission. */
|
||||
requestId?: string
|
||||
}
|
||||
@@ -65,8 +67,11 @@ export class FileUploads extends TypertRemoteService {
|
||||
/** @param ctx - Host context carrying Agent, attachment, command, and Connection services. */
|
||||
constructor(ctx: Context) {
|
||||
super(ctx, 'fileUploads')
|
||||
const resolve: CommandFileReceiptResolver = (agent, receiptId) =>
|
||||
this.resolve(agent, receiptId as FileUploadReceiptId)
|
||||
// Commands accept staged files only; an image receipt is unknown to them.
|
||||
const resolve: CommandFileReceiptResolver = (agent, receiptId) => {
|
||||
const staged = this.resolve(agent, receiptId as FileUploadReceiptId)
|
||||
return staged?.type === 'file' ? staged.attachment : undefined
|
||||
}
|
||||
ctx.effect(
|
||||
() => ctx.commands.registerFileReceiptResolver(resolve),
|
||||
'file-upload: command file receipt resolver',
|
||||
@@ -105,12 +110,13 @@ export class FileUploads extends TypertRemoteService {
|
||||
* @returns the staged receipt and durable file reference.
|
||||
*/
|
||||
@Remote('upload')
|
||||
upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise<FileUploadValue> {
|
||||
async upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise<FileUploadValue> {
|
||||
signal.throwIfAborted()
|
||||
return this.commit(agent, async () => this.ctx.attachments.admitEncodedFile({
|
||||
const file = await this.store(agent, async () => this.ctx.attachments.admitEncodedFile({
|
||||
data: request.data,
|
||||
...(request.name === undefined ? {} : { name: request.name }),
|
||||
}))
|
||||
return { receiptId: this.stage(agent, { type: 'file', attachment: file }), file }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,21 +131,68 @@ export class FileUploads extends TypertRemoteService {
|
||||
readonly name?: string
|
||||
}): Promise<FileUploadValue> {
|
||||
const agent = await this.resolveAgent(request.sessionId)
|
||||
return this.commit(agent, async () => this.ctx.attachments.saveFileStream({
|
||||
const file = await this.store(agent, async () => this.ctx.attachments.saveFileStream({
|
||||
data: request.data,
|
||||
...(request.signal === undefined ? {} : { signal: request.signal }),
|
||||
...(request.name === undefined ? {} : { name: request.name }),
|
||||
}))
|
||||
return { receiptId: this.stage(agent, { type: 'file', attachment: file }), file }
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist one prompt image for a Session: read at most the smaller of the
|
||||
* deployment's per-image and per-message byte limits, then validate,
|
||||
* normalize, and store the image the way prompt admission does, so a later
|
||||
* prompt cites it by receipt.
|
||||
* Cancellation before storage begins stores nothing; a cancelled upload
|
||||
* never receives a receipt, although an image whose storage already began
|
||||
* stays in the content-addressed store.
|
||||
* @param request - Session identity, ordered bytes, the declared media type that this deployment
|
||||
* must accept, cancellation, and optional display name.
|
||||
* @returns the staged receipt and durable normalized image reference.
|
||||
*/
|
||||
async uploadImageStream(request: {
|
||||
readonly sessionId: SessionId
|
||||
readonly data: AsyncIterable<Uint8Array>
|
||||
readonly mediaType: string
|
||||
readonly signal?: AbortSignal
|
||||
readonly name?: string
|
||||
}): Promise<ImageUploadValue> {
|
||||
const agent = await this.resolveAgent(request.sessionId)
|
||||
const limits = this.ctx.attachments.imageLimits
|
||||
const mediaType = limits.mediaTypes.find(type => type === request.mediaType)
|
||||
if (mediaType === undefined) {
|
||||
throw new RemoteError(
|
||||
'session/attachment-invalid' as never,
|
||||
`Image type ${request.mediaType} is not accepted by this deployment.`,
|
||||
{ reason: 'UNSUPPORTED_IMAGE_TYPE' } as never,
|
||||
)
|
||||
}
|
||||
const staged = await this.store(agent, async () => {
|
||||
// One image must also fit a whole message; stop at the smaller bound, as read-image does.
|
||||
const data = await readAtMost(request.data, Math.min(limits.maxImageBytes, limits.maxMessageImageBytes), request.signal)
|
||||
// readAtMost checks cancellation per chunk; an abort after the last chunk still stops here.
|
||||
request.signal?.throwIfAborted()
|
||||
const refs = await this.ctx.attachments.saveImages([{
|
||||
data,
|
||||
mediaType,
|
||||
...(request.name === undefined ? {} : { name: request.name }),
|
||||
}])
|
||||
request.signal?.throwIfAborted()
|
||||
// saveImages returns one reference per input, in input order.
|
||||
return { type: 'image' as const, attachment: refs[0] as ImageAttachmentRef, encodedBytes: data.byteLength }
|
||||
})
|
||||
return { receiptId: this.stage(agent, staged), image: staged.attachment }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one staged receipt for the receiving Agent's exact Session.
|
||||
* @param agent - receiving Agent.
|
||||
* @param receiptId - opaque receipt minted for one completed upload.
|
||||
* @returns durable file reference, or `undefined` for an unknown or foreign receipt.
|
||||
* @returns the staged file or image, or `undefined` for an unknown or foreign receipt.
|
||||
*/
|
||||
resolve(agent: Agent, receiptId: FileUploadReceiptId): FileAttachmentRef | undefined {
|
||||
return this.stagedFiles.get(agent.session)?.get(receiptId)?.file
|
||||
resolve(agent: Agent, receiptId: FileUploadReceiptId): StagedAttachment | undefined {
|
||||
return this.stagedFiles.get(agent.session)?.get(receiptId)?.attachment
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -179,12 +232,13 @@ export class FileUploads extends TypertRemoteService {
|
||||
this.retire(agent.session, requestId)
|
||||
}
|
||||
|
||||
private async commit(agent: Agent, save: () => Promise<FileAttachmentRef>): Promise<FileUploadValue> {
|
||||
/** Store one upload for an ordinary Agent; storage failures become Remote failures. */
|
||||
private async store<T>(agent: Agent, save: () => Promise<T>): Promise<T> {
|
||||
this.assertOrdinaryAgent(agent)
|
||||
let file: FileAttachmentRef
|
||||
try {
|
||||
file = await save()
|
||||
return await save()
|
||||
} catch (error) {
|
||||
if (remoteErrorOf(error) !== undefined) throw error
|
||||
if (this.ctx.attachments.isAttachmentError(error)) {
|
||||
throw new RemoteError('session/attachment-invalid' as never, error.message, { reason: error.code } as never)
|
||||
}
|
||||
@@ -195,6 +249,10 @@ export class FileUploads extends TypertRemoteService {
|
||||
{ cause: error },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Stage one stored upload under a new receipt for the Agent's exact Session. */
|
||||
private stage(agent: Agent, attachment: StagedAttachment): FileUploadReceiptId {
|
||||
if (this.ctx.agents.get(agent.id) !== agent) {
|
||||
throw new RemoteError(
|
||||
'session/not-found',
|
||||
@@ -208,8 +266,8 @@ export class FileUploads extends TypertRemoteService {
|
||||
this.stagedFiles.set(agent.session, staged)
|
||||
}
|
||||
const receiptId = randomUUID() as FileUploadReceiptId
|
||||
staged.set(receiptId, { file })
|
||||
return { receiptId, file }
|
||||
staged.set(receiptId, { attachment })
|
||||
return receiptId
|
||||
}
|
||||
|
||||
private async resolveAgent(sessionId: SessionId): Promise<Agent> {
|
||||
@@ -248,6 +306,31 @@ export class FileUploads extends TypertRemoteService {
|
||||
}
|
||||
}
|
||||
|
||||
/** Collect one body of at most `limit` bytes, refusing it as soon as it passes the limit. */
|
||||
async function readAtMost(data: AsyncIterable<Uint8Array>, limit: number, signal?: AbortSignal): Promise<Uint8Array> {
|
||||
const chunks: Uint8Array[] = []
|
||||
let length = 0
|
||||
for await (const chunk of data) {
|
||||
signal?.throwIfAborted()
|
||||
length += chunk.byteLength
|
||||
if (length > limit) {
|
||||
throw new RemoteError(
|
||||
'session/attachment-invalid' as never,
|
||||
'Image exceeds the configured byte limit.',
|
||||
{ reason: 'IMAGE_TOO_LARGE' } as never,
|
||||
)
|
||||
}
|
||||
chunks.push(chunk)
|
||||
}
|
||||
const bytes = new Uint8Array(length)
|
||||
let offset = 0
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset)
|
||||
offset += chunk.byteLength
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
function fileNotStaged(): RemoteError {
|
||||
return new RemoteError(
|
||||
'session/attachment-invalid' as never,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Browser-safe request and receipt types for staged file uploads. */
|
||||
|
||||
import type { FileAttachmentRef } from '@deepseek-ai/dsh-attachment/types'
|
||||
import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment/types'
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
|
||||
/** Canonical encoded upload accepted by the Remote fallback. */
|
||||
@@ -18,6 +18,23 @@ export interface FileUploadValue {
|
||||
readonly file: FileAttachmentRef
|
||||
}
|
||||
|
||||
/** Durable receipt for one staged image upload. */
|
||||
export interface ImageUploadValue {
|
||||
/** Per-upload authority accepted only inside the receiving Agent scope. */
|
||||
readonly receiptId: FileUploadReceiptId
|
||||
/** The normalized prompt image the Host stored. */
|
||||
readonly image: ImageAttachmentRef
|
||||
}
|
||||
|
||||
/**
|
||||
* Durable attachment one staged receipt names: a verbatim file, or a
|
||||
* normalized prompt image with `encodedBytes` holding the byte length of its
|
||||
* upload, which counts toward the per-message image byte limit.
|
||||
*/
|
||||
export type StagedAttachment =
|
||||
| { readonly type: 'file'; readonly attachment: FileAttachmentRef }
|
||||
| { readonly type: 'image'; readonly attachment: ImageAttachmentRef; readonly encodedBytes: number }
|
||||
|
||||
/** Host-minted authority for one staged file upload in one Agent scope. */
|
||||
export type FileUploadReceiptId = Branded<'file-upload-receipt-id'>
|
||||
|
||||
|
||||
@@ -9,12 +9,14 @@ function request(input: {
|
||||
method?: string
|
||||
sessionId?: string
|
||||
name?: string
|
||||
mediaType?: string
|
||||
contentType?: string
|
||||
body?: Uint8Array
|
||||
} = {}): Request {
|
||||
const query = new URLSearchParams()
|
||||
if (input.sessionId !== undefined) query.set('sessionId', input.sessionId)
|
||||
if (input.name !== undefined) query.set('name', input.name)
|
||||
if (input.mediaType !== undefined) query.set('mediaType', input.mediaType)
|
||||
const suffix = query.size === 0 ? '' : `?${query.toString()}`
|
||||
return new Request(`http://host/api/session/uploadFileBinary${suffix}`, {
|
||||
method: input.method ?? 'POST',
|
||||
@@ -91,6 +93,27 @@ describe('background file upload Fetch route', () => {
|
||||
expect(await response.json()).toEqual({ ok: true, value })
|
||||
})
|
||||
|
||||
it('stages the body as a prompt image when the request names its media type', async () => {
|
||||
const value: Awaited<ReturnType<FileUploads['uploadImageStream']>> = {
|
||||
receiptId: 'receipt-2' as never,
|
||||
image: { attachmentId: 'image-1' as never, mediaType: 'image/png', bytes: 2, width: 1, height: 1 },
|
||||
}
|
||||
const imageChunks: Uint8Array[] = []
|
||||
const uploadImageStream = vi.fn<FileUploads['uploadImageStream']>(async (input) => {
|
||||
for await (const chunk of input.data) imageChunks.push(chunk)
|
||||
return value
|
||||
})
|
||||
const service = Object.assign(uploads(Promise.resolve({})), { uploadImageStream })
|
||||
const response = await handleFileUploadHttp(service, request({
|
||||
sessionId: 's1', name: 'shot.png', mediaType: 'image/png',
|
||||
contentType: 'application/octet-stream', body: Uint8Array.of(7, 8),
|
||||
}))
|
||||
expect(service.uploadStream).not.toHaveBeenCalled()
|
||||
expect(uploadImageStream.mock.calls[0]?.[0]).toMatchObject({ sessionId: 's1', name: 'shot.png', mediaType: 'image/png' })
|
||||
expect(imageChunks).toEqual([Uint8Array.of(7, 8)])
|
||||
expect(await response.json()).toEqual({ ok: true, value })
|
||||
})
|
||||
|
||||
it('returns business and internal storage failures and keeps an absent name absent', async () => {
|
||||
const business = uploads(Promise.reject(new RemoteError(
|
||||
'session/attachment-invalid', 'denied', { reason: 'NOPE' },
|
||||
|
||||
@@ -492,4 +492,53 @@ describe('Session-addressed file upload', () => {
|
||||
})
|
||||
await failed.fiber.dispose()
|
||||
})
|
||||
|
||||
it('uploads an image with its media type and parses the stored image', async () => {
|
||||
const image = {
|
||||
attachmentId: 'image-1', mediaType: 'image/png', bytes: 4, width: 2, height: 2,
|
||||
name: 'shot.png', originalDimensions: { width: 4, height: 4 },
|
||||
}
|
||||
const fetch = vi.fn(() => Promise.resolve(new Response(JSON.stringify({
|
||||
ok: true, value: { receiptId: 'receipt-2', image },
|
||||
}), { status: 200 })))
|
||||
;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = { fetch }
|
||||
const { fiber, service } = await scopedService()
|
||||
const file = new Blob(['data'], { type: 'image/png' })
|
||||
await expect(service.uploadImage(SESSION_ID, file, 'image/png', 'shot.png')).resolves.toEqual({
|
||||
ok: true, value: { receiptId: 'receipt-2', image },
|
||||
})
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'api/session/uploadFileBinary?sessionId=s1&mediaType=image%2Fpng&name=shot.png',
|
||||
expect.objectContaining({ method: 'POST', body: file }),
|
||||
)
|
||||
await fiber.dispose()
|
||||
|
||||
const plain = { attachmentId: 'image-2', mediaType: 'image/webp', bytes: 1, width: 1, height: 1 }
|
||||
;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = {
|
||||
fetch: () => Promise.resolve(new Response(JSON.stringify({
|
||||
ok: true, value: { receiptId: 'receipt-4', image: plain },
|
||||
}), { status: 200 })),
|
||||
}
|
||||
const unnamed = await scopedService()
|
||||
await expect(unnamed.service.uploadImage(SESSION_ID, file, 'image/webp')).resolves.toEqual({
|
||||
ok: true, value: { receiptId: 'receipt-4', image: plain },
|
||||
})
|
||||
await unnamed.fiber.dispose()
|
||||
|
||||
for (const malformed of [
|
||||
null,
|
||||
{ receiptId: 'receipt-3', image: { ...image, mediaType: 'image/bmp' } },
|
||||
{ receiptId: 'receipt-3', image: { ...image, width: -1 } },
|
||||
{ receiptId: 'receipt-3', image: { ...image, name: 3 } },
|
||||
{ receiptId: 'receipt-3', image: { ...image, originalDimensions: { width: 1 } } },
|
||||
]) {
|
||||
;(globalThis as UploadGlobal).__DSH_FILE_UPLOAD__ = {
|
||||
fetch: () => Promise.resolve(new Response(JSON.stringify({ ok: true, value: malformed }), { status: 200 })),
|
||||
}
|
||||
const rejected = await scopedService()
|
||||
await expect(rejected.service.uploadImage(SESSION_ID, file, 'image/png'))
|
||||
.rejects.toThrow('file upload transport returned an invalid image receipt')
|
||||
await rejected.fiber.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -13,11 +13,11 @@ describe('locale host', () => {
|
||||
const ctx = new Context()
|
||||
const configuration = await liveConfig(ctx, { Config, apply })
|
||||
const { fiber } = configuration
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({})
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({})
|
||||
await configuration.update({ preference: 'en' })
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ preference: 'en' })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ preference: 'en' })
|
||||
await configuration.update({ preference: 'pt-BR' })
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ preference: 'pt-BR' })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ preference: 'pt-BR' })
|
||||
await expect(configuration.update({ preference: 'bad locale' })).rejects.toThrow()
|
||||
await expect(configuration.update({ preference: '123' })).rejects.toThrow()
|
||||
await fiber.dispose()
|
||||
|
||||
@@ -161,7 +161,7 @@ it('streams live policy changes and rejects intake disabled during identity look
|
||||
const next = iterator.next()
|
||||
// Loader commits the stable Config reference before publishing this notification.
|
||||
const { updateVolatile, createVolatile } = await import('../../../../vendor/cosmokit/src/volatile.ts')
|
||||
const config = b.fiber.config as import('../src/index.ts').Config
|
||||
const config = b.fiber.effectiveConfig as import('../src/index.ts').Config
|
||||
updateVolatile(config.enabled, createVolatile(false))
|
||||
b.fiber.ctx.emit('loader/volatile-update', [['enabled']])
|
||||
expect(await next).toEqual({ value: false, done: false })
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: df47b6abd789dcb5
|
||||
zh: 7e17c7f18631a572
|
||||
/deepseek-ai-dsh-client-ui-attachment/use-this-package/draft-attachments:
|
||||
en: a77c8ec48e219aec
|
||||
zh: 756d4fe881403006
|
||||
en: 8246cb3c470e3fc5
|
||||
zh: 7028cf466a832b99
|
||||
/deepseek-ai-dsh-client-ui-attachment/use-this-package/message-images-and-the-lightbox:
|
||||
en: 38717dbf90a2520d
|
||||
zh: b81915d2b06e18f8
|
||||
|
||||
@@ -31,7 +31,7 @@ Mount this plugin alongside [`ui-conversation`](../ui-conversation/README.md) an
|
||||
|
||||
### Draft attachments
|
||||
|
||||
Images and generic files retain pick order in one non-wrapping horizontal rail. Every item is 64px high: an image is a 64px square thumbnail, while a generic file is a 240px-wide DeepSeek Web card with a 16px radius, blue gradient document glyph, filename, and uppercase extension plus byte size. Edge arrows page hidden overflow, the scrollbar stays hidden, and a newly added item is revealed at the rail's end. Uploading replaces a file glyph with a spinner and shows byte progress when the carrier reports it, with an indeterminate bar before the first report; failure shows retry, and removal controls appear on hover or keyboard focus while remaining visible on touch devices. Clicking an image opens the original.
|
||||
Images and generic files retain pick order in one non-wrapping horizontal rail. Every item is 64px high: an image is a 64px square thumbnail, while a generic file is a 240px-wide DeepSeek Web card with a 16px radius, blue gradient document glyph, filename, and uppercase extension plus byte size. Edge arrows page hidden overflow, the scrollbar stays hidden, and a newly added item is revealed at the rail's end. Uploading replaces a file glyph with a spinner and shows byte progress when the carrier reports it, with an indeterminate bar before the first report; failure shows retry, and removal controls appear on hover or keyboard focus while remaining visible on touch devices. An uploading image shows the same progress bar along its thumbnail's bottom edge, and a failed image upload turns the thumbnail into its retry control, except an image the Host refused, whose thumbnail explains the refusal in a tooltip that a tap or click also pins and leaves removal as the way out. Clicking an image opens the original.
|
||||
|
||||
### Message images and the lightbox
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ kind: "package-reference"
|
||||
|
||||
### 草稿附件
|
||||
|
||||
图片与通用文件按选择顺序进入同一条不换行的横向附件栏。所有条目均为 64px 高:图片是 64px 方形缩略图,通用文件是 240px 宽的 DeepSeek Web 卡片,带 16px 圆角、蓝色渐变文档图标、文件名,以及大写扩展名与字节大小。溢出隐藏时由边缘箭头翻页,滚动条保持隐藏,新增条目会滚动到栏尾展示。文件上传时图标位置显示 spinner,传输层报告字节时显示进度,首次报告前使用不定态进度条;失败时显示重试。移除按钮在悬停或键盘聚焦时出现,在触摸设备上保持可见。单击图片会打开原图。
|
||||
图片与通用文件按选择顺序进入同一条不换行的横向附件栏。所有条目均为 64px 高:图片是 64px 方形缩略图,通用文件是 240px 宽的 DeepSeek Web 卡片,带 16px 圆角、蓝色渐变文档图标、文件名,以及大写扩展名与字节大小。溢出隐藏时由边缘箭头翻页,滚动条保持隐藏,新增条目会滚动到栏尾展示。文件上传时图标位置显示 spinner,传输层报告字节时显示进度,首次报告前使用不定态进度条;失败时显示重试。上传中的图片在缩略图底边显示同样的进度条,上传失败的图片缩略图变成重试控件;Host 拒绝的图片则用缩略图的提示说明原因,点按也能固定该提示,只能移除。移除按钮在悬停或键盘聚焦时出现,在触摸设备上保持可见。单击图片会打开原图。
|
||||
|
||||
### 消息图片与灯箱
|
||||
|
||||
|
||||
@@ -30,6 +30,57 @@
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.thumbnailFailed {
|
||||
border-color: var(--dsw-alias-state-error-primary, #d54941);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.thumbnailFailed img {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.thumbnailRefused {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.failureGlyph {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--dsw-alias-state-error-primary, #d54941);
|
||||
}
|
||||
|
||||
.progressTrack {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
bottom: 6px;
|
||||
left: 8px;
|
||||
overflow: hidden;
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
background: var(--dsw-alias-fill-tertiary, rgba(0, 0, 0, 0.08));
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.progressBar {
|
||||
display: block;
|
||||
width: 35%;
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: var(--dsw-alias-brand-primary, #4d6bfe);
|
||||
animation: image-upload-progress 1.2s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
.progressBar[style] {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
@keyframes image-upload-progress {
|
||||
from { transform: translateX(-70%); }
|
||||
to { transform: translateX(220%); }
|
||||
}
|
||||
|
||||
.remove {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
@@ -70,4 +121,8 @@
|
||||
.remove {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.progressBar {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type {
|
||||
ComposerAttachment, ComposerAttachmentsProps, ComposerImageAttachment,
|
||||
} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { IconCloseFillRegular } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import {
|
||||
IconCloseFillRegular, IconRefreshOutlineRegular, IconWarningOutlineRegular, Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { AttachmentRail } from '../AttachmentRail.tsx'
|
||||
import type { AttachmentRailItem } from '../AttachmentRail.tsx'
|
||||
import { DropOverlay } from '../DropOverlay.tsx'
|
||||
@@ -23,10 +25,15 @@ export interface ComposerAttachmentsInjected {
|
||||
readonly readFileDrag: (transfer: DataTransfer) => File | undefined
|
||||
}
|
||||
|
||||
/** The owner share and locale seat the attachment rail reads from its slot props. */
|
||||
type ComposerAttachmentsInput = Pick<ComposerAttachmentsProps,
|
||||
| 'attachments' | 'canAcceptDrop' | 'onAddFiles' | 'onRemoveAttachment' | 'uploads' | 'onRetryFile'
|
||||
| 'uploadFailureText' | 'dropLimits' | 't'>
|
||||
|
||||
/** Draft image previews, pending-file cards, drop target, and original-image preview. */
|
||||
export function ComposerAttachments({
|
||||
attachments, canAcceptDrop, onAddFiles, onRemoveAttachment, uploads, onRetryFile, dropLimits, t, readFileDrag,
|
||||
}: ComposerAttachmentsProps & InjectFace<ComposerAttachmentsInjected>) {
|
||||
attachments, canAcceptDrop, onAddFiles, onRemoveAttachment, uploads, onRetryFile, uploadFailureText, dropLimits, t, readFileDrag,
|
||||
}: ComposerAttachmentsInput & InjectFace<ComposerAttachmentsInjected>) {
|
||||
const [preview, setPreview] = useState<ComposerImageAttachment | null>(null)
|
||||
const [dragActive, setDragActive] = useState(false)
|
||||
const dragDepth = useRef(0)
|
||||
@@ -77,20 +84,68 @@ export function ComposerAttachments({
|
||||
/>
|
||||
)
|
||||
}
|
||||
// An uploading image shows its progress; a failed upload turns the thumbnail into its retry
|
||||
// control, except one the Host refused, which explains why and leaves removal as the way out.
|
||||
// The refusal is the only explanation of its warning, so a tap or click also pins it.
|
||||
const upload = uploads[attachment.id]
|
||||
const name = attachment.file.name || t('image.pending')
|
||||
const refusal = upload?.status === 'error' && upload.reason !== undefined
|
||||
? uploadFailureText(upload.reason)
|
||||
: undefined
|
||||
return (
|
||||
<div className={css.imageItem}>
|
||||
<button
|
||||
type="button"
|
||||
className={css.thumbnail}
|
||||
title={t('image.openOriginal')}
|
||||
onClick={() => { setPreview(attachment) }}
|
||||
>
|
||||
<img src={attachment.previewUrl} alt={attachment.file.name || t('image.pending')} />
|
||||
</button>
|
||||
{refusal !== undefined
|
||||
? (
|
||||
<Tooltip label={refusal} side="top" delayMs={300} portal openOnClick>
|
||||
<button
|
||||
type="button"
|
||||
className={`${css.thumbnail} ${css.thumbnailFailed} ${css.thumbnailRefused}`}
|
||||
aria-label={refusal}
|
||||
>
|
||||
<img src={attachment.previewUrl} alt="" />
|
||||
<span className={css.failureGlyph} aria-hidden><IconWarningOutlineRegular size={16} /></span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
: upload?.status === 'error'
|
||||
? (
|
||||
<Tooltip label={t('file.uploadFailed')} side="top" delayMs={300} portal>
|
||||
<button
|
||||
type="button"
|
||||
className={`${css.thumbnail} ${css.thumbnailFailed}`}
|
||||
aria-label={t('file.retry', { name })}
|
||||
onClick={() => { onRetryFile(attachment.id) }}
|
||||
>
|
||||
<img src={attachment.previewUrl} alt="" />
|
||||
<span className={css.failureGlyph} aria-hidden><IconRefreshOutlineRegular size={16} /></span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
: (
|
||||
<button
|
||||
type="button"
|
||||
className={css.thumbnail}
|
||||
title={t('image.openOriginal')}
|
||||
aria-busy={upload?.status === 'uploading'}
|
||||
onClick={() => { setPreview(attachment) }}
|
||||
>
|
||||
<img src={attachment.previewUrl} alt={name} />
|
||||
</button>
|
||||
)}
|
||||
{upload?.status === 'uploading' && (
|
||||
<span className={css.progressTrack} aria-hidden>
|
||||
<span
|
||||
className={css.progressBar}
|
||||
style={upload.total === undefined || upload.total <= 0
|
||||
? undefined
|
||||
: { width: `${String(Math.min(1, upload.loaded / upload.total) * 100)}%` }}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={css.remove}
|
||||
aria-label={t('image.remove', { name: attachment.file.name })}
|
||||
aria-label={t('image.remove', { name })}
|
||||
onClick={() => { onRemoveAttachment(attachment.id) }}
|
||||
>
|
||||
<IconCloseFillRegular size={12} />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import { act, cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import type {
|
||||
ComposerAttachment, ComposerAttachmentsOwnerProps, ComposerAttachmentsProps,
|
||||
} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
@@ -74,34 +74,15 @@ function fileDraft(id: string, name = `${id}.pdf`): ComposerAttachment {
|
||||
}
|
||||
}
|
||||
|
||||
type AttachmentProps = ComposerAttachmentsProps & import('@deepseek-ai/dsh-client-ui-slots').InjectFace<import('../src/client/ComposerAttachments.tsx').ComposerAttachmentsInjected>
|
||||
|
||||
const unusedHook = (): never => { throw new Error('Attachment view must use its supplied owner props') }
|
||||
|
||||
function props(overrides: Partial<ComposerAttachmentsOwnerProps> = {}): AttachmentProps {
|
||||
function props(overrides: Partial<ComposerAttachmentsOwnerProps> = {}): Parameters<typeof ComposerAttachments>[0] {
|
||||
return {
|
||||
sessionId: undefined,
|
||||
useSession: unusedHook,
|
||||
useProjection: unusedHook,
|
||||
useAccess: unusedHook,
|
||||
useConversation: unusedHook,
|
||||
useInput: unusedHook,
|
||||
inputActions: undefined,
|
||||
useSessions: unusedHook,
|
||||
useSessionStatus: unusedHook,
|
||||
useSessionRetainInfo: unusedHook,
|
||||
useSessionAccess: unusedHook,
|
||||
useWorkspaces: unusedHook,
|
||||
useWorkspaceAccess: unusedHook,
|
||||
useRemoteAccess: unusedHook,
|
||||
useResource: unusedHook,
|
||||
usePanelInfo: unusedHook,
|
||||
attachments: [],
|
||||
canAcceptDrop: true,
|
||||
onAddFiles: () => {},
|
||||
onRemoveAttachment: () => {},
|
||||
uploads: {},
|
||||
onRetryFile: () => {},
|
||||
uploadFailureText: (reason: string) => `refused:${reason}`,
|
||||
t,
|
||||
...overrides,
|
||||
readFileDrag: () => undefined,
|
||||
@@ -250,6 +231,77 @@ describe('ComposerAttachments', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ComposerAttachments image uploads', () => {
|
||||
it('shows image upload progress, retries a failed image, and explains one the Host refused', () => {
|
||||
const onRetryFile = vi.fn()
|
||||
const view = render(<ComposerAttachments {...props({
|
||||
attachments: [
|
||||
attachment('measured'), attachment('streaming'), attachment('failed'), attachment('refused'), attachment('ready'),
|
||||
],
|
||||
uploads: {
|
||||
measured: { status: 'uploading', loaded: 1, total: 2 },
|
||||
streaming: { status: 'uploading', loaded: 3 },
|
||||
failed: { status: 'error', message: 'boom' },
|
||||
refused: { status: 'error', message: 'too wide', reason: 'IMAGE_DIMENSION_TOO_LARGE' },
|
||||
ready: { status: 'ready', receiptId: 'receipt-ready' as never },
|
||||
},
|
||||
onRetryFile,
|
||||
})} />)
|
||||
expect(view.container.querySelector('[style="width: 50%;"]')).toBeTruthy()
|
||||
expect(view.getAllByTitle('查看原图').map(button => button.getAttribute('aria-busy')))
|
||||
.toEqual(['true', 'true', 'false'])
|
||||
fireEvent.click(view.getByRole('button', { name: '重试上传 failed.png' }))
|
||||
expect(onRetryFile).toHaveBeenCalledWith('failed')
|
||||
// A refusal names its reason and offers neither retry nor preview; removal stays available.
|
||||
fireEvent.click(view.getByRole('button', { name: 'refused:IMAGE_DIMENSION_TOO_LARGE' }))
|
||||
expect(onRetryFile).toHaveBeenCalledTimes(1)
|
||||
expect(view.queryByRole('button', { name: '重试上传 refused.png' })).toBeNull()
|
||||
expect(view.getByRole('button', { name: '移除图片 refused.png' })).toBeTruthy()
|
||||
expect(view.queryByRole('dialog', { name: '原图预览' })).toBeNull()
|
||||
})
|
||||
|
||||
it('explains a failed image on hover and pins a refusal on tap', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const view = render(<ComposerAttachments {...props({
|
||||
attachments: [attachment('failed'), attachment('refused')],
|
||||
uploads: {
|
||||
failed: { status: 'error', message: 'boom' },
|
||||
refused: { status: 'error', message: 'too wide', reason: 'IMAGE_DIMENSION_TOO_LARGE' },
|
||||
},
|
||||
})} />)
|
||||
// The stubbed ResizeObserver never measures, so the bubble mounts unplaced and hidden.
|
||||
const bubble = () => view.queryByRole('tooltip', { hidden: true })
|
||||
const retry = view.getByRole('button', { name: '重试上传 failed.png' })
|
||||
fireEvent.pointerEnter(retry)
|
||||
expect(bubble()).toBeNull()
|
||||
act(() => { vi.advanceTimersByTime(300) })
|
||||
expect(bubble()?.textContent).toBe('上传失败,点击重试')
|
||||
fireEvent.pointerLeave(retry)
|
||||
expect(bubble()).toBeNull()
|
||||
|
||||
const refused = view.getByRole('button', { name: 'refused:IMAGE_DIMENSION_TOO_LARGE' })
|
||||
fireEvent.click(refused)
|
||||
expect(bubble()?.textContent).toBe('refused:IMAGE_DIMENSION_TOO_LARGE')
|
||||
expect(refused.getAttribute('aria-describedby')).toBe(bubble()?.id)
|
||||
fireEvent.pointerLeave(refused)
|
||||
expect(bubble()?.textContent).toBe('refused:IMAGE_DIMENSION_TOO_LARGE')
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('names an image without a file name in its preview, retry, and remove controls', () => {
|
||||
const view = render(<ComposerAttachments {...props({
|
||||
attachments: [attachment('pasted', ''), attachment('shown', '')],
|
||||
uploads: { pasted: { status: 'error', message: 'boom' } },
|
||||
})} />)
|
||||
expect(view.getByRole('button', { name: '重试上传 待发送图片' })).toBeTruthy()
|
||||
expect(view.getAllByRole('button', { name: '移除图片 待发送图片' })).toHaveLength(2)
|
||||
expect(view.getByAltText('待发送图片')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ComposerAttachments file drafts', () => {
|
||||
it('renders uploading, ready, and failed cards with remove and retry affordances', () => {
|
||||
const onRemoveAttachment = vi.fn()
|
||||
|
||||
@@ -14,26 +14,26 @@ describe('ui-chat Host settings', () => {
|
||||
const configuration = await liveConfig(ctx, { Config, apply })
|
||||
const { fiber } = configuration
|
||||
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({
|
||||
performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion', foldedReplies: 'all',
|
||||
})
|
||||
await configuration.update({ transcriptView: 'normal' })
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({
|
||||
transcriptView: 'normal', performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion', foldedReplies: 'all',
|
||||
})
|
||||
for (const mode of ['expanded', 'compact', 'standard', 'detailed', 'verbose']) {
|
||||
await configuration.update({ transcriptView: mode })
|
||||
expect(plainConfig(configuration.fiber.config)).toMatchObject({ transcriptView: mode })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ transcriptView: mode })
|
||||
}
|
||||
for (const mode of ['dense', '', 42, false, {}, null, undefined]) {
|
||||
await configuration.update({ transcriptView: mode })
|
||||
expect(plainConfig(configuration.fiber.config)).toMatchObject({ transcriptView: mode === null ? null : undefined })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ transcriptView: mode === null ? null : undefined })
|
||||
}
|
||||
await configuration.update({ performanceUsage: 'compact' })
|
||||
expect(plainConfig(configuration.fiber.config)).toMatchObject({ performanceUsage: 'compact' })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ performanceUsage: 'compact' })
|
||||
await expect(configuration.update({ performanceUsage: 'hidden' })).rejects.toThrow()
|
||||
await configuration.update({ linkOpening: 'new-tab' })
|
||||
expect(plainConfig(configuration.fiber.config)).toMatchObject({ linkOpening: 'new-tab' })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ linkOpening: 'new-tab' })
|
||||
await expect(configuration.update({ linkOpening: 'popup' })).rejects.toThrow()
|
||||
|
||||
await fiber.dispose()
|
||||
@@ -42,15 +42,15 @@ describe('ui-chat Host settings', () => {
|
||||
it('validates collapse timing and restores its saved config independently of work details', async () => {
|
||||
const ctx = new Context()
|
||||
const configuration = await liveConfig(ctx, { Config, apply })
|
||||
expect(plainConfig(configuration.fiber.config)).toMatchObject({ collapseTiming: 'completion' })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ collapseTiming: 'completion' })
|
||||
await configuration.update({ transcriptView: 'compact', collapseTiming: 'next-input' })
|
||||
const saved = plainConfig(configuration.fiber.config)
|
||||
const saved = plainConfig(configuration.fiber.effectiveConfig)
|
||||
if (typeof saved !== 'object' || saved === null) throw new Error('expected saved configuration object')
|
||||
expect(saved).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' })
|
||||
await expect(configuration.update({ collapseTiming: 'never' })).rejects.toThrow()
|
||||
await configuration.fiber.dispose()
|
||||
const restored = await liveConfig(ctx, { Config, apply }, saved)
|
||||
expect(plainConfig(restored.fiber.config)).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' })
|
||||
expect(plainConfig(restored.fiber.effectiveConfig)).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' })
|
||||
await restored.fiber.dispose()
|
||||
})
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 7871f9fe6bcc4459
|
||||
zh: 0d51565c600b3958
|
||||
/deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props:
|
||||
en: 457e642073206f7d
|
||||
zh: 95ea47c204850314
|
||||
en: 1d70d520d4a7537c
|
||||
zh: 83febffaf90e0ac5
|
||||
/deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries:
|
||||
en: bb1244310f5c0382
|
||||
zh: 824b84077432b559
|
||||
|
||||
@@ -112,7 +112,7 @@ Clicking unused space inside an editable composer preserves its current caret or
|
||||
|
||||
Each composer attempt carries its original occurrence time, gesture, delivery intent, and Session model/run-state snapshot through asynchronous command arbitration. The snapshot also records whether the Session is still blank and the Agent preset id the Session records. The ordinary-message notification fires once before reference serialization, including attachment-only submissions; handled or claimed commands do not notify. Snapshot and notification failures cannot block sending. On Desktop, the notification reports `send_button_click`, which carries `is_new_session` (true while the Session is blank) and `agent_preset`, the preset category: `creator` for `cordis`; `ptc`, `minimal`, and `standard` under their own ids; `other` for any other preset. `agent_preset` is omitted while the Session records no preset. Custom preset ids are not sent.
|
||||
|
||||
Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint, encodes images through the browser's native `FileReader` data-URL path, and cites staged file receipts. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files enter one FIFO background-upload queue; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`.
|
||||
Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing, preserving selected image and file order in `pendingSubmissions`; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and cites the staged receipts of files and uploaded images; an image without an upload, as in a continuable subagent's draft, is encoded through the browser's native `FileReader` data-URL path. Command submissions use the same receipts for generic files, so sending `/goal` or `/plan` never reads those browser files again. The prompt reuses the submission `requestId`; Session retires the echo once at its display handoff, correlated by that `rpcId`. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their attachment ids through admission and Session scope disposal. An observed retirement immediately exposes each image preview through the durable cache, replaces it with the canonical URL after fetching the admitted attachment, revokes each URL after its use ends, and releases file cards. Selected generic files, and the images of an ordinary Session's draft, enter one FIFO background-upload queue as soon as they are added, and Send waits until each has a receipt; `maxConcurrentFileUploads` defaults to two active Worker transports, the Conversation service retains queued and active operations plus byte progress across Session navigation, and removing a draft skips its queued transfer or aborts its active transport. Where the browser shell exposes `__DSH_HOST_PATHS__` (the Desktop application), dropped or pasted folders and dropped, picked, or pasted non-image files with a real path become `@path` chips; images keep uploading. Drag-and-drop and paste identify directories through the browser entry API; when that API is absent or returns no entry, pasted items retain ordinary file handling. The file picker cannot select directories. References require the `ui-reference` plugin and the original paths to remain readable by the model's file tools. Paths inside the workspace are relative; others remain absolute. The whole batch is validated before insertion, retains source order and selected text, and uses whitespace-separated, closed-quote mentions. A browser without the bridge refuses dropped or pasted folders; a Desktop folder without a reported path is rejected separately. Continuable subagents accept pasted and dropped PNG, JPEG, WebP, and GIF images with the same projected limits and send them inline, because the Host stages uploads only for ordinary Sessions; a batch containing a generic file, unsupported image format, or directory is refused before intake. Their sends register the same local echo; the continuation request carries the echo's `requestId`, which the Host records as the child message's `rpcId`.
|
||||
|
||||
Queued submission echoes show “Sending…” beside disabled edit, remove, and steer buttons; a collapsed dock keeps the sending status in its header. A matching Host queue row replaces the echo and enables each action according to its normal text-content and running-state requirements. Prompt acknowledgement alone does not enable queue actions. A failed submission removes its echo and displays an error; the composer restores the failed draft when it is empty or still contains the previous automatic restoration, preserving subsequently typed text.
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染
|
||||
|
||||
每次输入框提交都携带原始发生时间、操作来源、投递意图以及会话模型和运行状态快照,贯穿异步命令裁决。快照还记录会话是否仍为空白,以及会话记录的 Agent preset id。普通消息通知在引用序列化前发出一次,纯附件提交也遵循这一规则;已处理或认领的命令不发出通知。快照读取与通知消费异常不能阻断发送。在桌面端,该通知报告 `send_button_click`,携带 `is_new_session`(会话为空白时为 true)和表示 preset 类别的 `agent_preset`:`cordis` 记为 `creator`;`ptc`、`minimal` 与 `standard` 沿用各自的 id;其他 preset 记为 `other`。会话未记录 preset 时省略 `agent_preset`。不发送自定义 preset 的 id。
|
||||
|
||||
默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码,文件则引用已暂存凭证。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件进入同一个先进先出的后台上传队列;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,并沿用相同的投影限制;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。
|
||||
默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`),并在 `pendingSubmissions` 中保留图片与文件的选择顺序;Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript(文本记录),繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,文件和已上传的图片引用已暂存凭证;没有上传的图片(例如 continuable 子代理草稿里的图片)经浏览器原生 `FileReader` data-URL 路径编码。命令提交也用同一凭证表示通用文件,因此发送 `/goal` 或 `/plan` 时不会再次读取这些浏览器文件。提示词复用提交 `requestId`;Session 按同一 `rpcId` 关联展示接管,并仅退休回显一次。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有附件 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开每个预览 URL,读取 admitted 附件后用规范化 URL 替换预览,并在各 URL 停止使用后撤销,同时释放文件卡。选中的通用文件以及普通 Session 草稿里的图片在加入时就进入同一个先进先出的后台上传队列,发送会等到每一项都取得凭证;`maxConcurrentFileUploads` 默认允许两个 Worker transport 同时运行,Conversation 服务在切换 Session 时继续持有排队和运行中的传输操作及字节进度,移除草稿会跳过排队中的传输或中止正在运行的传输。浏览器 shell 暴露 `__DSH_HOST_PATHS__` 时(桌面应用),拖入或粘贴的文件夹以及拖入、选择或粘贴的带真实路径的非图片文件会成为 `@路径` chip;图片仍然上传。拖放和粘贴通过浏览器 entry API 识别目录;该 API 不可用或没有返回 entry 时,粘贴项沿用普通文件处理。文件选择器不能选择目录。引用需要启用 `ui-reference` 插件,原路径也必须仍可由模型的文件工具读取。工作区内的路径使用相对形式,其他路径保留绝对形式。整批文件先校验再插入,保留来源顺序和已选中的文字,引用之间有空白分隔,含空格的路径使用闭合引号。没有该桥的浏览器会拒绝拖入或粘贴的文件夹,桌面端无法获取文件夹路径时单独报错。continuable 子代理允许粘贴和拖入 PNG、JPEG、WebP、GIF 图片,沿用相同的投影限制并以内联方式发送,因为 Host 只为普通 Session 暂存上传;包含通用文件、不支持的图片格式或目录的批次会在进入草稿前整批拒绝。它们的发送同样注册本地回显;continuation 请求携带回显的 `requestId`,Host 把它记录为子会话消息的 `rpcId`。
|
||||
|
||||
排队提交的本地回显在禁用的编辑、删除、插话按钮旁显示“发送中…”;折叠后的队列在标题栏保留发送状态。匹配的 Host 队列行替换回显后,各操作按原有的纯文本内容和运行状态要求启用。仅收到提示词确认不会启用队列操作。提交失败会移除回显并显示错误;输入框为空或仍保留上一次自动恢复的内容时,composer 恢复失败草稿,保留用户随后输入的文字。
|
||||
|
||||
|
||||
@@ -368,10 +368,13 @@ export function apply(ctx: Context, config: Config = Config({})): void {
|
||||
const attachmentIds = from.snapshot.attachmentIds
|
||||
const next = inputHub.shell(nextId)
|
||||
if (attachmentIds.length === 0 || next.addAttachments(attachmentIds)) {
|
||||
if (sessions.binding(nextId) === undefined) {
|
||||
const binding = sessions.binding(nextId)
|
||||
if (binding === undefined) {
|
||||
throw new Error(`ui-conversation: session "${nextId}" resolved no binding`)
|
||||
}
|
||||
concreteConversation(ctx).rebindDraftFiles(nextId, attachmentIds)
|
||||
// The same rule as intake: only an ordinary Session stages image uploads.
|
||||
const ordinary = binding.session.getSnapshot().subagent === null
|
||||
concreteConversation(ctx).rebindDraftFiles(nextId, attachmentIds, ordinary)
|
||||
if (draft.text !== '') {
|
||||
next.setDraft(draft)
|
||||
from.setDraft('')
|
||||
@@ -521,7 +524,9 @@ export function apply(ctx: Context, config: Config = Config({})): void {
|
||||
})
|
||||
}
|
||||
try {
|
||||
const drafts = conversation.createDrafts(sessionId, uploads)
|
||||
// The Host stages uploads for ordinary Sessions only; a subagent continuation's images travel inline.
|
||||
const ordinary = sessions.binding(sessionId)?.session.getSnapshot().subagent === null
|
||||
const drafts = conversation.createDrafts(sessionId, uploads, ordinary)
|
||||
if (!shell.addFiles(references, drafts.map(draft => draft.id))) {
|
||||
conversation.releaseDraftAttachments(drafts)
|
||||
return t('attachment.dropBlocked')
|
||||
|
||||
@@ -28,7 +28,11 @@ import type { UserTextDocumentInput, UserTextEvaluator, UserTextId, UserTextNode
|
||||
/** Browser-owned draft attachment that has not crossed the durable Host boundary. */
|
||||
export type ComposerAttachment = ComposerImageAttachment | ComposerFileAttachment
|
||||
|
||||
/** Browser-owned image, base64-encoded into the prompt at send time. */
|
||||
/**
|
||||
* Browser-owned image. An ordinary Session's draft uploads it to the Host as
|
||||
* soon as it is added, and the prompt cites the receipt; a subagent
|
||||
* continuation's draft base64-encodes it into the prompt at send time.
|
||||
*/
|
||||
export interface ComposerImageAttachment {
|
||||
kind: 'image'
|
||||
id: DraftAttachmentId
|
||||
@@ -47,11 +51,17 @@ export interface ComposerFileAttachment {
|
||||
file: File
|
||||
}
|
||||
|
||||
/** Upload lifecycle of one picked file draft (files upload on pick, not on send). */
|
||||
/**
|
||||
* Upload lifecycle of one draft that uploads when it is added, not on send:
|
||||
* every file draft, and every image draft of an ordinary Session. A failed
|
||||
* upload the Host refused keeps the attachment refusal `reason`, because
|
||||
* retrying the same bytes cannot succeed.
|
||||
*/
|
||||
export type DraftFileUpload =
|
||||
| { readonly status: 'uploading'; readonly loaded: number; readonly total?: number }
|
||||
| { readonly status: 'ready'; readonly receiptId: FileUploadReceiptId; readonly file: FileAttachmentRef }
|
||||
| { readonly status: 'error'; readonly message: string }
|
||||
| { readonly status: 'ready'; readonly receiptId: FileUploadReceiptId }
|
||||
| { readonly status: 'error'; readonly message: string; readonly reason?: string }
|
||||
|
||||
/** Per-draft upload states keyed by draft attachment id. */
|
||||
export type DraftFileUploads = Readonly<Record<string, DraftFileUpload>>
|
||||
@@ -74,6 +84,13 @@ export interface ComposerAttachmentsOwnerProps {
|
||||
uploads: DraftFileUploads
|
||||
/** Restart one failed file upload. */
|
||||
onRetryFile: (id: DraftAttachmentId) => void
|
||||
/**
|
||||
* Explain one upload the Host refused; such a draft cannot be retried and
|
||||
* stays until it is removed.
|
||||
* @param reason - the refusal `reason` the failed upload carries.
|
||||
* @returns localized text naming the limit or the way out.
|
||||
*/
|
||||
uploadFailureText: (reason: string) => string
|
||||
/** Display-ready limits for the drop invitation. */
|
||||
dropLimits?: { readonly count: number; readonly size: string } | undefined
|
||||
}
|
||||
@@ -518,7 +535,7 @@ export interface ComposerBarInjected {
|
||||
* and the primary Send button use while the addressed agent is busy.
|
||||
*/
|
||||
busyEnter: ObservableSnapshot<BusyEnterBehavior>
|
||||
/** Live per-draft upload states for file-kind drafts. */
|
||||
/** Live per-draft upload states for drafts that upload when added. */
|
||||
fileUploads: ObservableSnapshot<DraftFileUploads>
|
||||
notices: ObservableSnapshot<InputNotice | null>
|
||||
lexicon: ObservableSnapshot<ReadonlyMap<'/' | '@', readonly string[]>>
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import type { MouseEvent, MutableRefObject, RefObject } from 'react'
|
||||
import type { LexicalEditor } from 'lexical'
|
||||
import type { ComposerKeyboard } from '../../contract/draft-editor.ts'
|
||||
import type { ComposerBarProps } from '../../contract/slots.ts'
|
||||
import type { BusyEnterBehavior } from '../../contract/composer-submission.ts'
|
||||
import { resolveSubmitMode } from '../submission-policy.ts'
|
||||
import { registerComposerKeymap } from './keymap.ts'
|
||||
@@ -16,8 +15,9 @@ interface DraftViewGate {
|
||||
busyEnter: BusyEnterBehavior
|
||||
intakeFiles: (files: readonly File[], directories?: ReadonlySet<File>) => void
|
||||
uploadsPending: boolean
|
||||
/** Toast text explaining why pending uploads hold the send. */
|
||||
uploadsHeldText: string
|
||||
showToast: (text: string) => void
|
||||
t: ComposerBarProps['t']
|
||||
canAcceptDrop: boolean
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ export function installDraftKeymap(
|
||||
return
|
||||
}
|
||||
if (g.uploadsPending) {
|
||||
g.showToast(g.t('file.stillUploading'))
|
||||
g.showToast(g.uploadsHeldText)
|
||||
return
|
||||
}
|
||||
keyboard.submit(resolveSubmitMode(
|
||||
|
||||
@@ -18,7 +18,7 @@ import type {
|
||||
} from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-file-upload/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { ImageMediaType } from '@deepseek-ai/dsh-attachment'
|
||||
import type { FileAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type {
|
||||
@@ -155,7 +155,7 @@ export class ConversationController extends Service implements IConversation {
|
||||
readonly input: SessionInputResolver
|
||||
/** The per-session composer-block registry. */
|
||||
readonly blocks: ComposerBlocks
|
||||
/** Live upload state per file-kind draft; images never appear here. */
|
||||
/** Live upload state per draft that uploads when added: every file draft and every uploaded image draft. */
|
||||
readonly fileUploads: SnapshotStore<Record<string, DraftFileUpload>> = createSnapshotStore<Record<string, DraftFileUpload>>({})
|
||||
private readonly draftAttachments = new Map<DraftAttachmentId, ComposerAttachment>()
|
||||
private readonly fileUploadOperations = new Map<DraftAttachmentId, {
|
||||
@@ -238,13 +238,19 @@ export class ConversationController extends Service implements IConversation {
|
||||
throw new Error('conversation.sendSession: one or more draft attachments are no longer available')
|
||||
}
|
||||
const uploads = this.fileUploads.getSnapshot()
|
||||
const uploadFor = (attachment: ComposerFileAttachment): Extract<DraftFileUpload, { status: 'ready' }> => {
|
||||
const uploadFor = (attachment: ComposerAttachment): Extract<DraftFileUpload, { status: 'ready' }> => {
|
||||
const upload = uploads[attachment.id]
|
||||
if (upload === undefined || upload.status !== 'ready') {
|
||||
throw new Error('conversation.sendSession: one or more files have not finished uploading')
|
||||
}
|
||||
return upload
|
||||
}
|
||||
// A file draft's upload always stores a file; only image drafts store an image.
|
||||
const storedFileOf = (attachment: ComposerFileAttachment): FileAttachmentRef =>
|
||||
(uploadFor(attachment) as Extract<DraftFileUpload, { readonly file: FileAttachmentRef }>).file
|
||||
// An image draft without an upload, such as a subagent continuation's, sends its bytes inline.
|
||||
const imageReceipts = new Map(attachments.flatMap(attachment => attachment.kind === 'image'
|
||||
&& uploads[attachment.id] !== undefined ? [[attachment.id, uploadFor(attachment).receiptId] as const] : []))
|
||||
const pendingAttachments = attachments.map(attachment => attachment.kind === 'image'
|
||||
? {
|
||||
type: 'image' as const,
|
||||
@@ -255,11 +261,15 @@ export class ConversationController extends Service implements IConversation {
|
||||
...(attachment.height === undefined ? {} : { height: attachment.height }),
|
||||
},
|
||||
}
|
||||
: { type: 'file' as const, value: uploadFor(attachment).file })
|
||||
: { type: 'file' as const, value: storedFileOf(attachment) })
|
||||
const serializeAttachments = (): Promise<Parameters<SessionFace['prompt']>[0]> => Promise.all(
|
||||
attachments.map(async attachment => attachment.kind === 'image'
|
||||
? { type: 'image' as const, ...await this.encodeImage(attachment.file) }
|
||||
: { type: 'file' as const, receiptId: uploadFor(attachment).receiptId }),
|
||||
attachments.map(async (attachment) => {
|
||||
if (attachment.kind === 'file') return { type: 'file' as const, receiptId: uploadFor(attachment).receiptId }
|
||||
const receiptId = imageReceipts.get(attachment.id)
|
||||
return receiptId === undefined
|
||||
? { type: 'image' as const, ...await this.encodeImage(attachment.file) }
|
||||
: { type: 'file' as const, receiptId }
|
||||
}),
|
||||
)
|
||||
let finishRetirement: ((retirement: PendingSubmissionRetirement) => void) | undefined
|
||||
const retirement = attachments.length === 0
|
||||
@@ -291,20 +301,24 @@ export class ConversationController extends Service implements IConversation {
|
||||
|
||||
/**
|
||||
* Create runtime-only draft attachments. Files whose browser MIME is an
|
||||
* accepted image type become image drafts (object URL preview, bytes sent
|
||||
* with the prompt); every other file becomes a file draft whose background
|
||||
* upload starts immediately and remains owned by this service across Session
|
||||
* navigation until completion or explicit removal.
|
||||
* accepted image type become image drafts with an object URL preview; every
|
||||
* other file becomes a file draft. A file draft's background upload starts
|
||||
* immediately, and so does an image draft's when `uploadImages` is set; the
|
||||
* upload remains owned by this service across Session navigation until
|
||||
* completion or explicit removal. An image draft without an upload sends its
|
||||
* bytes with the prompt.
|
||||
* @param sessionId - target Agent-scope identity.
|
||||
* @param files - browser files to register.
|
||||
* @param uploadImages - whether the Session accepts image uploads; a subagent continuation does not.
|
||||
* @returns ordered draft descriptors.
|
||||
*/
|
||||
createDrafts(sessionId: SessionId, files: readonly File[]): readonly ComposerAttachment[] {
|
||||
createDrafts(sessionId: SessionId, files: readonly File[], uploadImages: boolean): readonly ComposerAttachment[] {
|
||||
return files.map((file) => {
|
||||
if (isImageMediaType(file.type)) {
|
||||
const attachment = browserDraftAttachment(file)
|
||||
this.draftAttachments.set(attachment.id, attachment)
|
||||
probeDimensions(attachment)
|
||||
if (uploadImages) this.beginFileUpload(sessionId, attachment)
|
||||
return attachment
|
||||
}
|
||||
const attachment: ComposerFileAttachment = {
|
||||
@@ -319,30 +333,33 @@ export class ConversationController extends Service implements IConversation {
|
||||
}
|
||||
|
||||
/**
|
||||
* Restart one failed file upload.
|
||||
* Restart one failed file or image upload.
|
||||
* @param sessionId - target Agent-scope identity.
|
||||
* @param id - draft attachment id whose upload previously failed.
|
||||
*/
|
||||
retryFileUpload(sessionId: SessionId, id: DraftAttachmentId): void {
|
||||
const attachment = this.draftAttachments.get(id)
|
||||
if (attachment === undefined || attachment.kind !== 'file') return
|
||||
if (attachment === undefined) return
|
||||
if (this.fileUploads.getSnapshot()[id]?.status !== 'error') return
|
||||
this.beginFileUpload(sessionId, attachment)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage carried file drafts again for a new Session.
|
||||
* Stage carried file and image drafts again for a new Session.
|
||||
* @param sessionId - target Agent-scope identity after a Workspace switch.
|
||||
* @param ids - carried draft attachment ids.
|
||||
* @param uploadImages - whether the target Session stages image uploads; an image draft otherwise sends inline.
|
||||
*/
|
||||
rebindDraftFiles(sessionId: SessionId, ids: readonly DraftAttachmentId[]): void {
|
||||
rebindDraftFiles(sessionId: SessionId, ids: readonly DraftAttachmentId[], uploadImages: boolean): void {
|
||||
for (const id of ids) {
|
||||
const attachment = this.draftAttachments.get(id)
|
||||
if (attachment?.kind === 'file') this.beginFileUpload(sessionId, attachment)
|
||||
if (attachment === undefined) continue
|
||||
if (attachment.kind === 'image' && !uploadImages) this.dropUpload(id)
|
||||
else this.beginFileUpload(sessionId, attachment)
|
||||
}
|
||||
}
|
||||
|
||||
private beginFileUpload(sessionId: SessionId, attachment: ComposerFileAttachment): void {
|
||||
private beginFileUpload(sessionId: SessionId, attachment: ComposerAttachment): void {
|
||||
this.fileUploadOperations.get(attachment.id)?.controller.abort()
|
||||
const controller = new AbortController()
|
||||
this.fileUploads.update((draft) => {
|
||||
@@ -353,33 +370,41 @@ export class ConversationController extends Service implements IConversation {
|
||||
this.fileUploadOperations.set(attachment.id, { controller, done })
|
||||
this.pendingFileUploads.add(done)
|
||||
void done.then(() => { this.pendingFileUploads.delete(done) })
|
||||
const name = attachment.file.name === '' ? undefined : attachment.file.name
|
||||
const onProgress = (progress: { readonly loaded: number; readonly total?: number }): void => {
|
||||
if (this.fileUploadOperations.get(attachment.id)?.controller !== controller) return
|
||||
this.fileUploads.update((draft) => {
|
||||
if (!(attachment.id in draft)) return
|
||||
draft[attachment.id] = {
|
||||
status: 'uploading',
|
||||
loaded: progress.loaded,
|
||||
...(progress.total === undefined ? {} : { total: progress.total }),
|
||||
}
|
||||
})
|
||||
}
|
||||
const run = async (): Promise<void> => {
|
||||
try {
|
||||
if (controller.signal.aborted
|
||||
|| this.fileUploadOperations.get(attachment.id)?.controller !== controller) return
|
||||
const result = await this.ctx.fileUpload.upload(
|
||||
sessionId,
|
||||
attachment.file,
|
||||
attachment.file.name === '' ? undefined : attachment.file.name,
|
||||
controller.signal,
|
||||
(progress) => {
|
||||
if (this.fileUploadOperations.get(attachment.id)?.controller !== controller) return
|
||||
this.fileUploads.update((draft) => {
|
||||
if (!(attachment.id in draft)) return
|
||||
draft[attachment.id] = {
|
||||
status: 'uploading',
|
||||
loaded: progress.loaded,
|
||||
...(progress.total === undefined ? {} : { total: progress.total }),
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
const result = attachment.kind === 'image'
|
||||
? await this.ctx.fileUpload.uploadImage(
|
||||
sessionId, attachment.file, imageMediaType(attachment.file.type), name, controller.signal, onProgress,
|
||||
)
|
||||
: await this.ctx.fileUpload.upload(sessionId, attachment.file, name, controller.signal, onProgress)
|
||||
if (this.fileUploadOperations.get(attachment.id)?.controller !== controller) return
|
||||
this.fileUploads.update((draft) => {
|
||||
if (!(attachment.id in draft)) return
|
||||
draft[attachment.id] = result.ok
|
||||
? { status: 'ready', receiptId: result.value.receiptId, file: result.value.file }
|
||||
: { status: 'error', message: result.error.message }
|
||||
if (result.ok) {
|
||||
draft[attachment.id] = 'file' in result.value
|
||||
? { status: 'ready', receiptId: result.value.receiptId, file: result.value.file }
|
||||
: { status: 'ready', receiptId: result.value.receiptId }
|
||||
return
|
||||
}
|
||||
const { error } = result
|
||||
// A Host refusal keeps its reason: retrying the same bytes cannot succeed.
|
||||
draft[attachment.id] = error.code === 'session/attachment-invalid' || error.code === 'subagent/attachment-invalid'
|
||||
? { status: 'error', message: error.message, reason: error.details.reason }
|
||||
: { status: 'error', message: error.message }
|
||||
})
|
||||
} catch (error) {
|
||||
if (this.fileUploadOperations.get(attachment.id)?.controller !== controller) return
|
||||
@@ -430,8 +455,9 @@ export class ConversationController extends Service implements IConversation {
|
||||
|
||||
/**
|
||||
* Serialize ordered draft attachments to command-submit wire payloads without
|
||||
* sending or releasing them. Images are encoded; generic files cite receipts
|
||||
* from their completed background uploads and never reread browser bytes.
|
||||
* sending or releasing them. Images are encoded even when an upload already
|
||||
* stored them, because commands accept only file receipts; generic files cite
|
||||
* receipts from their completed background uploads and never reread browser bytes.
|
||||
* @param attachmentIds - ordered draft-local attachment ids.
|
||||
* @returns wire payloads in id order.
|
||||
*/
|
||||
@@ -462,18 +488,25 @@ export class ConversationController extends Service implements IConversation {
|
||||
releaseDraftAttachment(id: DraftAttachmentId): void {
|
||||
const attachment = this.draftAttachments.get(id)
|
||||
if (attachment === undefined) return
|
||||
this.draftAttachments.delete(id)
|
||||
if (attachment.kind === 'image') revokePreview(attachment.previewUrl)
|
||||
// The stored Host object stays durable; only the draft's upload state ends.
|
||||
this.dropUpload(id)
|
||||
}
|
||||
|
||||
/** Abort one draft's active upload and drop its upload state. */
|
||||
private dropUpload(id: DraftAttachmentId): void {
|
||||
const operation = this.fileUploadOperations.get(id)
|
||||
this.fileUploadOperations.delete(id)
|
||||
operation?.controller.abort()
|
||||
this.draftAttachments.delete(id)
|
||||
if (attachment.kind === 'image') {
|
||||
revokePreview(attachment.previewUrl)
|
||||
return
|
||||
}
|
||||
// The stored Host object stays durable; only the draft's upload state ends.
|
||||
this.fileUploads.set(Object.fromEntries(
|
||||
Object.entries(this.fileUploads.getSnapshot()).filter(([key]) => key !== id),
|
||||
))
|
||||
this.forgetUpload(id)
|
||||
}
|
||||
|
||||
/** Drop one draft's upload state. */
|
||||
private forgetUpload(id: DraftAttachmentId): void {
|
||||
const uploads = this.fileUploads.getSnapshot()
|
||||
if (!(id in uploads)) return
|
||||
this.fileUploads.set(Object.fromEntries(Object.entries(uploads).filter(([key]) => key !== id)))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -559,6 +592,7 @@ export class ConversationController extends Service implements IConversation {
|
||||
continue
|
||||
}
|
||||
this.draftAttachments.delete(attachment.id)
|
||||
this.forgetUpload(attachment.id)
|
||||
if (ref !== undefined && 'mediaType' in ref
|
||||
&& uiConversation?.seedImageUrl(sessionId, ref, attachment.previewUrl) === true) continue
|
||||
revokePreview(attachment.previewUrl)
|
||||
|
||||
@@ -80,11 +80,12 @@ export const InputBar = memo(function InputBar({
|
||||
)
|
||||
const empty = draft.trim() === '' && attachments.length === 0
|
||||
const uploads = useFileUploads(snapshot => snapshot)
|
||||
// Send waits for every picked file: uploading and failed drafts both hold
|
||||
// the gate (a failed upload is retried or removed, never silently dropped).
|
||||
const uploadsPending = attachments.some(
|
||||
attachment => attachment.kind === 'file' && uploads[attachment.id]?.status !== 'ready',
|
||||
)
|
||||
// Send waits for every picked file and every uploading image: uploading and
|
||||
// failed drafts both hold the gate (a failed upload is retried or removed,
|
||||
// never silently dropped). An image draft without an upload sends inline.
|
||||
const uploadsPending = attachments.some(attachment => attachment.kind === 'file'
|
||||
? uploads[attachment.id]?.status !== 'ready'
|
||||
: uploads[attachment.id] !== undefined && uploads[attachment.id]?.status !== 'ready')
|
||||
// Transient error banner (machine notices, image-intake rejections, and
|
||||
// prompt failures): the seq keys the Toast so an identical repeated message
|
||||
// restarts the hold-then-fade cycle instead of reusing the faded one.
|
||||
@@ -98,6 +99,11 @@ export const InputBar = memo(function InputBar({
|
||||
// The deployment's image-intake limits (absent while no attachment service
|
||||
// is composed — the pre-check below then defers entirely to the host).
|
||||
const imageLimits = useProjection('imageLimits')
|
||||
// Enter while uploads hold the send explains the first failed draft; a Host refusal names its reason.
|
||||
const failedUpload = attachments.map(attachment => uploads[attachment.id]).find(upload => upload?.status === 'error')
|
||||
const uploadsHeldText = failedUpload?.status !== 'error'
|
||||
? t('file.stillUploading')
|
||||
: failedUpload.reason === undefined ? t('file.uploadFailed') : attachmentErrorText(t, failedUpload.reason, imageLimits)
|
||||
// Prompt failures are ordinary failures (no create/attach transaction exists
|
||||
// anymore): the toast announces promptError, the draft stays in the machine,
|
||||
// and the user resubmits. A remount over a session whose machine still holds
|
||||
@@ -252,11 +258,11 @@ export const InputBar = memo(function InputBar({
|
||||
// registration survives re-renders without re-arming per keystroke.
|
||||
const gate = useRef({
|
||||
locked, machineBusy, canSteerQueue, running, steeringAvailable, busyEnter,
|
||||
intakeFiles, uploadsPending, showToast, t, canAcceptDrop,
|
||||
intakeFiles, uploadsPending, uploadsHeldText, showToast, canAcceptDrop,
|
||||
})
|
||||
gate.current = {
|
||||
locked, machineBusy, canSteerQueue, running, steeringAvailable, busyEnter,
|
||||
intakeFiles, uploadsPending, showToast, t, canAcceptDrop,
|
||||
intakeFiles, uploadsPending, uploadsHeldText, showToast, canAcceptDrop,
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -411,6 +417,7 @@ export const InputBar = memo(function InputBar({
|
||||
onRemoveAttachment: (id) => { removeAttachment?.(id) },
|
||||
uploads,
|
||||
onRetryFile: (id) => { retryFileUpload?.(id) },
|
||||
uploadFailureText: reason => attachmentErrorText(t, reason, imageLimits),
|
||||
dropLimits: imageLimits === undefined ? undefined : {
|
||||
count: imageLimits.maxImagesPerMessage,
|
||||
size: imageSizeText(imageLimits.maxImageBytes),
|
||||
|
||||
@@ -13,9 +13,9 @@ describe('ui-conversation host', () => {
|
||||
const ctx = new Context()
|
||||
const configuration = await liveConfig(ctx, { Config, apply })
|
||||
const { fiber } = configuration
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: DEFAULT_BUSY_ENTER_BEHAVIOR })
|
||||
await configuration.update({ busyEnter: 'steer' })
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ busyEnter: 'steer' })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ busyEnter: 'steer' })
|
||||
await expect(configuration.update({ busyEnter: 'invalid' })).rejects.toThrow()
|
||||
await fiber.dispose()
|
||||
})
|
||||
|
||||
@@ -242,8 +242,9 @@ function bench(over?: BenchOptions) {
|
||||
const steeringAvailable = over?.subagent === undefined || over.subagent.address.mode === 'continuable'
|
||||
const composerLocked = over?.disabled === true || over?.inert === true || over?.blocked !== undefined
|
||||
|| (over?.subagent?.address.mode === 'continuable' && over.subagent.parentAvailable !== true)
|
||||
const uploadsPending = (over?.attachments ?? []).some(attachment =>
|
||||
attachment.kind === 'file' && over?.fileUploads?.[attachment.id]?.status !== 'ready')
|
||||
const uploadsPending = (over?.attachments ?? []).some(attachment => attachment.kind === 'file'
|
||||
? over?.fileUploads?.[attachment.id]?.status !== 'ready'
|
||||
: over?.fileUploads?.[attachment.id] !== undefined && over.fileUploads[attachment.id]?.status !== 'ready')
|
||||
const plainMessageDraft = sendableDraft && !uploadsPending && !(over?.draft?.trimStart().startsWith('/') ?? false)
|
||||
const primaryLabel = primaryStops
|
||||
? '停止生成'
|
||||
@@ -1100,6 +1101,58 @@ describe('running and lock semantics', () => {
|
||||
expect(ready.button.disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('running Send waits for an uploading image and treats an image without an upload as ready', () => {
|
||||
const image = {
|
||||
kind: 'image' as const,
|
||||
id: 'image-1' as DraftAttachmentId,
|
||||
file: new File(['x'], 'shot.png', { type: 'image/png' }),
|
||||
previewUrl: 'blob:shot',
|
||||
}
|
||||
const uploading = bench({
|
||||
running: true, busyEnter: 'steer', draft: '带图', attachments: [image],
|
||||
fileUploads: { [image.id]: { status: 'uploading', loaded: 0 } },
|
||||
})
|
||||
expect(uploading.button.getAttribute('aria-label')).toBe('发送消息')
|
||||
expect(uploading.button.disabled).toBe(true)
|
||||
|
||||
// A subagent continuation's image has no upload and travels inline.
|
||||
const inline = bench({ running: true, busyEnter: 'steer', draft: '带图', attachments: [image] })
|
||||
expect(inline.button.getAttribute('aria-label')).toBe('插话发送')
|
||||
expect(inline.button.disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('explains on Enter why uploads hold the send, naming a Host refusal', () => {
|
||||
const limits = {
|
||||
maxImageBytes: 1024 * 1024,
|
||||
maxImagesPerMessage: 2,
|
||||
maxMessageImageBytes: 2 * 1024 * 1024,
|
||||
maxImagePixels: 40_000_000,
|
||||
maxImageDimension: 2000,
|
||||
mediaTypes: ['image/png'] as const,
|
||||
}
|
||||
const image = {
|
||||
kind: 'image' as const,
|
||||
id: 'image-1' as DraftAttachmentId,
|
||||
file: new File(['x'], 'wide.png', { type: 'image/png' }),
|
||||
previewUrl: 'blob:wide',
|
||||
}
|
||||
const enterWith = (upload: NonNullable<BenchOptions['fileUploads']>[string]): string | null => {
|
||||
const result = bench({ draft: '带图', attachments: [image], fileUploads: { [image.id]: upload }, imageLimits: limits })
|
||||
fireEvent.keyDown(result.textarea, { key: 'Enter' })
|
||||
expect(result.sink).not.toHaveBeenCalled()
|
||||
const text = result.view.getByRole('alert').textContent
|
||||
cleanup()
|
||||
return text
|
||||
}
|
||||
expect(enterWith({ status: 'uploading', loaded: 0 })).toContain('文件还在上传,请等待上传完成后发送')
|
||||
expect(enterWith({ status: 'error', message: 'offline' })).toContain('上传失败,点击重试')
|
||||
const refusal = '图片宽高不能超过 2000px,请缩小后重试'
|
||||
expect(enterWith({ status: 'error', message: 'too wide', reason: 'IMAGE_DIMENSION_TOO_LARGE' })).toContain(refusal)
|
||||
// The attachments slot receives the same localized explanation for its thumbnail.
|
||||
const owner = attachmentOwner(bench({ attachments: [image], imageLimits: limits }).slotCalls)
|
||||
expect(owner.uploadFailureText('IMAGE_DIMENSION_TOO_LARGE')).toBe(refusal)
|
||||
})
|
||||
|
||||
it('idle Send keeps the plain label regardless of the busy-state preference', () => {
|
||||
const { button, sink } = bench({ busyEnter: 'steer', draft: '空闲发送' })
|
||||
expect(button.getAttribute('aria-label')).toBe('发送消息')
|
||||
|
||||
@@ -18,6 +18,19 @@ import { reportMessageSubmission } from '../src/client/input/submission-analytic
|
||||
import { ConversationController } from '../src/client/service.ts'
|
||||
import { zh } from '../src/client/locales.ts'
|
||||
|
||||
const IMAGE_REF = {
|
||||
attachmentId: 'image-stored-1' as never,
|
||||
mediaType: 'image/png' as const,
|
||||
bytes: 1,
|
||||
width: 1,
|
||||
height: 1,
|
||||
}
|
||||
|
||||
/** `createDrafts` mode of an ordinary Session draft, which uploads its images when added. */
|
||||
const UPLOAD_IMAGES = true
|
||||
/** `createDrafts` mode of a draft whose images travel inline, as a subagent continuation's do. */
|
||||
const INLINE_IMAGES = false
|
||||
|
||||
async function bench(maxConcurrentFileUploads = 2) {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
runtime.fileUpload.upload = (sessionId: SessionId, ...args: unknown[]) => {
|
||||
@@ -27,6 +40,13 @@ async function bench(maxConcurrentFileUploads = 2) {
|
||||
if (session.uploadFile === undefined) throw new Error('test file upload has no Session override')
|
||||
return session.uploadFile(...args)
|
||||
}
|
||||
runtime.fileUpload.uploadImage = (sessionId: SessionId, ...args: unknown[]) => {
|
||||
const session = runtime.sessions.behavior(sessionId) as {
|
||||
uploadImage?: (...input: unknown[]) => Promise<unknown>
|
||||
}
|
||||
if (session.uploadImage === undefined) throw new Error('test image upload has no Session override')
|
||||
return session.uploadImage(...args)
|
||||
}
|
||||
const prompt = vi.fn((
|
||||
_content?: unknown, _mode?: unknown, _signal?: AbortSignal, _rpcId?: string,
|
||||
) => Promise.resolve({ ok: true as const, value: { accepted: true as const } }))
|
||||
@@ -125,7 +145,7 @@ describe('ConversationController', () => {
|
||||
try {
|
||||
const [attachment] = b.root.createDrafts(b.runtime.sessions.binding('s1')!.session.sessionId, [
|
||||
new File([new Uint8Array(4)], 'a.png', { type: 'image/png' }),
|
||||
])
|
||||
], INLINE_IMAGES)
|
||||
if (attachment === undefined) throw new Error('draft attachment missing')
|
||||
b.root.input.for(b.runtime.sessions.scope('s1')!).addAttachments([attachment.id])
|
||||
b.reference.release()
|
||||
@@ -146,7 +166,7 @@ describe('ConversationController', () => {
|
||||
try {
|
||||
const [attachment] = b.root.createDrafts(b.runtime.sessions.binding('s1')!.session.sessionId, [
|
||||
new File([Uint8Array.of(1)], 'detached.png', { type: 'image/png' }),
|
||||
])
|
||||
], INLINE_IMAGES)
|
||||
if (attachment === undefined) throw new Error('draft attachment missing')
|
||||
b.shell.addAttachments([attachment.id])
|
||||
b.shell.submit()
|
||||
@@ -161,7 +181,7 @@ describe('ConversationController', () => {
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('classifies image MIME drafts as images and every other file as an uploading file draft', async () => {
|
||||
it('classifies image MIME drafts as images and other files as file drafts, uploading images only where accepted', async () => {
|
||||
const b = await bench()
|
||||
const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:preview')
|
||||
const session = b.runtime.sessions.binding('s1')!.session
|
||||
@@ -172,24 +192,95 @@ describe('ConversationController', () => {
|
||||
file: { attachmentId: 'sha256:1' as never, name: 'notes.pdf', bytes: 2 },
|
||||
},
|
||||
}))
|
||||
;(session as { uploadFile?: unknown }).uploadFile = uploadFile
|
||||
const uploadImage = vi.fn((_data: Blob, _mediaType: string, _name?: string) => Promise.resolve({
|
||||
ok: true as const,
|
||||
value: { receiptId: 'image-receipt-1' as never, image: IMAGE_REF },
|
||||
}))
|
||||
Object.assign(session, { uploadFile, uploadImage })
|
||||
const drafts = b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(1)], 'valid.png', { type: 'image/png' }),
|
||||
new File([Uint8Array.of(2)], 'notes.pdf', { type: 'application/pdf' }),
|
||||
])
|
||||
], UPLOAD_IMAGES)
|
||||
expect(drafts.map(draft => draft.kind)).toEqual(['image', 'file'])
|
||||
expect(created).toHaveBeenCalledTimes(1)
|
||||
const fileDraft = drafts[1]!
|
||||
const [imageDraft, fileDraft] = [drafts[0]!, drafts[1]!]
|
||||
expect(b.root.fileUploads.getSnapshot()[fileDraft.id]?.status).toBe('uploading')
|
||||
expect(b.root.fileUploads.getSnapshot()[imageDraft.id]?.status).toBe('uploading')
|
||||
await vi.waitFor(() => {
|
||||
expect(b.root.fileUploads.getSnapshot()[fileDraft.id]?.status).toBe('ready')
|
||||
expect(b.root.fileUploads.getSnapshot()[imageDraft.id])
|
||||
.toEqual({ status: 'ready', receiptId: 'image-receipt-1' })
|
||||
})
|
||||
expect(uploadFile).toHaveBeenCalledOnce()
|
||||
expect(uploadFile.mock.calls[0]?.[0]).toBe((fileDraft as { file: File }).file)
|
||||
expect(uploadFile.mock.calls[0]?.[0]).toBe(fileDraft.file)
|
||||
expect(uploadImage.mock.calls[0]?.slice(0, 3)).toEqual([imageDraft.file, 'image/png', 'valid.png'])
|
||||
const [inline] = b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(3)], 'child.png', { type: 'image/png' }),
|
||||
], INLINE_IMAGES)
|
||||
expect(b.root.fileUploads.getSnapshot()[inline!.id]).toBeUndefined()
|
||||
expect(uploadImage).toHaveBeenCalledOnce()
|
||||
created.mockRestore()
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('retries a failed image upload and aborts it with its draft', async () => {
|
||||
const b = await bench()
|
||||
const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:retry')
|
||||
const revoked = vi.spyOn(URL, 'revokeObjectURL').mockReturnValue(undefined)
|
||||
try {
|
||||
const session = b.runtime.sessions.binding('s1')!.session
|
||||
const signals: AbortSignal[] = []
|
||||
const uploadImage = vi.fn((_data: Blob, _mediaType: string, _name: string | undefined, signal: AbortSignal) => {
|
||||
signals.push(signal)
|
||||
return signals.length === 1
|
||||
? Promise.resolve({ ok: false, error: new RemoteError('session/attachment-invalid', 'too big', { reason: 'IMAGE_TOO_LARGE' }) })
|
||||
: new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
|
||||
})
|
||||
})
|
||||
;(session as { uploadImage?: unknown }).uploadImage = uploadImage
|
||||
const [draft] = b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(1)], 'big.png', { type: 'image/png' }),
|
||||
], UPLOAD_IMAGES)
|
||||
// A Host refusal keeps its reason; retrying stays available to the service.
|
||||
await vi.waitFor(() => {
|
||||
expect(b.root.fileUploads.getSnapshot()[draft!.id])
|
||||
.toEqual({ status: 'error', message: 'too big', reason: 'IMAGE_TOO_LARGE' })
|
||||
})
|
||||
b.root.retryFileUpload(session.sessionId, draft!.id)
|
||||
await vi.waitFor(() => { expect(uploadImage).toHaveBeenCalledTimes(2) })
|
||||
expect(b.root.fileUploads.getSnapshot()[draft!.id]?.status).toBe('uploading')
|
||||
b.root.releaseDraftAttachment(draft!.id)
|
||||
expect(signals[1]?.aborted).toBe(true)
|
||||
expect(b.root.fileUploads.getSnapshot()[draft!.id]).toBeUndefined()
|
||||
expect(revoked).toHaveBeenCalledWith('blob:retry')
|
||||
} finally {
|
||||
created.mockRestore()
|
||||
revoked.mockRestore()
|
||||
}
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('keeps no refusal reason when an image upload fails in transport', async () => {
|
||||
const b = await bench()
|
||||
const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:flaky')
|
||||
try {
|
||||
const session = b.runtime.sessions.binding('s1')!.session
|
||||
;(session as { uploadImage?: unknown }).uploadImage = vi.fn(() => Promise.resolve({
|
||||
ok: false, error: new RemoteError('gateway/internal', 'connection reset', {}),
|
||||
}))
|
||||
const [draft] = b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(1)], 'flaky.png', { type: 'image/png' }),
|
||||
], UPLOAD_IMAGES)
|
||||
await vi.waitFor(() => {
|
||||
expect(b.root.fileUploads.getSnapshot()[draft!.id]).toEqual({ status: 'error', message: 'connection reset' })
|
||||
})
|
||||
} finally {
|
||||
created.mockRestore()
|
||||
}
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('serializes command files as staged receipts without reading their bytes again', async () => {
|
||||
const b = await bench()
|
||||
const session = b.runtime.sessions.binding('s1')!.session
|
||||
@@ -204,7 +295,7 @@ describe('ConversationController', () => {
|
||||
const drafts = b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(1)], 'one.txt', { type: 'text/plain' }),
|
||||
new File([Uint8Array.of(2)], 'two.txt', { type: 'text/plain' }),
|
||||
])
|
||||
], UPLOAD_IMAGES)
|
||||
await vi.waitFor(() => {
|
||||
expect(drafts.every(draft => b.root.fileUploads.getSnapshot()[draft.id]?.status === 'ready')).toBe(true)
|
||||
})
|
||||
@@ -245,7 +336,7 @@ describe('ConversationController', () => {
|
||||
})
|
||||
;(session as { uploadFile?: unknown }).uploadFile = uploadFile
|
||||
const drafts = b.root.createDrafts(session.sessionId, ['one', 'two', 'three', 'four', 'removed'].map(name =>
|
||||
new File([Uint8Array.of(1)], `${name}.txt`, { type: 'text/plain' })))
|
||||
new File([Uint8Array.of(1)], `${name}.txt`, { type: 'text/plain' })), UPLOAD_IMAGES)
|
||||
|
||||
await vi.waitFor(() => { expect(uploadFile.mock.calls.map(call => call[1])).toEqual(['one.txt', 'two.txt']) })
|
||||
await expect(b.root.serializeDraftAttachments([drafts[2]!.id]))
|
||||
@@ -295,7 +386,7 @@ describe('ConversationController', () => {
|
||||
;(session as { uploadFile?: unknown }).uploadFile = uploadFile
|
||||
const [attachment] = b.root.createDrafts(session.sessionId, [
|
||||
new File([new Uint8Array(8)], 'background.bin', { type: 'application/octet-stream' }),
|
||||
])
|
||||
], UPLOAD_IMAGES)
|
||||
if (attachment === undefined) throw new Error('file draft missing')
|
||||
b.shell.addAttachments([attachment.id])
|
||||
await vi.waitFor(() => { expect(uploadFile).toHaveBeenCalledOnce() })
|
||||
@@ -328,6 +419,38 @@ describe('ConversationController', () => {
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('drops a carried image upload when the target Session sends images inline', async () => {
|
||||
const b = await bench()
|
||||
const created = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:carry')
|
||||
try {
|
||||
const source = b.runtime.sessions.binding('s1')!.session
|
||||
let sourceSignal: AbortSignal | undefined
|
||||
;(source as { uploadImage?: unknown }).uploadImage = vi.fn(
|
||||
(_data: Blob, _mediaType: string, _name: string | undefined, signal: AbortSignal) => {
|
||||
sourceSignal = signal
|
||||
return new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
|
||||
})
|
||||
},
|
||||
)
|
||||
const [image] = b.root.createDrafts(source.sessionId, [
|
||||
new File([Uint8Array.of(5)], 'carry.png', { type: 'image/png' }),
|
||||
], UPLOAD_IMAGES)
|
||||
await vi.waitFor(() => { expect(sourceSignal).toBeDefined() })
|
||||
const targetUpload = vi.fn()
|
||||
await b.runtime.sessions.add({ id: 's2', session: { uploadImage: targetUpload } })
|
||||
using _target = b.runtime.sessions.retain('s2' as SessionId)
|
||||
await _target.ready
|
||||
b.root.rebindDraftFiles(b.runtime.sessions.binding('s2')!.session.sessionId, [image!.id], INLINE_IMAGES)
|
||||
expect(sourceSignal?.aborted).toBe(true)
|
||||
expect(b.root.fileUploads.getSnapshot()[image!.id]).toBeUndefined()
|
||||
expect(targetUpload).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
created.mockRestore()
|
||||
}
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('cancels a superseded upload and stages the carried draft on the target Session', async () => {
|
||||
const b = await bench()
|
||||
const source = b.runtime.sessions.binding('s1')!.session
|
||||
@@ -343,7 +466,7 @@ describe('ConversationController', () => {
|
||||
;(source as { uploadFile?: unknown }).uploadFile = sourceUpload
|
||||
const [attachment] = b.root.createDrafts(source.sessionId, [
|
||||
new File([Uint8Array.of(4)], 'carry.pdf', { type: 'application/pdf' }),
|
||||
])
|
||||
], UPLOAD_IMAGES)
|
||||
if (attachment === undefined) throw new Error('file draft missing')
|
||||
await vi.waitFor(() => { expect(sourceUpload).toHaveBeenCalledOnce() })
|
||||
|
||||
@@ -359,7 +482,7 @@ describe('ConversationController', () => {
|
||||
await b.runtime.sessions.add({ id: 's2', session: target })
|
||||
using _target = b.runtime.sessions.retain('s2' as SessionId)
|
||||
await _target.ready
|
||||
b.root.rebindDraftFiles(b.runtime.sessions.binding('s2')!.session.sessionId, [attachment.id])
|
||||
b.root.rebindDraftFiles(b.runtime.sessions.binding('s2')!.session.sessionId, [attachment.id], UPLOAD_IMAGES)
|
||||
|
||||
expect(sourceSignal?.aborted).toBe(true)
|
||||
await vi.waitFor(() => {
|
||||
@@ -386,7 +509,7 @@ describe('ConversationController', () => {
|
||||
;(session as { uploadFile?: unknown }).uploadFile = uploadFile
|
||||
const [attachment] = b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(5)], 'removed.pdf', { type: 'application/pdf' }),
|
||||
])
|
||||
], UPLOAD_IMAGES)
|
||||
if (attachment === undefined) throw new Error('file draft missing')
|
||||
await vi.waitFor(() => { expect(uploadFile).toHaveBeenCalledOnce() })
|
||||
|
||||
@@ -415,7 +538,7 @@ describe('ConversationController', () => {
|
||||
}))
|
||||
const [attachment] = b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(6)], 'sent.pdf', { type: 'application/pdf' }),
|
||||
])
|
||||
], UPLOAD_IMAGES)
|
||||
if (attachment === undefined) throw new Error('file draft missing')
|
||||
await vi.waitFor(() => {
|
||||
expect(b.root.fileUploads.getSnapshot()[attachment.id]?.status).toBe('ready')
|
||||
@@ -454,7 +577,7 @@ describe('ConversationController', () => {
|
||||
)
|
||||
b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(7)], 'dispose.pdf', { type: 'application/pdf' }),
|
||||
])
|
||||
], UPLOAD_IMAGES)
|
||||
await vi.waitFor(() => { expect(uploadSignal).toBeDefined() })
|
||||
|
||||
let disposed = false
|
||||
@@ -516,7 +639,7 @@ describe('sendSession submission echo', () => {
|
||||
try {
|
||||
const [attachment] = b.root.createDrafts(b.runtime.sessions.binding('s1')!.session.sessionId, [
|
||||
new File([Uint8Array.of(1, 2, 3)], 'a.png', { type: 'image/png' }),
|
||||
])
|
||||
], INLINE_IMAGES)
|
||||
const session = b.runtime.sessions.binding('s1')!.session
|
||||
const sending = b.root.sendSession(session, '带图', [attachment!.id], 'queue')
|
||||
const echo = await b.begun
|
||||
@@ -563,7 +686,7 @@ describe('sendSession submission echo', () => {
|
||||
new File([Uint8Array.of(1)], 'first.png', { type: 'image/png' }),
|
||||
new File([Uint8Array.of(2)], 'notes.txt', { type: 'text/plain' }),
|
||||
new File([Uint8Array.of(3)], 'last.png', { type: 'image/png' }),
|
||||
])
|
||||
], INLINE_IMAGES)
|
||||
await vi.waitFor(() => {
|
||||
expect(b.root.fileUploads.getSnapshot()[drafts[1]!.id]?.status).toBe('ready')
|
||||
})
|
||||
@@ -612,6 +735,40 @@ describe('sendSession submission echo', () => {
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('sends an uploaded image draft by its receipt and holds a send while it uploads', async () => {
|
||||
const b = await echoBench()
|
||||
const readAsDataURL = vi.spyOn(FileReader.prototype, 'readAsDataURL')
|
||||
try {
|
||||
const session = b.runtime.sessions.binding('s1')!.session
|
||||
const uploaded = Promise.withResolvers<unknown>()
|
||||
;(session as { uploadImage?: unknown }).uploadImage = vi.fn(() => uploaded.promise)
|
||||
const [draft] = b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(1)], 'shot.png', { type: 'image/png' }),
|
||||
], UPLOAD_IMAGES)
|
||||
await expect(b.root.sendSession(session, 'look', [draft!.id], 'queue'))
|
||||
.rejects.toThrow('one or more files have not finished uploading')
|
||||
expect(b.beginSubmission).not.toHaveBeenCalled()
|
||||
uploaded.resolve({ ok: true, value: { receiptId: 'image-receipt-1', image: IMAGE_REF } })
|
||||
await vi.waitFor(() => { expect(b.root.fileUploads.getSnapshot()[draft!.id]?.status).toBe('ready') })
|
||||
const sending = b.root.sendSession(session, 'look', [draft!.id], 'queue')
|
||||
const echo = await b.begun
|
||||
expect(echo.attachments[0]).toMatchObject({ type: 'image', value: { previewUrl: 'blob:echo-1', name: 'shot.png' } })
|
||||
await vi.waitFor(() => { expect(b.prompt).toHaveBeenCalledOnce() })
|
||||
expect(b.prompt.mock.calls[0]?.[0]).toEqual([
|
||||
{ type: 'file', receiptId: 'image-receipt-1' },
|
||||
{ type: 'text', text: 'look' },
|
||||
])
|
||||
expect(readAsDataURL).not.toHaveBeenCalled()
|
||||
b.retire.onRetire?.({ reason: 'observed', attachments: [IMAGE_REF] })
|
||||
await expect(sending).resolves.toEqual({ kind: 'success' })
|
||||
expect(b.root.fileUploads.getSnapshot()[draft!.id]).toBeUndefined()
|
||||
} finally {
|
||||
readAsDataURL.mockRestore()
|
||||
b.restore()
|
||||
}
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('passes each delivery mode before image serialization', async () => {
|
||||
const b = await echoBench()
|
||||
try {
|
||||
@@ -643,7 +800,7 @@ describe('sendSession submission echo', () => {
|
||||
b.runtime.ctx.set('uiConversation', { seedImageUrl })
|
||||
const [attachment] = b.root.createDrafts(b.runtime.sessions.binding('s1')!.session.sessionId, [
|
||||
new File([Uint8Array.of(9)], 'seeded.png', { type: 'image/png' }),
|
||||
])
|
||||
], INLINE_IMAGES)
|
||||
const session = b.runtime.sessions.binding('s1')!.session
|
||||
const sending = b.root.sendSession(session, '', [attachment!.id], 'queue')
|
||||
await vi.waitFor(() => { expect(b.prompt).toHaveBeenCalledOnce() })
|
||||
@@ -684,7 +841,7 @@ describe('sendSession submission echo', () => {
|
||||
const attachments = b.root.createDrafts(session.sessionId, [
|
||||
new File([Uint8Array.of(7)], 'kept.png', { type: 'image/png' }),
|
||||
new File([Uint8Array.of(8)], 'kept.txt', { type: 'text/plain' }),
|
||||
])
|
||||
], INLINE_IMAGES)
|
||||
await vi.waitFor(() => {
|
||||
expect(b.root.fileUploads.getSnapshot()[attachments[1]!.id]?.status).toBe('ready')
|
||||
})
|
||||
@@ -713,7 +870,7 @@ describe('sendSession submission echo', () => {
|
||||
try {
|
||||
const [attachment] = b.root.createDrafts(b.runtime.sessions.binding('s1')!.session.sessionId, [
|
||||
new File([Uint8Array.of(1)], 'broken.png', { type: 'image/png' }),
|
||||
])
|
||||
], INLINE_IMAGES)
|
||||
const session = b.runtime.sessions.binding('s1')!.session
|
||||
await expect(b.root.sendSession(session, 'x', [attachment!.id], 'queue'))
|
||||
.rejects.toThrow('read failed')
|
||||
@@ -796,12 +953,12 @@ describe('draft image dimension probe', () => {
|
||||
try {
|
||||
const [probed] = b.root.createDrafts(b.runtime.sessions.binding('s1')!.session.sessionId, [
|
||||
new File([Uint8Array.of(1)], 'probed.png', { type: 'image/png' }),
|
||||
])
|
||||
], INLINE_IMAGES)
|
||||
expect(probed).toMatchObject({ width: 640, height: 480 })
|
||||
vi.stubGlobal('Image', undefined)
|
||||
const [unprobed] = b.root.createDrafts(b.runtime.sessions.binding('s1')!.session.sessionId, [
|
||||
new File([Uint8Array.of(2)], 'unprobed.png', { type: 'image/png' }),
|
||||
])
|
||||
], INLINE_IMAGES)
|
||||
expect(unprobed?.kind).toBe('image')
|
||||
if (unprobed?.kind !== 'image') throw new Error('image draft missing')
|
||||
expect(unprobed.width).toBeUndefined()
|
||||
|
||||
@@ -11,7 +11,7 @@ it('validates and updates onboarding preferences without remounting', async () =
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
const configuration = await liveConfig(ctx, General)
|
||||
await configuration.update({ welcomeNoticeVersion: 'v1' })
|
||||
expect(plainConfig(configuration.fiber.config)).toMatchObject({ welcomeNoticeVersion: 'v1' })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ welcomeNoticeVersion: 'v1' })
|
||||
expect(configuration.entry.fiber).toBe(configuration.fiber)
|
||||
})
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@ it('defaults on, persists valid choices and removes its schema on disposal', asy
|
||||
const ctx = new Context()
|
||||
const configuration = await liveConfig(ctx, { Config, apply })
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ enabled: true })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ enabled: true })
|
||||
await configuration.update({ enabled: false })
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ enabled: false })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ enabled: false })
|
||||
await expect(configuration.update({ enabled: 'yes' })).rejects.toThrow()
|
||||
await configuration.fiber.dispose()
|
||||
})
|
||||
|
||||
@@ -30,11 +30,11 @@ describe('ui-theme host', () => {
|
||||
const ctx = new Context()
|
||||
const configuration = await liveConfig(ctx, { Config, apply })
|
||||
const { fiber } = configuration
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ preference: DEFAULT_PREFERENCE, fontSize: 14, codeFontSize: 11, terminalFontSize: 13, textFontFamily: '', codeFontFamily: '', terminalFontFamily: '' })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ preference: DEFAULT_PREFERENCE, fontSize: 14, codeFontSize: 11, terminalFontSize: 13, textFontFamily: '', codeFontFamily: '', terminalFontFamily: '' })
|
||||
await configuration.update({ preference: 'dark', fontSize: 10, codeFontSize: 16, codeFontFamily: '"Iosevka"' })
|
||||
expect(plainConfig(configuration.fiber.config)).toEqual({ preference: 'dark', fontSize: 10, codeFontSize: 16, terminalFontSize: 13, textFontFamily: '', codeFontFamily: '"Iosevka"', terminalFontFamily: '' })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toEqual({ preference: 'dark', fontSize: 10, codeFontSize: 16, terminalFontSize: 13, textFontFamily: '', codeFontFamily: '"Iosevka"', terminalFontFamily: '' })
|
||||
await configuration.update({ fontSize: 22 })
|
||||
expect(plainConfig(configuration.fiber.config)).toMatchObject({ preference: 'dark', fontSize: 22 })
|
||||
expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ preference: 'dark', fontSize: 22 })
|
||||
await expect(configuration.update({ preference: 'sepia' })).rejects.toThrow()
|
||||
await expect(configuration.update({ fontSize: 9 })).rejects.toThrow()
|
||||
await expect(configuration.update({ fontSize: 23 })).rejects.toThrow()
|
||||
|
||||
@@ -72,8 +72,8 @@ function nativeOwner(ctx: Context, provider: PaidTranslationProvider): NativeOwn
|
||||
const entry = [...loader.entries()].find(row => row.options.id === directory.settingsNs && row.options.name === OWNER_PACKAGES[provider])
|
||||
if (entry?.fiber?.state !== FiberState.ACTIVE) return undefined
|
||||
return provider === 'deepseek-account'
|
||||
? { llm, fiber: entry.fiber, provider, config: entry.fiber.config as AccountNativeConfig }
|
||||
: { llm, fiber: entry.fiber, provider, config: entry.fiber.config as OfficialNativeConfig }
|
||||
? { llm, fiber: entry.fiber, provider, config: entry.fiber.effectiveConfig as AccountNativeConfig }
|
||||
: { llm, fiber: entry.fiber, provider, config: entry.fiber.effectiveConfig as OfficialNativeConfig }
|
||||
}
|
||||
|
||||
function unchanged(ctx: Context, provider: PaidTranslationProvider, previous: EligibleOwner): NativeOwner | undefined {
|
||||
|
||||
@@ -179,7 +179,7 @@ describe('native Flash translation', () => {
|
||||
before.resolve(undefined)
|
||||
await continueLookup.promise
|
||||
const owner = [...b.ctx.loader.entries()].find(entry => entry.options.id === 'official-custom-id')!
|
||||
const config = owner.fiber!.config as ReturnType<typeof OfficialConfig>
|
||||
const config = owner.fiber!.effectiveConfig as ReturnType<typeof OfficialConfig>
|
||||
config.models = OfficialConfig({ models: [{ id: 'deepseek-v4-flash', name: 'Flash' }] }).models
|
||||
return models
|
||||
})
|
||||
@@ -200,7 +200,7 @@ describe('native Flash translation', () => {
|
||||
vi.spyOn(b.ctx.llm, 'listConfigurableProviders').mockImplementation(() => {
|
||||
reads += 1
|
||||
if (reads === 2) queueMicrotask(() => {
|
||||
const config = owner.fiber!.config as ReturnType<typeof OfficialConfig>
|
||||
const config = owner.fiber!.effectiveConfig as ReturnType<typeof OfficialConfig>
|
||||
config.models = OfficialConfig({ models: [{ id: 'deepseek-v4-flash' }] }).models
|
||||
})
|
||||
return directory
|
||||
@@ -274,7 +274,7 @@ describe('native Flash translation', () => {
|
||||
await owner.fiber!.dispose()
|
||||
await rejected
|
||||
} else if (change === 'catalog') {
|
||||
const config = owner.fiber!.config as ReturnType<typeof OfficialConfig>
|
||||
const config = owner.fiber!.effectiveConfig as ReturnType<typeof OfficialConfig>
|
||||
config.models = OfficialConfig({ models: [{ id: 'deepseek-v4-flash' }] }).models
|
||||
} else b.setConfigured(false)
|
||||
release.resolve(undefined)
|
||||
@@ -293,7 +293,7 @@ describe('native Flash translation', () => {
|
||||
const rejected = expect(b.translate('deepseek-account')).rejects.toMatchObject({ code: 'TRANSLATION_UNAVAILABLE' })
|
||||
await entered.promise
|
||||
const owner = [...b.ctx.loader.entries()].find(entry => entry.options.id === 'account-custom-id')!
|
||||
const config = owner.fiber!.config as ReturnType<typeof AccountConfig>
|
||||
const config = owner.fiber!.effectiveConfig as ReturnType<typeof AccountConfig>
|
||||
config.modelOverrides = AccountConfig({ modelOverrides: { 'deepseek-flash': { maxTokens: 4096 } } }).modelOverrides
|
||||
release.resolve(undefined)
|
||||
await rejected
|
||||
@@ -309,7 +309,7 @@ describe('native Flash translation', () => {
|
||||
if (pluginRecordOf(event)?.type !== 'plugin:translator/request') return
|
||||
if (change === 'withdrawn') withdrawal = owner.fiber!.dispose()
|
||||
else if (change === 'catalog') {
|
||||
const config = owner.fiber!.config as ReturnType<typeof OfficialConfig>
|
||||
const config = owner.fiber!.effectiveConfig as ReturnType<typeof OfficialConfig>
|
||||
config.models = OfficialConfig({ models: [{ id: 'deepseek-v4-flash' }] }).models
|
||||
} else b.setConfigured(false)
|
||||
}, { global: true })
|
||||
|
||||
@@ -659,7 +659,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer\', () => ctx.slots.register(\n { name: \'conversation.composer\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:263',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:280',
|
||||
},
|
||||
{
|
||||
key: 'conversation.composer.bar',
|
||||
@@ -701,7 +701,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.composer.bar\', () => ctx.slots.register(\n { name: \'conversation.composer.bar\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:285',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:302',
|
||||
},
|
||||
{
|
||||
key: 'conversation.composer.dock',
|
||||
@@ -761,7 +761,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.dock\', () => ctx.slots.register(\n { name: \'conversation.composer.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:277',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:294',
|
||||
},
|
||||
{
|
||||
key: 'conversation.header',
|
||||
@@ -799,7 +799,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.header\', () => ctx.slots.register(\n { name: \'conversation.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:213',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:230',
|
||||
},
|
||||
{
|
||||
key: 'conversation.header.leading',
|
||||
@@ -830,7 +830,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
occupants: [],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.header.leading\', () => ctx.slots.register(\n { name: \'conversation.header.leading\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:242',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:259',
|
||||
},
|
||||
{
|
||||
key: 'conversation.hero.agentPreset',
|
||||
@@ -870,7 +870,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.hero.agentPreset\', () => ctx.slots.register(\n { name: \'conversation.hero.agentPreset\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:269',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:286',
|
||||
},
|
||||
{
|
||||
key: 'conversation.hero.brand.mark',
|
||||
@@ -901,7 +901,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
occupants: [],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.brand.mark\', () => ctx.slots.register(\n { name: \'conversation.hero.brand.mark\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:267',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:284',
|
||||
},
|
||||
{
|
||||
key: 'conversation.hero.options',
|
||||
@@ -958,7 +958,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
occupants: [],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.options\', () => ctx.slots.register(\n { name: \'conversation.hero.options\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:271',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:288',
|
||||
},
|
||||
{
|
||||
key: 'conversation.hero.workspace',
|
||||
@@ -993,7 +993,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.hero.workspace\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:265',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:282',
|
||||
},
|
||||
{
|
||||
key: 'conversation.hero.workspace.directoryFlow',
|
||||
@@ -1071,7 +1071,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.activity\', () => ctx.slots.register(\n { name: \'conversation.input.activity\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:283',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:300',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.attachments',
|
||||
@@ -1081,7 +1081,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
doc: 'Optional draft-attachment rail and drop target.',
|
||||
registerOptions: [],
|
||||
ownerProps: [
|
||||
'/** Input state handed to the optional attachment presentation plugin. */\nexport interface ComposerAttachmentsOwnerProps {\n /** Browser-owned draft attachments in input order. */\n attachments: readonly ComposerAttachment[]\n /** Whether a document-level file drop may add attachments now. */\n canAcceptDrop: boolean\n /**\n * Add one dropped batch through the composer\'s validation path.\n * @param files - dropped, pasted, or picked browser files in source order.\n * @param directories - members of `files` the drop source identified as directories.\n */\n onAddFiles: (files: readonly File[], directories?: ReadonlySet<File>) => void\n /** Remove one draft attachment through the Conversation service. */\n onRemoveAttachment: (id: DraftAttachmentId) => void\n /** Current per-draft upload states for file-kind attachments. */\n uploads: DraftFileUploads\n /** Restart one failed file upload. */\n onRetryFile: (id: DraftAttachmentId) => void\n /** Display-ready limits for the drop invitation. */\n dropLimits?: { readonly count: number; readonly size: string } | undefined\n}',
|
||||
'/** Input state handed to the optional attachment presentation plugin. */\nexport interface ComposerAttachmentsOwnerProps {\n /** Browser-owned draft attachments in input order. */\n attachments: readonly ComposerAttachment[]\n /** Whether a document-level file drop may add attachments now. */\n canAcceptDrop: boolean\n /**\n * Add one dropped batch through the composer\'s validation path.\n * @param files - dropped, pasted, or picked browser files in source order.\n * @param directories - members of `files` the drop source identified as directories.\n */\n onAddFiles: (files: readonly File[], directories?: ReadonlySet<File>) => void\n /** Remove one draft attachment through the Conversation service. */\n onRemoveAttachment: (id: DraftAttachmentId) => void\n /** Current per-draft upload states for file-kind attachments. */\n uploads: DraftFileUploads\n /** Restart one failed file upload. */\n onRetryFile: (id: DraftAttachmentId) => void\n /**\n * Explain one upload the Host refused; such a draft cannot be retried and\n * stays until it is removed.\n * @param reason - the refusal `reason` the failed upload carries.\n * @returns localized text naming the limit or the way out.\n /* …truncated — full shape in source */',
|
||||
],
|
||||
ownerPropsReferences: [
|
||||
'ComposerAttachment',
|
||||
@@ -1115,7 +1115,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.attachments\', () => ctx.slots.register(\n { name: \'conversation.input.attachments\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:287',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:304',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.dock',
|
||||
@@ -1182,7 +1182,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.dock\', () => ctx.slots.register(\n { name: \'conversation.input.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:273',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:290',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.left',
|
||||
@@ -1239,7 +1239,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
occupants: [],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.left\', () => ctx.slots.register(\n { name: \'conversation.input.left\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:279',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:296',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.model',
|
||||
@@ -1281,7 +1281,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\', () => ctx.slots.register(\n { name: \'conversation.input.model\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:301',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:318',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.model.label',
|
||||
@@ -1387,7 +1387,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.overlay\', () => ctx.slots.register(\n { name: \'conversation.input.overlay\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:275',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:292',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.permission',
|
||||
@@ -1429,7 +1429,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.permission\', () => ctx.slots.register(\n { name: \'conversation.input.permission\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:295',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:312',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.plan',
|
||||
@@ -1471,7 +1471,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.plan\', () => ctx.slots.register(\n { name: \'conversation.input.plan\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:293',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:310',
|
||||
},
|
||||
{
|
||||
key: 'conversation.input.right',
|
||||
@@ -1528,7 +1528,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
occupants: [],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.right\', () => ctx.slots.register(\n { name: \'conversation.input.right\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:281',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:298',
|
||||
},
|
||||
{
|
||||
key: 'conversation.plan-review.actions',
|
||||
@@ -1629,7 +1629,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.session\', () => ctx.slots.register(\n { name: \'conversation.session\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:207',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:224',
|
||||
},
|
||||
{
|
||||
key: 'conversation.session.header',
|
||||
@@ -1669,7 +1669,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.session.header\', () => ctx.slots.register(\n { name: \'conversation.session.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:215',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:232',
|
||||
},
|
||||
{
|
||||
key: 'conversation.session.header.actions',
|
||||
@@ -1733,7 +1733,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.actions\', () => ctx.slots.register(\n { name: \'conversation.session.header.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:230',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:247',
|
||||
},
|
||||
{
|
||||
key: 'conversation.session.header.corner',
|
||||
@@ -1775,7 +1775,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.session.header.corner\', () => ctx.slots.register(\n { name: \'conversation.session.header.corner\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:253',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:270',
|
||||
},
|
||||
{
|
||||
key: 'conversation.session.header.lineage',
|
||||
@@ -1819,7 +1819,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.session.header.lineage\', () => ctx.slots.register(\n { name: \'conversation.session.header.lineage\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:224',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:241',
|
||||
},
|
||||
{
|
||||
key: 'conversation.session.header.utilities',
|
||||
@@ -1882,7 +1882,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.utilities\', () => ctx.slots.register(\n { name: \'conversation.session.header.utilities\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:236',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:253',
|
||||
},
|
||||
{
|
||||
key: 'conversation.session.header.views.actions',
|
||||
@@ -1936,7 +1936,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.views.actions\', () => ctx.slots.register(\n { name: \'conversation.session.header.views.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:259',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:276',
|
||||
},
|
||||
{
|
||||
key: 'conversation.trajectory.images',
|
||||
@@ -2038,7 +2038,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.user.text.node\', () => ctx.slots.register(\n { name: \'conversation.user.text.node\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:197',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:214',
|
||||
},
|
||||
{
|
||||
key: 'conversation.view',
|
||||
@@ -2102,7 +2102,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'none',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.view\', () => ctx.slots.register(\n { name: \'conversation.view\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:261',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:278',
|
||||
},
|
||||
{
|
||||
key: 'deliverables.file.actions',
|
||||
@@ -2305,7 +2305,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'main.conversation\', () => ctx.slots.register(\n { name: \'main.conversation\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:205',
|
||||
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:222',
|
||||
},
|
||||
{
|
||||
key: 'plugins.add.actions',
|
||||
|
||||
@@ -451,8 +451,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
},
|
||||
{
|
||||
signature: 'async admitPromptContent( content: readonly AttachmentAdmissionPart[], ): Promise<AdmittedPromptContentPart[]>',
|
||||
description: 'Admit one Host prompt and replace each uploaded image with its durable reference. Text and durable file references pass through unchanged. A prompt without image parts performs no storage operation.',
|
||||
parameters: [{ name: 'content', description: 'prompt parts in message order after file receipt resolution.' }],
|
||||
description: 'Admit one Host prompt and replace each encoded image with its durable reference. Text, durable file references, and already stored images pass through unchanged. Every image part counts toward `maxImagesPerMessage` and `maxMessageImageBytes`; a stored image counts the bytes of the upload that stored it. Refused content starts no writes. A prompt without encoded images performs no storage operation.',
|
||||
parameters: [{ name: 'content', description: 'prompt parts in message order after upload receipt resolution.' }],
|
||||
returns: 'admitted prompt parts in the same order as `content`.',
|
||||
throws: ['AttachmentError when the image batch is refused.'],
|
||||
},
|
||||
@@ -1150,7 +1150,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
returns: 'disposer removing this resolver.',
|
||||
},
|
||||
{
|
||||
signature: '@Remote(\'upload\') upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise<FileUploadValue>',
|
||||
signature: '@Remote(\'upload\') async upload(agent: Agent, request: EncodedFileUploadRequest, signal: AbortSignal): Promise<FileUploadValue>',
|
||||
description: 'Persist one encoded upload and stage it under the Agent receiver selected by Typert.',
|
||||
parameters: [{ name: 'agent', description: 'receiving Agent resolved from the Remote Agent scope.' }, { name: 'request', description: 'canonical base64 bytes and optional display name.' }, { name: 'signal', description: 'caller cancellation before storage begins.' }],
|
||||
returns: 'the staged receipt and durable file reference.',
|
||||
@@ -1162,10 +1162,16 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
returns: 'the staged receipt and durable file reference.',
|
||||
},
|
||||
{
|
||||
signature: 'resolve(agent: Agent, receiptId: FileUploadReceiptId): FileAttachmentRef | undefined',
|
||||
signature: 'async uploadImageStream(request: { readonly sessionId: SessionId readonly data: AsyncIterable<Uint8Array> readonly mediaType: string readonly signal?: AbortSignal readonly name?: string }): Promise<ImageUploadValue>',
|
||||
description: 'Persist one prompt image for a Session: read at most the smaller of the deployment\'s per-image and per-message byte limits, then validate, normalize, and store the image the way prompt admission does, so a later prompt cites it by receipt. Cancellation before storage begins stores nothing; a cancelled upload never receives a receipt, although an image whose storage already began stays in the content-addressed store.',
|
||||
parameters: [{ name: 'request', description: 'Session identity, ordered bytes, the declared media type that this deployment must accept, cancellation, and optional display name.' }],
|
||||
returns: 'the staged receipt and durable normalized image reference.',
|
||||
},
|
||||
{
|
||||
signature: 'resolve(agent: Agent, receiptId: FileUploadReceiptId): StagedAttachment | undefined',
|
||||
description: 'Resolve one staged receipt for the receiving Agent\'s exact Session.',
|
||||
parameters: [{ name: 'agent', description: 'receiving Agent.' }, { name: 'receiptId', description: 'opaque receipt minted for one completed upload.' }],
|
||||
returns: 'durable file reference, or `undefined` for an unknown or foreign receipt.',
|
||||
returns: 'the staged file or image, or `undefined` for an unknown or foreign receipt.',
|
||||
},
|
||||
{
|
||||
signature: 'bindPrompt( agent: Agent, receiptIds: readonly FileUploadReceiptId[], requestId: string, ): PromptFileBinding',
|
||||
@@ -5041,7 +5047,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'AttachmentAdmissionPart',
|
||||
declaration: 'export type AttachmentAdmissionPart = PromptContentPart | {\n readonly type: \'file\';\n readonly attachment: FileAttachmentRef;\n};',
|
||||
declaration: 'export type AttachmentAdmissionPart = PromptContentPart | {\n readonly type: \'file\';\n readonly attachment: FileAttachmentRef;\n} | {\n readonly type: \'image\';\n readonly attachment: ImageAttachmentRef;\n readonly encodedBytes: number;\n};',
|
||||
},
|
||||
{
|
||||
name: 'AttachmentError',
|
||||
@@ -5863,6 +5869,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'ImageRequestTarget',
|
||||
declaration: 'export interface ImageRequestTarget {\n width: number;\n height: number;\n maxBytes: number;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ImageUploadValue',
|
||||
declaration: 'export interface ImageUploadValue {\n readonly receiptId: FileUploadReceiptId;\n readonly image: ImageAttachmentRef;\n}',
|
||||
},
|
||||
{
|
||||
name: 'ImageVariantId',
|
||||
declaration: 'export type ImageVariantId = Branded<\'ImageVariantId\'>;',
|
||||
@@ -8055,6 +8065,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'SshStreamEndpoint',
|
||||
declaration: 'export type SshStreamEndpoint = z.infer<typeof streamEndpointSchema>;',
|
||||
},
|
||||
{
|
||||
name: 'StagedAttachment',
|
||||
declaration: 'export type StagedAttachment = {\n readonly type: \'file\';\n readonly attachment: FileAttachmentRef;\n} | {\n readonly type: \'image\';\n readonly attachment: ImageAttachmentRef;\n readonly encodedBytes: number;\n};',
|
||||
},
|
||||
{
|
||||
name: 'StorageBackend',
|
||||
declaration: 'export interface StorageBackend {\n readonly kv?: KvFacet;\n close(): Promise<void>;\n}',
|
||||
|
||||
@@ -135,8 +135,8 @@
|
||||
en: f5d5f97a153f7c70
|
||||
zh: 3d6bc05b9eadfbc2
|
||||
/deepseek-ai-dsh-tool-fs/known-limitations-and-deferred-work:
|
||||
en: ce7a91d41d2f7597
|
||||
zh: d4a3c905e124fd7f
|
||||
en: 28aadb772cdbc497
|
||||
zh: a50e3bb6b4a8f645
|
||||
/deepseek-ai-dsh-tool-fs/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 3bb0c20c93f16f98
|
||||
|
||||
@@ -250,7 +250,7 @@ These limits define when the tool suite is a poor fit or needs special operation
|
||||
- **No model-facing directory listing ships** — `ctx.fs.listDir` serves provider code such as skill discovery, while the sibling `dsh-tool-fs-search` package supplies ripgrep-backed `glob` and `grep` rather than extending the filesystem seam.
|
||||
- **`read` handles UTF-8 text files only** — images use the separate `read_image` tool; PDF, audio, and video remain deferred. A directory target is `FS_NOT_REGULAR_FILE`.
|
||||
- **Extension-declared media type** — an extension selects the declared type and the attachment store's magic-byte validation stays authoritative; a correctly formatted image under a wrong extension is refused with the rename remedy rather than sniffed. Only a path with no extension is identified from its file signature.
|
||||
- **Object paths re-enter source admission** — `read_image` on a normalized attachment object re-admits its bytes as a new source, so a deployment whose `maxImageBytes`/`maxMessageImageBytes` sit below the normalized-image byte budget can refuse an object path that `ctx.attachments.readImage` still serves; shipped defaults keep the normalized budget (4 MiB) far under the source caps (20 MiB).
|
||||
- **Object paths re-enter source admission** — `read_image` on a normalized attachment object re-admits its bytes as a new source, so a deployment whose `maxImageBytes`/`maxMessageImageBytes` sit below the normalized-image byte budget can refuse an object path that `ctx.attachments.readImage` still serves; shipped defaults keep the normalized budget (4 MiB) far under the source caps (50 MiB).
|
||||
- **Inline image preview rides the UI composition** — the tool-result card renders the image through the browser's `tool.call.images` slot, which the attachment presentation plugin fills; a UI without that plugin shows the result's envelope text instead.
|
||||
- **No attachment-region tool** — an agent may crop an image through another available tool when it has a filesystem path; a pasted or dragged image without a path cannot be re-read at higher resolution.
|
||||
- **No timeout surface** — `read`/`write`/`edit` take no timeout argument and declare no timeout budget; cancellation rides `exec.signal` only ([provider rationale](../README.md)).
|
||||
|
||||
@@ -250,7 +250,7 @@ Read a file before editing it (the default fs-observation-policy requires it), u
|
||||
- **未交付面向模型的目录列表工具**:`ctx.fs.listDir` 服务于 skill(技能)发现等提供方代码,同级 `dsh-tool-fs-search` 包则提供基于 ripgrep 的 `glob` 与 `grep`,而不是扩展文件系统 seam。
|
||||
- **`read` 只处理 UTF-8 文本文件**:图像使用独立的 `read_image` 工具;PDF、音频和视频仍延期处理。目录目标为 `FS_NOT_REGULAR_FILE`。
|
||||
- **媒体类型按扩展名声明**:扩展名选择声明类型,附件存储的魔数校验保持权威;扩展名错误但格式正确的图像会得到改名修复提示,而不是被嗅探接受。只有没有扩展名的路径按文件签名识别格式。
|
||||
- **对象路径重新走源准入**:对规范化附件对象调用 `read_image` 会把其字节作为新来源重新准入,因此把 `maxImageBytes`/`maxMessageImageBytes` 配置得低于规范化图片字节预算的部署可能拒绝 `ctx.attachments.readImage` 仍可读取的对象路径;默认配置下规范化预算(4 MiB)远低于源上限(20 MiB)。
|
||||
- **对象路径重新走源准入**:对规范化附件对象调用 `read_image` 会把其字节作为新来源重新准入,因此把 `maxImageBytes`/`maxMessageImageBytes` 配置得低于规范化图片字节预算的部署可能拒绝 `ctx.attachments.readImage` 仍可读取的对象路径;默认配置下规范化预算(4 MiB)远低于源上限(50 MiB)。
|
||||
- **内嵌图像预览依赖 UI 组合**:工具结果卡片经由浏览器的 `tool.call.images` 槽位渲染图像,由附件呈现插件填充;未组合该插件的 UI 改为显示结果的信封文本。
|
||||
- **没有附件区域工具**:agent 在拥有文件系统路径时可以通过其他可用工具裁剪图片;没有路径的粘贴或拖入图片无法按更高分辨率重新读取。
|
||||
- **没有超时接口**:`read`/`write`/`edit` 不接受超时参数,也不声明超时预算;取消只通过 `exec.signal` 传递(见[提供方理由](../README.zh.md))。
|
||||
|
||||
@@ -316,7 +316,8 @@ export class SettingsForms extends Service {
|
||||
if (previous?.raw !== raw || previous.autoGenerate !== autoGenerate) {
|
||||
this.ownerContext.emit('settings/document-updated', entry.options.id as SettingsNamespace, revision)
|
||||
}
|
||||
const value = projectForm(form, plainConfig(entry.fiber.config))
|
||||
const value = projectForm(form, plainConfig(entry.fiber.effectiveConfig))
|
||||
// Inherited layers omit profile fields, so only interpolate and validate them, without the running fiber's config hooks.
|
||||
const resolved: unknown = interpolate(entry.fiber.ctx, inherited)
|
||||
const base = projectForm(form, plainConfig(inheritedConfig(entry.fiber.runtime, resolved)))
|
||||
const user = projectForm(form, override)
|
||||
|
||||
@@ -70,9 +70,9 @@ it('preserves configuration expressions while editing a different live field', a
|
||||
await ctx.fiber.dispose()
|
||||
const restored = await start()
|
||||
const entry = [...restored.loader.entries()].find(row => row.options.id === 'first')!
|
||||
expect((entry.fiber!.config as { ordinary: string }).ordinary).toBe('expression-value')
|
||||
expect((entry.fiber!.effectiveConfig as { ordinary: string }).ordinary).toBe('expression-value')
|
||||
const second = [...restored.loader.entries()].find(entry => entry.options.id === 'second')!
|
||||
expect((second.fiber!.config as { ordinary: string }).ordinary).toBe('untouched-expression')
|
||||
expect((second.fiber!.effectiveConfig as { ordinary: string }).ordinary).toBe('untouched-expression')
|
||||
expect(restored.settings.describe().find(row => row.ns === 'first')!.value).toEqual({ count: 4, list: [] })
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Test fixtures using the same Loader updates as profile reconciliation. */
|
||||
import { Context, resolveConfig, type Fiber, type Plugin } from '@deepseek-ai/cordis'
|
||||
import { Context, type Fiber, type Plugin } from '@deepseek-ai/cordis'
|
||||
import { expect, vi } from 'vitest'
|
||||
import Loader from '@deepseek-ai/cordis-plugin-loader'
|
||||
|
||||
@@ -27,7 +27,7 @@ export async function liveConfig(ctx: Context, plugin: Plugin, initial: object =
|
||||
await entry.fiber!.await()
|
||||
const replace = async (next: Record<string, unknown>) => {
|
||||
const fiber = entry.fiber!
|
||||
resolveConfig(fiber.runtime!, fiber.ctx.waterfall(fiber, 'internal/config', next, () => next))
|
||||
fiber.resolveConfig(next)
|
||||
await entry.update({ config: next })
|
||||
await entry.fiber!.await()
|
||||
ctx.emit('app-boot/config-reload')
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 12afbb217bc06678
|
||||
zh: c07f001ed8bb3300
|
||||
/deepseek-ai-dsh-client-test-runtime/use-this-package/setting-up-a-feature-spec:
|
||||
en: 411248e12f21d834
|
||||
zh: cfb151ce0acbe4e7
|
||||
en: 2cc497326fc544d9
|
||||
zh: db7f73ab937d7c05
|
||||
/deepseek-ai-dsh-client-test-runtime/use-this-package/local-dom-snapshots:
|
||||
en: 1abbbed6cc4cf57b
|
||||
zh: ab3975178b589653
|
||||
|
||||
@@ -42,7 +42,7 @@ expect(view.container).toMatchSnapshot()
|
||||
await runtime.dispose()
|
||||
```
|
||||
|
||||
`mount` prechecks required services and fails loud when one is missing — `provide(name, value)` supplies an extra service first. The runtime provides a `fileUpload` stub that rejects every call until a suite replaces `runtime.fileUpload.upload`. `storeOf(key, scopeKey)` returns the live store instance the renderer hands a slot's component for identity and action-driven-write assertions.
|
||||
`mount` prechecks required services and fails loud when one is missing — `provide(name, value)` supplies an extra service first. The runtime provides a `fileUpload` stub whose `upload` and `uploadImage` reject every call until a suite replaces them. `storeOf(key, scopeKey)` returns the live store instance the renderer hands a slot's component for identity and action-driven-write assertions.
|
||||
|
||||
The runtime installs `allowAllAccessPlugin` before ui-session: its `remoteAccess` service, a `StaticRemoteAccess`, answers true for every resource, so every access Hook allows every action and every `whenAccess` callback runs at once. `TestClientOptions.access` fixes the answer per action instead, through `staticAccessPlugin(allows)`. Hand-built component props spread `...allowAllAccess` to receive the same Hooks; a spec of a refused path overrides one Hook or provides `new StaticRemoteAccess(ctx, allows)`.
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ expect(view.container).toMatchSnapshot()
|
||||
await runtime.dispose()
|
||||
```
|
||||
|
||||
`mount` 会预检必需服务,缺失时自明报错——先用 `provide(name, value)` 提供额外服务。运行时提供的 `fileUpload` 替身会拒绝每次调用,直到测试套件替换 `runtime.fileUpload.upload`。`storeOf(key, scopeKey)` 返回渲染器交给 slot 组件的实时存储实例,用于身份与动作驱动写入断言。
|
||||
`mount` 会预检必需服务,缺失时自明报错——先用 `provide(name, value)` 提供额外服务。运行时提供的 `fileUpload` 替身,其 `upload` 与 `uploadImage` 会拒绝每次调用,直到测试套件替换它们。`storeOf(key, scopeKey)` 返回渲染器交给 slot 组件的实时存储实例,用于身份与动作驱动写入断言。
|
||||
|
||||
运行时在 ui-session 之前安装 `allowAllAccessPlugin`:它的 `remoteAccess` 服务是一个 `StaticRemoteAccess`,对每个资源都回答 true,因此每个访问 Hook 都允许每个 action,每个 `whenAccess` 回调都立即执行。`TestClientOptions.access` 改为按 action 固定答案,经由 `staticAccessPlugin(allows)`。手工构造的组件 props 展开 `...allowAllAccess` 以获得同样的 Hook;测试被拒绝路径的 spec 覆盖其中一个 Hook,或提供 `new StaticRemoteAccess(ctx, allows)`。
|
||||
|
||||
|
||||
@@ -127,6 +127,8 @@ export interface FeatureHandle {
|
||||
export interface TestFileUpload {
|
||||
/** Test-supplied upload behavior; the default rejects every call. */
|
||||
upload: (sessionId: SessionId, ...args: unknown[]) => Promise<unknown>
|
||||
/** Test-supplied image upload behavior; the default rejects every call. */
|
||||
uploadImage: (sessionId: SessionId, ...args: unknown[]) => Promise<unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -259,6 +261,7 @@ export class SlotTestRuntime {
|
||||
this.workspaces = new TestWorkspaces(this.stabilizer)
|
||||
this.fileUpload = {
|
||||
upload: () => Promise.reject(new Error('client test runtime: file upload is not stubbed')),
|
||||
uploadImage: () => Promise.reject(new Error('client test runtime: image upload is not stubbed')),
|
||||
}
|
||||
ctx.provide('sessions', this.sessions)
|
||||
ctx.provide('workspaces', this.workspaces)
|
||||
|
||||
@@ -124,6 +124,7 @@ describe('fixture helpers', () => {
|
||||
it('rejects an upload until a suite replaces the default stub', async () => {
|
||||
const runtime = await SlotTestRuntime.create()
|
||||
await expect(runtime.fileUpload.upload('fixture-session' as SessionId)).rejects.toThrow('file upload is not stubbed')
|
||||
await expect(runtime.fileUpload.uploadImage('fixture-session' as SessionId)).rejects.toThrow('image upload is not stubbed')
|
||||
await runtime.dispose()
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/** Raw retention and candidate evaluation preserve the running plugin's config identity. */
|
||||
import { Context, type Fiber } from '@deepseek-ai/cordis'
|
||||
import Loader from '@deepseek-ai/cordis-plugin-loader'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
|
||||
function root(): Context {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
return ctx
|
||||
}
|
||||
|
||||
describe('Fiber configuration access', () => {
|
||||
it('keeps raw and running references unchanged while resolving valid or invalid candidates', async () => {
|
||||
const ctx = root()
|
||||
await ctx.plugin(Loader)
|
||||
const Config = z.object({ value: z.number().min(0).volatile() })
|
||||
const applied = vi.fn()
|
||||
ctx.loader.builtins.consumer = { Config, apply: applied }
|
||||
const raw = { value: { __jsExpr: '1 + 1' } }
|
||||
const id = await ctx.loader.create({ name: 'cordis:consumer', config: raw })
|
||||
const fiber = ctx.loader.resolve(id).fiber!
|
||||
await fiber.await()
|
||||
const running = applied.mock.calls[0]![1] as ReturnType<typeof Config>
|
||||
expect(fiber.rawConfig).toBe(raw)
|
||||
expect(fiber.effectiveConfig).toBe(running)
|
||||
const candidate = fiber.resolveConfig({ value: { __jsExpr: '2 + 2' } }) as ReturnType<typeof Config>
|
||||
expect(candidate.value.get()).toBe(4)
|
||||
expect(candidate.value).not.toBe(running.value)
|
||||
expect(() => fiber.resolveConfig({ value: -1 })).toThrow()
|
||||
expect(fiber.rawConfig).toBe(raw)
|
||||
expect(fiber.effectiveConfig).toBe(running)
|
||||
expect(running.value.get()).toBe(2)
|
||||
expect(applied).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('uses the canonical fiber through registry wrappers and retains raw input without updating', async () => {
|
||||
const ctx = root()
|
||||
const initial = { value: 1 }
|
||||
const apply = vi.fn()
|
||||
const wrapper = ctx.plugin(apply, initial)
|
||||
await wrapper
|
||||
const fiber = wrapper.ctx.fiber
|
||||
const hook = vi.fn(function (this: Fiber, _config: unknown, next: () => unknown) {
|
||||
expect(this).toBe(fiber)
|
||||
return next()
|
||||
})
|
||||
fiber.ctx.on('internal/config', hook)
|
||||
const raw = { value: 2 }
|
||||
wrapper.rawConfig = raw
|
||||
expect(fiber.rawConfig).toBe(raw)
|
||||
expect(wrapper.effectiveConfig).toBe(initial)
|
||||
expect(wrapper.resolveConfig(raw)).toBe(raw)
|
||||
expect(hook).toHaveBeenCalledOnce()
|
||||
expect(fiber.effectiveConfig).toBe(initial)
|
||||
expect(apply).toHaveBeenCalledOnce()
|
||||
await wrapper.restart()
|
||||
expect(fiber.effectiveConfig).toBe(raw)
|
||||
expect(apply).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('publishes updates through registry wrappers to the canonical fiber', async () => {
|
||||
const ctx = root()
|
||||
const initial = { value: 1 }
|
||||
const apply = vi.fn()
|
||||
const wrapper = ctx.plugin(apply, initial)
|
||||
await wrapper
|
||||
const raw = { value: 2 }
|
||||
wrapper.update(raw)
|
||||
await wrapper.await()
|
||||
expect(apply).toHaveBeenLastCalledWith(wrapper.ctx, raw)
|
||||
expect(wrapper.rawConfig).toBe(raw)
|
||||
expect(wrapper.effectiveConfig).toBe(raw)
|
||||
expect(wrapper.ctx.fiber.rawConfig).toBe(raw)
|
||||
expect(wrapper.ctx.fiber.effectiveConfig).toBe(raw)
|
||||
expect(apply).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('retains a pending raw update until its injection is available', async () => {
|
||||
const ctx = root()
|
||||
ctx.provide('configAccessTest')
|
||||
const apply = vi.fn()
|
||||
const wrapper = ctx.plugin({ inject: ['configAccessTest'], apply }, { value: 1 })
|
||||
const raw = { value: 2 }
|
||||
wrapper.update(raw)
|
||||
expect(wrapper.rawConfig).toBe(raw)
|
||||
expect(wrapper.effectiveConfig).toBeUndefined()
|
||||
ctx.set('configAccessTest', {})
|
||||
await wrapper
|
||||
expect(wrapper.effectiveConfig).toBe(raw)
|
||||
expect(apply).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -467,6 +467,8 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
PromptFileBinding: 'attachment.md',
|
||||
FileUploadReceiptId: 'attachment.md',
|
||||
FileUploadValue: 'attachment.md',
|
||||
ImageUploadValue: 'attachment.md',
|
||||
StagedAttachment: 'attachment.md',
|
||||
SessionStartSource: 'core.md',
|
||||
ToolCallId: 'core.md',
|
||||
SessionLogSnapshot: 'session-query.md',
|
||||
|
||||
@@ -47,9 +47,9 @@ describe('volatile Loader updates', () => {
|
||||
const fiber = await mountEntry(ctx, { Config, apply(owner: Context) {
|
||||
owner.on('loader/volatile-update', events)
|
||||
} }, { title: 'first' })
|
||||
const reference = fiber.config as ReturnType<typeof Config>
|
||||
const reference = fiber.effectiveConfig as ReturnType<typeof Config>
|
||||
await update(fiber, { title: 'second' })
|
||||
expect(fiber.config).toBe(reference)
|
||||
expect(fiber.effectiveConfig).toBe(reference)
|
||||
expect(reference.get()).toEqual({ title: 'second' })
|
||||
expect(events).toHaveBeenCalledExactlyOnceWith([[]])
|
||||
})
|
||||
@@ -70,7 +70,7 @@ describe('volatile Loader updates', () => {
|
||||
await update(first, { title: 'next', nested: { count: 2 } })
|
||||
await first.await()
|
||||
expect(mount).toHaveBeenCalledTimes(2)
|
||||
expect(first.config).toBe(initial)
|
||||
expect(first.effectiveConfig).toBe(initial)
|
||||
expect(initial.title).toBe(title)
|
||||
expect(configs[1]!.title.get()).toBe('hello')
|
||||
expect(observed).toEqual([{ paths: [['title'], ['nested', 'count']], title: 'next', count: 2 }])
|
||||
@@ -117,9 +117,9 @@ describe('volatile Loader updates', () => {
|
||||
hooks.push(config.title.get())
|
||||
})
|
||||
} }, {})
|
||||
const initial = fiber.config as ReturnType<typeof Config>
|
||||
const initial = fiber.effectiveConfig as ReturnType<typeof Config>
|
||||
await update(fiber, { title: 'accepted' })
|
||||
expect(fiber.config).toBe(initial)
|
||||
expect(fiber.effectiveConfig).toBe(initial)
|
||||
expect(initial.title.get()).toBe('accepted')
|
||||
await update(fiber, { title: 'accepted' })
|
||||
expect(hooks).toEqual([])
|
||||
@@ -180,11 +180,11 @@ describe('volatile Loader updates', () => {
|
||||
const oldUrl = 'https://a.example/'
|
||||
const newUrl = 'https://b.example/'
|
||||
const fiber = await mountEntry(ctx, { Config: schema, apply }, { live: 'a', url: oldUrl })
|
||||
const before = fiber.config as ReturnType<typeof schema>
|
||||
const before = fiber.effectiveConfig as ReturnType<typeof schema>
|
||||
await update(fiber, { live: 'b', url: newUrl })
|
||||
await fiber.await()
|
||||
expect(apply).toHaveBeenCalledTimes(2)
|
||||
expect((fiber.config as ReturnType<typeof schema>).url.href).toBe(newUrl)
|
||||
expect((fiber.effectiveConfig as ReturnType<typeof schema>).url.href).toBe(newUrl)
|
||||
expect(before.live.get()).toBe('a')
|
||||
await update(fiber, { live: 'c', url: newUrl, data: 'first' })
|
||||
await update(fiber, { live: 'd', url: newUrl, data: 'second' })
|
||||
@@ -199,7 +199,7 @@ describe('volatile Loader updates', () => {
|
||||
owner.on('loader/volatile-update', events)
|
||||
} }, { values: [undefined] })
|
||||
await update(fiber, { values: [null] })
|
||||
expect((fiber.config as ReturnType<typeof schema>).values.get()).toEqual([null])
|
||||
expect((fiber.effectiveConfig as ReturnType<typeof schema>).values.get()).toEqual([null])
|
||||
expect(events).toHaveBeenCalledExactlyOnceWith([['values']])
|
||||
})
|
||||
})
|
||||
@@ -308,7 +308,7 @@ it('updates volatile children through Group and Include custom updates and saves
|
||||
expect(includeEntry.fiber).toBe(originalInclude)
|
||||
expect(group.fiber).toBe(originalGroup)
|
||||
expect(consumer.fiber).toBe(originalConsumer)
|
||||
expect(consumer.fiber!.config).toBe(initial)
|
||||
expect(consumer.fiber!.effectiveConfig).toBe(initial)
|
||||
expect(configs).toHaveLength(1)
|
||||
expect(notifications).toHaveBeenCalledTimes(2)
|
||||
expect(childUpdates).not.toHaveBeenCalled()
|
||||
@@ -318,7 +318,7 @@ it('updates volatile children through Group and Include custom updates and saves
|
||||
entry.fiber!.update({ title: 'custom-update', fixed: 'ordinary' })
|
||||
expect(childUpdates).toHaveBeenCalledOnce()
|
||||
expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' })
|
||||
expect((entry.fiber!.config as ReturnType<typeof Config>).title.get()).toBe('hello')
|
||||
expect((entry.fiber!.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('hello')
|
||||
entry.fiber!.update({ title: 'ephemeral', fixed: 'ordinary' }, true)
|
||||
expect(childUpdates).toHaveBeenCalledTimes(2)
|
||||
expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' })
|
||||
@@ -332,11 +332,11 @@ it('commits volatile edits in place and retains direct Fiber updates', async ()
|
||||
const notifications = vi.fn()
|
||||
const apply = vi.fn(function (owner: Context) { owner.on('loader/volatile-update', notifications) })
|
||||
const fiber = await mountEntry(ctx, { Config, apply }, {})
|
||||
const original = fiber.config as ReturnType<typeof Config>
|
||||
const original = fiber.effectiveConfig as ReturnType<typeof Config>
|
||||
await ctx.loader.create({ name: 'cordis:disabled', disabled: true })
|
||||
await update(fiber, { title: 'enabled' })
|
||||
expect(apply).toHaveBeenCalledOnce()
|
||||
expect(fiber.config).toBe(original)
|
||||
expect(fiber.effectiveConfig).toBe(original)
|
||||
expect(original.title.get()).toBe('enabled')
|
||||
expect(notifications).toHaveBeenCalledExactlyOnceWith([['title']])
|
||||
await update(fiber, { title: 'invalid', nested: { count: -1 } })
|
||||
@@ -344,7 +344,7 @@ it('commits volatile edits in place and retains direct Fiber updates', async ()
|
||||
await update(fiber, { title: 'mixed', fixed: 'changed' })
|
||||
expect(apply).toHaveBeenCalledTimes(2)
|
||||
expect(original.title.get()).toBe('enabled')
|
||||
const current = fiber.config as ReturnType<typeof Config>
|
||||
const current = fiber.effectiveConfig as ReturnType<typeof Config>
|
||||
expect(current.title.get()).toBe('mixed')
|
||||
|
||||
const hook = vi.fn((_config: unknown, _noSave: boolean, next: () => void) => { next() })
|
||||
@@ -365,7 +365,7 @@ it('parses a volatile-only update through the config hook without patching the e
|
||||
const fiber = await mountEntry(ctx, { Config, apply(owner: Context) {
|
||||
owner.on('loader/volatile-update', () => { trace.push('notify') })
|
||||
} }, { block: { title: 'initial' } })
|
||||
const current = fiber.config as ReturnType<typeof Config>
|
||||
const current = fiber.effectiveConfig as ReturnType<typeof Config>
|
||||
const resolveHook = vi.fn((_raw: unknown, next: () => unknown) => next())
|
||||
fiber.ctx.on('internal/config', resolveHook)
|
||||
const contextPatch = vi.fn((_entry: unknown, next: () => void) => { next() })
|
||||
@@ -379,7 +379,7 @@ it('parses a volatile-only update through the config hook without patching the e
|
||||
expect(resolveHook).toHaveBeenCalledOnce()
|
||||
expect(trace).toEqual(['validate', 'notify'])
|
||||
expect(current.block.get()).toEqual({ title: 'changed' })
|
||||
expect(fiber._config).toBe(raw)
|
||||
expect(fiber.rawConfig).toBe(raw)
|
||||
})
|
||||
|
||||
it.each([true, false])('keeps old references untouched when isolation replaces a dependency (available: %s)', async (available) => {
|
||||
@@ -452,7 +452,7 @@ it.each(['group', 'include'] as const)('applies profile patches to a %s subtree
|
||||
await reconcileProfilePatches(ctx, patch('second'), 'volatile-test')
|
||||
expect(parent.fiber).toBe(parentFiber)
|
||||
expect(entry.fiber).toBe(childFiber)
|
||||
expect(entry.fiber!.config).toBe(original)
|
||||
expect(entry.fiber!.effectiveConfig).toBe(original)
|
||||
expect(original.title).toBe(reference)
|
||||
expect(reference.get()).toBe('second')
|
||||
expect(configs).toHaveLength(1)
|
||||
@@ -481,9 +481,9 @@ it('logs an invalid candidate and keeps its references while other entries commi
|
||||
await invalid.entry!.update({ config: { title: 'invalid', nested: { count: -1 } } })
|
||||
await healthy.entry!.update({ config: { title: 'healthy' } })
|
||||
expect(warning).toHaveBeenCalledTimes(2)
|
||||
expect((invalid.config as ReturnType<typeof Config>).title.get()).toBe('hello')
|
||||
expect(invalid._config).toEqual({ title: 'invalid', nested: { count: -1 } })
|
||||
expect((healthy.config as ReturnType<typeof Config>).title.get()).toBe('healthy')
|
||||
expect((invalid.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('hello')
|
||||
expect(invalid.rawConfig).toEqual({ title: 'invalid', nested: { count: -1 } })
|
||||
expect((healthy.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('healthy')
|
||||
expect(events).toHaveBeenCalledExactlyOnceWith([['title']])
|
||||
})
|
||||
|
||||
@@ -500,7 +500,7 @@ it.each([false, true])('retains raw expression edits for dependency restoration
|
||||
await fiber.entry!.update({ config: raw })
|
||||
await fiber.await()
|
||||
expect(values).toEqual(volatile ? ['same'] : ['same', 'same'])
|
||||
expect(fiber._config).toBe(raw)
|
||||
expect(fiber.rawConfig).toBe(raw)
|
||||
await provider.dispose()
|
||||
await provide('old-route', 'new-route')
|
||||
await fiber.await()
|
||||
@@ -540,10 +540,10 @@ it('compares ordinary URL transforms by value and remounts when an expression re
|
||||
const fixed = { __jsExpr: "ctx.get('volatile-transform-source').value" }
|
||||
const raw = { url: 'https://example.com/', fixed, live: 'old' }
|
||||
const fiber = await mountEntry(ctx, { Config: schema, apply: mount }, raw)
|
||||
const current = fiber.config as ReturnType<typeof schema>
|
||||
const current = fiber.effectiveConfig as ReturnType<typeof schema>
|
||||
await update(fiber, { ...raw, live: 'new' })
|
||||
expect(mount).toHaveBeenCalledOnce()
|
||||
expect(fiber.config).toBe(current)
|
||||
expect(fiber.effectiveConfig).toBe(current)
|
||||
expect(current.url.href).toBe(raw.url)
|
||||
expect(current.fixed).toBe('initial')
|
||||
expect(current.live.get()).toBe('new')
|
||||
@@ -554,7 +554,7 @@ it('compares ordinary URL transforms by value and remounts when an expression re
|
||||
expect(current.fixed).toBe('initial')
|
||||
expect(current.live.get()).toBe('new')
|
||||
expect(events).toHaveBeenCalledOnce()
|
||||
const replaced = fiber.config as ReturnType<typeof schema>
|
||||
const replaced = fiber.effectiveConfig as ReturnType<typeof schema>
|
||||
expect(replaced.fixed).toBe('changed')
|
||||
expect(replaced.live.get()).toBe('remounted')
|
||||
})
|
||||
@@ -568,13 +568,13 @@ it('remounts when an ordinary parent expression removes a live reference path',
|
||||
const mount = vi.fn(function (owner: Context) { owner.on('loader/volatile-update', events) })
|
||||
const raw = { block: { __jsExpr: "ctx.get('volatile-path-source').block" }, live: 'old' }
|
||||
const fiber = await mountEntry(ctx, { Config: schema, apply: mount }, raw)
|
||||
const current = fiber.config as ReturnType<typeof schema>
|
||||
const current = fiber.effectiveConfig as ReturnType<typeof schema>
|
||||
source.block = undefined
|
||||
await update(fiber, { ...raw, live: 'new' })
|
||||
expect(mount).toHaveBeenCalledTimes(2)
|
||||
expect(current.block.value.get()).toBe('old')
|
||||
expect(events).not.toHaveBeenCalled()
|
||||
expect((fiber.config as ReturnType<typeof schema>).block).toBeUndefined()
|
||||
expect((fiber.effectiveConfig as ReturnType<typeof schema>).block).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps an ordinary plugin mounted when an absent object becomes its explicit default', async () => {
|
||||
@@ -582,13 +582,13 @@ it('keeps an ordinary plugin mounted when an absent object becomes its explicit
|
||||
const Config = z.object({ nested: z.object({ fixed: z.string() }).default({ fixed: 'default' }) })
|
||||
const mount = vi.fn()
|
||||
const fiber = await mountEntry(ctx, { Config, apply: mount }, {})
|
||||
const config: unknown = fiber.config
|
||||
const config: unknown = fiber.effectiveConfig
|
||||
await update(fiber, { nested: { fixed: 'default' } })
|
||||
expect(fiber.config).toBe(config)
|
||||
expect(fiber.effectiveConfig).toBe(config)
|
||||
expect(mount).toHaveBeenCalledTimes(1)
|
||||
await update(fiber, { nested: { fixed: 'changed' } })
|
||||
expect(mount).toHaveBeenCalledTimes(2)
|
||||
expect(fiber.config).toEqual({ nested: { fixed: 'changed' } })
|
||||
expect(fiber.effectiveConfig).toEqual({ nested: { fixed: 'changed' } })
|
||||
})
|
||||
|
||||
it('keeps a noSave volatile value as the pending raw config across a no-op entry update', async () => {
|
||||
@@ -596,11 +596,11 @@ it('keeps a noSave volatile value as the pending raw config across a no-op entry
|
||||
const fiber = await mountEntry(ctx, { Config, apply() {} }, { title: 'saved' })
|
||||
fiber.update({ title: 'ephemeral' }, true)
|
||||
await fiber.await()
|
||||
expect((fiber.config as ReturnType<typeof Config>).title.get()).toBe('ephemeral')
|
||||
expect((fiber.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('ephemeral')
|
||||
expect(fiber.entry!.options.config).toEqual({ title: 'saved' })
|
||||
await fiber.entry!.update({ config: { title: 'saved' } })
|
||||
expect(fiber._config).toEqual({ title: 'ephemeral' })
|
||||
expect((fiber.config as ReturnType<typeof Config>).title.get()).toBe('ephemeral')
|
||||
expect(fiber.rawConfig).toEqual({ title: 'ephemeral' })
|
||||
expect((fiber.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('ephemeral')
|
||||
})
|
||||
|
||||
it('isolates a failing notification listener and dispatches with a Context receiver', async () => {
|
||||
@@ -613,11 +613,11 @@ it('isolates a failing notification listener and dispatches with a Context recei
|
||||
const warning = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
|
||||
onTestFinished(() => { warning.mockRestore() })
|
||||
await update(fiber, { title: 'committed' })
|
||||
expect((fiber.config as ReturnType<typeof Config>).title.get()).toBe('committed')
|
||||
expect((fiber.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('committed')
|
||||
expect(receivers).toEqual([fiber])
|
||||
expect(warning).toHaveBeenCalledWith(expect.objectContaining({ message: 'listener boom' }))
|
||||
await update(other, { title: 'unaffected' })
|
||||
expect((other.config as ReturnType<typeof Config>).title.get()).toBe('unaffected')
|
||||
expect((other.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('unaffected')
|
||||
})
|
||||
|
||||
it('remounts instead of committing when an ordinary field parses into a fresh class instance', async () => {
|
||||
@@ -626,9 +626,9 @@ it('remounts instead of committing when an ordinary field parses into a fresh cl
|
||||
const schema = z.object({ handle: z.transform(z.string(), value => new Handle(value)), live: z.string().volatile() })
|
||||
const mount = vi.fn()
|
||||
const fiber = await mountEntry(ctx, { Config: schema, apply: mount }, { handle: 'h', live: 'old' })
|
||||
const before = fiber.config as ReturnType<typeof schema>
|
||||
const before = fiber.effectiveConfig as ReturnType<typeof schema>
|
||||
await update(fiber, { handle: 'h', live: 'new' })
|
||||
expect(mount).toHaveBeenCalledTimes(2)
|
||||
expect(before.live.get()).toBe('old')
|
||||
expect((fiber.config as ReturnType<typeof schema>).live.get()).toBe('new')
|
||||
expect((fiber.effectiveConfig as ReturnType<typeof schema>).live.get()).toBe('new')
|
||||
})
|
||||
|
||||
Vendored
+2
-2
@@ -46,7 +46,7 @@ Keep this log exhaustive — every divergence from upstream must be listed.
|
||||
12. **`loader/src/config/entry.ts` activation observer**: the detached `Entry.init()` completion observer handles both outcomes; the fiber retains its activation error for explicit consumer audits. Covered by `packages/boot/app-boot/tests/user-patches.spec.ts`.
|
||||
13. **`include/src/index.ts` `writeTask` type**: widened the optional `writeTask?: NodeJS.Timeout` property to `NodeJS.Timeout | undefined` — the debounced writer assigns `undefined` on flush, which `exactOptionalPropertyTypes` rejects on a plain optional. Type-only; no behavior change.
|
||||
14. **`include/src/index.ts` durable debounced writes**: serialized and tracked config-file writes, retried transient `EACCES`/`EBUSY`/`EPERM` rename failures with a bounded backoff, observed asynchronous timer rejections, and drained writes before and after child removal during Include teardown. The first drain preserves an existing terminal write failure even if child removal schedules a later write. Missing-file initialization awaits the write and forces a fresh parse before mounting the initial entries. Windows can briefly retain a destination handle after a Loader child disposes; the upstream fire-and-forget rename escaped as an unhandled rejection and could lose the persisted `disabled` state. A terminal failure is logged by the asynchronous writer and remains on the queue so `Include.stop()` rethrows it instead of silently declaring persistence complete; Cordis's ordinary fiber teardown retains its separate error-containment contract. Covered by `packages/host/directory-picker-auto/tests/loader-composition.spec.ts` with injected transient and terminal rename failures.
|
||||
15. **Lazy Loader config resolution across `cordis/src/{events,fiber}.ts`, `loader/src/{index,config/entry}.ts`, `include/src/index.ts`, and `hmr/src/index.ts`**: ports [cordiverse/cordis#41](https://github.com/cordiverse/cordis/pull/41), retaining raw fiber config and resolving it through `internal/config` only after declared injections are active. Provider replacement re-resolves the raw expression, pending updates retain it, and HMR transfers it. Resolution applies only to the entry root, so child plugins mounted by a row keep caller-owned config identity. Include declares the `EntryGroup.key` tree-carrier marker (as Group does): its config is entry and patch lists, so interpolation keeps it literal and a `!!js` expression inside a nested row's config resolves lazily in that row's own fiber (Include's own `path` therefore stays literal too). Deferred failures retain the owning row diagnostic, and tree teardown does not persist failure-driven self-disposal. Covered by `packages/boot/app-boot/tests/{app-boot,user-patches}.spec.ts`, `packages/boot/cmdline/tests/cmdline.spec.ts`, `apps/cli/tests/web-agent-presets.e2e.ts`, and the built custom-profile cases in `apps/cli/tests/built-bin.e2e.ts`.
|
||||
15. **Lazy Loader config resolution across `cordis/src/{events,fiber}.ts`, `loader/src/{index,config/entry}.ts`, `include/src/index.ts`, and `hmr/src/index.ts`**: ports [cordiverse/cordis#41](https://github.com/cordiverse/cordis/pull/41), retaining raw fiber config and resolving it through `internal/config` only after declared injections are active. Provider replacement re-resolves the raw expression, pending updates retain it, and HMR transfers it. Resolution applies only to the entry root, so child plugins mounted by a row keep caller-owned config identity. Include declares the `EntryGroup.key` tree-carrier marker (as Group does): its config is entry and patch lists, so interpolation keeps it literal and a `!!js` expression inside a nested row's config resolves lazily in that row's own fiber (Include's own `path` therefore stays literal too). Deferred failures retain the owning row diagnostic, and tree teardown does not persist failure-driven self-disposal. `Fiber.rawConfig`, `Fiber.resolveConfig(candidate)` and `Fiber.effectiveConfig` centralize raw retention, candidate evaluation and reads of the lifecycle-published object. Accessors, updates and restarts use the canonical fiber, including calls through registry wrappers; candidate resolution never publishes or commits references. Loader volatile updates, config editing, settings, translator and both HMR providers use these accessors while the existing Core config fields and event protocol remain in place. Covered by `scripts/cordis-config-access.spec.ts`, `packages/boot/app-boot/tests/{app-boot,user-patches}.spec.ts`, `packages/boot/cmdline/tests/cmdline.spec.ts`, `apps/cli/tests/web-agent-presets.e2e.ts`, and the built custom-profile cases in `apps/cli/tests/built-bin.e2e.ts`.
|
||||
16. **`cordis/package.json` publishes `src`**: added `src` to the `files` list, joining the other eight vendored packages. Cordis declares `"./src/*": "./src/*"` in its exports, so a tarball without `src` publishes an export map pointing at absent files; the release change judgement also reads `files` to decide whether a diff reaches the payload, and a package whose only published paths are build output has no tracked path to match.
|
||||
17. **`@deepseek-ai` rescope**: every vendored manifest `name`, every internal dependency entry among the vendored set, and every module specifier that reaches them use the scoped names in the manifest table's `npm name` column. Directory names, version numbers, and dependency ranges are unchanged, and no upstream runtime identifier is renamed — `Symbol.for('schemastery')` and Schemastery's `vendor:` metadata field keep their upstream values. Re-apply with `pnpm run rescope-vendor --apply` after a sync; the table's two name columns are the mapping, restated for consumers in [docs/rescope.md](../docs/rescope.md).
|
||||
18. **Entry `disabled` interpolation in `loader/src/config/entry.ts`**: a `disabled: !!js` expression evaluates against the loader context at every mount decision; the raw node stays in the options, so write-back keeps the `!!js` form. `disabled` is the only interpolated metadata field. Covered by `packages/boot/app-boot/tests/user-patches.spec.ts` and `apps/cli/tests/windows-shell.spec.ts`.
|
||||
@@ -56,7 +56,7 @@ Keep this log exhaustive — every divergence from upstream must be listed.
|
||||
|
||||
21. **`cordis/src/logger.ts` exporter disposal**: each disposer retains its registration id, so removing an earlier exporter cannot delete a later console or telemetry exporter. Covered by startup collector cleanup in `packages/boot/app-boot/tests/app-boot.spec.ts` and disabled-feedback output in `packages/session/session-telemetry-otel/tests/loader-composition.e2e.ts`.
|
||||
|
||||
22. **Volatile config across `cosmokit`, `schemastery`, `cordis`, and `loader`**: Cosmokit supplies immutable references and framework-owned commits; `deepEqual` treats two references as equal, propagates strict comparison into arrays, compares every array slot with holes treated as undefined, handles cycles conservatively, compares URLs by normalized href, and compares other opaque objects by identity in strict mode. Schemastery adds `.volatile()`, optional/default inference, placement validation without eager lazy-schema expansion (a lazy inner is validated once when built), metadata-free serialized node compatibility, serialized metadata, reference-aware simplification, unsupported volatile values reported as `ValidationError` with their path, and `.default()` accepting the raw input type `Partial<S>` because a volatile field makes the output type carry references. Loader's save path calls `simplify` with its schema receiver (`unparse.call`), an independent fix for the unbound-`this` call. Cordis exports consumer types without changing Fiber lifecycle. Loader compares raw options strictly in `Entry.update`; for a config-only change on an active fiber it calls the pure `equalExceptVolatile` function in `config/diff.ts`, which narrows the Standard Schema to Schemastery's `Schema` type (a new type-only `@deepseek-ai/schemastery` dependency of `loader`) and recursively skips fixed volatile paths using schema metadata without executing config hooks or validation. Missing or null object nodes compare using their declared defaults, including nodes without volatile descendants; schema backedges retain raw comparison. Entry passes its actual schema and preserves ordinary context and custom-update lifecycles. For a volatile-only change, `Entry._commitVolatile` re-parses the raw config through the fiber's `internal/config` hook and `resolveConfig`, compares ordinary effective values, commits references and emits the instance-local `loader/volatile-update` declared in `loader/src/index.ts`; a changed ordinary effective value falls back to the ordinary remount, and an invalid candidate is logged while the raw config stays retained for the next activation. Cosmokit provides reference enumeration and commits, and `simplify` is called with its schema receiver. The package READMEs document these additions; schema tests live in `scripts/volatile-config.spec.ts`, Loader runtime and real-file tests in `scripts/loader-volatile-update.spec.ts`, and code replacement tests in the HMR module suite.
|
||||
22. **Volatile config across `cosmokit`, `schemastery`, `cordis`, and `loader`**: Cosmokit supplies immutable references and framework-owned commits; `deepEqual` treats two references as equal, propagates strict comparison into arrays, compares every array slot with holes treated as undefined, handles cycles conservatively, compares URLs by normalized href, and compares other opaque objects by identity in strict mode. Schemastery adds `.volatile()`, optional/default inference, placement validation without eager lazy-schema expansion (a lazy inner is validated once when built), metadata-free serialized node compatibility, serialized metadata, reference-aware simplification, unsupported volatile values reported as `ValidationError` with their path, and `.default()` accepting the raw input type `Partial<S>` because a volatile field makes the output type carry references. Loader's save path calls `simplify` with its schema receiver (`unparse.call`), an independent fix for the unbound-`this` call. Cordis exports consumer types without changing Fiber lifecycle. Loader compares raw options strictly in `Entry.update`; for a config-only change on an active fiber it calls the pure `equalExceptVolatile` function in `config/diff.ts`, which narrows the Standard Schema to Schemastery's `Schema` type (a new type-only `@deepseek-ai/schemastery` dependency of `loader`) and recursively skips fixed volatile paths using schema metadata without executing config hooks or validation. Missing or null object nodes compare using their declared defaults, including nodes without volatile descendants; schema backedges retain raw comparison. Entry passes its actual schema and preserves ordinary context and custom-update lifecycles. For a volatile-only change, `Entry._commitVolatile` re-parses the raw config through `Fiber.resolveConfig()`, compares ordinary effective values, commits references and emits the instance-local `loader/volatile-update` declared in `loader/src/index.ts`; a changed ordinary effective value falls back to the ordinary remount, and an invalid candidate is logged while the raw config stays retained for the next activation. Cosmokit provides reference enumeration and commits, and `simplify` is called with its schema receiver. The package READMEs document these additions; schema tests live in `scripts/volatile-config.spec.ts`, Loader runtime and real-file tests in `scripts/loader-volatile-update.spec.ts`, and code replacement tests in the HMR module suite.
|
||||
|
||||
23. **`loader/src/config/entry.ts` module identity**: retains each entry's raw import result as `moduleNamespace`, before plugin export normalization. HMR matches that object to Node's cached module namespace and updates it after a successful reload. `EntryTree.import()` keeps its existing arguments and return value; `loader/README.md` documents the additive field.
|
||||
|
||||
|
||||
Vendored
+6
@@ -103,3 +103,9 @@ docs use public APIs from `cordis`; loader examples additionally use
|
||||
## Volatile configuration
|
||||
|
||||
Schemas may return `Volatile<T>` references, whose values are read through `.get()`. Cordis exports the consumer types; Loader commits volatile-only changes into the running references without restarting and notifies the owning fiber through `loader/volatile-update`. Direct `fiber.update()` retains its existing update waterfall and default restart.
|
||||
|
||||
## Configuration access
|
||||
|
||||
`fiber.rawConfig` reads or retains the raw input for a later activation. Assigning it does not validate, update the running instance or trigger a restart. Registry wrappers route raw writes, updates and restarts through the same canonical fiber. `fiber.resolveConfig(candidate)` evaluates the fiber's config hooks and schema without publishing the result; any services used by those hooks must already be available. `fiber.effectiveConfig` returns the lifecycle-published object without re-parsing, preserving the identity of volatile references. It is undefined before the first resolution and stays readable after unload, so consumers that require a running instance also check the fiber state.
|
||||
|
||||
Use `fiber.update()` for an ordinary config change. Loader retains raw input separately when committing only volatile values into the running object.
|
||||
|
||||
Vendored
+50
-21
@@ -186,9 +186,9 @@ export class Fiber {
|
||||
public uid: number | null
|
||||
/** The context this fiber's plugin runs in (extends the parent context). */
|
||||
public readonly ctx: Context
|
||||
/** The validated plugin config (updated by `update()`). */
|
||||
/** The validated plugin config (updated by `update()`); read through {@link effectiveConfig}. */
|
||||
public config: any
|
||||
/** The raw plugin config, re-resolved before each activation. */
|
||||
/** The raw plugin config, re-resolved before activation; use {@link rawConfig} to read or retain it. */
|
||||
public _config: any
|
||||
/** Current lifecycle state; transitions emit `internal/status`. */
|
||||
public state = FiberState.PENDING
|
||||
@@ -638,9 +638,36 @@ export class Fiber {
|
||||
})
|
||||
}
|
||||
|
||||
private _resolveConfig(config: any) {
|
||||
config = this.context.waterfall(this, 'internal/config', config, () => config)
|
||||
return this.runtime ? resolveConfig(this.runtime, config) : config
|
||||
/** Raw input retained for the next activation, without evaluating expressions or validating it. */
|
||||
get rawConfig(): unknown {
|
||||
return this.ctx.fiber._config
|
||||
}
|
||||
|
||||
/** Retain raw input without changing the running config or triggering an update. */
|
||||
set rawConfig(config: unknown) {
|
||||
this.ctx.fiber._config = config
|
||||
}
|
||||
|
||||
/**
|
||||
* The config object published by the existing activation/update lifecycle, without cloning or re-parsing.
|
||||
* It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`.
|
||||
*/
|
||||
get effectiveConfig(): unknown {
|
||||
return this.ctx.fiber.config
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema.
|
||||
* Does not publish the result, replace raw input, or commit running volatile references.
|
||||
* Required injections must be available when a hook uses them.
|
||||
* @param config Raw candidate input.
|
||||
* @returns The candidate's resolved config, retaining the schema's result identity.
|
||||
* @throws {ValidationError} when the runtime schema rejects the candidate; hook errors propagate.
|
||||
*/
|
||||
resolveConfig(config: unknown): unknown {
|
||||
const fiber = this.ctx.fiber
|
||||
config = fiber.context.waterfall(fiber, 'internal/config', config, () => config)
|
||||
return fiber.runtime ? resolveConfig(fiber.runtime, config) : config
|
||||
}
|
||||
|
||||
private async _reload() {
|
||||
@@ -652,7 +679,7 @@ export class Fiber {
|
||||
// the load. Do not run plugin code for a stale epoch; the state update
|
||||
// below will drain any effects collected while the fiber was PENDING.
|
||||
if (this._runner.epoch === oldEpoch) {
|
||||
this.config = this._resolveConfig(this._config)
|
||||
this.config = this.resolveConfig(this._config)
|
||||
await this._execute(this._runner)
|
||||
this._error = undefined
|
||||
}
|
||||
@@ -716,10 +743,11 @@ export class Fiber {
|
||||
* @throws {CordisError} `INACTIVE_EFFECT` when the fiber is already disposed.
|
||||
*/
|
||||
async restart() {
|
||||
this.assertActive()
|
||||
this._setEpoch(INACTIVE)
|
||||
this._refresh()
|
||||
await this.await()
|
||||
const fiber = this.ctx.fiber
|
||||
fiber.assertActive()
|
||||
fiber._setEpoch(INACTIVE)
|
||||
fiber._refresh()
|
||||
await fiber.await()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -734,21 +762,22 @@ export class Fiber {
|
||||
* @throws {ValidationError} when the new config fails validation.
|
||||
*/
|
||||
update(config: any, noSave = false) {
|
||||
this.assertActive()
|
||||
this._config = config
|
||||
if (this.state !== FiberState.ACTIVE) {
|
||||
const fiber = this.ctx.fiber
|
||||
fiber.assertActive()
|
||||
fiber._config = config
|
||||
if (fiber.state !== FiberState.ACTIVE) {
|
||||
// Config resolution may access injected services, so defer it until the
|
||||
// fiber can activate.
|
||||
this._error = undefined
|
||||
this._setEpoch(INACTIVE)
|
||||
this._refresh()
|
||||
fiber._error = undefined
|
||||
fiber._setEpoch(INACTIVE)
|
||||
fiber._refresh()
|
||||
return
|
||||
}
|
||||
config = this._resolveConfig(config)
|
||||
this.context.waterfall(this, 'internal/update', config, noSave, () => {
|
||||
this.config = config
|
||||
this._error = undefined
|
||||
return this.restart()
|
||||
config = fiber.resolveConfig(config)
|
||||
fiber.context.waterfall(fiber, 'internal/update', config, noSave, () => {
|
||||
fiber.config = config
|
||||
fiber._error = undefined
|
||||
return fiber.restart()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user