Merge remote-tracking branch 'origin/master' into feat/dingtalk-plugin

This commit is contained in:
gengruilin committed 2026-11-19 14:53:34 +08:00
commit adb7c7d3f4
1227 files changed
+34992 -3185

No files matched your search

@@ -12,8 +12,8 @@
en: a15c7c13f167e5ac
zh: 63bcc2ef60c2f344
/agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/packaging-route-yao-pkg-pkg-s-sea-mode:
en: f1c2b60e9474111d
zh: 5de398b5e8554429
en: da2d0e038a0cab9d
zh: 495c770640264c1d
/agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/the-serving-interface-is-a-plugin-inside-the-dsh-application:
en: 5fdde26e9e8c6108
zh: 629559d733c1f0c5
@@ -25,6 +25,8 @@ The exe is packaged with the **`--sea` (enhanced SEA) mode** of [@yao-pkg/pkg](h
The same patch makes the SEA bootstrap's native-addon extraction atomic. On the first `dlopen` of an addon inside the VFS, pkg's `patchDlopen` copies the addon's package tree to `$PKG_NATIVE_CACHE_PATH/pkg/<sha256 of the .node file>/` (default `~/.cache/pkg/...`), a per-user directory that every concurrent process of the same executable shares; upstream writes each file straight to its final path with `writeFileSync`, which truncates a file another process may already have mapped and lets that process's `existsSync`/hash check read a half-written file. Concurrent first starts therefore die with SIGBUS on Linux or fail with `ERR_DLOPEN_FAILED: Library not loaded` on sharp's libvips on macOS (#4664). The patch routes the three write sites through a same-directory temporary file and `renameSync`, so a cache path is either absent or complete, every process finishes its own copy pass before it loads, and concurrent renames of identical content need no lock. The cache location, hash keying, and per-file comparison are unchanged, so a consumer that isolates the cache per instance through `PKG_NATIVE_CACHE_PATH` keeps working; worker threads only define the hook and never install it. Measured (linux-x64, node24 target, pkg 6.21.0, a probe that loads sharp with its 18 MB libvips library, 16 concurrent first starts against one empty cache, five rounds): 39 of 80 processes died with SIGBUS before the change and 0 of 80 after it, with no temporary files left behind.
The same patch makes the VFS honor `{ bigint: true }` in `stat`, `lstat`, their synchronous forms, and `fs.promises`. Upstream returns the same number-valued stats whatever the options, while `dsh-fs-local` and `dsh-fs-sandbox` read VFS paths through BigInt stats, so every `ctx.fs` access to a packaged file failed with `Cannot mix BigInt and other types`: the `read` tool could not open a packaged skill file, and a `skill-filesystem` root inside the VFS made skill discovery incomplete. The patch converts a VFS entry's numbers to the `BigIntStats` fields, including nanosecond times derived from the millisecond values; paths outside the VFS keep Node's own results.
Terminology reminder: pkg's `/snapshot` VFS has nothing to do with this repo's testing-system "snapshot" (ACP replay expected outputs, `$DSH_SNAPSHOT`); this document says "VFS" for the former.
### The serving interface is a plugin inside the dsh application
@@ -25,6 +25,8 @@ exe 使用 [@yao-pkg/pkg](https://github.com/yao-pkg/pkg)(vercel/pkg 归档后
同一补丁还把 SEA bootstrap 的原生插件解包改成原子写入。VFS 内的插件首次 `dlopen` 时,pkg 的 `patchDlopen` 会把该插件所在的包目录整棵拷到 `$PKG_NATIVE_CACHE_PATH/pkg/<.node 文件的 sha256>/`(默认 `~/.cache/pkg/...`),这是同一个 exe 的所有并发进程共用的按用户目录;上游用 `writeFileSync` 直接写目标路径,会把另一个进程可能已经映射的文件截断,并让该进程的 `existsSync`/哈希比对读到写了一半的文件。因此并发首次启动在 Linux 上以 SIGBUS 崩溃,在 macOS 上对 sharp 的 libvips 报 `ERR_DLOPEN_FAILED: Library not loaded`(#4664)。补丁让三处写入都经过同目录临时文件加 `renameSync`,于是缓存路径要么不存在、要么完整,每个进程都在加载前走完自己的拷贝,相同内容的并发 rename 不需要锁。缓存位置、哈希键与逐文件比对均未改变,通过 `PKG_NATIVE_CACHE_PATH` 按实例隔离缓存的消费方照常工作;worker 线程只定义该钩子而从不安装。 实测(linux-x64、node24 构建目标、pkg 6.21.0,一个加载 sharp 及其 18 MB libvips 库的探针,16 个进程对同一个空缓存并发首次启动,跑五轮):改动前 80 个进程中 39 个以 SIGBUS 崩溃,改动后 80 个全部正常,且无残留临时文件。
同一补丁还让 VFS 的 `stat`、`lstat`、它们的同步形式以及 `fs.promises` 遵守 `{ bigint: true }`。上游无论选项如何都返回同一份数值型 stats,而 `dsh-fs-local` 与 `dsh-fs-sandbox` 通过 BigInt stats 读取 VFS 路径,因此经 `ctx.fs` 访问打包文件时都会以 `Cannot mix BigInt and other types` 失败:`read` 工具打不开打包的 skill 文件,位于 VFS 内的 `skill-filesystem` 根使 skill 发现不完整。补丁把 VFS 条目的数值转换为 `BigIntStats` 字段,其中纳秒时间由毫秒值换算;VFS 之外的路径仍使用 Node 自身的结果。
术语提醒:pkg 的 `/snapshot` VFS 与本仓库测试体系的「快照」(ACP(Agent Client Protocol)回放预期输出、`$DSH_SNAPSHOT`)无关,本文用「VFS」指前者。
### 对外服务接口是 dsh 应用中的插件
@@ -9,8 +9,8 @@
en: 31fba384d90ce7d2
zh: f8b814868f3280c3
/agent-note-session-working-directory/decision:
en: 5de5171ee52a62b4
zh: 7f78197ea38af658
en: 5ff0c24c29c916b9
zh: bfbb082623c2a86c
/agent-note-session-working-directory/alternatives-considered:
en: f0995feb9b6bcce8
zh: 97417085fd17f70f
@@ -16,11 +16,11 @@ Only Host operations change the directory: worktree creation and exit, the forge
Required user-context snapshots carry the current value; each committed change attempts to queue a notice through the ordinary Agent inbox. Cancellation or disposal may discard unadmitted notices while the directory event survives for subsequent requests. The original project is the recovery destination when the selected directory disappears. Missing recovery destinations produce an error. Write permissions remain independent.
Subagents start in the parent's current directory or a Host-chosen directory and commit that directory after inherited history. Existing processes, terminals, and persistent shells keep their process-local directory. Project instructions, skills, and completion follow the effective directory without changing Session identity, grouping, or runtime composition.
Subagents start in the parent's current directory or a Host-chosen directory and commit that directory after inherited history. Existing processes, terminals, and persistent shells keep their process-local directory. The model's file and process tools, project instructions, skills, completion, and the sandbox boundary follow the effective directory, which is the [workspace root](2026-11-03-session-workspace-root.md), without changing Session identity, grouping, or runtime composition.
Live Session skill catalogs and file completion validate through the same directory owner. These reads can commit recovery and queue its notice before discovery, keeping discovered files and subsequent operations tied to the committed Session directory. Cold skill catalogs read the recorded projection without activating an Agent.
Live Session skill catalogs and file completion validate through the same directory owner, then read the workspace root. These reads can commit recovery and queue its notice before discovery, keeping discovered files and subsequent operations tied to the committed Session directories. Cold skill catalogs read the recorded root projection without activating an Agent.
Web sidebar terminal environment lookup reads the effective directory without filesystem validation or recovery, so a missing directory does not prevent reconnecting to a retained terminal. New terminal creation validates and recovers through the directory owner before spawning; the process keeps that directory independently of later Session changes.
Web sidebar terminal environment lookup reads the workspace root without filesystem validation or recovery, so a missing directory does not prevent reconnecting to a retained terminal. New terminal creation validates and recovers through the directory owner before spawning in the workspace root; the process keeps that directory independently of later Session changes.
Playwright MCP and Chrome DevTools MCP validate the effective directory when acquiring a Session's MCP connection and use it to launch the server. Later directory changes do not restart the retained server or change its process directory.
@@ -16,11 +16,11 @@ Status: implemented
必需的用户上下文快照携带当前值;每次已提交变更都会尝试通过普通 Agent 收件箱排入通知。取消或销毁可能丢弃尚未进入请求的通知,但目录事件仍然保留,供后续请求使用。所选目录消失时恢复到原始项目。恢复目录也消失时返回错误。写权限保持独立。
子代理从父代理的当前目录或 Host 选定的目录启动,并在继承历史之后提交该目录。已有进程、终端和持久 shell 保留进程局部目录。项目指令、技能和补全跟随有效目录,不改变 Session 身份、归属或运行时组合。
子代理从父代理的当前目录或 Host 选定的目录启动,并在继承历史之后提交该目录。已有进程、终端和持久 shell 保留进程局部目录。模型的文件与进程工具、项目指令、技能、补全和沙箱边界都跟随有效目录,即[工作区根](2026-11-03-session-workspace-root.zh.md),不改变 Session 身份、归属或运行时组合。
活跃 Session 的技能目录与文件补全通过同一个目录 owner 验证目录。这些读取可在发现操作之前提交恢复并排入通知,使发现的文件与后续操作关联到已提交的 Session 目录。冷态技能目录读取已记录的投影,不激活 Agent。
活跃 Session 的技能目录与文件补全通过同一个目录 owner 验证目录,再读取工作区根。这些读取可在发现操作之前提交恢复并排入通知,使发现的文件与后续操作关联到已提交的 Session 目录。冷态技能目录读取已记录的根投影,不激活 Agent。
Web 侧栏终端的环境查询读取有效目录,不验证文件系统或执行恢复,因此目录缺失不会阻止重新连接保留的终端。新终端在创建进程前通过目录 owner 验证和恢复目录;后续 Session 目录变更不会改变该进程的目录。
Web 侧栏终端的环境查询读取工作区根,不验证文件系统或执行恢复,因此目录缺失不会阻止重新连接保留的终端。新终端在创建进程前通过目录 owner 验证和恢复目录,并在工作区根中启动;后续 Session 目录变更不会改变该进程的目录。
Playwright MCP 和 Chrome DevTools MCP 在获取 Session 的 MCP 连接时验证有效目录,并在该目录启动服务器。后续目录变更不会重启保留的服务器,也不会改变其进程目录。
@@ -9,8 +9,8 @@
en: abd0263d14861926
zh: e1736cd08e87f795
/agent-note-shared-time-vocabulary-for-wall-clock-selectors/decision:
en: f1c2b98bf56cdba3
zh: 7e9444f8e73a4834
en: cf4dc376cbdb0e90
zh: 6aea79fb9dfe419d
/agent-note-shared-time-vocabulary-for-wall-clock-selectors/alternatives-considered:
en: 3964f7d653747b55
zh: b50636faea4917ef
@@ -16,7 +16,7 @@ The library answers discriminated results and carries no failure vocabulary. `pa
Schedule consumes it and keeps every domain decision. `canonicalizeTimeZone`, `decodeInstant`, `parseAtInput`, and `futureInstant` remain Schedule entry points with their existing codes and diagnostics; they call the shared parser and map its reason. Pure Cron/RRULE parsing and bounded occurrence searches belong to the library, take explicit reference times, and validate committed targets with `fourDigitYearEpoch`. Schedule owns durable records, the fold and transition authority, injection-resistant framing, daily and weekly date walks, delivery limits, and domain errors. The shared values own no task state, wall clock, or timers.
`dsh-time-context` consumes it too and keeps its stricter policy. `deriveBrowserTimeZoneContext` reads each user-rpc zone through `canonicalizeTimeZone` and refuses an alias whose canonical answer differs from the reported value, so the request boundary still requires an identity another process resolves back to the same name. Time-context owns its three refusals and their messages; the shared entry only answers the canonical name or a reason, and its `unsupported` rejection carries the platform error the library caught, so that refusal keeps its `cause` in both consumers.
`dsh-time-context` consumes it too and keeps its stricter policy. `deriveBrowserTimeZoneContext` reads each reported user-message zone through `canonicalizeTimeZone` and refuses an alias whose canonical answer differs from the reported value, so the request boundary still requires an identity another process resolves back to the same name. Time-context owns its three refusals and their messages; the shared entry only answers the canonical name or a reason, and its `unsupported` rejection carries the platform error the library caught, so that refusal keeps its `cause` in both consumers.
`Duration` holds one span as a single millisecond count, and it is a class rather than a branded number because TypeScript's arithmetic erases a brand: adding two differently branded numbers answers an unbranded `number`, so a brand cannot stop seconds and milliseconds from being mixed, while an instance can. The unit is milliseconds because every producer and consumer in this repository already uses it (`Date.now()`, `SessionEvent.time`, the session log, the client), and because a double holds every millisecond of the whole `Date` range exactly, so no precision is spent on the unit. Instances are frozen, no coercion hook is overridden, and a span is bounded by the exactly representable millisecond range, which is what makes the split exact. The published surface is `fromMilliseconds` and a whole-part `decompose()`, the two entries the migrated consumer calls.
@@ -16,7 +16,7 @@ Status: implemented
Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`decodeInstant`、`parseAtInput` 与 `futureInstant` 仍是 Schedule 的入口,保留既有错误码与诊断文案;它们调用共享解析器并映射其原因。纯 Cron/RRULE 解析与有界发生时点搜索归本库所有,接收显式参考时间,并通过 `fourDigitYearEpoch` 校验已提交时点。Schedule 拥有持久记录、折叠与状态转移权威、抗注入的框架文本、每日与每周日期遍历、投递限制及领域错误。共享值不拥有任务状态、墙钟或定时器。
`dsh-time-context` 同样消费它,并保留自己更严格的策略。`deriveBrowserTimeZoneContext` 通过 `canonicalizeTimeZone` 读取每条 user-rpc 时区,并拒绝规范答案与所报值不同的别名,因此请求边界仍然要求另一个进程能解析回同一名称。三条拒绝与它们的文案归 time-context 所有;共享入口只回答规范名称或一个原因;被拒绝的结果中只有 `unsupported` 会携带本库捕获到的平台错误,使该拒绝在两个消费方都保留其 `cause`。
`dsh-time-context` 同样消费它,并保留自己更严格的策略。`deriveBrowserTimeZoneContext` 通过 `canonicalizeTimeZone` 读取每条用户消息上报的时区,并拒绝规范答案与所报值不同的别名,因此请求边界仍然要求另一个进程能解析回同一名称。三条拒绝与它们的文案归 time-context 所有;共享入口只回答规范名称或一个原因;被拒绝的结果中只有 `unsupported` 会携带本库捕获到的平台错误,使该拒绝在两个消费方都保留其 `cause`。
`Duration` 以单一毫秒计数保存一段时间;它做成类而不是 branded number,是因为 TypeScript 的算术会抹掉 brand:两个不同品牌的数字相加得到的是无品牌的 `number`,所以 brand 挡不住秒与毫秒的混用,而实例可以。单位选毫秒,是因为本仓库的每个生产者与消费者本来就用它(`Date.now()`、`SessionEvent.time`、Session 日志、客户端),也因为 double 能精确表示 `Date` 全范围内的每一个毫秒,这个单位不消耗任何精度。实例被冻结,不覆盖任何强制转换钩子,且时间段受可精确表示的毫秒范围约束——这正是拆分精确的前提。公开面就是 `fromMilliseconds` 与整数量拆解 `decompose()`,即已迁移消费方所调用的两个入口。
@@ -15,8 +15,8 @@
en: 7f33895364a9f5cc
zh: f1c79ea15f5c151e
/agent-note-initial-draft-content-and-structured-reference-restoration/decision/classes-and-methods:
en: e57394545d9d93ff
zh: 5ab142e661750b82
en: 9039c6bf700da3cf
zh: 2808757aed8615b3
/agent-note-initial-draft-content-and-structured-reference-restoration/decision/data-flow:
en: dd57e639e9328f1d
zh: 5e16cb2e3a73597c
@@ -37,7 +37,7 @@ The existing `dsh.conversation.<sessionId>` key remains. Readers accept both leg
| `SessionInputShell.refreshLexiconSubscription()` / `DraftEditorRuntime.refreshLexiconSubscription()` | `InputHub` owns the Session-scope `inject` callback that connects the lexicon after caching the shell, reconnects when the service arrives or is replaced, and unsubscribes on disposal. Both connection and catalog updates rescan the current editor without writing old text back; `setDraft` does not establish the subscription |
| `ConversationStoreState` / `createConversationStore` | Support structured input and legacy strings in draft storage, keeping View state and the original key |
| `DefaultConversationViews` | Remove restoration and prefill effects, retaining persistence binding and unbinding. Initial saving reads the owner's current snapshot, never text captured during render |
| The existing `selectWorkspace` callback in `apply.ts` | Keep the existing cross-Workspace draft-transfer rules, passing `draftSnapshot` instead of plain text so transfer retains references |
| The cross-Workspace draft move (`moveDraft` in `apply.ts`) | Keep the existing cross-Workspace draft-transfer rules, passing `draftSnapshot` instead of plain text so transfer retains references |
There is no new draft service, storage key, general task framework, or Session creation entry point. SlotRenderer, Host Session logs, command execution, and file-discovery RPCs are unchanged. `InputActions` remains the shared input-action entry; components receive no separate content-initialization callback.
@@ -37,7 +37,7 @@ Status: implemented
| `SessionInputShell.refreshLexiconSubscription()`/`DraftEditorRuntime.refreshLexiconSubscription()` | `InputHub` 拥有 Session scope 的 `inject` 回调,在缓存输入对象后连接词典,服务到达或替换时重接,销毁时退订。连接和词典更新都会重扫当前 editor,不覆盖旧文本;`setDraft` 不负责建立订阅 |
| `ConversationStoreState`/`createConversationStore` | draft 支持兼容旧字符串的结构化输入,View 状态及原 key 保持 |
| `DefaultConversationViews` | 删除恢复/预填 effect;保留持久化回调的绑定和解绑。初始保存只能读取 owner 的当前快照,不能把 render 时的旧文字写回 |
| `apply.ts` 中现有 `selectWorkspace` 回调 | 沿用原有跨工作区携带规则,但传递 `draftSnapshot` 而不是纯文本,防止携带时再次丢失引用 |
| 跨工作区的草稿移动(`apply.ts` 中的 `moveDraft`) | 沿用原有跨工作区携带规则,但传递 `draftSnapshot` 而不是纯文本,防止携带时再次丢失引用 |
不新增草稿服务、存储 key、通用任务框架或另一套 Session 创建入口;不改 SlotRenderer、Host Session 日志、命令执行和文件发现 RPC。`InputActions` 保留统一输入操作入口,组件不单独注入另一条内容初始化回调。
@@ -9,11 +9,11 @@
en: 755fe8a192cfebe1
zh: 855ad2920b33e364
/agent-note-runtime-download-of-upstream-skills/decision:
en: e601879f83a17cba
zh: a5ab03a7804787fc
en: 98f6d4a4c6b7849f
zh: a361378d5020c954
/agent-note-runtime-download-of-upstream-skills/alternatives-considered:
en: 3828cc141c037db6
zh: 3a164d7a5886cbd2
en: 250ab524fc33cd94
zh: bc4d8008af1f9d61
/agent-note-runtime-download-of-upstream-skills/consequences:
en: 124556ff88e9e014
zh: d25070f79bb2c726
en: 5df2a8d5d5b9fbb6
zh: b827f6539833ee87
@@ -10,7 +10,7 @@ The WeCom and Tencent Meeting plugins index guides that their vendors publish on
## Decision
Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the upstream files by repository, commit, kept directory, exclusions, license file, total size, and a digest of the kept files, and registers both with `ctx.upstreamSkills`, the Service of [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.md). The Service downloads the commit archive from GitHub when the plugin loads, keeps the directory and the license file, verifies them, publishes them in `$DSH_HOME/cache/<plugin>`, and lists the entry skill with that directory as its base directory. The plugin shows the download state beside the account state. Its check reads only the account and restarts a failed download without waiting for it: the CLI account runtime runs one operation at a time, so a check that waited for a slow GitHub download would also hold sign-in. Each archive source has `skillsTimeoutMs` to deliver the whole archive, and reading stops once the kept files exceed the pinned size. A plugin's `skillsDir` points at prepared files for tests and offline installations, and the Service's `skillsUrls` replaces the archive host for every plugin.
Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the upstream files by repository, commit, kept directory, exclusions, license file, total size, and a digest of the kept files, and registers both with `ctx.upstreamSkills`, the Service of [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.md). The Service downloads the commit archive from GitHub when the plugin loads, keeps the directory and the license file, verifies them, publishes them under `$DSH_HOME/cache/<plugin>`, and lists the entry skill with the published directory as its base directory. In a profile the files go to that profile's own directory, `$DSH_HOME/cache/<plugin>/<profile>`, which only that profile's processes read, and each registration deletes the other pins there once, when its own pin first is in place: a plugin update leaves one copy, and an unchanged pin is never downloaded again. The plugin shows the download state beside the account state. Its check reads only the account and restarts a failed download without waiting for it: the CLI account runtime runs one operation at a time, so a check that waited for a slow GitHub download would also hold sign-in. Each archive source has `skillsTimeoutMs` to deliver the whole archive, and reading stops once the kept files exceed the pinned size. A plugin's `skillsDir` points at prepared files for tests and offline installations, and the Service's `skillsUrls` replaces the archive host for every plugin.
## Alternatives considered
@@ -24,8 +24,14 @@ Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the ups
**A digest of the archive bytes.** The files of a commit archive are stable, but GitHub does not keep its compressed bytes stable, so the digest covers the kept files' paths and contents instead.
**One cache directory shared by every profile.** It saves one download per profile. Two DSH installations of different versions on one `$DSH_HOME` can pin different commits for one plugin, so deleting a replaced pin there deletes files the other installation reads, and keeping every pin leaves a copy per plugin update.
**Deleting the other pins after every download.** Processes of one profile can run different versions of a plugin at the same time, such as one started before a plugin update and one started after it, and they share the profile's directory. Each would delete the other's pin after each of its downloads and download its own again at its next check, without end. Deleting once per registration ends that: the later process still deletes the earlier one's pin once, the earlier one downloads it again, and both pins stay until another load. A record of the pins in use, or a period during which a replaced pin stays, would also keep the running process's pin, at the price of a protocol between processes or of a second copy for that period.
**The DSH version in the directory name.** Connector packages carry the DSH version, but a version in the name does not decide which installation may delete which directory, and it downloads the files again at every DSH release although the pin rarely changes.
**DingTalk's downloader.** DingTalk downloads checksummed release assets together with its executable. WeCom and Tencent Meeting publish no release assets and install their CLIs from npm, so only these two plugins register with this Service, and DingTalk keeps its own downloader.
## Consequences
The repository and the plugins' npm packages carry only the entry skills. The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed and the plugin shows the failure, which its next check retries. Tests, recorded Sessions, and Web end-to-end tests set `skillsDir` to fixture files and make no network requests. Published directories are never pruned. Updating a pin is a code change: `scripts/upstream-skills-digest.ts` prints the new pin, and the entry's guide index and a real-model run follow it.
The repository and the plugins' npm packages carry only the entry skills. The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed and the plugin shows the failure, which its next check retries. Tests, recorded Sessions, and Web end-to-end tests set `skillsDir` to fixture files and make no network requests. Each profile that loads a plugin downloads its own copy. A process that still runs another version of a plugin loses its pin once to a later process of the same profile and downloads it again at its next check. Removing a plugin leaves its pin in the cache, and without a profile no pin is deleted. Updating a pin is a code change: `scripts/upstream-skills-digest.ts` prints the new pin, and the entry's guide index and a real-model run follow it.
@@ -10,7 +10,7 @@ Status: implemented
## 决策
这些插件只保留 DSH 自己编写的入口 `SKILL.md`,按仓库、提交、保留的目录、排除项、许可证文件、总大小和保留文件的摘要固定上游文件,并把两者注册到 `ctx.upstreamSkills`,即 [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.zh.md) 的 Service。插件加载时,Service 从 GitHub 下载这个提交的归档,保留该目录和许可证文件,校验后发布到 `$DSH_HOME/cache/<插件>`,再列出入口技能,并把这个目录作为它的基础目录。插件在账号状态旁显示下载状态。它的检查只读取账号,并在不等待的情况下重新开始失败的下载:CLI 账号运行时一次只执行一个操作,检查若等待缓慢的 GitHub 下载,登录也会被占住。每个归档来源要在 `skillsTimeoutMs` 内送达完整归档,保留文件超过固定的大小时停止读取。插件的 `skillsDir` 为测试和离线安装指向准备好的文件,Service 的 `skillsUrls` 为所有插件替换归档主机。
这些插件只保留 DSH 自己编写的入口 `SKILL.md`,按仓库、提交、保留的目录、排除项、许可证文件、总大小和保留文件的摘要固定上游文件,并把两者注册到 `ctx.upstreamSkills`,即 [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.zh.md) 的 Service。插件加载时,Service 从 GitHub 下载这个提交的归档,保留该目录和许可证文件,校验后发布到 `$DSH_HOME/cache/<插件>` 下,再列出入口技能,并把发布的目录作为它的基础目录。在 profile 中,文件发布到这个 profile 自己的目录 `$DSH_HOME/cache/<插件>/<profile>`,只有这个 profile 的进程读取它;每次注册在自己的固定提交第一次就位时,删除一次那里其他的固定提交:插件更新后只留下一份,固定提交不变时也不会重新下载。插件在账号状态旁显示下载状态。它的检查只读取账号,并在不等待的情况下重新开始失败的下载:CLI 账号运行时一次只执行一个操作,检查若等待缓慢的 GitHub 下载,登录也会被占住。每个归档来源要在 `skillsTimeoutMs` 内送达完整归档,保留文件超过固定的大小时停止读取。插件的 `skillsDir` 为测试和离线安装指向准备好的文件,Service 的 `skillsUrls` 为所有插件替换归档主机。
## 考虑过的替代方案
@@ -24,8 +24,14 @@ Status: implemented
**对归档字节做摘要。** 提交归档中的文件是稳定的,但 GitHub 不保证压缩后的字节稳定,因此摘要覆盖保留文件的路径和内容。
**所有 profile 共用一个缓存目录。** 它让每个 profile 少下载一次。同一个 `$DSH_HOME` 上两个不同版本的 DSH 安装,可能为同一个插件固定不同的提交,因此在那里删除被替换的固定提交,会删掉另一个安装正在读取的文件;而全部保留,则每次插件更新都多留一份。
**每次下载完成后都删除其他固定提交。** 同一个 profile 的多个进程可以同时运行同一插件的不同版本,例如一个在插件更新之前启动,另一个在更新之后启动,它们共用这个 profile 的目录。这样每个进程都会在自己每次下载完成后删除对方的固定提交,并在下一次检查时重新下载自己的,没有尽头。每次注册只删除一次就结束了这个循环:后启动的进程仍会删除一次先启动的进程的固定提交,先启动的进程重新下载,此后两个固定提交都保留,直到下一次加载。记录正在使用的固定提交,或让被替换的固定提交保留一段时间,也能保住运行中进程的固定提交,代价是进程之间要有一套约定,或者在这段时间里多留一份。
**在目录名中加入 DSH 版本。** Connector 包的版本与 DSH 版本一致,但目录名里的版本并不能决定哪个安装可以删除哪个目录,而且固定提交很少变化,每次 DSH 发版却都要重新下载这些文件。
**钉钉的下载器。** 钉钉把带校验和的发布资产和可执行文件一起下载。企业微信和腾讯会议没有发布资产,CLI 从 npm 安装,因此只有这两个插件注册到这个 Service,钉钉保留自己的下载器。
## 影响
仓库和插件的 npm 包里只有入口技能。换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,插件显示失败,下一次检查会重试。测试、录制的 Session 和 Web 端到端测试都把 `skillsDir` 设为夹具文件,不发起网络请求。已发布的目录从不清理。更新固定提交需要改代码:`scripts/upstream-skills-digest.ts` 输出新的固定信息,随后更新入口的子指南索引,并用真实模型运行一次。
仓库和插件的 npm 包里只有入口技能。换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,插件显示失败,下一次检查会重试。测试、录制的 Session 和 Web 端到端测试都把 `skillsDir` 设为夹具文件,不发起网络请求。每个加载该插件的 profile 都各自下载一份。仍在运行插件另一个版本的进程,会被同一 profile 后启动的进程删除一次固定提交,并在下一次检查时重新下载。移除插件后,它的固定提交仍留在缓存中;没有 profile 时,任何固定提交都不会被删除。更新固定提交需要改代码:`scripts/upstream-skills-digest.ts` 输出新的固定信息,随后更新入口的子指南索引,并用真实模型运行一次。
@@ -9,8 +9,8 @@
en: 3f5dacf86015cebb
zh: cf0d5bceb9941554
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision:
en: 0682ebef17f6a5e7
zh: 6ea399459262eb0c
en: e243a7d535022011
zh: fd1dd8634b9603cf
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/registered-providers-are-observable-availability-is-not:
en: 38ce796dea91fa35
zh: d312a9cd29fd5cc9
@@ -21,17 +21,17 @@
en: dca56d7ced4e5294
zh: e984a7fddac3228f
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections:
en: 5fcd3319fbceed1d
zh: 20771646b9c36fa6
en: eba9b7ca32681406
zh: 7ab74b8054bea720
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/legacy-messages-search:
en: 2c7c84f8fa1e8745
zh: 5d0244e4f17ba12a
en: 8f3180e3dd327bfc
zh: 012b2ebe8d2f5aac
/agent-note-web-provider-selection-independent-menus-over-registered-providers/alternatives-considered:
en: 2ec7f019ec3ce309
zh: a6a5a8db1f1dd682
en: d72b359bb9ff9666
zh: 33c9a12488a81826
/agent-note-web-provider-selection-independent-menus-over-registered-providers/consequences:
en: ea4d3f05e8be197a
zh: 81faeb3edf122869
en: fe529b10fcbb2d0a
zh: ed3eabbce90ddb92
/agent-note-web-provider-selection-independent-menus-over-registered-providers/verification:
en: 0db673b16e4aeda3
zh: 3b086edecebdc5b5
en: a8f08dc7ec5845fd
zh: a491c4a93db41c3f
@@ -10,7 +10,7 @@ The web service selects search and fetch providers through two independent field
## Decision
Users choose search and fetch providers independently from the Host's registered provider lists. The shipped composition selects the Search API for search and local HTTP fetch for fetch, and the DeepSeek Search and Fetch APIs follow the conversation's DeepSeek credential.
Users choose search and fetch providers independently from the Host's registered provider lists. The shipped composition fixes no search provider, so search follows the conversation's model route, and selects local HTTP fetch for fetch; the DeepSeek Search and Fetch APIs follow the conversation's DeepSeek credential.
### Registered providers are observable; availability is not
@@ -38,18 +38,24 @@ A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (`
### Defaults and stored selections
The [base composition](../../../../packages/bundle/base/cordis.patch.yml) sets `searchProvider: deepseek-search-api` and `fetchProvider: http`. Search defaults to the Search API because it returns sources without Harness starting an auxiliary model request. Fetch defaults to local HTTP fetch because it has no per-request API charge, applies Harness's own URL validation and resource limits, and reaches intranet and local addresses. The Fetch API remains one menu choice away.
The [base composition](../../../../packages/bundle/base/cordis.patch.yml) sets `fetchProvider: http` and no `searchProvider`. With no search provider configured, `dsh-web` prefers one registered, usable provider per provider route of the model request a search serves: Messages search (`deepseek-official`) on the `deepseek-official` and `deepseek-account` model routes, because DeepSeek makes no per-search charge for the server-side search tool a DeepSeek model request declares, and the Search API (`deepseek-search-api`) on every other route and outside a model request, because it returns sources without an auxiliary model request to a provider the conversation does not use. `dsh-tool-web` puts the route of the calling Session's latest model request into each search request, and `searchReady()` selects with the route of the step being prepared, so readiness and execution name the same provider. The two routes and two provider ids are constants of `dsh-web`: a deployment changes the outcome only by configuring `searchProvider`, and the settings page shows the unconfigured state as **Automatic**. Fetch defaults to local HTTP fetch because it has no per-request API charge, applies Harness's own URL validation and resource limits, and reaches intranet and local addresses. The Fetch API remains one menu choice away.
A stored selection, whether in the settings document or in a deployment's own composition, wins over the shipped default, and an upgrade does not rewrite it. A selection is never replaced at execution: when the selected provider is missing, unavailable, or fails, the operation fails with its structured error and does not fall back to another search or fetch provider. A fallback would send the query and credential to an endpoint the user did not choose and change billing without notice.
### Legacy Messages search
The DeepSeek Messages search provider remains available as **DeepSeek (legacy)**. A stored `web.searchProvider: deepseek-official` (or `DSH_WEB_SEARCH_PROVIDER=deepseek-official`) selects it, so users whose gateways serve Messages search but not `/v1/tools` can retain their working provider.
The DeepSeek Messages search provider remains available as **DeepSeek server-side search** and serves unconfigured searches on the DeepSeek model routes. A stored `web.searchProvider: deepseek-official` (or `DSH_WEB_SEARCH_PROVIDER=deepseek-official`) selects it for every route, so users whose gateways serve Messages search but not `/v1/tools` can retain their working provider.
The Messages provider owns and writes `web/deepseek-search-llm-request`. The declaration and payload retain compatibility with released Sessions; the Search and Fetch API package neither declares nor writes this auxiliary event.
## Alternatives considered
**Let each provider declare the routes it is the default for.** A `defaultFor(llmProvider)` member on `WebSearchProvider` keeps `dsh-web` free of DeepSeek ids, but it changes both DeepSeek provider packages for a rule that has one instance.
**Put the route-to-provider table in `dsh-web` configuration.** A profile patch replaces a row's whole `config`, so a stored provider selection would also store a copy of the table and stop following the shipped one, and the table is not a choice users need: fixing a provider already overrides it.
**Have the Search API provider delegate to Messages search on DeepSeek routes.** The menu would keep two entries, but the entry named DeepSeek Search API would run another provider, a user could not fix the Search API for a DeepSeek model, and one provider package would depend on the other.
**Keep one switch for both APIs.** It lets Fetch API adoption need no configuration edit, but it ties fetch billing and target access policy to the search choice, and it cannot express a provider that another plugin registers.
**Filter the lists by availability, or add availability to each entry.** A filtered list hides a provider while its credential is missing, right when the user needs to choose and configure it. Availability also depends on the request's model route and credential state, so a listed boolean could disagree with execution. The archived [observation-surface decision](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md) allows only the smallest signal a consumer reads; the menus read registration only.
@@ -76,10 +82,10 @@ The Messages provider owns and writes `web/deepseek-search-llm-request`. The dec
## Consequences
Users without a stored search selection search through the Search API: their queries go to the Search endpoint the conversation's DeepSeek credential selects, cost a Search API request each, and send up to 128 characters of the latest human prompt as `ori_question` unless `sendOriginalQuestion` is off. Deployments whose gateway has no `/v1/tools` routes get search failures until they select Messages search or set `searchBaseURL` to a base that serves them. A stored `deepseek-official` selection uses Messages search. Users without a stored fetch selection fetch through local HTTP fetch. A signed-in user without an API key has DeepSeek web search with `auto` billing in every conversation except those on the DeepSeek API-key route; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.md) lists each affected setup.
Users without a stored search selection search through Messages search in a conversation on a DeepSeek model route: each search is one auxiliary Messages request billed as model tokens, to Messages search's own endpoint, which does not follow the model provider's base URL, so a deployment whose DeepSeek model provider points at a gateway gets search failures until it saves that gateway as the Messages Base URL or fixes the Search API ([upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.md)). On every other route they search through the Search API: their queries go to the Search endpoint the conversation's DeepSeek credential selects, cost a Search API request each, and send up to 128 characters of the latest human prompt as `ori_question` unless `sendOriginalQuestion` is off. Deployments whose gateway has no `/v1/tools` routes get search failures there until they select Messages search or set `searchBaseURL` to a base that serves them. `dsh-web` names two DeepSeek model routes and two DeepSeek search providers, which a second route-specific default would have to replace with a provider-neutral rule. A stored `deepseek-official` selection uses Messages search. Users without a stored fetch selection fetch through local HTTP fetch. A signed-in user without an API key has DeepSeek web search with `auto` billing in every conversation except those on the DeepSeek API-key route; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.md) lists each affected setup.
A plugin provider, including one written in creator mode, appears in the matching menu as soon as it registers, under its `title`. The menus can offer a provider that cannot run for the current request; the failure appears when a search or fetch runs. Each registry change costs one forwarded event and one list read in each Client that observes it.
## Verification
[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) covers list contents and order, titles, events after registration and disposal, no event for a rejected duplicate, and contained listener failures. [deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) covers the independent Messages provider, and [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) covers, for both capabilities, the account token on the account route and its invalidation after HTTP 401, the API-key fallback without a sign-in, the route key and endpoint in official, non-DeepSeek, and Session-less conversations, the account fallback without a key outside the DeepSeek routes, account-only and API-key-only billing on every route, own fields over billing, `DEEPSEEK_API_KEY` and the official base without that route, YAML-only own fields that never send the token, independent capabilities, readiness matching each operation, and ignored removed fields; [composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) boots the real model routes through the Loader. [remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) covers event forwarding, and [base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) pins the shipped defaults. The settings page's controller and card specs and the [plugin configuration browser scenario](../../../../apps/web/tests/plugin-config.e2e.ts) cover menu contents, independent Search and Fetch selection, the billing menus of the DeepSeek APIs, and the settings each provider keeps.
[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) covers list contents and order, titles, events after registration and disposal, no event for a rejected duplicate, contained listener failures, and the per-route preference with its fallbacks; [tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) covers the route `web_search` sends, and the `web-search-legacy-endpoint-guidance` snapshot runs Messages search on a DeepSeek route with no provider configured. [deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) covers the independent Messages provider, and [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) covers, for both capabilities, the account token on the account route and its invalidation after HTTP 401, the API-key fallback without a sign-in, the route key and endpoint in official, non-DeepSeek, and Session-less conversations, the account fallback without a key outside the DeepSeek routes, account-only and API-key-only billing on every route, own fields over billing, `DEEPSEEK_API_KEY` and the official base without that route, YAML-only own fields that never send the token, independent capabilities, readiness matching each operation, and ignored removed fields; [composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) boots the real model routes through the Loader. [remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) covers event forwarding, and [base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) pins the shipped defaults. The settings page's controller and card specs and the [plugin configuration browser scenario](../../../../apps/web/tests/plugin-config.e2e.ts) cover menu contents, independent Search and Fetch selection, the billing menus of the DeepSeek APIs, and the settings each provider keeps.
@@ -10,7 +10,7 @@ Web 服务通过 `web.searchProvider` 和 `web.fetchProvider` 两个独立字段
## 决策
用户从 Host 已注册的提供方列表中分别选择搜索和抓取提供方。内置组合将搜索设为 Search API,将抓取设为本地 HTTP 抓取;DeepSeek Search 与 Fetch API 跟随会话的 DeepSeek 凭据。
用户从 Host 已注册的提供方列表中分别选择搜索和抓取提供方。内置组合不固定搜索提供方,搜索因此跟随会话的模型路由,抓取设为本地 HTTP 抓取;DeepSeek Search 与 Fetch API 跟随会话的 DeepSeek 凭据。
### 已注册的提供方可观察,可用性不可观察
@@ -38,18 +38,24 @@ Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling`
### 默认值与已保存的选择
[base 组合](../../../../packages/bundle/base/cordis.patch.yml)设置 `searchProvider: deepseek-search-api` 和 `fetchProvider: http`。搜索默认使用 Search API,因为它返回来源时无需 Harness 发起辅助模型请求。抓取默认使用本地 HTTP 抓取,因为它没有按次的 API 费用,执行 Harness 自身的 URL 校验和资源限制,并且可以访问内网和本地地址。Fetch API 仍可在下拉框中直接选择。
[base 组合](../../../../packages/bundle/base/cordis.patch.yml)设置 `fetchProvider: http`,不设置 `searchProvider`。没有配置搜索提供方时,`dsh-web` 按搜索所服务的模型请求的提供方路由,优先选用一个已注册且可用的提供方:在 `deepseek-official` 与 `deepseek-account` 模型路由上是 Messages 搜索(`deepseek-official`),因为 DeepSeek 不对 DeepSeek 模型请求声明的服务端搜索工具按次收费;在其他路由上以及模型请求之外是 Search API(`deepseek-search-api`),因为它返回来源时无需向会话没有使用的提供方发起辅助模型请求。`dsh-tool-web` 把发起调用的 Session 最近一次模型请求的路由写入每个搜索请求,`searchReady()` 按正在准备的步骤的路由选择,因此就绪判断与执行指向同一个提供方。这两条路由和两个提供方 id 是 `dsh-web` 中的常量:部署只能通过配置 `searchProvider` 改变结果,设置页把未配置的状态显示为**自动选择**。抓取默认使用本地 HTTP 抓取,因为它没有按次的 API 费用,执行 Harness 自身的 URL 校验和资源限制,并且可以访问内网和本地地址。Fetch API 仍可在下拉框中直接选择。
已保存的选择——无论位于设置文档还是部署自身的组合中——优先于内置默认值,升级不会改写它。执行时从不替换选择:所选提供方缺失、不可用或失败时,操作以结构化错误失败,不会回退到其他搜索或抓取提供方。回退会把查询和凭据发往用户未选择的端点,并在不提示的情况下改变计费。
### 旧版 Messages 搜索
DeepSeek Messages 搜索提供方仍以 **DeepSeek(旧版)**提供。已保存的 `web.searchProvider: deepseek-official`(或 `DSH_WEB_SEARCH_PROVIDER=deepseek-official`)会选中它,因此网关支持 Messages 搜索但不提供 `/v1/tools` 的用户可以保留可用的提供方。
DeepSeek Messages 搜索提供方仍以 **DeepSeek 服务端搜索**提供,并承担 DeepSeek 模型路由上未配置提供方的搜索。已保存的 `web.searchProvider: deepseek-official`(或 `DSH_WEB_SEARCH_PROVIDER=deepseek-official`)会在所有路由上选中它,因此网关支持 Messages 搜索但不提供 `/v1/tools` 的用户可以保留可用的提供方。
Messages 提供方负责声明并写入 `web/deepseek-search-llm-request`。声明和载荷保持与已发布会话兼容;Search 与 Fetch API 包既不声明也不写入这一辅助事件。
## 考虑过的替代方案
**让每个提供方声明自己是哪些路由的默认项。** 在 `WebSearchProvider` 上加一个 `defaultFor(llmProvider)` 成员可以让 `dsh-web` 不含 DeepSeek 的 id,但要为只有一个实例的规则修改两个 DeepSeek 提供方包。
**把路由到提供方的表放进 `dsh-web` 的配置。** profile 补丁会替换条目的整个 `config`,因此已存的提供方选择会连带存下这张表的副本,不再跟随内置的表;而这张表也不是用户需要做的选择:固定提供方已经可以覆盖它。
**让 Search API 提供方在 DeepSeek 路由上转交给 Messages 搜索。** 菜单可以保持两项,但名为 DeepSeek Search API 的条目会运行另一个提供方,用户无法为 DeepSeek 模型固定 Search API,而且一个提供方包要依赖另一个。
**保留一个同时切换两个 API 的开关。** 它让使用 Fetch API 无需修改配置,但把抓取的计费和目标访问策略绑在搜索选择上,也无法表达其他插件注册的提供方。
**按可用性过滤列表,或在每个条目中加入可用性。** 过滤后的列表恰好会在凭据缺失时隐藏提供方,而这正是用户需要选择并配置它的时候。可用性还取决于请求的模型路由和凭据状态,列表中的布尔值可能与实际执行结果不一致。已归档的[观察面决策](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md)只允许引入消费方实际读取的最小信号;下拉框只读取注册情况。
@@ -76,10 +82,10 @@ Messages 提供方负责声明并写入 `web/deepseek-search-llm-request`。声
## 影响
没有已保存搜索选择的用户通过 Search API 搜索:查询发往会话的 DeepSeek 凭据所选的 Search 端点,每次计为一次 Search API 请求,并且除非关闭 `sendOriginalQuestion`,还会把最近一条用户提示的至多 128 个字符作为 `ori_question` 发送。网关没有 `/v1/tools` 路由的部署会遇到搜索失败,直到选择 Messages 搜索,或把 `searchBaseURL` 设为提供这些路由的基础地址。已保存的 `deepseek-official` 选择使用 Messages 搜索。没有已保存抓取选择的用户通过本地 HTTP 抓取。已登录但没有 API 密钥的用户在 `auto` 计费下,除 DeepSeek API 密钥路由上的会话外,都可以使用 DeepSeek 网页搜索;[升级指南](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.zh.md)列出了每种受影响的配置。
没有已保存搜索选择的用户在 DeepSeek 模型路由上的会话中通过 Messages 搜索进行搜索:每次搜索是一次按模型 token 计费的辅助 Messages 请求,发往 Messages 搜索自己的端点,该端点不跟随模型提供方的基础地址,因此 DeepSeek 模型提供方指向网关的部署会遇到搜索失败,直到把该网关保存为 Messages Base URL 或固定使用 Search API([升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.zh.md))。在其他路由上他们通过 Search API 搜索:查询发往会话的 DeepSeek 凭据所选的 Search 端点,每次计为一次 Search API 请求,并且除非关闭 `sendOriginalQuestion`,还会把最近一条用户提示的至多 128 个字符作为 `ori_question` 发送。网关没有 `/v1/tools` 路由的部署在这些路由上会遇到搜索失败,直到选择 Messages 搜索,或把 `searchBaseURL` 设为提供这些路由的基础地址。`dsh-web` 点名了两条 DeepSeek 模型路由和两个 DeepSeek 搜索提供方,再出现一个按路由的默认值时须改为提供方无关的规则。已保存的 `deepseek-official` 选择使用 Messages 搜索。没有已保存抓取选择的用户通过本地 HTTP 抓取。已登录但没有 API 密钥的用户在 `auto` 计费下,除 DeepSeek API 密钥路由上的会话外,都可以使用 DeepSeek 网页搜索;[升级指南](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.zh.md)列出了每种受影响的配置。
插件提供方(包括在创作模式下编写的提供方)一经注册,就会以其 `title` 出现在对应的下拉框中。下拉框可能提供在当前请求中无法运行的提供方;失败会在执行搜索或抓取时出现。每次注册表变更会在每个观察它的 Client 中产生一次转发事件和一次列表读取。
## 验证
[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) 覆盖列表内容与顺序、标题、注册与撤销后的事件、重复注册被拒绝时不触发事件,以及监听器失败的隔离。[deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) 覆盖独立的 Messages 提供方,[credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) 针对两个能力覆盖账号路由上的账号令牌及其在 HTTP 401 后被作废、未登录时回退到 API 密钥、官方、非 DeepSeek 和会话之外的操作使用路由密钥与端点、DeepSeek 路由之外没有密钥时回退到账号、在每个路由上只用账号或只用 API 密钥的计费、单独字段优先于计费方式、没有该路由时使用 `DEEPSEEK_API_KEY` 与官方基础地址、从不发送令牌的 YAML 单独字段、两个能力相互独立、就绪判断与每次操作一致,以及被忽略的已移除字段;[composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) 通过 Loader 启动真实的模型路由。[remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) 覆盖事件转发,[base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) 固定内置默认值。设置页的 controller 与 card 测试以及[插件配置浏览器场景](../../../../apps/web/tests/plugin-config.e2e.ts)覆盖下拉框内容、Search 与 Fetch 的分别选择、DeepSeek API 的计费方式下拉框,以及各提供方保留的设置。
[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) 覆盖列表内容与顺序、标题、注册与撤销后的事件、重复注册被拒绝时不触发事件、监听器失败的隔离,以及按路由的优先规则及其回退;[tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) 覆盖 `web_search` 发送的路由,`web-search-legacy-endpoint-guidance` 快照在未配置提供方的 DeepSeek 路由上运行 Messages 搜索。[deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) 覆盖独立的 Messages 提供方,[credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) 针对两个能力覆盖账号路由上的账号令牌及其在 HTTP 401 后被作废、未登录时回退到 API 密钥、官方、非 DeepSeek 和会话之外的操作使用路由密钥与端点、DeepSeek 路由之外没有密钥时回退到账号、在每个路由上只用账号或只用 API 密钥的计费、单独字段优先于计费方式、没有该路由时使用 `DEEPSEEK_API_KEY` 与官方基础地址、从不发送令牌的 YAML 单独字段、两个能力相互独立、就绪判断与每次操作一致,以及被忽略的已移除字段;[composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) 通过 Loader 启动真实的模型路由。[remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) 覆盖事件转发,[base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) 固定内置默认值。设置页的 controller 与 card 测试以及[插件配置浏览器场景](../../../../apps/web/tests/plugin-config.e2e.ts)覆盖下拉框内容、Search 与 Fetch 的分别选择、DeepSeek API 的计费方式下拉框,以及各提供方保留的设置。
@@ -9,14 +9,11 @@
en: 6938aa715106bb99
zh: ea1497b337712f33
/agent-note-session-workspace-root/decision:
en: b42597fdf9838587
zh: cb36853abde00754
/agent-note-session-workspace-root/deferred:
en: 8807b3829badfdcd
zh: 2ec10ce7f0dda3f4
en: 0b07db6326c2ecd6
zh: 19ba9a1adf93af1f
/agent-note-session-workspace-root/alternatives-considered:
en: 35ccc31b8b40d014
zh: 7bf3c9f45afae8ab
en: 8a4859a6f96ef49e
zh: fa7088d29ebe3dd6
/agent-note-session-workspace-root/consequences:
en: 7cef9fcd81f95833
zh: 4211d4ae53dd4974
en: a6bf8aa40464f524
zh: 61997dc31615bdbb
@@ -16,9 +16,9 @@ A Session works in one directory, and only Host operations move it. The model-fa
Worktree creation enters the checkout through `set`. The model has one tool for entering a checkout, `enter_worktree`: a name selects a worktree inside the pool of the checkout the Session works in. An existing one is entered through `ctx.worktrees.enter`, and a new one is created through `ctx.worktrees.create` when none has that name. The name cannot leave that pool, so the model still cannot choose an arbitrary directory. `ctx.worktrees.exit`, exposed as `exit_worktree`, returns the Session from the recorded worktree that contains its directory to the checkout it created or entered that worktree from. A child subagent keeps the parent's original project in its header and starts, through `set`, in the parent's directory or a Host-chosen directory.
## Deferred
Every consumer reads that directory. The model's file, search, and process tools resolve relative paths from it, and everything the user sees or that describes the project is bounded by it: the sandbox `workspace-write` boundary, the workspace file service and desktop file drag, the change recorder, the Files tree, deliverables, open-in-app actions and Session rows, new sidebar terminals, `@` file candidates, the skill catalog, project-instruction discovery, and the LSP workspace.
The sandbox write boundary, the workspace file service, desktop file drag, the change recorder, and the client file tree, deliverables, open-in-app actions, and Session rows still read `header.cwd`. Until those consumers read the Session's directory, they behave as they did before this decision, and a worktree outside the original project is writable only where the original project's boundary already allows it.
The sandbox policy reads no Git layout: it bounds a Session by its directory and adds only the directories the deployment configured or a Host plugin registered for that Session through `registerWritableRoot`. A repository's Git directory lies outside a linked worktree, so after a move into a worktree a Git command that writes it, such as `git commit`, is denied under `workspace-write` until a grant covers that directory; the original project is not writable either. Granting the Git directory of the checkout a Session works in belongs to a separate plugin that reads the Git layout and registers the directory, which this decision defers. Host maintenance of a checkout the Session does not work in keeps the original boundary: removing a worktree on archive, restoring a removed one, and reading its branch in the source repository run under a policy the worktree service and the forge panel build themselves, the Session's mode and grants with the recorded source checkout as the root. The Session's own root may be the removed directory, and a process sandbox cannot bind a missing or vanishing root.
## Alternatives considered
@@ -40,10 +40,10 @@ The sandbox write boundary, the workspace file service, desktop file drag, the c
**Two public reads.** `get` for relative paths beside `rootOf` for the workspace root kept every stored directory, and made each consumer choose between two values that are equal in every Session started from this version on. One read removes that choice.
**Keep every stored directory.** Reading every stored `working-directory/change` as the directory would let a stored model `cd`, including one to a home directory, become the write boundary once consumers follow the directory.
**Keep every stored directory.** Reading every stored `working-directory/change` as the directory would let a stored model `cd`, including one to a home directory, become the write boundary, because consumers follow the directory.
**Keep stored directories inside the original project.** A Session that entered a worktree would resume there, but the rule cannot tell a worktree from a `cd`: a stored `cd` into a subdirectory would narrow the write boundary and the file views, and a worktree outside the directory a Session was opened in would be dropped.
## Consequences
Consumers read one directory through `get`. A stored Session resumes in its original project whatever directory its `working-directory/change` events recorded, and follows Host moves from there. One that worked in a worktree returns to it through `enter_worktree`; until then its relative paths resolve in the original project. The model enters a checkout only through `enter_worktree`: a new one, or a registered one in the pool. A checkout elsewhere needs a Host operation. The ACP, SDK, and Web producers record the original project by its canonical spelling, so a Host move back to it records no change. The worktree snapshot fixture covers entering, leaving, and losing a worktree. Moving the consumers listed under Deferred is a separate change.
Consumers read one directory through `get`. A stored Session resumes in its original project whatever directory its `working-directory/change` events recorded, and follows Host moves from there. One that worked in a worktree returns to it through `enter_worktree`; until then its relative paths resolve in the original project. The model enters a checkout only through `enter_worktree`: a new one, or a registered one in the pool. A checkout elsewhere needs a Host operation. The ACP, SDK, and Web producers record the original project by its canonical spelling, so a Host move back to it records no change. A Session that works in a linked worktree, whether it entered one or was opened in one, cannot run `git commit` under `workspace-write` without a grant for the repository's Git directory; on the previous boundary a Session that entered a worktree inside its project could. An SDK `setWorkingDirectory` call and a child started in a Host-chosen directory move the `workspace-write` boundary with the directory. The worktree snapshot fixture covers entering, leaving, and losing a worktree.
@@ -16,9 +16,9 @@ Status: implemented
工作树创建通过 `set` 进入检出目录。模型只有一个进入检出的工具 `enter_worktree`:名称在 Session 所在检出的池中选中一个工作树。已有的工作树通过 `ctx.worktrees.enter` 进入,没有同名工作树时通过 `ctx.worktrees.create` 新建。名称无法离开该池,因此模型仍然不能选择任意目录。`ctx.worktrees.exit` 以 `exit_worktree` 的形式提供,它找到包含 Session 目录的已记录工作树,把 Session 送回创建或进入该工作树时所在的检出。子代理的 header 保留父级的原始项目,并通过 `set` 从父级的目录或 Host 选定的目录启动。
## Deferred
每个消费方都读取这个目录。模型的文件、搜索与进程工具从它解析相对路径,用户看到的、以及描述项目的一切都以它为界:沙箱 `workspace-write` 边界、工作区文件服务与桌面文件拖拽、变更记录器、文件树、交付物、在应用中打开操作与 Session 行、新开的侧栏终端、`@` 文件候选、技能目录、项目指令发现和 LSP 工作区。
沙箱写边界、工作区文件服务、桌面文件拖拽、变更记录器,以及客户端文件树、交付物、在应用中打开的操作和 Session 行仍然读取 `header.cwd`。在这些消费方改读 Session 的目录之前,它们的行为与本决策之前相同,位于原始项目之外的工作树只有在原始项目的边界已经允许时才可写。
沙箱策略不读取任何 Git 布局:它以 Session 的目录为界,只加入部署配置的目录,以及 Host 插件通过 `registerWritableRoot` 为该 Session 注册的目录。仓库的 Git 目录位于链接工作树之外,因此移入工作树之后,写入它的 Git 命令(例如 `git commit`)在 `workspace-write` 下会被拒绝,直到有授权覆盖该目录;原始项目也不再可写。为 Session 所在检出目录授权其 Git 目录,属于一个读取 Git 布局并注册该目录的独立插件,本决策将其延后。Host 对 Session 并不在其中工作的检出目录做维护时保留原来的边界:归档时移除 worktree、恢复被删除的 worktree、在源仓库中读取其分支,都在 worktree 服务与 forge 面板自己构造的策略下运行,即沿用 Session 的模式与授权、以记录中的源检出目录为根。Session 自身的根可能正是被删除的目录,而进程沙箱无法绑定缺失或正在消失的根。
## Alternatives considered
@@ -40,10 +40,10 @@ Status: implemented
**两个公开读取接口。** 用 `get` 读相对路径的基准、用 `rootOf` 读工作区根,可以保留每个已存储的目录,但每个消费方都要在两个值之间做选择,而这两个值在从这个版本起启动的每个 Session 中都相等。只保留一个读取接口,就不需要这种选择。
**保留每个已存储的目录。** 把每条已存储的 `working-directory/change` 都读作目录,消费方跟随目录之后,已存储的模型 `cd`(包括进入用户主目录的)会成为写边界。
**保留每个已存储的目录。** 把每条已存储的 `working-directory/change` 都读作目录,由于消费方跟随目录,已存储的模型 `cd`(包括进入用户主目录的)会成为写边界。
**保留原始项目之内的已存储目录。** 进入过工作树的 Session 会在工作树中恢复,但这条规则分不清工作树与 `cd`:已存储的进入子目录的 `cd` 会收窄写边界和文件视图,而位于 Session 打开目录之外的工作树会被丢弃。
## Consequences
消费方通过 `get` 读取一个目录。无论 `working-directory/change` 事件记录了什么目录,已存储的 Session 都在原始项目中恢复,并从那里跟随 Host 移动。曾在工作树中工作的 Session 通过 `enter_worktree` 回到工作树;在此之前,它的相对路径在原始项目中解析。模型只能通过 `enter_worktree` 进入检出:新建的检出,或池中已登记的检出。其他位置的检出需要 Host 操作。ACP、SDK 与 Web 的生产方以规范拼写记录原始项目,因此 Host 移回原始项目时不记录变更。工作树快照夹具覆盖进入、离开和失去工作树。迁移 Deferred 中列出的消费方是另一项变更。
消费方通过 `get` 读取一个目录。无论 `working-directory/change` 事件记录了什么目录,已存储的 Session 都在原始项目中恢复,并从那里跟随 Host 移动。曾在工作树中工作的 Session 通过 `enter_worktree` 回到工作树;在此之前,它的相对路径在原始项目中解析。模型只能通过 `enter_worktree` 进入检出:新建的检出,或池中已登记的检出。其他位置的检出需要 Host 操作。ACP、SDK 与 Web 的生产方以规范拼写记录原始项目,因此 Host 移回原始项目时不记录变更。在链接工作树中工作的 Session,无论是进入的还是直接在其中打开的,在没有仓库 Git 目录授权时都不能在 `workspace-write` 下运行 `git commit`;在此前的边界下,进入项目内工作树的 Session 可以。SDK 的 `setWorkingDirectory` 调用以及在 Host 选定目录启动的子代理,会让 `workspace-write` 边界随目录一起移动。工作树快照夹具覆盖进入、离开和失去工作树。
@@ -12,8 +12,8 @@
en: 5d2dc730467e4bf3
zh: 4aca28691504cd7b
/agent-note-change-request-panel-and-worktree-sessions/deferred:
en: 32ef8af85f4d2f66
zh: b82b67f94346399e
en: e76e8129691db30f
zh: fd242e67bab2633d
/agent-note-change-request-panel-and-worktree-sessions/alternatives-considered:
en: e471e16b6b6450ca
zh: 5fbc9242edc8d112
@@ -32,12 +32,7 @@ Review comments capture the file, side, range, complete hunk, and reviewed head
## Deferred
A left-navigation review page next to Plugins and Scheduled tasks, listing the user's pull requests or merge requests on the selected provider, is deferred. It attaches without changing this package's Session surfaces:
- **Provider capability** — an optional `ForgeProvider` method such as `listForViewer(host, filter, signal)` returns change request references; GitHub implements it with `gh search prs --author @me` or the GraphQL `viewer`, and the registry aggregates enabled providers.
- **Remote** — a stream like `follow` that is keyed by provider and filter instead of a Session and polls through the same `ctx.forge.watch`.
- **Client** — a `sidebar.panellist` entry with a `main` page in this package, as `ui-schedule` does, rendering `ChangeRequestCard`, which takes a change request, its snapshot, and optional actions.
- **Settings** — provider choice and hosts on the bundle's configuration page.
The left-navigation review page this section deferred is implemented as the [code review page](2026-11-11-forge-review-page.md); its lists come from an optional provider capability and its page reads change requests by URL, so this package's Session surfaces did not change.
The changes view offers no scope for one commit or for the last turn yet; both would be further `ForgeLocalScope` kinds read through `localDiff`.
@@ -32,12 +32,7 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都
## Deferred
在左侧导航“插件”“自动化任务”旁边新增代码审查页、列出用户在所选提供方上的 pull request 或 merge request,这项工作推迟。它的接入不需要改动本包面向 Session 的界面:
- **提供方能力**——`ForgeProvider` 增加一个可选方法,例如 `listForViewer(host, filter, signal)`,返回变更请求引用;GitHub 用 `gh search prs --author @me` 或 GraphQL `viewer` 实现,注册表汇总已启用的提供方。
- **Remote**——一条类似 `follow` 的流,以提供方与筛选条件而不是 Session 为键,通过同一个 `ctx.forge.watch` 轮询。
- **客户端**——在本包中以 `sidebar.panellist` 条目加一个 `main` 页面实现(与 `ui-schedule` 相同),渲染接收变更请求、其快照与可选操作的 `ChangeRequestCard`。
- **设置**——在套件的配置页中选择提供方与主机。
本节曾暂缓的左侧导航代码审查页已实现为[代码评审页](2026-11-11-forge-review-page.zh.md);它的列表来自可选的提供方能力,页面按 URL 读取变更请求,因此本包的会话界面没有改变。
变更视图目前还没有单个提交与上一轮的范围;两者将是经 `localDiff` 读取的更多 `ForgeLocalScope` 种类。
@@ -12,8 +12,8 @@
en: 43298ccae4f7a6d4
zh: eb7ef46b6f290c15
/agent-note-direct-deepseek-search-and-fetch-apis/decision/protocol-selection-and-deployment:
en: 90e5031d0d2fa9e4
zh: a9c0229b20555d9e
en: b07c0667e25927aa
zh: 45eda3e151040201
/agent-note-direct-deepseek-search-and-fetch-apis/decision/search-results-and-model-input:
en: ad7b3e4fbe528cf2
zh: 8ab8779bfdaaa4fa
@@ -21,14 +21,14 @@
en: 7566e400f9ab3a51
zh: 118b2e84d0030480
/agent-note-direct-deepseek-search-and-fetch-apis/decision/default-migration:
en: cb2f0910955b6730
zh: 7df057048acd7858
en: 9b1e46885451ada3
zh: 0deab76a188294dd
/agent-note-direct-deepseek-search-and-fetch-apis/decision/legacy-messages-search:
en: 0dcc97d8105fab60
zh: d80d40ae3a0c601d
/agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered:
en: e377ad3c0327300e
zh: 4b9f7f83f464e657
en: da027a3c18b4fa0a
zh: a3f0f448a0cae63f
/agent-note-direct-deepseek-search-and-fetch-apis/consequences:
en: 7ec21c5b1124e5f8
zh: af769dbdb4face9f
@@ -14,7 +14,7 @@ The [DeepSeek Search and Fetch guide](https://api-docs.deepseek.com/zh-cn/guides
### Protocol selection and deployment
The APIs register as `deepseek-search-api` and `deepseek-fetch-api`. Messages search remains separately registered as `deepseek-official`. The web service selects each provider through `web.searchProvider` and `web.fetchProvider`, which the Search and Fetch menus on the Web search and fetch page set independently; the shipped composition selects the Search API and local HTTP fetch, as the [selection decision](../architecture/2026-10-29-web-provider-selection.md) records. A saved selection takes effect on the next operation because the web service reads both selections per operation. Each operation resolves one settings snapshot, including its endpoint and credential. Both APIs read the `web-deepseek-api` namespace, and each capability resolves its own endpoint and credential.
The APIs register as `deepseek-search-api` and `deepseek-fetch-api`. Messages search remains separately registered as `deepseek-official`. The web service selects each provider through `web.searchProvider` and `web.fetchProvider`, which the Search and Fetch menus on the Web search and fetch page set independently; the shipped composition selects local HTTP fetch and no search provider, which runs the Search API outside the DeepSeek model routes, as the [selection decision](../architecture/2026-10-29-web-provider-selection.md) records. A saved selection takes effect on the next operation because the web service reads both selections per operation. Each operation resolves one settings snapshot, including its endpoint and credential. Both APIs read the `web-deepseek-api` namespace, and each capability resolves its own endpoint and credential.
Direct retrieval appends `/search` or `/fetch` to an API base. A capability without its own YAML endpoint fields uses the origin of the conversation's DeepSeek model route base URL with `/v1/tools`, which for the public deployment is the guide's `https://api.deepseek.com/v1/tools`; the [selection decision](../architecture/2026-10-29-web-provider-selection.md) owns that derivation and the credential each operation sends. The verified development base is `http://api-dev.deepseek.com:8031/api/v1/tools`; its prefix differs and is never inferred from the hostname, so such a deployment sets the complete base in `searchBaseURL` or `fetchBaseURL`. An unparseable base leaves that capability's provider unavailable.
@@ -36,7 +36,7 @@ The HTTP provider retains its own URL validation and resource limits. Selecting
### Default migration
The shipped composition selects `deepseek-search-api`; the [selection decision](../architecture/2026-10-29-web-provider-selection.md) owns that default and its no-fallback rule. API keys and account tokens both reach the public routes. Deployments behind a gateway without `/v1/tools` routes set `searchBaseURL` to a base that serves them. A stored `web.searchProvider: deepseek-official` selects Messages search, and any other stored selection keeps its provider.
The shipped composition fixes no search provider: a search runs Messages search for a model request on a DeepSeek model route and `deepseek-search-api` on every other route; the [selection decision](../architecture/2026-10-29-web-provider-selection.md) owns that default and its no-fallback rule. API keys and account tokens both reach the public routes. Deployments behind a gateway without `/v1/tools` routes set `searchBaseURL` to a base that serves them. A stored `web.searchProvider: deepseek-official` selects Messages search, and any other stored selection keeps its provider.
### Legacy Messages search
@@ -48,7 +48,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request
**Reuse the Messages address or infer a route prefix.** The protocols and deployed prefixes differ. Separate bases preserve existing configurations and avoid sending a valid request to the wrong route.
**Require an explicit Search API base.** The Search API is the shipped search default, and an empty default would leave it unavailable until every user enters an address that the DeepSeek model route already determines. Other deployments still set their own base.
**Require an explicit Search API base.** The Search API is the shipped search default outside the DeepSeek model routes, and an empty default would leave it unavailable until every user enters an address that the DeepSeek model route already determines. Other deployments still set their own base.
**Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider.
@@ -14,7 +14,7 @@ Status: implemented
### 协议选择与部署
两个 API 注册为 `deepseek-search-api` 和 `deepseek-fetch-api`;Messages 搜索仍独立注册为 `deepseek-official`。Web 服务通过 `web.searchProvider` 和 `web.fetchProvider` 选择各个提供方,「网页搜索与获取」页上的 Search 和 Fetch 下拉框分别设置这两项;内置组合选择 Search API 与本地 HTTP 抓取,见[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)。已保存的选择从下一次操作起生效,因为 Web 服务在每次操作时读取两项选择。每次操作解析一份包含端点和凭据的设置快照。两个 API 读取 `web-deepseek-api` namespace,每个能力各自解析端点与凭据。
两个 API 注册为 `deepseek-search-api` 和 `deepseek-fetch-api`;Messages 搜索仍独立注册为 `deepseek-official`。Web 服务通过 `web.searchProvider` 和 `web.fetchProvider` 选择各个提供方,「网页搜索与获取」页上的 Search 和 Fetch 下拉框分别设置这两项;内置组合选择本地 HTTP 抓取,不选择搜索提供方,此时 DeepSeek 模型路由之外的搜索使用 Search API,见[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)。已保存的选择从下一次操作起生效,因为 Web 服务在每次操作时读取两项选择。每次操作解析一份包含端点和凭据的设置快照。两个 API 读取 `web-deepseek-api` namespace,每个能力各自解析端点与凭据。
直接检索在 API 基础地址后追加 `/search` 或 `/fetch`。没有在 YAML 中单独设置端点字段的能力,使用会话的 DeepSeek 模型路由基础地址的 origin 加 `/v1/tools`,公网部署即指南中的 `https://api.deepseek.com/v1/tools`;该推导及每次操作发送的凭据由[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)负责。已验证的开发地址为 `http://api-dev.deepseek.com:8031/api/v1/tools`;其前缀不同,程序不会根据主机名推断,此类部署需在 `searchBaseURL` 或 `fetchBaseURL` 中填写完整基础地址。基础地址无法解析时,该能力的提供方不可用。
@@ -36,7 +36,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek
### 默认值迁移
内置组合选择 `deepseek-search-api`;[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)负责这项默认值及其不回退规则。API 密钥和账号 token 都能访问公网路由。位于没有 `/v1/tools` 路由的网关之后的部署,需把 `searchBaseURL` 设为提供这些路由的基础地址。已保存的 `web.searchProvider: deepseek-official` 会选中 Messages 搜索,其他已保存的选择保持其提供方。
内置组合不固定搜索提供方:为 DeepSeek 模型路由上的模型请求发起的搜索运行 Messages 搜索,其他路由上的搜索运行 `deepseek-search-api`;[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)负责这项默认值及其不回退规则。API 密钥和账号 token 都能访问公网路由。位于没有 `/v1/tools` 路由的网关之后的部署,需把 `searchBaseURL` 设为提供这些路由的基础地址。已保存的 `web.searchProvider: deepseek-official` 会选中 Messages 搜索,其他已保存的选择保持其提供方。
### 旧版 Messages 搜索
@@ -48,7 +48,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek
**复用 Messages 地址或推断路由前缀。** 协议与部署前缀不同。分别保存基础地址可保留现有配置,避免把有效请求发往错误路由。
**要求显式填写 Search API 基础地址。** Search API 是内置的搜索默认值,空默认值会让它在每位用户填写一个 DeepSeek 模型路由已经确定的地址之前都不可用。其他部署仍可设置自己的基础地址。
**要求显式填写 Search API 基础地址。** Search API 是 DeepSeek 模型路由之外内置的搜索默认值,空默认值会让它在每位用户填写一个 DeepSeek 模型路由已经确定的地址之前都不可用。其他部署仍可设置自己的基础地址。
**把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-09-sdk-prompt-time-zone.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.md
/agent-note-per-prompt-sdk-time-zone:
en: 44d838b330c01b71
zh: 322844db122f305f
/agent-note-per-prompt-sdk-time-zone/problem:
en: 225547dcc5d63b6e
zh: b62fa355a827d662
/agent-note-per-prompt-sdk-time-zone/decision:
en: be0afd0975a15d3a
zh: 91f161bc2f7cd938
/agent-note-per-prompt-sdk-time-zone/alternatives-considered:
en: b67b2d44aeb2dc6b
zh: 69d0356bfe3204a6
/agent-note-per-prompt-sdk-time-zone/consequences:
en: ec0b5f4a68aaa351
zh: 4eb09ed822f456a2
@@ -0,0 +1,35 @@
# Agent Note: Per-prompt SDK time zone
Status: implemented
English | [中文](2026-11-09-sdk-prompt-time-zone.zh.md)
## Problem
Web and Desktop prompts carry the browser zone that the Host canonicalizes and records on that user message, and [time-context](../../../../packages/context/time-context/README.md) tells the model to interpret unqualified dates and times in it. SDK prompts recorded `{ kind: 'user' }`, and time-context read a zone only from a user source that also had a Web `rpcId`. Every SDK request therefore showed `Browser time zone for this request: unavailable.`, and the model asked about dates that a Web user would never be asked about. The SDK protocol had no field through which an embedding application could report its user's zone.
## Decision
The zone stays request-local message source data, as in the [explicit Schedule time-zone decision](../simplification/2026-08-09-explicit-schedule-time-zone.md); the SDK supplies it per prompt.
- `session/prompt` and `session/query` accept an optional `timeZone`. The TypeScript client accepts it in `HarnessClient.prompt()` options and `run()` options; the Python client accepts the `time_zone` keyword in `session_prompt()` and `run()`.
- The SDK server canonicalizes an explicit value with `canonicalClientTimeZone`, the check the Web Host uses. A rejected value fails that request with a `TypeError`, answered as JSON-RPC `-32603` like the server's other parameter errors, before a Session is created or input is routed.
- An omitted value samples `Intl.DateTimeFormat().resolvedOptions().timeZone` when each prompt is accepted. A sampled value that does not canonicalize, such as `+00:00` under `TZ=GMT` or `Etc/Unknown`, records no zone and does not fail the prompt.
- The prompt records the `sdk-user` message source `{ kind: 'user', clientTimeZone? }` without `rpcId`. The `rpcId` identifies a Web submission for prompt acknowledgement and attachment reclamation, which the SDK does not have.
- `reportedBrowserTimeZone` reads a string `clientTimeZone` from any `user` source. Writers canonicalize before commit, and request preparation still refuses a noncanonical value, so the Web path and the model-visible text stay unchanged.
- Native commands record no zone. Web executes slash commands through `commands.execute` without `clientTimeZone`, and SDK `session/query` routes commands to the same handlers, so `/plan <text>` steers a zone-less message on both paths.
## Alternatives considered
**Inject one runtime-wide zone into every request.** A process or configuration zone applied by time-context would also cover in-process children and plugin messages, but it would present a deployment fact as user authority. The time-context fallback display zone already exists and deliberately keeps the `unavailable` policy.
**Write a synthetic `rpcId` on SDK prompts.** This reuses the Web source variant unchanged, but Web clients use `rpcId` to settle submissions and reclaim attachments, so a synthetic identity would claim a Web submission that never existed.
**Fix the zone at `initialize`.** One value per connection saves a field per prompt, but a long-lived runtime can serve users in different zones and a process zone can change, so the value would become stale. A per-prompt value matches the Web browser sample.
## Consequences
- SDK embeddings that pass no zone now report the runtime process zone. In a container this is usually `UTC`, which may differ from the user's zone; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.md) tells consumers to pass `timeZone` or `time_zone`, or to set `TZ`.
- SDK subagent children receive prompts without a zone, so they report their own process zone; in-process children see `unavailable`, as on Web.
- A reader that predates the relaxed check ignores an SDK prompt zone; the [persistence record](../../../../docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.md) keeps the format version.
- `packages/sdk/server/tests/time-zone.spec.ts` pins canonical, rejected, sampled, and unusable zones, the `session/query` route, and matching `/plan` sources on the SDK and native command paths. `apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts` asserts the model-visible line through the shipped `sdk` profile. The SDK snapshot driver sends `timeZone: 'UTC'` and runs with `TZ=UTC`.
@@ -0,0 +1,35 @@
# Agent Note:SDK prompt 逐条上报时区
Status: implemented
[English](2026-11-09-sdk-prompt-time-zone.md) | 中文
## 问题
Web 与 Desktop 的 prompt 携带浏览器时区,Host 规范化后把它记录在该条用户消息上,[time-context](../../../../packages/context/time-context/README.zh.md) 随后让模型按该时区解释未限定时区的日期与时间。SDK prompt 记录的是 `{ kind: 'user' }`,而 time-context 只从同时带有 Web `rpcId` 的 user 来源读取时区。因此每个 SDK 请求都显示 `Browser time zone for this request: unavailable.`,模型会就 Web 用户从不会被追问的日期去询问用户。SDK 协议也没有字段让嵌入方应用上报其用户的时区。
## 决定
时区仍是请求本地的消息来源数据,与[显式定时任务时区决定](../simplification/2026-08-09-explicit-schedule-time-zone.zh.md)一致;SDK 逐条 prompt 提供它。
- `session/prompt` 与 `session/query` 接受可选的 `timeZone`。TypeScript 客户端在 `HarnessClient.prompt()` 选项和 `run()` 选项中接受它;Python 客户端在 `session_prompt()` 和 `run()` 中接受 `time_zone` 关键字参数。
- SDK server 用 Web Host 所用的同一检查 `canonicalClientTimeZone` 规范化显式值。被拒的值让该请求以 `TypeError` 失败,与 server 的其他参数错误一样应答为 JSON-RPC `-32603`,发生在创建 Session 或路由输入之前。
- 省略时,在接受每条 prompt 时采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。采样值无法规范化时(例如 `TZ=GMT` 下的 `+00:00` 或 `Etc/Unknown`),不记录时区,也不让 prompt 失败。
- prompt 记录不带 `rpcId` 的 `sdk-user` 消息来源 `{ kind: 'user', clientTimeZone? }`。`rpcId` 标识一次 Web 提交,用于 prompt 确认和附件回收,SDK 没有这样的提交。
- `reportedBrowserTimeZone` 从任何 `user` 来源读取字符串 `clientTimeZone`。写入方在提交前规范化,请求准备阶段仍拒绝非规范值,因此 Web 路径和模型可见文本都不变。
- 原生命令不记录时区。Web 通过 `commands.execute` 执行 slash 命令且不带 `clientTimeZone`,SDK `session/query` 把命令路由到同一批 handler,因此两条路径上的 `/plan <text>` 都 steer 一条不带时区的消息。
## 备选方案
**向每个请求注入一个运行时级时区。** 由 time-context 应用的进程或配置时区也能覆盖进程内子 agent 与插件消息,但它会把部署事实当作用户依据呈现。time-context 已有回退显示时区,并且有意保留 `unavailable` 策略。
**在 SDK prompt 上写入合成的 `rpcId`。** 这样可以原样复用 Web 来源变体,但 Web 客户端用 `rpcId` 结算提交并回收附件,合成标识会声称存在一次从未发生的 Web 提交。
**在 `initialize` 时固定时区。** 每个连接一个值可以省去每条 prompt 的字段,但长期运行的运行时可能服务不同时区的用户,进程时区也可能变化,该值会过时。逐条 prompt 的值与 Web 浏览器采样一致。
## 影响
- 不传时区的 SDK 嵌入方现在上报运行时进程时区。容器中通常是 `UTC`,可能与用户时区不同;[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.zh.md)要求使用方传入 `timeZone` 或 `time_zone`,或设置 `TZ`。
- SDK subagent 子运行时收到的 prompt 不带时区,因此上报自身进程时区;进程内子 agent 与 Web 上一样看到 `unavailable`。
- 早于放宽检查的读取方会忽略 SDK prompt 的时区;[持久化记录](../../../../docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.zh.md)保持格式版本不变。
- `packages/sdk/server/tests/time-zone.spec.ts` 固定规范化、拒绝、采样与不可用时区,`session/query` 路由,以及 SDK 与原生命令路径上一致的 `/plan` 来源。`apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts` 通过随发行版交付的 `sdk` profile 断言模型可见的那一行。SDK snapshot 驱动发送 `timeZone: 'UTC'` 并在 `TZ=UTC` 下运行。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-11-forge-review-page.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-11-forge-review-page.md
/agent-note-code-review-page:
en: 88e0f71d0da6eda5
zh: ff17f12fd505c772
/agent-note-code-review-page/problem:
en: ad1da0c97cfc9c2d
zh: f4420c0b004fd189
/agent-note-code-review-page/decision:
en: b0ba35d7c5818dc3
zh: 5414ec6190be0726
/agent-note-code-review-page/alternatives-considered:
en: 963b1be39a0e4bac
zh: 940b86a5e2036477
/agent-note-code-review-page/consequences:
en: c17a96adbec69d92
zh: 06b5f2c28a9ec331
@@ -0,0 +1,31 @@
# Agent Note: Code review page
Status: implemented
English | [中文](2026-11-11-forge-review-page.zh.md)
## Problem
The [forge panel](2026-10-09-forge-panel.md) shows the change requests one Session created or pushed. A reviewer also needs the change requests that ask for their review, that they created, or that involve them, read and reviewed without first finding or creating the Session that owns them, and a conversation with the Agent about one of them that does not mix into an unrelated existing conversation.
## Decision
A left-navigation Code review page in [`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) lists three viewer lists and shows one change request in full.
- **Lists** — an optional `ForgeProvider` capability (`viewer`, `listForViewer`, `countForViewer`) returns summaries of open change requests; GitHub answers each list with one GraphQL search, because one document with several searches times out. The Host reads the lists only while a page or count stream lasts, outside the forge's status polling, since a batch snapshot of dozens of change requests exceeds GitHub's query timeout; only the shown change request is polled through `ForgeService.watch`.
- **Reads by URL** — the page's `forgePanel/review*` methods name a change request by URL and no Session; they share the Session-bound methods' implementation and are reachable only by callers that may use the Host's code host credentials.
- **Description** — `readDescription` returns the Markdown body, labels, and signed addresses for private attachments, which the page substitutes before rendering with HTML omitted.
- **Changes** — the page draws the changes view itself, split from the right-sidebar tab, with a panel state that holds only the shown change request; plugin lenses, annotations, and slots stay with the Session tab, whose extension points name a Session.
- **Chat** — the chat tab embeds `conversation.content` for the blank Session `connectWorkspace` resolves in the Workspace named like the repository, and never offers an existing conversation. A Workspace picked in the Hero is handled by the page, as every owner of the content handles its own picks: the page connects that Workspace's blank and shows it in the chat tab, where the main Conversation opens it as the main Session. The change request is bound when the Session's first message enters its inbox, so a blank that is never used stays unbound.
- **Hosts** — the page lists every configured host together; choosing among hosts and accounts waits for a second provider that lists change requests.
## Alternatives considered
- **A Session per change request for reading** — rejected: reading the description or the diff would create Sessions nobody converses in, and bind them.
- **Reviewing in an existing conversation** — rejected by the user: the conversation's context would mix with the review.
- **Listing through the status poller** — rejected: the batch snapshot query times out at the list sizes a reviewer has.
- **Binding when the chat opens** — rejected: the blank Session is shared with New Session, so it would carry the binding into an unrelated conversation.
## Consequences
The forge registry gains a fifth optional capability family and a `rate-limited` failure code, recorded in the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.md). A Host restart before the chat's first message forgets the staged binding.
@@ -0,0 +1,31 @@
# Agent Note: 代码评审页
Status: implemented
[English](2026-11-11-forge-review-page.md) | 中文
## Problem
[forge 面板](2026-10-09-forge-panel.zh.md)显示一个会话创建或推送的变更请求。评审者还需要请自己评审的、自己创建的以及与自己有关的变更请求,不必先找到或创建拥有它们的会话就能阅读和评审;也需要就其中一个与 Agent 对话,而且这段对话不能混进无关的已有对话。
## Decision
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 在左侧导航中加入“代码评审”页,列出三个登录用户列表,并完整显示一个变更请求。
- **列表**——可选的 `ForgeProvider` 能力(`viewer`、`listForViewer`、`countForViewer`)返回未关闭变更请求的摘要;GitHub 每个列表用一次 GraphQL 搜索回答,因为在一个文档中放多个搜索会超时。Host 只在页面流或计数流存在时读取列表,不经过 forge 的状态轮询,因为几十个变更请求的批量快照会超过 GitHub 的查询时限;只有显示中的变更请求经 `ForgeService.watch` 轮询。
- **按 URL 读取**——页面的 `forgePanel/review*` 方法以 URL 而不是会话指定变更请求;它们与会话绑定的方法共用实现,只有可以使用 Host 代码托管凭据的调用方能访问。
- **描述**——`readDescription` 返回 Markdown 正文、标签以及私有附件的签名地址,页面替换这些地址后以省略 HTML 的方式渲染。
- **变更**——页面自己绘制变更视图(从右侧栏标签中拆出),面板状态只含显示中的变更请求;插件的透镜、行注释和插槽仍只在会话标签中,因为这些扩展点以会话为对象。
- **对话**——对话标签为 `connectWorkspace` 在与仓库同名的工作区中解析出的空白会话嵌入 `conversation.content`,从不提供已有对话。在 Hero 中选择工作区由页面自己处理,这与内容的每个属主处理各自的选择一致:页面连接该工作区的空白会话并在对话标签中显示它,而主 Conversation 会把它打开为主会话。该会话的首条消息进入收件箱时才绑定变更请求,因此从未使用的空白会话保持未绑定。
- **主机**——页面把所有已配置的主机合并列出;在主机与账号之间选择要等到第二个能列出变更请求的提供方。
## Alternatives considered
- **每个变更请求用一个会话来阅读**——否决:阅读描述或 diff 会创建无人对话的会话并绑定它们。
- **在已有对话中评审**——用户否决:对话上下文会与评审混在一起。
- **经状态轮询列出**——否决:在评审者常见的列表规模下,批量快照查询会超时。
- **打开对话时就绑定**——否决:空白会话与“新会话”共用,会把绑定带进无关的对话。
## Consequences
forge 注册表增加第五组可选能力和 `rate-limited` 失败码,记录在[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.zh.md)中。在对话的首条消息之前重启 Host 会丢失暂存的绑定。
@@ -9,8 +9,8 @@
en: dc43ba84345e1405
zh: dbc03572ab7710d2
/agent-note-ship-optional-bundles-with-the-installation/decision:
en: 0f3e0daee65b6510
zh: 2e9c8000da75fb6c
en: e4ecfa61b6f71d8c
zh: a33d16e5843cf097
/agent-note-ship-optional-bundles-with-the-installation/alternatives-considered:
en: 95b48b61757f1f13
zh: e9fb2d6ea492a4bc
@@ -10,7 +10,7 @@ The Web plugin page manages only the bundles a person installed into the profile
## Decision
The launcher names in `OPTIONAL_BUNDLES` (`packages/util/official-bundles/src/bundles.ts`, beside the profile templates) the bundles the installation ships for a person to switch on. Each must be a runtime dependency of `apps/cli` that declares `dsh.bundle.patch`, and no shipped profile template selects it. The plugin manager's `listBundles` reports such a bundle as `optional`: switched off until selected, never removable, resolved from the installation like any installation-supplied bundle. The Web plugin page presents offered optional bundles in its Official group, tagged experimental when the package is experimental, ahead of the profile's own installed bundles. The [persistent-terminal bundle](../../../../packages/experimental/terminal-bundle/README.md) remains available to the Host but has no page switch, even when enabled; its existing profile selection remains intact.
The launcher names in `OPTIONAL_BUNDLES` (`packages/util/official-bundles/src/bundles.ts`, beside the profile templates) the bundles the installation ships for a person to switch on. Each must be a runtime dependency of `apps/cli` that declares `dsh.bundle.patch`, and no shipped profile template selects it. The plugin manager's `listBundles` reports such a bundle as `optional`: switched off until selected, never removable, resolved from the installation like any installation-supplied bundle. The Web plugin page presents offered optional bundles in its Official group, tagged experimental when the package is experimental, ahead of the profile's own installed bundles.
Default-product isolation keeps its rules with one declared exception: an optional bundle's dependency graph is outside the default product. The static gate skips the `dependencies` edge from `@deepseek-ai/dsh` to a listed bundle and still rejects a runtime import, a shipped composition, a preset, or a default template that names it, an experimental dependency the list does not name, and a listed name that is not a runtime dependency or not a bundle. The workspace-constraints check accepts the same `dependencies` edges and no other runtime section, and the packed-install release check skips them from the installed entry package while requiring each listed bundle to be installed.
@@ -10,7 +10,7 @@ Web 插件页只管理用户装进 profile 的组合包。像 Agent Teams 这样
## 决策
启动器在 `OPTIONAL_BUNDLES`(`packages/util/official-bundles/src/bundles.ts`,与 profile 模板并列)里点名安装随附、供用户开启的组合包。每一个都必须是 `apps/cli` 声明了 `dsh.bundle.patch` 的运行时依赖,且不被任何随附 profile 模板选中。插件管理器的 `listBundles` 把这类组合包报告为 `optional`:选中前保持关闭、永不可卸载、像其他安装提供的组合包一样从安装目录解析。Web 插件页在「官方」分组展示可供选择的可选组合包,属于实验包的带实验性标签,排在 profile 自己已安装的组合包之前。[持久终端组合包](../../../../packages/experimental/terminal-bundle/README.zh.md)仍可供 Host 使用,但即使已启用也不提供页面开关;已有的 profile 选择保持不变。
启动器在 `OPTIONAL_BUNDLES`(`packages/util/official-bundles/src/bundles.ts`,与 profile 模板并列)里点名安装随附、供用户开启的组合包。每一个都必须是 `apps/cli` 声明了 `dsh.bundle.patch` 的运行时依赖,且不被任何随附 profile 模板选中。插件管理器的 `listBundles` 把这类组合包报告为 `optional`:选中前保持关闭、永不可卸载、像其他安装提供的组合包一样从安装目录解析。Web 插件页在「官方」分组展示可供选择的可选组合包,属于实验包的带实验性标签,排在 profile 自己已安装的组合包之前。
默认产品隔离的规则保持不变,只声明一个例外:可选组合包的依赖图在默认产品之外。静态门禁跳过从 `@deepseek-ai/dsh` 到列表中组合包的 `dependencies` 边,仍然拒绝运行时 import、随附组合、preset 或默认模板对它的引用,拒绝列表没有点名的实验依赖,也拒绝不是运行时依赖或不是组合包的列表项。workspace 约束检查接受同样的 `dependencies` 边而不接受其他运行时依赖段;发布时的 packed-install 检查对已安装入口包跳过这些边,并要求列表中的每个组合包都已安装。
@@ -9,8 +9,8 @@
en: 4a7e52f6a16dec96
zh: d558db30801355d9
/agent-note-explicit-schedule-time-zone-boundary/decision:
en: 6f233286c95b5294
zh: 5a1f4ba6f5ccbd36
en: ab632daa5d687c77
zh: b406216a5b35e5ac
/agent-note-explicit-schedule-time-zone-boundary/alternatives-considered:
en: 982fe0b8d24a66ce
zh: e6dceee1ce776d21
@@ -18,5 +18,5 @@
en: 56dcb44f09be3713
zh: 59a6814a662458ad
/agent-note-explicit-schedule-time-zone-boundary/consequences:
en: d9358667c58662e4
zh: d536bb0fccd9f0a9
en: 43980cd5ebdf6685
zh: ed3051f8eb45ead4
@@ -12,9 +12,9 @@ Most of that complexity sat outside Schedule. The model already interprets natur
## Decision
The browser zone is request-local source data. The Web client samples `Intl.DateTimeFormat().resolvedOptions().timeZone` for every prompt. The Host accepts an optional `clientTimeZone`, validates and canonicalizes `UTC` or an IANA Area/Location at the RPC boundary, and logs it on that exact `user-rpc` message. Invalid values reject prompt admission. Non-browser clients may omit it.
The browser zone is request-local source data. The Web client samples `Intl.DateTimeFormat().resolvedOptions().timeZone` for every prompt. The Host accepts an optional `clientTimeZone`, validates and canonicalizes `UTC` or an IANA Area/Location at the RPC boundary, and logs it on that exact `user-rpc` message. Invalid values reject prompt admission. Non-browser clients may omit it; SDK prompts report an explicit or sampled process zone on an `sdk-user` source without `rpcId`, as recorded in [per-prompt SDK time zone](../feature/2026-11-09-sdk-prompt-time-zone.md).
Time-context derives unique, mixed, or missing browser facts from original user-rpc messages in the open turn. A unique zone formats the clock and tells the model to interpret otherwise-unqualified dates and times in that zone. Mixed or missing browser-zone records tell the model to ask the user. The configured or process zone is only a display fallback and is never presented as user authority.
Time-context derives unique, mixed, or missing browser facts from original user messages in the open turn that carry `clientTimeZone`. A unique zone formats the clock and tells the model to interpret otherwise-unqualified dates and times in that zone. Mixed or missing browser-zone records tell the model to ask the user. The configured or process zone is only a display fallback and is never presented as user authority.
Schedule accepts no implicit local zone. `at` is either a strict offset-bearing RFC 3339 string or exact `{ date, time, time_zone }`. The structured form requires its zone even when time-context just showed the model a browser zone. Schedule does not import time-context, inspect user-message sources, read a Session header, or produce a confirmation error. Its parser validates the explicit value, rejects daylight-saving gaps, chooses the first instant in overlaps, and stores only canonical UTC `scheduledAt`.
@@ -43,5 +43,5 @@ Source audits reject `SessionHeader.timeZone`, persistence `time_zone` columns,
- Browser-local natural language works without a persisted Session-zone subsystem.
- Schedule has one explicit, independently testable absolute-time boundary.
- Travel and concurrent tabs affect only their own prompts; a turn with mixed browser-zone records asks instead of mutating shared state.
- Non-browser clients remain valid but must provide enough natural-language context or explicit tool arguments.
- Non-browser clients without a reported zone remain valid but must provide enough natural-language context or explicit tool arguments.
- The model may still make an interpretation error; the tool guarantees only that the explicit calendar value is valid and deterministic.
@@ -12,9 +12,9 @@ Status: implemented
## 决策
浏览器时区是请求本地的来源数据。Web client 会为每条提示词采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。Host 接受可选的 `clientTimeZone`,在 RPC 边界校验并规范化 `UTC` 或 IANA Area/Location,再将其记录在确切的那条 `user-rpc` 消息上。无效值会使提示词准入被拒绝。非浏览器 client 可以省略它。
浏览器时区是请求本地的来源数据。Web client 会为每条提示词采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。Host 接受可选的 `clientTimeZone`,在 RPC 边界校验并规范化 `UTC` 或 IANA Area/Location,再将其记录在确切的那条 `user-rpc` 消息上。无效值会使提示词准入被拒绝。非浏览器 client 可以省略它;SDK prompt 在不带 `rpcId` 的 `sdk-user` 来源上上报显式或采样的进程时区,见 [SDK prompt 逐条上报时区](../feature/2026-11-09-sdk-prompt-time-zone.zh.md)。
Time-context 从 open turn 中的原始 user-rpc 消息派生唯一、混合或缺失的浏览器事实。唯一时区会用于格式化时钟,并告诉模型把未明确限定时区的日期和时间解释为该时区。浏览器时区记录混合或缺失时,模型会被告知询问用户。配置或进程时区只作为显示 fallback,绝不会被呈现为用户权威。
Time-context 从 open turn 中带 `clientTimeZone` 的原始 user 消息派生唯一、混合或缺失的浏览器事实。唯一时区会用于格式化时钟,并告诉模型把未明确限定时区的日期和时间解释为该时区。浏览器时区记录混合或缺失时,模型会被告知询问用户。配置或进程时区只作为显示 fallback,绝不会被呈现为用户权威。
Schedule 不接受隐式本地时区。`at` 要么是带显式偏移量且严格符合 RFC 3339 的字符串,要么是精确的 `{ date, time, time_zone }`。即使 time-context 刚向模型展示了浏览器时区,结构化形式仍要求自己的时区。Schedule 不导入 time-context、不检查 user message 来源、不读取 Session header,也不产生确认错误。它的 parser 会校验显式值、拒绝夏令时缺口、在重叠时选择第一个时点,并且只存储规范化后的 UTC `scheduledAt`。
@@ -43,5 +43,5 @@ Host 测试固定别名的规范化、可省略行为和进入 Agent(智能体
- 无需持久 Session 时区子系统,浏览器本地自然语言也能工作。
- Schedule 具有一个显式且可独立测试的绝对时间边界。
- 旅行与并发 tab 只影响各自的提示词;浏览器时区记录混合的 turn 会询问用户,而不是改变共享状态。
- 非浏览器 client 仍然有效,但必须提供足够的自然语言上下文或显式工具参数。
- 未上报时区的非浏览器 client 仍然有效,但必须提供足够的自然语言上下文或显式工具参数。
- 模型仍可能产生解释错误;工具只保证显式日历值有效且具有确定性。
@@ -0,0 +1,28 @@
# Bilingual-pair consistency record for 2026-11-18-tool-reachability-and-initial-disclosure.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/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.md
/agent-note-tool-reachability-and-initial-disclosure:
en: 702b42d555430e20
zh: d94f3adf52d9d7cb
/agent-note-tool-reachability-and-initial-disclosure/problem:
en: 006eb992e4c0dd4d
zh: 530d13e4f832653b
/agent-note-tool-reachability-and-initial-disclosure/proposal:
en: 86ededd59a892229
zh: 1ed3ac1f5b160f9d
/agent-note-tool-reachability-and-initial-disclosure/proposal/reachability:
en: 7e8256e97b924e34
zh: be334f4469d0b5e1
/agent-note-tool-reachability-and-initial-disclosure/proposal/initial-disclosure:
en: 1c2466dff8ba70e1
zh: d0e2c35a0e74008f
/agent-note-tool-reachability-and-initial-disclosure/alternatives-considered:
en: 27bff0dbad805d7a
zh: be5b8d1746b5bc02
/agent-note-tool-reachability-and-initial-disclosure/acceptance-criteria:
en: 099ebf6f7c753286
zh: 50e29d2522d7fee9
/agent-note-tool-reachability-and-initial-disclosure/risks:
en: 9366e2866f4b2555
zh: 5d7b94bb85019f58
@@ -0,0 +1,50 @@
# Agent Note: Tool reachability and initial disclosure
Status: proposed
English | [中文](2026-11-18-tool-reachability-and-initial-disclosure.zh.md)
## Problem
Both executors disclose every reachable tool in full at every step: `tool-executor-native` through the request `tools` field, `tool-executor-ptc` through the `tools:sdk` section. No per-tool statement exists for how the model may call a tool and how much it receives before any discovery; `ToolSchema.deferLoading` names one provider mechanism instead.
## Proposal
Describe every reachable tool with two model-facing dimensions, defined by what the model receives, not by what the host or provider transmits.
### Reachability
| Value | Meaning |
|---|---|
| `native` | Callable only as a provider tool call. |
| `program` | Callable only from inside a `run_code` program. |
| `both` | Callable either way. |
Authorization is separate: a tool removed by `restrict()` or an inactive `when` condition is absent from this model; a guard denies one execution and changes neither dimension.
### Initial disclosure
| Value | What the model receives before any discovery |
|---|---|
| `none` | Nothing about this tool. |
| `name` | The tool name. |
| `summary` | A description without parameters; may be given per namespace. |
| `full` | Name, description, parameters, and for `program` reachability the return type. |
Every reachable tool is searchable; `none` only means absent from the initial disclosure.
## Alternatives considered
**A visibility axis of `invisible`, `discoverable`, `injected`, `system prompt`.** `injected` is the state a tool enters after a search hit, `system prompt` is a channel, and no name-only level exists; the axis mixed policy, state, and channel.
**A `discoverable` boolean.** Every case that seemed to need an unsearchable tool is authorization, search ranking, an alias, or a runtime builtin that is not a tool; omitting a schema is not enforcement ([packages/AGENTS.md](../../../../packages/AGENTS.md)).
## Acceptance criteria
- Each registered tool resolves to one value per dimension per step, and both executors read the same resolution.
- A `none` tool is found through `tool_search` and then called under each executor in a recorded snapshot; a `native` activation projects through [active tool headers](../../implemented/architecture/2026-09-20-dynamic-tool-updates.md).
## Risks
- Discovery adds a model round trip, and search quality depends on tool names and descriptions.
- Per-step recomputation moves tools between values and changes the declaration prefix the cache relies on.
@@ -0,0 +1,50 @@
# Agent Note: 工具可达性与初始披露
Status: proposed
[English](2026-11-18-tool-reachability-and-initial-disclosure.md) | 中文
## Problem
两个执行器在每个步骤都完整披露每个可达工具:`tool-executor-native` 通过请求的 `tools` 字段,`tool-executor-ptc` 通过 `tools:sdk` 章节。没有任何按工具的说明能表达模型可以如何调用某个工具,以及在任何发现之前它能收到多少内容;`ToolSchema.deferLoading` 只是以某一个提供方机制命名。
## Proposal
用两个面向模型的维度描述每个可达工具,两者都由模型收到的内容定义,而不是由宿主或提供方传输的内容定义。
### 可达性
| 取值 | 含义 |
|---|---|
| `native` | 只能作为提供方工具调用来调用。 |
| `program` | 只能在 `run_code` 程序内部调用。 |
| `both` | 两种方式都可调用。 |
授权是独立的:被 `restrict()` 移除或因 `when` 条件未激活而移除的工具不在此模型之内;guard 拒绝的是一次执行,不改变任何一个维度。
### 初始披露
| 取值 | 模型在任何发现之前收到的内容 |
|---|---|
| `none` | 关于该工具的任何内容都没有。 |
| `name` | 工具名称。 |
| `summary` | 不含参数的描述;可以按命名空间给出。 |
| `full` | 名称、描述、参数,以及 `program` 可达性下的返回类型。 |
每个可达工具都可被搜索;`none` 只表示不在初始披露中。
## Alternatives considered
**一个由 `invisible`、`discoverable`、`injected`、`system prompt` 构成的可见性轴。** `injected` 是工具在搜索命中后进入的状态,`system prompt` 是通道,且不存在仅名称级别;该轴混合了策略、状态和通道。
**一个 `discoverable` 布尔值。** 每个看似需要不可搜索工具的情形都是授权、搜索排序、别名或不是工具的运行时内建函数;省略 schema 不是强制手段([packages/AGENTS.md](../../../../packages/AGENTS.md))。
## Acceptance criteria
- 每个已注册工具在每个步骤为每个维度解析出一个取值,两个执行器读取同一次解析。
- 在录制快照中,一个 `none` 工具在每个执行器下都通过 `tool_search` 被找到并随后被调用;`native` 激活按[活跃工具请求头](../../implemented/architecture/2026-09-20-dynamic-tool-updates.zh.md)投影。
## Risks
- 发现增加一次模型往返,且搜索质量取决于工具名称和描述。
- 按步骤重新计算会在取值之间移动工具,并改变缓存所依赖的声明前缀。
+1
View File
@@ -32,6 +32,7 @@ mise.toml
dist-exe/
/dist/
apps/desktop/.desktop-build/
apps/desktop/.desktop-dev/
python/sdk-runtime/src/deepseek_harness_runtime/runtime/
python/**/__pycache__/
python/**/.pytest_cache/
+4
View File
@@ -46,6 +46,7 @@ External packages installed for runtime use or embedded in distributed Host or b
| [`@joplin/turndown-plugin-gfm`](https://github.com/laurent22/joplin-turndown-plugin-gfm) | MIT |
| [`@jridgewell/gen-mapping`](https://github.com/jridgewell/sourcemaps) | MIT |
| [`@js-temporal/polyfill`](https://github.com/js-temporal/temporal-polyfill) | ISC |
| [`@larksuite/cli`](https://github.com/larksuite/cli) | MIT |
| [`@lexical/history`](https://github.com/facebook/lexical) | MIT |
| [`@lexical/plain-text`](https://github.com/facebook/lexical) | MIT |
| [`@lexical/text`](https://github.com/facebook/lexical) | MIT |
@@ -69,8 +70,10 @@ External packages installed for runtime use or embedded in distributed Host or b
| [`@shikijs/langs`](https://github.com/shikijs/shiki) | MIT |
| [`@standard-schema/spec`](https://github.com/standard-schema/standard-schema) | MIT |
| [`@tanstack/react-virtual`](https://github.com/TanStack/virtual) | MIT |
| [`@tencentcloud/tmeet`](https://github.com/TencentCloud/tencentmeeting-cli) | MIT |
| [`@trycua/cua-driver`](https://github.com/trycua/cua) | MIT |
| [`@vscode/ripgrep`](https://github.com/microsoft/vscode-ripgrep) | MIT |
| [`@wecom/cli`](https://github.com/WecomTeam/wecom-cli) | MIT |
| [`@xterm/addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit) | MIT |
| [`@xterm/addon-serialize`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-serialize) | MIT |
| [`@xterm/headless`](https://github.com/xtermjs/xterm.js) | MIT |
@@ -314,6 +317,7 @@ The [shared runtime lock](scripts/primary-runtime/lock.json) records each distri
| [`openpyxl`](https://foss.heptapod.net/openpyxl/openpyxl) | 3.1.5 | MIT |
| [`pandas`](https://github.com/pandas-dev/pandas) | 3.0.1 | BSD-3-Clause |
| [`pillow`](https://github.com/python-pillow/Pillow) | 12.3.0 | MIT-CMU |
| [`pypdf`](https://github.com/py-pdf/pypdf) | 6.21.4 | BSD-3-Clause |
| [`python-dateutil`](https://github.com/dateutil/dateutil) | 2.9.0.post0 | Apache-2.0 OR BSD-3-Clause |
| [`python-docx`](https://github.com/python-openxml/python-docx) | 1.2.0 | MIT |
| [`python-pptx`](https://github.com/scanny/python-pptx) | 1.0.2 | MIT |
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@deepseek-ai/dsh",
"description": "dsh CLI: profile launch, plugin management, and configuration inspection",
"version": "0.2.2-rc.4",
"version": "0.2.2-rc.5",
"publishConfig": {
"access": "public"
},
@@ -13,9 +13,9 @@ Setup and discovery:
- cua.listApps() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp.
- cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches.
- cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation.
- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, start a stopped application in the background only where the provider supports launch, and return without reading AX or activating the app.
- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, start a stopped application in the background only where the provider supports launch, and return without reading accessibility state or activating the app.
- app.getWindows() -> { windowId: string, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership.
- app.getWindow(windowId: string) -> Window — select a window by an ID from getWindows without reading AX. Providers reject closed or foreign windows when operating on them.
- app.getWindow(windowId: string) -> Window — select a window by an ID from getWindows without reading accessibility state. Providers reject closed or foreign windows when operating on them.
- app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required.
- app.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation.
- window.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation.
@@ -23,9 +23,10 @@ Setup and discovery:
## Accessibility tree
Available at app or window level depending on the platform.
Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing.
Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current accessibility snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing.
- getAccessibilityTree(options?: { includeMenus?: boolean, details?: boolean, maxElements?: number, maxDepth?: number }) -> string — set the node count or depth for one read. Omitted limits use the provider settings. includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names.
- listActions(elementId: string) -> string[] — list the actions an element advertises.
- getActionSchema(action: string) -> JSON Schema — query the parameter schema for an action.
- invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none.
- performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument.
- setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value.
@@ -43,7 +44,7 @@ Use an explicit window for pointer input. Before coordinate input, including rel
- scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left.
- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window.
A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry.
A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current accessibility observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry.
## Simulated keyboard
Available at app or window level depending on the platform.
@@ -486,6 +486,87 @@ describe('Python SDK dsh profile keyless smoke', () => {
}
}, 30_000)
// TZ belongs to the spawned runtime only; GMT makes ICU report "+00:00", which is not a usable zone name.
it.each([
{ tz: 'America/New_York', sampled: 'Browser time zone for this request: America/New_York. Interpret otherwise-unqualified dates and times in this zone.' },
{ tz: 'GMT', sampled: 'Browser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.' },
])('shows the model the reported or sampled prompt time zone (TZ=$tz)', async ({ tz, sampled }) => {
const root = await mkdtemp(join(tmpdir(), 'dsh-sdk-time-zone-'))
onTestFinished(() => rm(root, { recursive: true, force: true }))
const modelRequests: string[] = []
const modelServer = createServer((request, response) => {
let body = ''
request.setEncoding('utf8')
request.on('data', (chunk: string) => { body += chunk })
request.on('end', () => {
modelRequests.push(body)
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(messagesResponse({ type: 'text', text: 'done' }, 'end_turn'))
})
})
onTestFinished(() => new Promise<void>((resolve) => { modelServer.close(() => { resolve() }) }))
await new Promise<void>(resolve => modelServer.listen(0, '127.0.0.1', resolve))
const address = modelServer.address()
if (address === null || typeof address === 'string') throw new Error('model server did not bind a TCP port')
const child = execa(launch.command, [...launch.args, '--profile', 'sdk'], {
cwd: repoRoot,
env: {
...launch.env,
DSH_HOME: join(root, '.dsh'),
DSH_TELEMETRY_DISABLED: '1',
DEEPSEEK_API_KEY: 'keyless-smoke-no-call',
DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
TZ: tz,
},
timeout: 35_000,
killSignal: 'SIGKILL',
reject: false,
})
onTestFinished(async () => { child.kill('SIGKILL'); await child })
const lines: string[] = []
let stdoutBuffer = ''
let stderr = ''
child.stdout.on('data', (chunk: Buffer) => {
stdoutBuffer += chunk.toString('utf8')
const parts = stdoutBuffer.split('\n')
stdoutBuffer = parts.pop() ?? ''
lines.push(...parts)
})
child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
const send = (id: number, method: string, params?: object) => {
child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`)
return waitForLine(lines, value => value.id === id, () => stderr)
}
const promptRequest = async (id: number, sessionId: string, timeZone?: string): Promise<string> => {
const requests = modelRequests.length
expect(await send(id, 'session/prompt', {
sessionId, contentBlocks: [{ type: 'text', text: 'When is noon tomorrow?' }], ...timeZone === undefined ? {} : { timeZone },
})).toHaveProperty('result.messageId')
await waitForLine(lines, (value) => {
const params = value.params as { sessionId?: string; event?: { type?: string } } | undefined
return value.method === 'session.event' && params?.sessionId === sessionId && params.event?.type === 'turn/end'
}, () => stderr)
expect(modelRequests).toHaveLength(requests + 1)
return modelRequests.at(-1)!
}
await send(1, 'initialize', { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro' })
expect(await promptRequest(2, 'explicit', 'US/Eastern')).toContain(
'Browser time zone for this request: America/New_York. Interpret otherwise-unqualified dates and times in this zone.',
)
expect(await promptRequest(3, 'sampled')).toContain(sampled)
expect(await send(4, 'session/prompt', {
sessionId: 'invalid', contentBlocks: [{ type: 'text', text: 'When is noon?' }], timeZone: 'CST',
})).toMatchObject({
error: { code: -32603, message: 'timeZone must be UTC or a valid IANA Area/Location name: "CST"' },
})
expect(modelRequests).toHaveLength(2)
await send(5, 'shutdown')
const exit = await child
expect(exit.exitCode, `signal=${String(exit.signal)}; stderr=${stderr}`).toBe(0)
}, 40_000)
it('rejects an invalid max-token success env value', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-python-sdk-runtime-invalid-'))
try {
@@ -656,3 +737,64 @@ it.each(['unset', 'empty', 'full', 'python-only', 'python-only-patched', 'wrong-
expect(exit.exitCode, stderr).toBe(0)
await expect(readFile(join(home, 'dsh-runtimes', 'dsh-primary-runtime', 'runtime.json'))).rejects.toMatchObject({ code: 'ENOENT' })
})
it.each(['standard', 'ptc'] as const)('lists and loads the packaged dsh-doc skill through the SDK profile (%s)', async (mode) => {
const root = await mkdtemp(join(tmpdir(), 'sdk-dsh-doc-'))
onTestFinished(() => rm(root, { recursive: true, force: true }))
const requests: { tools: { name: string }[]; messages: unknown }[] = []
const toolUses = mode === 'standard' ? [{ type: 'tool_use', id: 'dsh-doc', name: 'skill', input: { name: 'dsh-doc' } } as const] : []
const server = createServer((request, response) => {
let body = ''
request.setEncoding('utf8').on('data', (chunk: string) => { body += chunk })
request.on('end', () => {
requests.push(JSON.parse(body) as { tools: { name: string }[]; messages: unknown })
const toolUse = toolUses[requests.length - 1]
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(toolUse === undefined ? messagesResponse({ type: 'text', text: 'done' }, 'end_turn') : messagesResponse(toolUse, 'tool_use'))
})
})
onTestFinished(() => new Promise<void>((resolve) => { server.close(() => { resolve() }) }))
await new Promise<void>((resolve) => { server.listen(0, '127.0.0.1', resolve) })
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('model fixture did not bind')
const launch = resolveExampleLaunch({
srcBin: fileURLToPath(new URL('../../../src/bin.ts', import.meta.url)), mode: 'lib',
configArgs: ['--profile', 'sdk', ...mode === 'ptc' ? ['--patch', join(repoRoot, 'apps/cli/config/examples/ptc.yml')] : []],
env: { DSH_HOME: join(root, 'home'), DSH_PRIMARY_RUNTIME: '', DSH_PERMISSION_MODE: 'danger-full-access', DSH_TELEMETRY_DISABLED: '1',
DEEPSEEK_API_KEY: 'local-fixture', DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}` },
})
const child = execa(launch.command, launch.args, { cwd: repoRoot, env: launch.env, timeout: 60_000, reject: false })
onTestFinished(async () => { child.kill('SIGKILL'); await child })
let buffer = '', stderr = ''
const lines: string[] = []
child.stdout.on('data', (chunk: Buffer) => {
buffer += chunk.toString()
const parts = buffer.split('\n')
buffer = parts.pop() ?? ''
lines.push(...parts)
})
child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
const send = (id: number, method: string, params?: object) => {
child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`)
return waitForLine(lines, value => value.id === id, () => stderr)
}
expect(await send(1, 'initialize', { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro' })).toHaveProperty('result')
await send(2, 'session/prompt', { sessionId: 'dsh-doc', contentBlocks: [{ type: 'text', text: 'How do DSH presets work?' }] })
await waitForLine(lines, (value) => {
const params = value.params as { sessionId?: string; event?: { type?: string } } | undefined
return value.method === 'session.event' && params?.sessionId === 'dsh-doc' && params.event?.type === 'turn/end'
}, () => stderr)
expect(requests).toHaveLength(toolUses.length + 1)
expect(JSON.stringify(requests[0]!.messages)).toMatch(/- `dsh-doc`: Use when a task needs facts about DeepSeek Harness/)
if (mode === 'ptc') expect(requests[0]!.tools.map(tool => tool.name)).toEqual(['run_code'])
else {
const messages = requests[1]!.messages as { content: { tool_use_id?: string }[] }[]
const loaded = JSON.stringify(messages.flatMap(message => message.content).find(block => block.tool_use_id === 'dsh-doc'))
const directory = join(repoRoot, 'packages/preset/agent-preset/skills/dsh-doc').split(sep).join('/')
expect(loaded).toContain(JSON.stringify(`Base directory for this skill: ${directory}`).slice(1, -1))
expect(loaded).toContain('# DeepSeek Harness documentation')
}
await send(3, 'shutdown')
const exit = await child
expect(exit.exitCode, stderr).toBe(0)
})
+5
View File
@@ -995,6 +995,11 @@ describe('the standard preset documentation skill', () => {
setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'cordis').then(() => undefined),
})
expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: creator.agent }))?.path).toBe(definition.path)
const ptc = await testCtx.agents.create({
sessionId: brandString<SessionId>('standard-doc-ptc'), meta: { cwd: root },
setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'ptc').then(() => undefined),
})
expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: ptc.agent }))?.path).toBe(definition.path)
const schemas = testCtx.tools.schemas(standardAgent.agent)
expect(schemas).toEqual(testCtx.tools.schemas(baseline.agent))
expect(schemas.map(tool => tool.name)).toContain('cordis_inspect')
+4 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@deepseek-ai/dsh-desktop-host",
"description": "Private Node-mode host process for the Electron desktop application",
"version": "0.2.2-rc.4",
"version": "0.2.2-rc.5",
"private": true,
"license": "MIT",
"type": "module",
@@ -37,6 +37,8 @@
"@deepseek-ai/dsh-session-persistence": "workspace:*",
"@deepseek-ai/dsh-sandbox-policy": "workspace:*",
"@deepseek-ai/dsh-util-workspace-path": "workspace:*",
"@deepseek-ai/dsh-brand": "workspace:*"
"@deepseek-ai/dsh-brand": "workspace:*",
"@deepseek-ai/dsh-tool-executor-native": "workspace:*",
"@deepseek-ai/dsh-api-workspace-files": "workspace:*"
}
}
+7 -11
View File
@@ -1,10 +1,8 @@
/** Resolve desktop-only file references through the active Host filesystem and Session. */
import { createHash } from 'node:crypto'
import type { Context } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-api-workspace-files'
import type {} from '@deepseek-ai/dsh-fs'
import type {} from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-session-persistence'
import type {} from '@deepseek-ai/dsh-sandbox-policy'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { parseFileAddress } from '@deepseek-ai/dsh-util-workspace-path'
@@ -17,6 +15,7 @@ export interface LocalDragResource {
/**
* Authorize an unmodified local file through the composed filesystem's actual read operations.
* Relative paths resolve from the same workspace root the workspace file service uses for the Session.
* @param ctx - booted Desktop Host.
* @param address - Session-scoped resource reference.
* @param cancellation - caller cancellation, combined with the read deadline.
@@ -25,17 +24,14 @@ export interface LocalDragResource {
export async function localDragResource(ctx: Context, address: string, cancellation?: AbortSignal): Promise<LocalDragResource | null> {
const resource = parseFileAddress(address)
if (resource?.scope !== 'session') throw new Error('File drag requires a Session resource')
const sessions = ctx.get('sessions')
const persistence = ctx.get('sessionPersistence')
const fs = ctx.get('fs')
const policy = ctx.get('sandboxPolicy')
if (fs === undefined || sessions === undefined || policy === undefined) throw new Error('File access unavailable')
const sessionId = resource.sessionId as SessionId
const header = sessions.get(sessionId)?.header ?? (await persistence?.stat(sessionId))?.header
if (header === undefined) throw new Error('File drag Session unavailable')
const workspaceFiles = ctx.get('workspaceFiles')
if (fs === undefined || workspaceFiles === undefined) throw new Error('File access unavailable')
const signal = cancellation === undefined ? AbortSignal.timeout(10_000) : AbortSignal.any([cancellation, AbortSignal.timeout(10_000)])
signal.throwIfAborted()
const cwd = header.cwd ?? policy.workspaceRoot
const scope = await workspaceFiles.scopeOf(resource.sessionId as SessionId, signal)
if (scope === undefined) throw new Error('File drag Session unavailable')
const cwd = scope.workspaceRoot
const entry = await fs.lstat(resource.path, { cwd }, signal)
if (entry?.type !== 'file') return null
const target = await fs.resolve(resource.path, { cwd, signal })
+5 -1
View File
@@ -17,9 +17,13 @@ async function fixture() {
onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) })
await ctx.plugin(LocalFileSystem, { cwd: root })
await ctx.plugin(SessionStore)
ctx.provide('sandboxPolicy', { workspaceRoot: root } as never)
const id = brandString<SessionId>('file-drag-test')
ctx.sessions.create(id, { meta: { cwd: root, origin: 'subagent' } })
// The workspace file service resolves a live Session's root; its own tests cover that resolution.
ctx.provide('workspaceFiles', {
scopeOf: (sessionId: SessionId) =>
Promise.resolve(ctx.sessions.get(sessionId) === undefined ? undefined : { sessionId, workspaceRoot: root }),
} as never)
const path = join(root, '报告.pdf')
const bytes = Buffer.from('%PDF-1.4\n原始内容\n%%EOF')
await writeFile(path, bytes)
+1
View File
@@ -11,6 +11,7 @@
{ "path": "../../packages/host/authentication-desktop" },
{ "path": "../../vendor/cordis" },
{ "path": "../../packages/core/agent" },
{ "path": "../../packages/api/workspace-files/tsconfig.host.json" },
{ "path": "../../packages/jobs/jobs" },
{ "path": "../../packages/schedule/schedule" },
{ "path": "../../packages/workspace/workspace" },
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-desktop-publisher",
"version": "0.2.2-rc.4",
"version": "0.2.2-rc.5",
"description": "Private Desktop release metadata, rollout and website publisher",
"private": true,
"type": "module",
+4 -4
View File
@@ -42,8 +42,8 @@
en: 98cf848762482d48
zh: 74f9100a39ec8c2f
/deepseek-harness-desktop/develop:
en: faf7676ba18bbf2f
zh: f1d7b75ad348c548
en: 4e4b26cfaaa098ee
zh: e0a2965606020041
/deepseek-harness-desktop/develop/startup-onboarding:
en: 67dc7ef3e293236a
zh: 1b224db684a2d1d7
@@ -54,8 +54,8 @@
en: 7200a35dbed997c3
zh: 511d6961530757f1
/deepseek-harness-desktop/windows-installer-interface:
en: 3a70021830865253
zh: 0467be8b505446cb
en: eb9d30bca4134f80
zh: bf201d18ae5ba697
/deepseek-harness-desktop/updates:
en: 8b0b9efeb83727ef
zh: 5ee95de48ceab392
+2 -2
View File
@@ -199,7 +199,7 @@ The development application menu offers Reload Page (Cmd+R on macOS, Ctrl+R else
pnpm run dev:desktop
```
Development Harness state defaults to `apps/desktop/.desktop-build/development/home`, the disposable npm project lives at `apps/desktop/.desktop-build/development/project`, and Electron browser data lives at `apps/desktop/.desktop-build/development/electron-user-data`. Sessions, settings, credentials, package links, and browser data therefore stay out of the user's normal Harness home. An explicit `DSH_HOME` replaces only the development Harness home. Renderer DevTools opens automatically; Main, Renderer, and dsh Host debugging listen on ports 9229, 9222, and 9230. `DSH_DESKTOP_MAIN_INSPECT_PORT`, `DSH_DESKTOP_RENDERER_DEBUG_PORT`, and `DSH_DESKTOP_HOST_INSPECT_PORT` replace those ports, while `DSH_DESKTOP_OPEN_DEVTOOLS=0` keeps the detached Renderer tools closed.
Development Harness state defaults to `apps/desktop/.desktop-dev/home` and Electron browser data to `apps/desktop/.desktop-dev/electron-user-data`; `pnpm run clean` removes `.desktop-build` but keeps this directory. The disposable npm project lives at `apps/desktop/.desktop-build/development/project`. Sessions, settings, credentials, package links, and browser data therefore stay out of the user's normal Harness home. A launch moves each missing default directory from `.desktop-build/development`, and stops instead while a running Harness Dev still uses that browser data. An explicit `DSH_HOME` replaces only the development Harness home, and `DSH_DESKTOP_USER_DATA_DIR` replaces only the browser data. Renderer DevTools opens automatically; Main, Renderer, and dsh Host debugging listen on ports 9229, 9222, and 9230. `DSH_DESKTOP_MAIN_INSPECT_PORT`, `DSH_DESKTOP_RENDERER_DEBUG_PORT`, and `DSH_DESKTOP_HOST_INSPECT_PORT` replace those ports, while `DSH_DESKTOP_OPEN_DEVTOOLS=0` keeps the detached Renderer tools closed.
After an explicit build, `start:desktop` reconstructs the disposable project and launches the existing artifacts without building again:
@@ -261,7 +261,7 @@ During a confirmed Windows update restart, a separate process displays a draggab
The Windows installer uses native NSIS pages with light and dark palettes, system shadows, an editable installation directory, and a finish page whose launch checkbox is selected by default. Installation is restricted to the current user. Clicking Install or pressing Enter validates the current path; drive roots remain invalid after normalization, including repeated trailing separators. New destinations must be empty, and nonempty destinations must be registered installations. Running executables at the affected installation path produce a native prompt and remain running; same-named applications in other directories do not block installation. Silent updates wait up to ten seconds for the affected application to exit, then stop with exit code 2 if it is still running.
The theme follows Windows at startup; `/THEME=light`, `/THEME=dark`, and `/THEME=auto` select a palette explicitly. The window appears after its branded controls are ready. When the welcome page first appears, the installer moves above ordinary windows once and flashes its taskbar button if another window has focus; it does not remain always on top. Progress reads the pinned 7-Zip extractor’s percentage; directory promotion, registration, and cleanup retain bounded estimates. The weighted percentage does not predict remaining time. After NSIS reports success, the bar fills over 600 ms and displays 100% briefly before the finish page appears; the transition targets 750 ms. The finish page preserves the window position. Finish dismisses the installer before launching the installed executable; a launch failure restores the page for retry. Directory replacement and failure recovery follow the [installation checks](packaging/README.md#runtime-file-selection). First-launch profile preparation remains a separate Desktop operation.
The theme follows Windows at startup; `/THEME=light`, `/THEME=dark`, and `/THEME=auto` select a palette explicitly. The window appears after its branded controls are ready. When the welcome page first appears, the installer moves above ordinary windows once and flashes its taskbar button if another window has focus; it does not remain always on top. Progress reads the pinned 7-Zip extractor’s percentage; directory promotion, registration, and cleanup retain bounded estimates. The weighted percentage does not predict remaining time. After NSIS reports success, the bar fills over 600 ms and displays 100% briefly before the finish page appears; the transition targets 750 ms. Finish controls appear in the existing progress window while a title-bar drag or system menu remains active. Completion flashes the taskbar button three times if the installer is minimized or another window has focus. During installation, the Close button is disabled and dimmed without changing the cursor. On the finish page, Close exits without launching the application. Finish dismisses the installer before launching the installed executable; a launch failure restores the page for retry. Directory replacement and failure recovery follow the [installation checks](packaging/README.md#runtime-file-selection). First-launch profile preparation remains a separate Desktop operation.
Windows packaging compiles an x86 Win32/GDI+ helper with Visual C++ Build Tools and a Windows SDK; signed builds sign this helper through the configured Windows signer. The progress page keeps one opaque pixel buffer for its lifetime, draws static artwork once, and copies repainted pixels with GDI. The preparation hook leaves production dependency collection to electron-builder on every platform.
+2 -2
View File
@@ -199,7 +199,7 @@ macOS 和 Linux 从图形界面启动的程序只继承会话管理器提供的
pnpm run dev:desktop
```
开发 Harness 状态默认写入 `apps/desktop/.desktop-build/development/home`,一次性 npm 项目位于 `apps/desktop/.desktop-build/development/project`,Electron 浏览器数据则位于 `apps/desktop/.desktop-build/development/electron-user-data`。因此,会话、设置、凭据、包链接和浏览器数据都不会进入用户正常使用的 Harness home;显式 `DSH_HOME` 只会替换开发 Harness home。Renderer DevTools 默认自动打开,Main、Renderer 和 dsh Host 调试端口依次为 9229、9222 和 9230。`DSH_DESKTOP_MAIN_INSPECT_PORT`、`DSH_DESKTOP_RENDERER_DEBUG_PORT` 与 `DSH_DESKTOP_HOST_INSPECT_PORT` 可以替换这些端口,`DSH_DESKTOP_OPEN_DEVTOOLS=0` 则保持 Renderer 调试窗口关闭。
开发 Harness 状态默认写入 `apps/desktop/.desktop-dev/home`,Electron 浏览器数据默认写入 `apps/desktop/.desktop-dev/electron-user-data`;`pnpm run clean` 会删除 `.desktop-build`,但保留该目录。一次性 npm 项目位于 `apps/desktop/.desktop-build/development/project`。因此,会话、设置、凭据、包链接和浏览器数据都不会进入用户正常使用的 Harness home。启动时会把每个缺失的默认目录从 `.desktop-build/development` 移过来;若正在运行的 Harness Dev 仍在使用那里的浏览器数据,启动会停止而不迁移。显式 `DSH_HOME` 只会替换开发 Harness home,`DSH_DESKTOP_USER_DATA_DIR` 只会替换浏览器数据。Renderer DevTools 默认自动打开,Main、Renderer 和 dsh Host 调试端口依次为 9229、9222 和 9230。`DSH_DESKTOP_MAIN_INSPECT_PORT`、`DSH_DESKTOP_RENDERER_DEBUG_PORT` 与 `DSH_DESKTOP_HOST_INSPECT_PORT` 可以替换这些端口,`DSH_DESKTOP_OPEN_DEVTOOLS=0` 则保持 Renderer 调试窗口关闭。
显式构建完成后,`start:desktop` 会重新生成一次性项目,并跳过构建直接启动已有产物:
@@ -261,7 +261,7 @@ Windows 更新确认重启后,独立进程显示可拖动的状态提示,直
Windows 安装程序使用原生 NSIS 页面,提供亮暗配色、系统阴影、可编辑的安装目录,以及默认勾选立即启动的完成页。安装仅面向当前用户。点击安装或按 Enter 均校验当前路径;路径规范化后仍拒绝磁盘根目录,包括带重复末尾分隔符的写法。新安装位置必须为空,非空位置必须是已登记的安装目录。受影响安装路径中的程序运行时显示系统提示,并保持应用运行;其他目录中的同名应用不阻止安装。静默更新最多等待受影响应用退出十秒,若仍在运行则以退出码 2 结束。
主题在启动时跟随 Windows;可用 `/THEME=light`、`/THEME=dark` 和 `/THEME=auto` 显式选择配色。窗口在品牌控件准备完成后显示。欢迎页首次出现时,安装窗口会一次性移到普通窗口前方;若焦点在其他窗口,任务栏按钮会闪烁提示,但安装窗口不会始终置顶。进度读取锁定版本的 7-Zip 解压器百分比;目录替换、注册和清理仍使用有界估算。加权百分比不代表剩余时间。NSIS 报告成功后,进度条用 600 毫秒补满并短暂显示 100%,再显示完成页;切换目标时长为 750 毫秒。完成页保留窗口位置。点击完成后,安装程序先隐藏窗口,再启动已安装的可执行文件;启动失败会恢复页面以供重试。目录替换和失败恢复遵循[安装检查](packaging/README.zh.md#runtime-file-selection)。首次启动的配置档案准备仍属于独立的 Desktop 操作。
主题在启动时跟随 Windows;可用 `/THEME=light`、`/THEME=dark` 和 `/THEME=auto` 显式选择配色。窗口在品牌控件准备完成后显示。欢迎页首次出现时,安装窗口会一次性移到普通窗口前方;若焦点在其他窗口,任务栏按钮会闪烁提示,但安装窗口不会始终置顶。进度读取锁定版本的 7-Zip 解压器百分比;目录替换、注册和清理仍使用有界估算。加权百分比不代表剩余时间。NSIS 报告成功后,进度条用 600 毫秒补满并短暂显示 100%,再显示完成页;切换目标时长为 750 毫秒。完成按钮与启动复选框在原进度窗口中显示,拖动标题栏或打开系统菜单时也会更新。若安装器已最小化或焦点在其他窗口,安装完成时任务栏按钮会闪烁三次。安装中关闭按钮禁用并变灰,鼠标指针保持不变;完成页的关闭按钮退出安装器且不启动应用。点击完成后,安装程序先隐藏窗口,再启动已安装的可执行文件;启动失败会恢复页面以供重试。目录替换和失败恢复遵循[安装检查](packaging/README.zh.md#runtime-file-selection)。首次启动的配置档案准备仍属于独立的 Desktop 操作。
Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI+ 辅助库;签名构建通过已配置的 Windows 签名器对该库签名。进度页在其生命周期内保留一个不透明像素缓冲,只绘制一次静态图像,并通过 GDI 复制重绘的像素。准备钩子在所有平台上均由 electron-builder 继续负责收集生产依赖。
@@ -24,5 +24,5 @@
en: f1c19c1516a51ab6
zh: b350f7c18086d274
/desktop-recovery-and-diagnostics/collection-and-shutdown:
en: bac4a49f63d4aaf8
zh: df1ae908ee2148e1
en: 67555a4116943e85
zh: 451231cb6e28ffe9
+2
View File
@@ -67,6 +67,8 @@ The Host announces its run ID before profile loading; reported Host errors carry
Collection reads only two owned files under `userData/plugin-operations`, at most 64 KiB and 100 records; the complete appended section is limited to 64 KiB.
Only a predecessor whose handle reports the exact bigint file identity of the segment already read is deduplicated as already collected: the predecessor is skipped, so its records are not collected twice, and records appended to it after it was read are not collected. On Windows, opening a segment retries `EACCES`, `EBUSY` and `EPERM` up to four times with a 10→40 ms backoff before the segment counts as unavailable, cancellation ends those retries, and `filesRead` counts owned segments that yielded bytes.
The 500 ms collection budget reserves its final 100 ms for cooperative cancellation before requesting forced Worker termination; completion waits for its exit. Application exit, recovery exit or restart, and confirmed update installation also cancel collection and wait at most 500 ms for Worker exit. A rejected shutdown cleanup is logged without skipping the remaining cleanup waits. Shutdown prevents late basic-report saves from starting another collector. An update installation failure permits future collection again.
Worker messages interrupt collection between bounded records; an in-flight file open, stat, read or close must settle, and synchronous parsing cannot be preempted within one record. The final append uses an abort signal but can leave partial bytes. Forced termination remains the fallback when cooperative cleanup does not finish.
@@ -67,6 +67,8 @@ Host 在加载 profile 前报告运行 ID;Host 错误中的 `hostRunId` 与该
收集只读取 `userData/plugin-operations` 下归其管理的两个文件,最多读取 64 KiB 和 100 条记录;完整追加内容不超过 64 KiB。
只有前驱段的句柄给出与已读段完全相同的 bigint 文件身份时才判为已收集:该前驱段会被跳过,因此它的记录不会被重复收集,但在被读取之后追加到它的记录不会被收集。Windows 上打开文件段遇到 `EACCES`、`EBUSY`、`EPERM` 时最多重试四次,退避 10→40 ms,之后该段才计入不可用;取消会结束这些重试;`filesRead` 统计实际读到字节的所属文件段。
500 ms 收集预算中的最后 100 ms 用于协作取消,随后才请求强制终止 Worker;只有 Worker 退出后才确认收集结束。应用退出、恢复退出或重启、确认安装更新也会取消收集,并最多等待 500 ms 确认 Worker 退出。退出清理中的拒绝会被记录,但不会跳过其他清理等待。退出过程中,延迟保存完成的基本报告不会再启动收集器。更新安装失败后可再次收集。
Worker 在有界记录之间处理取消消息;已经发出的文件打开、状态读取、读取或关闭操作必须等待完成,单条记录的同步解析不能被抢占。最后的追加写入传入取消信号,但仍可能留下部分字节。协作清理未及时完成时仍需强制终止。
-75
View File
@@ -43,78 +43,3 @@ Function InstallerDrawEditFrame
System::Call 'gdiplus::GdipDeleteGraphics(p R4)'
System::Call 'gdiplus::GdipDisposeImage(p R5)'
FunctionEnd
; BS_AUTOCHECKBOX retains its native state, text, keyboard and accessibility role.
Function InstallerPaintCheckbox
Pop $R0
Pop $R1
Pop $R2
${If} $R1 != -12
Return
${EndIf}
System::Call '*$R2(p, p, i, i .R3, p .R4, i, i, i, i, p, i .R9)'
${If} $R3 != 1
Return
${EndIf}
System::Call 'gdi32::SaveDC(p R4)'
System::Alloc 16
Pop $R2
System::Call 'user32::GetClientRect(p R0, p R2)'
System::Call 'gdi32::CreateSolidBrush(i $InstallerBgColorref) p.R3'
System::Call 'user32::FillRect(p R4, p R2, p R3)'
System::Call 'gdi32::DeleteObject(p R3)'
System::Call 'kernel32::MulDiv(i 8, i $InstallerDpi, i 96) i.r2'
System::Call 'kernel32::MulDiv(i 7, i $InstallerDpi, i 96) i.r3'
System::Call 'gdi32::SetViewportOrgEx(p R4, i r2, i r3, p 0)'
System::Call 'gdiplus::GdipCreateFromHDC(p R4, *p .R5)'
System::Call 'gdiplus::GdipSetSmoothingMode(p R5, i 4)'
System::Call 'kernel32::MulDiv(i 18, i $InstallerDpi, i 96) i.R7'
StrCpy $R8 $R7
System::Call 'kernel32::MulDiv(i 6, i $InstallerDpi, i 96) i.R3'
!insertmacro InstallerRoundPath $R6 $R7 $R8 $R3
${NSD_GetState} $R0 $R8
StrCpy $R3 $InstallerBgArgb
${If} $R8 == ${BST_CHECKED}
StrCpy $R3 $InstallerPrimary
${EndIf}
System::Call 'gdiplus::GdipCreateSolidFill(i R3, *p .R1)'
System::Call 'gdiplus::GdipFillPath(p R5, p R1, p R6)'
System::Call 'gdiplus::GdipDeleteBrush(p R1)'
${If} $R8 != ${BST_CHECKED}
System::Call 'gdiplus::GdipCreatePen1(i $InstallerBorder, i 0x40000000, i 2, *p .R1)'
System::Call 'gdiplus::GdipDrawPath(p R5, p R1, p R6)'
System::Call 'gdiplus::GdipDeletePen(p R1)'
${EndIf}
System::Call 'gdiplus::GdipDeletePath(p R6)'
System::Call 'gdiplus::GdipDeleteGraphics(p R5)'
${If} $R8 == ${BST_CHECKED}
System::Call 'kernel32::MulDiv(i 2, i $InstallerDpi, i 96) i.r0'
System::Call 'gdi32::CreatePen(i 0, i r0, i $InstallerButtonText) p.R1'
System::Call 'gdi32::SelectObject(p R4, p R1) p.R3'
System::Call 'kernel32::MulDiv(i 4, i $InstallerDpi, i 96) i.r0'
System::Call 'kernel32::MulDiv(i 9, i $InstallerDpi, i 96) i.r1'
System::Call 'gdi32::MoveToEx(p R4, i r0, i r1, p 0)'
System::Call 'kernel32::MulDiv(i 8, i $InstallerDpi, i 96) i.r0'
System::Call 'kernel32::MulDiv(i 13, i $InstallerDpi, i 96) i.r1'
System::Call 'gdi32::LineTo(p R4, i r0, i r1)'
System::Call 'kernel32::MulDiv(i 14, i $InstallerDpi, i 96) i.r0'
System::Call 'kernel32::MulDiv(i 5, i $InstallerDpi, i 96) i.r1'
System::Call 'gdi32::LineTo(p R4, i r0, i r1)'
System::Call 'gdi32::SelectObject(p R4, p R3)'
System::Call 'gdi32::DeleteObject(p R1)'
${EndIf}
System::Call 'gdi32::SetViewportOrgEx(p R4, i 0, i 0, p 0)'
System::Call 'kernel32::MulDiv(i 34, i $InstallerDpi, i 96) i.r0'
System::Call '*$R2(i r0)'
System::Call 'gdi32::SetBkMode(p R4, i 1)'
System::Call 'gdi32::SetTextColor(p R4, i $InstallerTextColorref)'
System::Call 'gdi32::SelectObject(p R4, p $InstallerSmallFont)'
System::Call 'user32::DrawTextW(p R4, w "$(INSTALLER_LAUNCH)", i -1, p R2, i 0x24)'
IntOp $R9 $R9 & 16
${If} $R9 != 0
System::Call 'user32::DrawFocusRect(p R4, p R2)'
${EndIf}
System::Call 'gdi32::RestoreDC(p R4, i -1)'
System::Free $R2
${NSD_Return} 4
FunctionEnd
+20 -7
View File
@@ -54,6 +54,7 @@ Function InstallerBeforeInstall
FunctionEnd
Function InstallerProgressShow
StrCpy $InstallerPhase "installing"
; Only the stock worker executes installation; this overlay runs on the UI thread.
ShowWindow $mui.InstFilesPage 0
StrCpy $0 0
@@ -79,12 +80,24 @@ Function .onInstFailed
Quit
FunctionEnd
Function InstallerFinish
System::Call '$PLUGINSDIR\window-frame.dll::InstallerFinishProgress(p $InstallerProgressWindow) i.r0 ?c'
${If} $0 == 0
Quit
Function InstallerProgressLeave
IfAbort failed
${If} $InstallerPhase == "installing"
System::Call '$PLUGINSDIR\window-frame.dll::InstallerFinishProgress(p $InstallerProgressWindow, w "$(INSTALLER_FINISH)", w "$(INSTALLER_LAUNCH)") i.r0 ?c'
${If} $0 == 0
MessageBox MB_OK|MB_ICONSTOP "$(INSTALLER_UI_ERROR)"
SetErrorLevel 2
Quit
${EndIf}
StrCpy $InstallerPhase "success"
Abort
${EndIf}
System::Call 'user32::DestroyWindow(p $InstallerProgressWindow)'
StrCpy $InstallerPhase "success"
Call InstallerCreate
System::Call '$PLUGINSDIR\window-frame.dll::InstallerTakeFinishChoice(p $InstallerProgressWindow) i.r0 ?c'
${If} $0 < 0
Abort
${EndIf}
Call InstallerFinishLeave
Return
failed:
; NSIS owns installation failure and its exit code.
FunctionEnd
+6 -38
View File
@@ -16,7 +16,6 @@ Var InstallerChoose
Var InstallerEdit
Var InstallerEditFrame
Var InstallerBrowse
Var InstallerLaunch
Var InstallerExpanded
Var InstallerMinimizeButton
Var InstallerCloseButton
@@ -137,30 +136,6 @@ Function InstallerCreate
!insertmacro InstallerPlace $InstallerBrowse 456 434 80 34
${NSD_OnClick} $InstallerBrowse InstallerBrowsePath
${NSD_OnNotify} $InstallerBrowse InstallerPaintButton
${NSD_CreateCheckbox} 0 0 0 0 "$(INSTALLER_LAUNCH)"
Pop $InstallerLaunch
SendMessage $InstallerLaunch ${WM_SETFONT} $InstallerSmallFont 1
System::Call 'user32::GetDC(p $InstallerLaunch) p.r4'
System::Call 'gdi32::SelectObject(p r4, p $InstallerSmallFont) p.r5'
StrLen $0 "$(INSTALLER_LAUNCH)"
System::Alloc 8
Pop $6
System::Call 'gdi32::GetTextExtentPoint32W(p r4, w "$(INSTALLER_LAUNCH)", i r0, p r6)'
System::Call '*$6(i .r7)'
System::Free $6
System::Call 'gdi32::SelectObject(p r4, p r5)'
System::Call 'user32::ReleaseDC(p $InstallerLaunch, p r4)'
System::Call 'kernel32::MulDiv(i 42, i $InstallerDpi, i 96) i.r2'
IntOp $2 $2 + $7
IntOp $0 $InstallerSize - $2
IntOp $0 $0 / 2
System::Call 'kernel32::MulDiv(i 438, i $InstallerDpi, i 96) i.r1'
System::Call 'kernel32::MulDiv(i 32, i $InstallerDpi, i 96) i.r3'
System::Call 'user32::MoveWindow(p $InstallerLaunch, i r0, i r1, i r2, i r3, i 1)'
!insertmacro InstallerControlColors $InstallerLaunch
${NSD_OnNotify} $InstallerLaunch InstallerPaintCheckbox
${NSD_Check} $InstallerLaunch
${NSD_CreateButton} 0 0 0 0 "$(INSTALLER_INSTALL)"
Pop $InstallerButton
!insertmacro InstallerPlace $InstallerButton ${INSTALLER_BUTTON_X} ${INSTALLER_BUTTON_Y} ${INSTALLER_BUTTON_WIDTH} ${INSTALLER_BUTTON_HEIGHT}
@@ -188,20 +163,13 @@ Function InstallerRender
ShowWindow $InstallerEdit 0
ShowWindow $InstallerEditFrame 0
ShowWindow $InstallerBrowse 0
ShowWindow $InstallerLaunch 0
ShowWindow $InstallerStatus 0
${If} $InstallerPhase == "success"
${NSD_SetText} $InstallerButton "$(INSTALLER_FINISH)"
ShowWindow $InstallerLaunch 5
${If} $InstallerExpanded == 1
ShowWindow $InstallerEditFrame 5
ShowWindow $InstallerEdit 5
ShowWindow $InstallerBrowse 5
${Else}
${NSD_SetText} $InstallerButton "$(INSTALLER_INSTALL)"
${If} $InstallerExpanded == 1
ShowWindow $InstallerEditFrame 5
ShowWindow $InstallerEdit 5
ShowWindow $InstallerBrowse 5
${Else}
ShowWindow $InstallerChoose 5
${EndIf}
ShowWindow $InstallerChoose 5
${EndIf}
FunctionEnd
@@ -220,8 +188,8 @@ Function InstallerWelcomeLeave
${EndIf}
FunctionEnd
; The completed page requests exit with the user's launch choice in $0.
Function InstallerFinishLeave
${NSD_GetState} $InstallerLaunch $0
HideWindow
${If} $0 == ${BST_CHECKED}
StrCpy $0 ""
+183 -45
View File
@@ -140,8 +140,14 @@ struct ProgressPage {
ARGB controlHover;
ARGB controlPressed;
WCHAR captions[5][128];
HWND finish, launch, minimize, close;
bool controlsVisible = false;
int finishChoice = -1;
HFONT finishFont, launchFont;
~ProgressPage() {
if (finishFont) DeleteObject(finishFont);
if (launchFont) DeleteObject(launchFont);
delete buffer;
delete brand;
if (previousBitmap) SelectObject(bufferDc, previousBitmap);
@@ -178,13 +184,16 @@ static UINT CaptionCommand(const ProgressPage& page, LPARAM position) {
const int x = static_cast<short>(LOWORD(position));
const int y = static_cast<short>(HIWORD(position));
if (y < 0 || y >= MulDiv(48, page.dpi, 96) || x < MulDiv(504, page.dpi, 96) || x >= MulDiv(600, page.dpi, 96)) return 0;
return x >= MulDiv(548, page.dpi, 96) ? SC_CLOSE : SC_MINIMIZE;
// Installation cannot be cancelled with the progress page close button.
return x >= MulDiv(548, page.dpi, 96) ? 0 : SC_MINIMIZE;
}
static void PaintCaptionButtons(Graphics& graphics, const ProgressPage& page) {
SolidBrush background(page.dark ? Color(255, 21, 21, 23) : Color(255, 255, 255, 255));
graphics.FillRectangle(&background, 504, 0, 96, 48);
SolidBrush ink(page.dark ? Color(255, 255, 255, 255) : Color(255, 15, 17, 21));
// Disabled caption uses the same foreground with reduced opacity in both themes.
SolidBrush disabledInk(page.dark ? Color(96, 255, 255, 255) : Color(96, 15, 17, 21));
FontFamily family(L"Microsoft YaHei UI");
Font font(&family, 16, FontStyleRegular, UnitPixel);
StringFormat centered;
@@ -204,7 +213,7 @@ static void PaintCaptionButtons(Graphics& graphics, const ProgressPage& page) {
graphics.FillPath(&fill, &path);
}
graphics.DrawString(command == SC_MINIMIZE ? L"\x2212" : L"\x00d7", -1,
&font, RectF(static_cast<REAL>(x), 8, 40, 32), &centered, &ink);
&font, RectF(static_cast<REAL>(x), 8, 40, 32), &centered, command == SC_CLOSE ? &disabledInk : &ink);
}
}
@@ -213,15 +222,109 @@ static void InvalidateCaptionButtons(HWND window, const ProgressPage& page) {
InvalidateRect(window, &bounds, FALSE);
}
// NSIS ui.h: request that the stock instfiles page run its leave callback.
constexpr UINT WM_NOTIFY_OUTER_NEXT = WM_USER + 8;
static void RequestFinish(HWND window, ProgressPage& page, bool launch) {
if (!page.controlsVisible || page.finishChoice >= 0) return;
if (PostMessageW(GetParent(window), WM_NOTIFY_OUTER_NEXT, 1, 0)) page.finishChoice = launch ? 1 : 0;
}
static void RevealFinish(HWND window, ProgressPage& page) {
page.controlsVisible = true;
KillTimer(window, 1);
SetWindowTextW(window, L"");
InvalidateRect(window, nullptr, FALSE);
for (HWND child : {page.finish, page.launch, page.minimize, page.close}) ShowWindow(child, SW_SHOWNA);
HWND frame = GetParent(window);
if (GetForegroundWindow() != frame || IsIconic(frame)) {
FLASHWINFO flash = {sizeof(flash), frame, FLASHW_TRAY, 3, 0};
FlashWindowEx(&flash);
}
}
static LRESULT DrawFinishControl(const ProgressPage& page, NMCUSTOMDRAW& draw) {
if (draw.dwDrawStage != CDDS_PREPAINT) return CDRF_DODEFAULT;
const HWND control = draw.hdr.hwndFrom;
const bool primary = control == page.finish;
const bool checkbox = control == page.launch;
const bool pressed = (draw.uItemState & CDIS_SELECTED) != 0;
const bool hot = (draw.uItemState & CDIS_HOT) != 0;
const Color background = page.dark ? Color(255,21,21,23) : Color(255,255,255,255);
const Color foreground = page.dark ? Color(255,255,255,255) : Color(255,15,17,21);
const Color accent = page.dark ? Color(255,249,250,251) : Color(255,15,17,21);
const Color inverse = page.dark ? Color(255,15,17,21) : Color(255,255,255,255);
RECT rect; GetClientRect(control, &rect);
HDC dc = draw.hdc;
const int saved = SaveDC(dc);
{
Graphics graphics(dc);
graphics.ScaleTransform(page.dpi / 96.0f, page.dpi / 96.0f);
graphics.SetSmoothingMode(SmoothingModeAntiAlias);
graphics.Clear(background);
const bool checked = checkbox && SendMessageW(control, BM_GETCHECK, 0, 0) == BST_CHECKED;
Color fill = primary ? accent : background;
if (primary && (hot || pressed)) {
fill = page.dark ? (pressed ? Color(255,212,219,233) : Color(255,233,236,242))
: (pressed ? Color(255,0,0,0) : Color(255,45,49,53));
} else if (checkbox) {
fill = checked ? accent : background;
} else if (hot || pressed) {
fill = Color(pressed ? page.controlPressed : page.controlHover);
}
const REAL x = checkbox ? 8.0f : 0.0f, y = checkbox ? 7.0f : 0.0f;
const REAL w = checkbox ? 18.0f : rect.right * 96.0f / page.dpi;
const REAL h = checkbox ? 18.0f : rect.bottom * 96.0f / page.dpi;
const REAL d = checkbox ? 6.0f : 20.0f;
GraphicsPath path;
path.AddArc(x,y,d,d,180,90); path.AddArc(x+w-d,y,d,d,270,90);
path.AddArc(x+w-d,y+h-d,d,d,0,90); path.AddArc(x,y+h-d,d,d,90,90); path.CloseFigure();
SolidBrush brush(fill); graphics.FillPath(&brush,&path);
if (checkbox && !checked) {
Pen border(page.dark ? Color(255,97,102,107) : Color(255,187,192,200)); graphics.DrawPath(&border,&path);
} else if (checked) {
Pen pen(inverse,2.0f); Point points[] = {{12,16},{16,20},{22,12}};
graphics.DrawLines(&pen,points,3);
}
}
WCHAR caption[256]; GetWindowTextW(control,caption,ARRAYSIZE(caption));
const Color text = primary ? inverse : foreground;
SetTextColor(dc,RGB(text.GetR(),text.GetG(),text.GetB())); SetBkMode(dc,TRANSPARENT);
SelectObject(dc,checkbox ? page.launchFont : page.finishFont);
if (checkbox) rect.left += MulDiv(34,page.dpi,96);
DrawTextW(dc,caption,-1,&rect,DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX | (checkbox ? DT_LEFT : DT_CENTER));
if (draw.uItemState & CDIS_FOCUS) { InflateRect(&rect,-3,-3); DrawFocusRect(dc,&rect); }
RestoreDC(dc,saved);
return CDRF_SKIPDEFAULT;
}
static LRESULT CALLBACK ProgressProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
auto* page = reinterpret_cast<ProgressPage*>(GetWindowLongPtrW(window, GWLP_USERDATA));
if (message == WM_CREATE) {
page = static_cast<ProgressPage*>(reinterpret_cast<CREATESTRUCTW*>(lparam)->lpCreateParams);
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(page));
SetTimer(window, 1, 16, nullptr);
}
if (message == WM_ERASEBKGND) return 1;
if (message == WM_TIMER) { InvalidateRect(window, nullptr, FALSE); return 0; }
if (message == WM_TIMER && page && wparam == 1) {
if (page->controlsVisible) return 0;
InvalidateRect(window, nullptr, FALSE);
if (page->progress.succeeded && GetTickCount64() - page->progress.animationStarted >= 750) {
// A covered window may not have painted its final frame on the last tick.
UpdateWindow(window);
RevealFinish(window, *page);
}
return 0;
}
if (message == WM_NOTIFY && page && reinterpret_cast<NMHDR*>(lparam)->code == NM_CUSTOMDRAW) {
return DrawFinishControl(*page, *reinterpret_cast<NMCUSTOMDRAW*>(lparam));
}
if (message == WM_COMMAND && page && page->controlsVisible && HIWORD(wparam) == BN_CLICKED) {
HWND control = reinterpret_cast<HWND>(lparam);
if (control == page->finish || control == page->close) {
RequestFinish(window, *page, control == page->finish && SendMessageW(page->launch, BM_GETCHECK, 0, 0) == BST_CHECKED);
} else if (control == page->minimize) ShowWindow(GetParent(window), SW_MINIMIZE);
return 0;
}
if (message == WM_MOUSEMOVE && page) {
TRACKMOUSEEVENT tracking{sizeof(tracking), TME_LEAVE, window, 0};
TrackMouseEvent(&tracking);
@@ -259,10 +362,7 @@ static LRESULT CALLBACK ProgressProc(HWND window, UINT message, WPARAM wparam, L
InvalidateCaptionButtons(window, *page);
const bool activate = command && GetCapture() == window && CaptionCommand(*page, lparam) == command;
if (GetCapture() == window) ReleaseCapture();
if (activate) {
if (command == SC_CLOSE) PostMessageW(GetParent(window), WM_CLOSE, 0, 0);
else ShowWindow(GetParent(window), SW_MINIMIZE);
}
if (activate) ShowWindow(GetParent(window), SW_MINIMIZE);
return 0;
}
if ((message == WM_CAPTURECHANGED || message == WM_CANCELMODE) && page) {
@@ -284,23 +384,25 @@ static LRESULT CALLBACK ProgressProc(HWND window, UINT message, WPARAM wparam, L
PaintCaptionButtons(graphics, *page);
SolidBrush background(page->dark ? Color(255, 21, 21, 23) : Color(255, 255, 255, 255));
graphics.FillRectangle(&background, 48, 480, 504, 56);
const int stage = static_cast<int>(reinterpret_cast<INT_PTR>(GetPropW(GetParent(window), L"HarnessInstaller.Stage")));
const double fraction = reinterpret_cast<UINT_PTR>(GetPropW(GetParent(window), L"HarnessInstaller.ExtractProgress")) / 100.0;
page->progress.Advance(stage, fraction, GetTickCount64());
const int percent = static_cast<int>(page->progress.value);
SolidBrush track(page->dark ? Color(255, 97, 102, 107) : Color(255, 233, 236, 242));
SolidBrush ink(page->dark ? Color(255, 255, 255, 255) : Color(255, 15, 17, 21));
FillProgress(graphics, track, 472.0f);
FillProgress(graphics, ink, 472.0f * static_cast<REAL>(page->progress.value) / 100);
FontFamily family(L"Microsoft YaHei UI");
Font font(&family, 14, FontStyleRegular, UnitPixel);
StringFormat centered;
centered.SetAlignment(StringAlignmentCenter);
centered.SetLineAlignment(StringAlignmentCenter);
WCHAR caption[160];
wsprintfW(caption, page->captions[page->progress.CaptionStage()], percent);
SetWindowTextW(window, caption);
graphics.DrawString(caption, -1, &font, RectF(48, 512, 504, 22), &centered, &ink);
if (!page->controlsVisible) {
const int stage = static_cast<int>(reinterpret_cast<INT_PTR>(GetPropW(GetParent(window), L"HarnessInstaller.Stage")));
const double fraction = reinterpret_cast<UINT_PTR>(GetPropW(GetParent(window), L"HarnessInstaller.ExtractProgress")) / 100.0;
page->progress.Advance(stage, fraction, GetTickCount64());
const int percent = static_cast<int>(page->progress.value);
SolidBrush track(page->dark ? Color(255, 97, 102, 107) : Color(255, 233, 236, 242));
SolidBrush ink(page->dark ? Color(255, 255, 255, 255) : Color(255, 15, 17, 21));
FillProgress(graphics, track, 472.0f);
FillProgress(graphics, ink, 472.0f * static_cast<REAL>(page->progress.value) / 100);
FontFamily family(L"Microsoft YaHei UI");
Font font(&family, 14, FontStyleRegular, UnitPixel);
StringFormat centered;
centered.SetAlignment(StringAlignmentCenter);
centered.SetLineAlignment(StringAlignmentCenter);
WCHAR caption[160];
wsprintfW(caption, page->captions[page->progress.CaptionStage()], percent);
SetWindowTextW(window, caption);
graphics.DrawString(caption, -1, &font, RectF(48, 512, 504, 22), &centered, &ink);
}
}
BitBlt(dc, paint.rcPaint.left, paint.rcPaint.top,
paint.rcPaint.right - paint.rcPaint.left, paint.rcPaint.bottom - paint.rcPaint.top,
@@ -372,9 +474,10 @@ extern "C" __declspec(dllexport) HWND __cdecl InstallerShowProgress(HWND parent,
}
delete page->brand;
page->brand = nullptr;
HWND window = CreateWindowExW(0, type.lpszClassName, L"", WS_CHILD,
HWND window = CreateWindowExW(WS_EX_CONTROLPARENT, type.lpszClassName, L"", WS_CHILD | WS_CLIPCHILDREN,
0, 0, MulDiv(600, dpi, 96), MulDiv(600, dpi, 96), parent, nullptr, module, page);
if (!window) { delete page; return nullptr; }
if (!SetTimer(window, 1, 16, nullptr)) { DestroyWindow(window); return nullptr; }
// Keep the stock page available until the replacement is fully constructed.
HWND stockPage = GetParent(source);
if (!SetWindowSubclass(stockPage, HiddenPageProc, 1, 0)) {
@@ -385,32 +488,65 @@ extern "C" __declspec(dllexport) HWND __cdecl InstallerShowProgress(HWND parent,
return window;
}
// NSIS has already reported success. Pump the UI for the bounded final animation,
// including a painted 100% frame, before constructing the interactive finish page.
extern "C" __declspec(dllexport) BOOL __cdecl InstallerFinishProgress(HWND window) {
// Called from the instfiles leave callback on success. Timer paints finish the
// animation while USER32 continues dispatching the current move or menu.
extern "C" __declspec(dllexport) BOOL __cdecl InstallerFinishProgress(HWND window, LPCWSTR finish, LPCWSTR launch) {
auto* page = reinterpret_cast<ProgressPage*>(GetWindowLongPtrW(window, GWLP_USERDATA));
if (!page) return FALSE;
const ULONGLONG started = GetTickCount64();
if (page->progress.succeeded) return TRUE;
const auto scaled = [&](int n) { return MulDiv(n,page->dpi,96); };
page->finishFont = CreateFontW(-scaled(16),0,0,0,FW_MEDIUM,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");
page->launchFont = CreateFontW(-scaled(14),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");
if (!page->finishFont || !page->launchFont) return FALSE;
HDC dc = GetDC(window);
if (!dc) return FALSE;
HGDIOBJ old = SelectObject(dc,page->launchFont);
SIZE size = {};
const BOOL measured = GetTextExtentPoint32W(dc,launch,lstrlenW(launch),&size);
SelectObject(dc,old); ReleaseDC(window,dc);
if (!measured) return FALSE;
const int launchWidth = std::min(scaled(600),static_cast<int>(size.cx) + scaled(42));
auto button = [&](INT_PTR id, LPCWSTR title, DWORD style, int x, int y, int w, int h, HFONT font) {
HWND child = CreateWindowW(L"BUTTON",title,WS_CHILD|WS_TABSTOP|style,x,y,w,h,window,reinterpret_cast<HMENU>(id),GetModuleHandleW(nullptr),nullptr);
if (child) SendMessageW(child,WM_SETFONT,reinterpret_cast<WPARAM>(font),FALSE);
return child;
};
page->finish = button(0x6100,finish,BS_DEFPUSHBUTTON,scaled(240),scaled(490),scaled(120),scaled(44),page->finishFont);
page->launch = button(0x6101,launch,BS_AUTOCHECKBOX,(scaled(600)-launchWidth)/2,scaled(438),launchWidth,scaled(32),page->launchFont);
page->minimize = button(0x6102,L"\x2212",BS_PUSHBUTTON,scaled(504),scaled(8),scaled(40),scaled(32),page->finishFont);
page->close = button(0x6103,L"\x00d7",BS_PUSHBUTTON,scaled(548),scaled(8),scaled(40),scaled(32),page->finishFont);
if (!page->finish || !page->launch || !page->minimize || !page->close) return FALSE;
SendMessageW(page->launch,BM_SETCHECK,BST_CHECKED,0);
SetPropW(GetParent(window), L"HarnessInstaller.Succeeded", reinterpret_cast<HANDLE>(1));
page->progress.Complete(started);
while (IsWindow(window) && GetTickCount64() - started < 750) {
MSG message;
if (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
if (message.message == WM_QUIT) { PostQuitMessage(static_cast<int>(message.wParam)); return FALSE; }
TranslateMessage(&message);
DispatchMessageW(&message);
} else {
MsgWaitForMultipleObjectsEx(0, nullptr, 16, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
}
}
if (!IsWindow(window)) return FALSE;
InvalidateRect(window, nullptr, FALSE);
UpdateWindow(window);
page->progress.Complete(GetTickCount64());
return TRUE;
}
// Reading consumes one explicit Finish/Close action so a failed launch can retry.
extern "C" __declspec(dllexport) int __cdecl InstallerTakeFinishChoice(HWND window) {
auto* page = reinterpret_cast<ProgressPage*>(GetWindowLongPtrW(window,GWLP_USERDATA));
if (!page) return -1;
int choice = page->finishChoice;
page->finishChoice = -1;
return choice;
}
static LRESULT CALLBACK FrameProc(HWND window, UINT message, WPARAM wparam,
LPARAM lparam, UINT_PTR id, DWORD_PTR) {
if (message == WM_COMMAND && HIWORD(wparam) == BN_CLICKED) {
HWND progress = FindWindowExW(window, nullptr, L"HarnessInstallerProgress", nullptr);
auto* page = reinterpret_cast<ProgressPage*>(GetWindowLongPtrW(progress, GWLP_USERDATA));
HWND control = reinterpret_cast<HWND>(lparam);
if (page && page->controlsVisible) {
// IsDialogMessage can route Enter to the outer NSIS dialog.
if (control && GetParent(control) == progress)
return SendMessageW(progress, WM_COMMAND, wparam, lparam);
if (LOWORD(wparam) == IDOK) {
RequestFinish(progress, *page, SendMessageW(page->launch, BM_GETCHECK, 0, 0) == BST_CHECKED);
return 0;
}
}
}
if (message == WM_NCCALCSIZE && wparam) return 0;
// Activation must not repaint the standard frame over the custom client area.
if (message == WM_NCACTIVATE) return DefSubclassProc(window, message, wparam, -1);
@@ -419,7 +555,9 @@ static LRESULT CALLBACK FrameProc(HWND window, UINT message, WPARAM wparam,
// The installer has a fixed size; its page provides the drag area.
return hit >= HTLEFT && hit <= HTBOTTOMRIGHT ? HTCLIENT : hit;
}
if (message == WM_NCDESTROY) RemoveWindowSubclass(window, FrameProc, id);
if (message == WM_NCDESTROY) {
RemoveWindowSubclass(window, FrameProc, id);
}
return DefSubclassProc(window, message, wparam, lparam);
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@deepseek-ai/dsh-desktop",
"description": "Electron desktop shell for a bundled dsh runtime and external plugins",
"version": "0.2.2-rc.4",
"version": "0.2.2-rc.5",
"private": true,
"license": "MIT",
"author": {
+2 -2
View File
@@ -10,6 +10,7 @@ import type { DesktopRelease } from '../src/release.ts'
import { developmentRuntimeDirectory, resolveDesktopBuildTarget } from './desktop-build-paths.mjs'
import { prepareDevelopmentProject } from './development-project.ts'
import { prepareDevelopmentApp } from './development-app.ts'
import { prepareDevelopmentState } from './development-state.ts'
import { preparePrimaryRuntime } from './prepare-primary-runtime.ts'
const APP_ROOT = resolve(import.meta.dirname, '..')
@@ -63,8 +64,7 @@ async function launchElectron(): Promise<void> {
const mainPort = debugPort('DSH_DESKTOP_MAIN_INSPECT_PORT', 9229)
const rendererPort = debugPort('DSH_DESKTOP_RENDERER_DEBUG_PORT', 9222)
const hostPort = debugPort('DSH_DESKTOP_HOST_INSPECT_PORT', 9230)
const home = resolve(process.env.DSH_HOME ?? join(DEVELOPMENT_ROOT, 'home'))
const userData = resolve(process.env.DSH_DESKTOP_USER_DATA_DIR ?? join(DEVELOPMENT_ROOT, 'electron-user-data'))
const { home, userData } = prepareDevelopmentState(APP_ROOT)
const environment: NodeJS.ProcessEnv = {
...process.env,
DSH_HOME: home,
+69
View File
@@ -0,0 +1,69 @@
/** Persistent Harness home and Electron browser data for unpackaged Desktop launches. */
import { existsSync, mkdirSync, readlinkSync, renameSync } from 'node:fs'
import { join, resolve } from 'node:path'
/** Development state locations selected for one launch. */
export interface DevelopmentState {
readonly home: string
readonly userData: string
}
function running(pid: number): boolean {
try {
process.kill(pid, 0)
return true
} catch (error) {
return error instanceof Error && 'code' in error && error.code === 'EPERM'
}
}
/** Chromium links `SingletonLock` to `<host>-<pid>` while a browser process owns the profile on macOS and Linux. */
function profileInUse(userData: string): boolean {
let target: string
try {
target = readlinkSync(join(userData, 'SingletonLock'))
} catch (error) {
// A missing lock or a non-link lock file means no live owner records itself this way.
if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'EINVAL')) return false
throw error
}
const pid = /-(\d+)$/.exec(target)?.[1]
return pid !== undefined && running(Number(pid))
}
/**
* Resolve development state outside `.desktop-build`, which `pnpm run clean` removes.
* A default location that does not exist yet receives the state an earlier launcher left under
* `.desktop-build/development` unless a running Harness Dev still owns that browser profile;
* explicit `DSH_HOME` and `DSH_DESKTOP_USER_DATA_DIR` are used as given.
* @param appRoot - Desktop application directory.
* @param environment - Launch environment with optional location overrides.
* @returns Harness home and Electron user-data directories.
*/
export function prepareDevelopmentState(appRoot: string, environment: NodeJS.ProcessEnv = process.env): DevelopmentState {
const legacyRoot = join(appRoot, '.desktop-build', 'development')
const select = (override: string | undefined, name: string): string => {
if (override !== undefined) return resolve(override)
const path = join(appRoot, '.desktop-dev', name)
const legacy = join(legacyRoot, name)
if (!existsSync(path) && existsSync(legacy)) {
// POSIX renames a directory that a running process still writes, which would split its state.
if (profileInUse(join(legacyRoot, 'electron-user-data'))) {
throw new Error(`desktop development: a running Harness Dev still uses ${legacyRoot}; quit it and retry`)
}
try {
mkdirSync(join(appRoot, '.desktop-dev'), { recursive: true })
renameSync(legacy, path)
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
throw new Error(`desktop development: cannot move ${legacy} to ${path}: ${reason}`, { cause: error })
}
console.log(`desktop development: moved ${legacy} to ${path}`)
}
return path
}
return {
home: select(environment.DSH_HOME, 'home'),
userData: select(environment.DSH_DESKTOP_USER_DATA_DIR, 'electron-user-data'),
}
}
+2 -1
View File
@@ -100,10 +100,11 @@ ManifestDPIAware true
!macro customPageAfterChangeDir
!define MUI_PAGE_CUSTOMFUNCTION_PRE InstallerBeforeInstall
!define MUI_PAGE_CUSTOMFUNCTION_SHOW InstallerProgressShow
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE InstallerProgressLeave
!macroend
!macro customFinishPage
Page custom InstallerFinish InstallerFinishLeave
; The final instfiles page keeps its controls until the user dismisses it.
!macroend
; Installation work publishes stage changes without disturbing the NSIS caller.
+69 -13
View File
@@ -1,9 +1,16 @@
/** Bounded, cancellable reads of Desktop-owned plugin operation history. */
import { open } from 'node:fs/promises'
import type { BigIntStats } from 'node:fs'
import { open, type FileHandle } from 'node:fs/promises'
import { join } from 'node:path'
import { setImmediate } from 'node:timers/promises'
import { setImmediate, setTimeout as wait } from 'node:timers/promises'
import { parsePluginOperationRecord, type PluginOperationRecord } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
/** Windows reports these while another handle temporarily owns an otherwise readable file. */
const WINDOWS_TRANSIENT_OPEN_ERRORS: ReadonlySet<string> = new Set(['EACCES', 'EBUSY', 'EPERM'])
const WINDOWS_OPEN_RETRY_INITIAL_MS = 10
const WINDOWS_OPEN_RETRY_MAX_MS = 40
const WINDOWS_OPEN_RETRY_LIMIT = 4
/** Resource budgets for auxiliary history collection, independent of basic crash report writing. */
export interface OperationHistoryReadLimits {
readonly bytes: number
@@ -15,7 +22,7 @@ export interface OperationHistoryReadLimits {
export interface OperationHistoryReadResult {
readonly records: readonly PluginOperationRecord[]
readonly bytesRead: number
/** Distinct files from which at least one byte was read. */
/** Owned history segments from which at least one byte was read. */
readonly filesRead: number
readonly truncated: boolean
readonly invalidRecords: number
@@ -23,9 +30,53 @@ export interface OperationHistoryReadResult {
readonly cancelled: boolean
}
/**
* Exact two-name key for one file; BigInt stats keep a Windows 64-bit file ID at its
* value instead of the 53-bit Number form, where two adjacent IDs can coincide.
* @param info - Stats of the opened history segment.
* @returns Device and inode as one comparable string.
*/
function fileIdentity(info: BigIntStats): string {
return `${String(info.dev)}:${String(info.ino)}`
}
/** Whether Windows reported temporary interference with opening a history segment. */
function isTransientWindowsOpenError(error: unknown): boolean {
if (process.platform !== 'win32') return false
return WINDOWS_TRANSIENT_OPEN_ERRORS.has((error as NodeJS.ErrnoException | null)?.code ?? '')
}
/**
* Open one segment, retrying the temporary Windows sharing and permission failures a scanner
* causes on a freshly written file. One persistent failure would otherwise drop the whole
* segment from the report. A signal aborted during the bounded wait ends the retries without
* another open.
* @param filename - Absolute path of the owned segment.
* @param signal - Caller-owned collection deadline or shutdown cancellation.
* @returns The opened read handle.
*/
async function openSegment(filename: string, signal: AbortSignal): Promise<FileHandle> {
// A call keeps the post-wait check outside the catch's narrowing to the pre-wait value.
const aborted = (): boolean => signal.aborted
let delay = WINDOWS_OPEN_RETRY_INITIAL_MS
for (let retries = 0;; retries += 1) {
try {
return await open(filename, 'r')
} catch (error) {
if (!isTransientWindowsOpenError(error) || retries >= WINDOWS_OPEN_RETRY_LIMIT || aborted()) throw error
await wait(delay)
if (aborted()) throw error
delay = Math.min(delay * 2, WINDOWS_OPEN_RETRY_MAX_MS)
}
}
}
/**
* Read only the bounded tails of the two owned history files, newest segment first.
* Cancellation is observed between bounded records after yielding to Worker messages and stops subsequent I/O and parsing.
* A segment is deduplicated as already read when its handle reports the exact bigint identity of
* the segment already read; the predecessor is skipped, so its records are not collected twice and
* records appended to it after the read are not collected.
* An already-issued OS read must settle before its handle closes.
* @param directory - Desktop's operation history directory; unrelated files are never enumerated.
* @param limits - Positive byte, record-size and record-count budgets.
@@ -44,33 +95,35 @@ export async function readOperationHistory(
const cancelled = (): boolean => signal.aborted
const records: PluginOperationRecord[] = []
let bytesRead = 0
const seenFiles = new Set<string>()
let filesRead = 0
let lastReadIdentity: string | undefined
let truncated = false
let invalidRecords = 0
let unavailableFiles = 0
for (const name of ['operations.jsonl', 'operations.previous.jsonl']) {
if (cancelled()) break
try {
await using handle = await open(join(directory, name), 'r')
await using handle = await openSegment(join(directory, name), signal)
if (cancelled()) break
const fileStat = await handle.stat()
const fileStat = await handle.stat({ bigint: true })
if (cancelled()) break
if (!fileStat.isFile()) {
unavailableFiles++
continue
}
const identity = `${String(fileStat.dev)}:${String(fileStat.ino)}`
if (seenFiles.has(identity)) {
const identity = fileIdentity(fileStat)
const size = Number(fileStat.size)
if (lastReadIdentity !== undefined && identity === lastReadIdentity) {
truncated = true
continue
}
if (fileStat.size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) {
if (size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) {
truncated = true
break
}
const readLength = Math.min(fileStat.size, limits.bytes - bytesRead)
const readStart = fileStat.size - readLength
const readLength = Math.min(size, limits.bytes - bytesRead)
const readStart = size - readLength
const buffer = Buffer.alloc(readLength)
let readOffset = 0
while (readOffset < readLength && !cancelled()) {
@@ -79,7 +132,10 @@ export async function readOperationHistory(
if (read.bytesRead === 0) break
readOffset += read.bytesRead
}
if (readOffset > 0) seenFiles.add(identity)
if (readOffset > 0) {
filesRead++
lastReadIdentity = identity
}
if (cancelled()) break
truncated ||= readStart > 0 || readOffset < readLength
@@ -116,5 +172,5 @@ export async function readOperationHistory(
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') unavailableFiles++
}
}
return { records, bytesRead, filesRead: seenFiles.size, truncated, invalidRecords, unavailableFiles, cancelled: cancelled() }
return { records, bytesRead, filesRead, truncated, invalidRecords, unavailableFiles, cancelled: cancelled() }
}
@@ -0,0 +1,75 @@
/** Development launches keep Harness state where repository cleaning does not remove it. */
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished, vi } from 'vitest'
import { prepareDevelopmentState } from '../scripts/development-state.ts'
function fixture(): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-development-state-'))
onTestFinished(() => { rmSync(root, { recursive: true, force: true }) })
return root
}
it('moves state from .desktop-build into the default development state directory', () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
onTestFinished(() => { vi.restoreAllMocks() })
const root = fixture()
const legacy = join(root, '.desktop-build', 'development')
mkdirSync(join(legacy, 'home'), { recursive: true })
mkdirSync(join(legacy, 'electron-user-data'))
writeFileSync(join(legacy, 'home', 'session.jsonl'), 'session')
const state = prepareDevelopmentState(root, {})
expect(state).toEqual({ home: join(root, '.desktop-dev', 'home'), userData: join(root, '.desktop-dev', 'electron-user-data') })
expect(readFileSync(join(state.home, 'session.jsonl'), 'utf8')).toBe('session')
expect(existsSync(state.userData)).toBe(true)
expect(existsSync(join(legacy, 'home'))).toBe(false)
})
it('keeps existing default state and leaves legacy state in place', () => {
const root = fixture()
mkdirSync(join(root, '.desktop-dev', 'home'), { recursive: true })
mkdirSync(join(root, '.desktop-build', 'development', 'home'), { recursive: true })
expect(prepareDevelopmentState(root, {}).home).toBe(join(root, '.desktop-dev', 'home'))
expect(existsSync(join(root, '.desktop-build', 'development', 'home'))).toBe(true)
})
it('moves only the default directory that is missing', () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
onTestFinished(() => { vi.restoreAllMocks() })
const root = fixture()
const legacy = join(root, '.desktop-build', 'development')
mkdirSync(join(legacy, 'home'), { recursive: true })
mkdirSync(join(legacy, 'electron-user-data'))
const state = prepareDevelopmentState(root, { DSH_HOME: join(root, 'h') })
expect(state).toEqual({ home: join(root, 'h'), userData: join(root, '.desktop-dev', 'electron-user-data') })
expect(existsSync(state.userData)).toBe(true)
expect(existsSync(join(legacy, 'home'))).toBe(true)
})
it('uses explicit locations without moving legacy state', () => {
const root = fixture()
mkdirSync(join(root, '.desktop-build', 'development', 'home'), { recursive: true })
expect(prepareDevelopmentState(root, { DSH_HOME: join(root, 'h'), DSH_DESKTOP_USER_DATA_DIR: join(root, 'u') }))
.toEqual({ home: join(root, 'h'), userData: join(root, 'u') })
expect(existsSync(join(root, '.desktop-build', 'development', 'home'))).toBe(true)
expect(existsSync(join(root, '.desktop-dev'))).toBe(false)
})
it.skipIf(process.platform === 'win32')('does not move state that a running Harness Dev still owns', () => {
const root = fixture()
const legacy = join(root, '.desktop-build', 'development')
mkdirSync(join(legacy, 'home'), { recursive: true })
mkdirSync(join(legacy, 'electron-user-data'))
symlinkSync(`host-${String(process.pid)}`, join(legacy, 'electron-user-data', 'SingletonLock'))
expect(() => prepareDevelopmentState(root, {})).toThrow('a running Harness Dev still uses')
expect(existsSync(join(legacy, 'home'))).toBe(true)
expect(existsSync(join(root, '.desktop-dev'))).toBe(false)
})
@@ -8,6 +8,7 @@
"welcome-ready-before-first-show",
"welcome-presented-on-first-show",
"successful-install-paints-100-before-finish",
"completion-close-exits-without-launch",
"locked-directory-shows-error-and-copy-control-and-preserves-installation",
"registered-directory-with-trailing-separators",
"registered-directory-and-checked-launch",
+200 -5
View File
@@ -1,7 +1,8 @@
import { mkdtemp, mkdir, open, rename, rm, writeFile } from 'node:fs/promises'
import { appendFile, mkdtemp, mkdir, open, rename, rm, writeFile } from 'node:fs/promises'
import type { BigIntStats, StatOptions, Stats } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished, vi } from 'vitest'
import { beforeEach, expect, it, onTestFinished, vi } from 'vitest'
import { readOperationHistory } from '../src/operation-history.ts'
vi.mock('node:fs/promises', async (importOriginal) => {
@@ -10,6 +11,7 @@ vi.mock('node:fs/promises', async (importOriginal) => {
})
const limits = { bytes: 64 * 1024, recordBytes: 2048, records: 100 }
beforeEach(() => { vi.mocked(open).mockClear() })
function record(id: string | number) {
return { runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0,
operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z',
@@ -25,11 +27,183 @@ async function fixture() {
it('collects recent complete records and reports malformed and incomplete entries', async () => {
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(1) + '{broken}\n' + line(2) + '{"incomplete":')
const current = line(1) + '{broken}\n' + line(2) + '{"incomplete":'
await writeFile(join(path, 'operations.jsonl'), current)
await writeFile(join(path, 'operations.previous.jsonl'), line(0))
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(2), record(1), record(0)])
expect(result).toMatchObject({ invalidRecords: 1, truncated: true, cancelled: false, unavailableFiles: 0 })
// The whole result is asserted so a missing record also names the collection facts that caused it.
expect(result).toEqual({
records: [record(2), record(1), record(0)],
bytesRead: Buffer.byteLength(current) + Buffer.byteLength(line(0)),
filesRead: 2,
truncated: true,
invalidRecords: 1,
unavailableFiles: 0,
cancelled: false,
})
})
it('does not collect a rotated predecessor twice after it was appended', async () => {
const path = await fixture()
const current = join(path, 'operations.jsonl')
const previous = join(path, 'operations.previous.jsonl')
await writeFile(current, line(1))
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const handle = await open(current, 'r')
const opener = vi.mocked(open).mockClear()
.mockImplementationOnce(async () => handle)
.mockImplementationOnce(async () => {
// The writer appends one record, then rotates: both names still denote one file.
await appendFile(current, line(2))
await rename(current, previous)
await writeFile(current, line(3))
return actualFs.open(previous, 'r')
})
try {
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result).toMatchObject({ filesRead: 1, truncated: true, unavailableFiles: 0 })
} finally {
opener.mockClear()
}
})
it('compares exact bigint identities so two nearby Numbers cannot collapse one segment', async () => {
const path = await fixture()
const current = join(path, 'operations.jsonl')
const previous = join(path, 'operations.previous.jsonl')
const currentText = line('current')
const previousText = line('old')
await writeFile(current, currentText)
await writeFile(previous, previousText)
const currentHandle = await open(current, 'r')
const previousHandle = await open(previous, 'r')
onTestFinished(async () => { await currentHandle.close(); await previousHandle.close() })
const currentStat = await currentHandle.stat({ bigint: true })
const previousStat = await previousHandle.stat({ bigint: true })
const currentNumberStat = await currentHandle.stat()
const previousNumberStat = await previousHandle.stat()
// Adjacent 64-bit file IDs: distinct as bigints, one Number after the 53-bit mantissa.
const base = 2n ** 58n + 1000n
currentStat.dev = 0n
currentStat.ino = base
previousStat.dev = 0n
previousStat.ino = base + 1n
currentNumberStat.dev = 0
currentNumberStat.ino = Number(base)
previousNumberStat.dev = 0
previousNumberStat.ino = Number(base + 1n)
expect(currentNumberStat.ino).toBe(previousNumberStat.ino)
const optionAware = (exact: BigIntStats, numeric: Stats) =>
async (options?: StatOptions): Promise<BigIntStats | Stats> => options?.bigint === true ? exact : numeric
const currentStats = vi.spyOn(currentHandle, 'stat').mockImplementation(optionAware(currentStat, currentNumberStat))
const previousStats = vi.spyOn(previousHandle, 'stat').mockImplementation(optionAware(previousStat, previousNumberStat))
const opener = vi.mocked(open).mockClear().mockResolvedValueOnce(currentHandle).mockResolvedValueOnce(previousHandle)
try {
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record('current'), record('old')])
expect(result).toMatchObject({ filesRead: 2, unavailableFiles: 0, truncated: false })
} finally {
currentStats.mockRestore()
previousStats.mockRestore()
opener.mockClear()
}
})
it('retries transient Windows sharing failures while opening a segment', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
opener.mockRejectedValueOnce(Object.assign(new Error('sharing violation'), { code: 'EBUSY' }))
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(2), record(1)])
expect(result.unavailableFiles).toBe(0)
expect(opener).toHaveBeenCalledTimes(3)
})
it('counts a segment unavailable after bounded Windows open retries expire', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
for (let attempt = 0; attempt <= 4; attempt++) {
opener.mockRejectedValueOnce(Object.assign(new Error('access denied'), { code: 'EPERM' }))
}
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result.unavailableFiles).toBe(1)
expect(opener).toHaveBeenCalledTimes(6)
})
it('does not retry a Windows transient code outside Windows', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
opener.mockRejectedValueOnce(Object.assign(new Error('access denied'), { code: 'EPERM' }))
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result.unavailableFiles).toBe(1)
expect(opener).toHaveBeenCalledTimes(2)
})
it('stops Windows open retries when the collection is already cancelled', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
const controller = new AbortController()
opener.mockImplementationOnce(async () => {
controller.abort()
throw Object.assign(new Error('sharing violation'), { code: 'EBUSY' })
})
const result = await readOperationHistory(path, limits, controller.signal)
expect(result).toMatchObject({ records: [], cancelled: true, unavailableFiles: 1 })
expect(opener).toHaveBeenCalledTimes(1)
})
it('stops Windows open retries when cancellation lands during the retry wait', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
const controller = new AbortController()
opener.mockImplementationOnce(async () => {
setImmediate(() => { controller.abort() })
throw Object.assign(new Error('sharing violation'), { code: 'EBUSY' })
})
const result = await readOperationHistory(path, limits, controller.signal)
expect(result).toMatchObject({ records: [], cancelled: true, unavailableFiles: 1 })
expect(opener).toHaveBeenCalledTimes(1)
})
it('reads no more than its byte budget from a two GiB file and ignores unrelated history', async () => {
@@ -159,6 +333,27 @@ it('does not collect the same open segment twice when it rotates during collecti
}
})
it('does not re-collect a rotated segment while the current path is briefly absent', async () => {
const path = await fixture()
const current = join(path, 'operations.jsonl')
await writeFile(current, line(1))
const handle = await open(current, 'r')
onTestFinished(async () => { await handle.close() })
const opener = vi.mocked(open).mockClear().mockImplementationOnce(async () => {
await rename(current, join(path, 'operations.previous.jsonl'))
return handle
})
try {
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result).toMatchObject({ filesRead: 1, truncated: true })
expect(handle.fd).toBe(-1)
} finally {
opener.mockClear()
await handle.close()
}
})
it.each(['absent', 'empty', 'nonempty'])('reports omitted bytes at an exact budget: previous segment %s', async (previous) => {
const path = await fixture()
const current = line(1)
@@ -65,6 +65,8 @@ int main() {
progress.Complete(done);
double previous = progress.value;
for (std::uint64_t elapsed = 0; elapsed < 600; elapsed += 16) {
// A repeated completion notification must not restart the final animation.
if (elapsed == 320) progress.Complete(done + elapsed);
progress.Advance(4, 1, done + elapsed);
assert(progress.value >= previous && progress.value < 100);
previous = progress.value;
+109 -15
View File
@@ -11,9 +11,67 @@ extern "C" __declspec(dllimport) HRESULT __cdecl InstallerApplyFrame(HWND window
extern "C" __declspec(dllimport) HWND __cdecl InstallerShowProgress(HWND parent, HWND source,
BOOL dark, UINT dpi, DWORD controlHover, DWORD controlPressed, const WCHAR* brand, const WCHAR* preparing, const WCHAR* extracting,
const WCHAR* copying, const WCHAR* registering, const WCHAR* cleaning);
extern "C" __declspec(dllimport) BOOL __cdecl InstallerFinishProgress(HWND window);
extern "C" __declspec(dllimport) BOOL __cdecl InstallerFinishProgress(HWND window, const WCHAR* finish, const WCHAR* launch);
extern "C" __declspec(dllimport) int __cdecl InstallerTakeFinishChoice(HWND window);
struct CompletionProbe {
HWND progress;
ULONGLONG deadline;
RECT bounds;
bool requested = false;
bool completedDuringMove = false;
};
static void PollCompletion(HWND window, CompletionProbe& probe) {
const HWND finish = FindWindowExW(probe.progress, nullptr, L"Button", L"Finish");
const HWND launch = FindWindowExW(probe.progress, nullptr, L"Button", L"Launch");
if (finish && launch && IsWindowVisible(finish) && IsWindowVisible(launch)) {
GUITHREADINFO input{sizeof(input)};
RECT current;
probe.completedDuringMove = GetGUIThreadInfo(GetCurrentThreadId(), &input)
&& input.hwndMoveSize == window && GetWindowRect(window, &current)
&& EqualRect(&current, &probe.bounds) && IsWindowEnabled(finish)
&& SendMessageW(launch, BM_GETCHECK, 0, 0) == BST_CHECKED
&& GetPropW(window, L"HarnessInstaller.CompletedPercent") == reinterpret_cast<HANDLE>(100);
} else if (GetTickCount64() < probe.deadline) {
return;
}
SendMessageW(window, WM_CANCELMODE, 0, 0);
}
static bool CompleteWhileMinimized(HWND window, HWND progress) {
ShowWindow(window, SW_MINIMIZE);
const HWND foreground = GetForegroundWindow();
if (!IsIconic(window) || !InstallerFinishProgress(progress, L"Finish", L"Launch")) return false;
const ULONGLONG deadline = GetTickCount64() + 5000;
while (GetTickCount64() < deadline) {
const HWND finish = FindWindowExW(progress, nullptr, L"Button", L"Finish");
if (finish && IsWindowVisible(finish)) {
return IsIconic(window) && (foreground == window || GetForegroundWindow() != window)
&& GetPropW(window, L"HarnessInstaller.Succeeded") != nullptr;
}
MSG message;
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) DispatchMessageW(&message);
MsgWaitForMultipleObjectsEx(0, nullptr, 16, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
}
return false;
}
static LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
auto* probe = reinterpret_cast<CompletionProbe*>(GetWindowLongPtrW(window, GWLP_USERDATA));
if (probe && message == WM_ENTERSIZEMOVE) {
GetWindowRect(window, &probe->bounds);
PostMessageW(window, WM_APP, 0, 0);
}
if (probe && message == WM_APP) {
probe->requested = InstallerFinishProgress(probe->progress, L"Finish", L"Launch") != FALSE;
if (!probe->requested || !SetTimer(window, 1, 16, nullptr)) SendMessageW(window, WM_CANCELMODE, 0, 0);
return 0;
}
if (probe && message == WM_TIMER && wparam == 1) {
PollCompletion(window, *probe);
return 0;
}
if (message == WM_DESTROY) { PostQuitMessage(0); return 0; }
return DefWindowProcW(window, message, wparam, lparam);
}
@@ -68,10 +126,12 @@ int wmain(int argc, wchar_t** argv) {
HWND warmup = createProgress();
if (!warmup) { DestroyWindow(window); return 5; }
UpdateWindow(warmup);
ShowWindow(window, SW_MINIMIZE);
const bool minimizedCompletion = CompleteWhileMinimized(window, warmup);
ShowWindow(window, SW_RESTORE);
UpdateWindow(warmup);
DestroyWindow(warmup);
RemovePropW(window, L"HarnessInstaller.CompletedPercent");
RemovePropW(window, L"HarnessInstaller.Succeeded");
const DWORD initialGdi = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS);
HWND progress = createProgress();
if (!progress) { DestroyWindow(window); return 5; }
@@ -124,14 +184,15 @@ int wmain(int argc, wchar_t** argv) {
};
bool captionStates = true;
ShowWindow(progress, SW_HIDE);
for (int x : {504, 548}) {
{
constexpr int x = 504;
const LPARAM point = MAKELPARAM(MulDiv(x + 20, dpi, 96), MulDiv(24, dpi, 96));
captionStates = expectPixel(x, normalColor) && captionStates;
SendMessageW(progress, WM_MOUSEMOVE, 0, point);
captionStates = expectPixel(x, hoverColor) && captionStates;
SendMessageW(progress, WM_LBUTTONDOWN, MK_LBUTTON, point);
captionStates = expectPixel(x, pressedColor) && captionStates;
const int other = x == 504 ? 548 : 504;
constexpr int other = 548;
SendMessageW(progress, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(MulDiv(other + 20, dpi, 96), MulDiv(24, dpi, 96)));
captionStates = expectPixel(other, normalColor) && captionStates;
captionStates = expectPixel(x, normalColor) && captionStates;
@@ -167,12 +228,15 @@ int wmain(int argc, wchar_t** argv) {
const LPARAM closePoint = MAKELPARAM(MulDiv(568, dpi, 96), MulDiv(24, dpi, 96));
MSG closeMessage;
SendMessageW(progress, WM_LBUTTONDOWN, MK_LBUTTON, closePoint);
bool closeRelease = !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
bool closeDisabled = GetCapture() != progress && expectPixel(548, normalColor)
&& !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
SendMessageW(progress, WM_MOUSEMOVE, MK_LBUTTON, closePoint);
closeDisabled = closeDisabled && expectPixel(548, normalColor);
SendMessageW(progress, WM_LBUTTONUP, 0, minimizePoint);
closeRelease = closeRelease && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
closeDisabled = closeDisabled && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
SendMessageW(progress, WM_LBUTTONDOWN, MK_LBUTTON, closePoint);
SendMessageW(progress, WM_LBUTTONUP, 0, closePoint);
closeRelease = closeRelease && PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
closeDisabled = closeDisabled && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE) && GetCapture() != progress;
LARGE_INTEGER frequency, started, finished;
QueryPerformanceFrequency(&frequency);
std::vector<double> samples;
@@ -196,15 +260,45 @@ int wmain(int argc, wchar_t** argv) {
std::printf("fixture=standalone-progress dpi=%d dark=%d frames=%d screen=%dx%d foreground=%d mean_ms=%.3f p50_ms=%.3f p95_ms=%.3f max_ms=%.3f\n",
dpi, dark, frameCount, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), GetForegroundWindow() == window,
total / samples.size(), samples[samples.size() / 2], samples[samples.size() * 95 / 100], samples.back());
const bool completed = InstallerFinishProgress(progress) &&
GetPropW(window, L"HarnessInstaller.CompletedPercent") == reinterpret_cast<HANDLE>(100);
WCHAR caption[160] = {};
GetWindowTextW(progress, caption, ARRAYSIZE(caption));
const bool finalCaption = wcscmp(caption, L"Extracting 100%") == 0;
CompletionProbe probe{progress, GetTickCount64() + 5000, {}};
POINT originalCursor{};
const bool restoreCursor = GetCursorPos(&originalCursor) != FALSE;
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(&probe));
SendMessageW(window, WM_SYSCOMMAND, SC_MOVE, 0);
if (restoreCursor) SetCursorPos(originalCursor.x, originalCursor.y);
KillTimer(window, 1);
SetWindowLongPtrW(window, GWLP_USERDATA, 0);
const bool completed = probe.requested && probe.completedDuringMove;
bool finishActions = completed && InstallerTakeFinishChoice(progress) == -1;
bool finishInTabOrder = false, launchInTabOrder = false;
if (finishActions) {
const HWND finish = FindWindowExW(progress, nullptr, L"Button", L"Finish");
const HWND launch = FindWindowExW(progress, nullptr, L"Button", L"Launch");
const HWND close = FindWindowExW(progress, nullptr, L"Button", L"\x00d7");
const HWND first = GetNextDlgTabItem(window, nullptr, FALSE);
HWND tab = first;
for (int next = 0; tab && next < 4; ++next) {
finishInTabOrder |= tab == finish;
launchInTabOrder |= tab == launch;
tab = GetNextDlgTabItem(window, tab, FALSE);
if (tab == first) break;
}
SendMessageW(finish, BM_CLICK, 0, 0);
finishActions = InstallerTakeFinishChoice(progress) == 1 && InstallerTakeFinishChoice(progress) == -1;
SendMessageW(close, BM_CLICK, 0, 0);
finishActions = finishActions && InstallerTakeFinishChoice(progress) == 0;
SendMessageW(launch, BM_CLICK, 0, 0);
SendMessageW(window, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), 0);
finishActions = finishActions && InstallerTakeFinishChoice(progress) == 0;
}
DestroyWindow(progress);
const DWORD finalGdi = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS);
DestroyWindow(window);
std::printf("client_frame=%d stock_preserved=%d completed=%d final_caption=%d caption_states=%d button_release=%d close_release=%d minimized=%d restored=%d gdi_before=%lu gdi_after=%lu\n",
clientFrame, failurePreservesStock, completed, finalCaption, captionStates, buttonRelease, closeRelease, minimized, restored, initialGdi, finalGdi);
return clientFrame && failurePreservesStock && completed && finalCaption && captionStates && buttonRelease && closeRelease && minimized && restored && finalGdi <= initialGdi ? 0 : 6;
std::printf("client_frame=%d stock_preserved=%d completed_during_move=%d caption_states=%d button_release=%d close_disabled=%d minimized=%d restored=%d gdi_before=%lu gdi_after=%lu\n",
clientFrame, failurePreservesStock, completed, captionStates, buttonRelease, closeDisabled, minimized, restored, initialGdi, finalGdi);
std::printf("minimized_completion=%d finish_actions=%d finish_tab=%d launch_tab=%d\n",
minimizedCompletion, finishActions, finishInTabOrder, launchInTabOrder);
return clientFrame && failurePreservesStock && completed && minimizedCompletion && finishActions
&& finishInTabOrder && launchInTabOrder && captionStates && buttonRelease && closeDisabled
&& minimized && restored && finalGdi <= initialGdi ? 0 : 6;
}
@@ -157,6 +157,14 @@ try {
$results.Add('welcome-ready-before-first-show')
$results.Add('successful-install-paints-100-before-finish')
$process = Start-Setup light
Click-Control $process $copy.INSTALLER_INSTALL
[void](Wait-Control $process $copy.INSTALLER_FINISH)
Click-Control $process ([string][char]0xD7)
if (-not $process.WaitForExit(10000) -or $process.ExitCode -ne 0) { throw 'Completion close did not exit successfully' }
if (Test-Path -LiteralPath (Join-Path $installPath 'launched.txt')) { throw 'Completion close launched the application' }
$results.Add('completion-close-exits-without-launch')
$lockedFile = [IO.File]::Open($appPath, 'Open', 'Read', 'Read')
try {
$process = Start-Setup light
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@deepseek-ai/dsh-plugin-market-generator",
"description": "Reference generator of plugin market index files from a list of npm packages and Git repositories",
"version": "0.2.2-rc.4",
"version": "0.2.2-rc.5",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@deepseek-ai/dsh-web-frontend",
"description": "Web application entry: vite build over the @deepseek-ai/dsh-client-web shell library; dist/ served by apps/cli's dsh web",
"version": "0.2.2-rc.4",
"version": "0.2.2-rc.5",
"publishConfig": {
"access": "public"
},
@@ -82,7 +82,11 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', '
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true })
await edit.click()
const key = dialog.getByLabel('API 密钥', { exact: true })
// This row's card alone. Between the credential delete and the profile
// write that restores native auth, google's row reports no usable
// provider and the page mounts the DeepSeek first-run setup card, whose
// key field would answer a dialog-wide count.
const key = edit.locator('xpath=ancestor::li').getByLabel('API 密钥', { exact: true })
await key.press('Delete')
expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`)
await dialog.getByText(`保存以清除已保存的 API key。之后使用环境认证(${envRef})。`, { exact: true }).waitFor()
@@ -94,7 +98,7 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', '
await edit.click()
await key.press('Delete')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => key.count()).toBe(0)
await expect.poll(() => key.count(), { timeout: 10_000 }).toBe(0)
await generate()
expect(calls).toHaveLength(2)
expect(calls[0]?.key).toBe(messages || google ? 'fixture-saved-key' : 'Bearer fixture-saved-key')
@@ -134,7 +138,9 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true })
await edit.click()
const key = dialog.getByLabel('API 密钥', { exact: true })
// This row's card alone: the dialog can show another provider's card,
// with its own key field, beside this row.
const key = edit.locator('xpath=ancestor::li').getByLabel('API 密钥', { exact: true })
expect(await key.getAttribute('placeholder')).toBe(`fixture-prote${'•'.repeat(8)}-key`)
expect(await key.inputValue()).toBe('')
expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0)
@@ -155,7 +161,12 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki
await expect.poll(() => key.inputValue()).toBe('')
await key.fill('fixture-new-key')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => key.count()).toBe(0)
// The editor closes before the save's reload lands, and an Edit press
// while the settings snapshot is loading is dropped. The saved notice is
// published by that reload's completion, so waiting for it also makes the
// reopen below deterministic.
await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
await expect.poll(() => key.count(), { timeout: 10_000 }).toBe(0)
await edit.click()
expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-new-key'.length))
expect(await key.inputValue()).toBe('')
@@ -0,0 +1,5 @@
- listitem:
- button "查看 持久终端": 持久终端
- text: 实验性 为智能体提供以侧栏标签页打开的终端,你可以旁观,也可以直接在其中键入来接管。进程在多次工具调用之间持续运行,因此它可以启动开发服务器或 REPL,稍后再读取输出;它也能读取你自己打开的终端。
- status
- switch "启用 持久终端"
+144
View File
@@ -0,0 +1,144 @@
// Feishu setup failures and recovery through the real Host/Remote/browser composition.
// A stand-in CLI waits for each authorization page visit and keeps account state on disk.
import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, BrowserContext, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const FEISHU_DIR = fileURLToPath(new URL('../../../packages/connector/feishu', import.meta.url))
const SETUP_URL = 'https://open.feishu.cn/page/cli?e2e=1'
const SETUP_RETRY_URL = `${SETUP_URL}&retry=1`
const SIGN_IN_URL = 'https://accounts.feishu.cn/oauth/device?e2e=1'
// The stand-in keeps its account in state.json beside itself; app setup and
// sign-in wait until the test marks their page visited.
const LARK_CLI = `#!/usr/bin/env node
const { existsSync, readFileSync, writeFileSync } = require('node:fs')
const { join } = require('node:path')
const dir = __dirname
const statePath = join(dir, 'state.json')
const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { app: false, user: false }
const save = () => { writeFileSync(statePath, JSON.stringify(state)) }
const visited = (name, done) => {
const poll = setInterval(() => {
if (!existsSync(join(dir, name))) return
clearInterval(poll)
done()
}, 50)
}
const line = (value) => { process.stdout.write(JSON.stringify(value) + '\\n') }
switch (process.argv.slice(2).join(' ')) {
case 'auth status --verify --json':
if (!state.app) {
process.stderr.write(JSON.stringify({ ok: false, error: { type: 'config', subtype: 'not_configured' } }))
process.exitCode = 3
} else if (!state.user) line({ appId: 'cli_e2e', identities: { user: { status: 'missing', available: false } } })
else line({ appId: 'cli_e2e', identities: { user: { status: 'ready', available: true, verified: true, userName: '测试用户', openId: 'ou_e2e' } } })
break
case 'config init --new':
process.stderr.write('Open this link to create an app:\\n ' + (existsSync(join(dir, 'setup-fails')) ? '${SETUP_URL}' : '${SETUP_RETRY_URL}') + '\\n')
visited('setup-visited', () => {
if (existsSync(join(dir, 'setup-fails'))) {
process.stderr.write('OK: App configured!\\n' + JSON.stringify({ ok: false, error: {
type: 'internal', subtype: 'sdk_error',
message: 'keychain Set failed: /private/user/appsecret.enc.tmp: operation not permitted; token=fixture-secret',
hint: 'https://open.feishu.cn/page/cli?user_code=fixture-code',
} }, null, 2) + '\\n')
process.exitCode = 5
} else { state.app = true; save() }
})
break
case 'auth login --json':
line({ event: 'device_authorization', verification_uri_complete: '${SIGN_IN_URL}' })
visited('sign-in-visited', () => { state.user = true; save(); line({ event: 'authorization_complete', user_open_id: 'ou_e2e', missing: [] }) })
break
case 'auth logout --json': state.user = false; save(); line({ ok: true }); break
default:
process.stderr.write('unexpected lark-cli arguments: ' + process.argv.slice(2).join(' ') + '\\n')
process.exitCode = 1
}
`
// The stand-in runs through its shebang, which Windows cannot execute.
describe.skipIf(process.platform === 'win32')('web e2e: Feishu plugin connection', () => {
let binDir: string
let scaffold: WebScaffold
let browser: Browser
let context: BrowserContext
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
binDir = await mkdtemp(join(tmpdir(), 'dsh-feishu-e2e-'))
await writeFile(join(binDir, 'lark-cli'), LARK_CLI)
await chmod(join(binDir, 'lark-cli'), 0o755)
const overlay = join(binDir, 'feishu.overlay.yml')
await writeFile(overlay, `- id: feishu\n config:\n binDir: ${JSON.stringify(binDir)}\n`)
scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
profile: { packages: [{ dir: FEISHU_DIR, enabled: true }] },
})
browser = await chromium.launch()
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
for (const [url, marker] of [[SETUP_URL, 'setup-visited'], [SETUP_RETRY_URL, 'setup-visited'], [SIGN_IN_URL, 'sign-in-visited']] as const) {
await context.route(url, async (route) => {
await writeFile(join(binDir, marker), '')
await route.fulfill({ contentType: 'text/html; charset=utf-8', body: '<!doctype html><title>Feishu</title><p>Feishu stand-in page</p>' })
})
}
page = await context.newPage()
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
if (binDir !== undefined) await rm(binDir, { recursive: true, force: true })
})
it('reports failed local setup, then links an existing app, signs in, and signs out', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-feishu-connection'))
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const panel = page.locator('[data-plugin-panel]')
await panel.getByRole('button', { name: '查看 飞书插件', exact: true }).click({ timeout: 20_000 })
const section = panel.locator('[data-connector-account-key="@deepseek-ai/dsh-feishu"]')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
const opened: Page[] = []
context.on('page', (popup) => { opened.push(popup) })
await writeFile(join(binDir, 'setup-fails'), '')
await section.getByRole('button', { name: '关联飞书应用', exact: true }).click()
await section.getByRole('alert').waitFor({ timeout: 20_000 })
expect(await section.getAttribute('data-connector-account')).toBe('disconnected')
expect(await section.getByRole('alert').innerText()).toContain('config-init · exit 5')
expect(await section.getByRole('alert').innerText()).toContain('已有应用')
expect(await section.innerText()).not.toContain('fixture-secret')
expect(await section.innerText()).not.toContain('fixture-code')
expect(await section.innerText()).not.toContain('/private/user')
await expect(readFile(join(binDir, 'state.json'), 'utf8')).rejects.toMatchObject({ code: 'ENOENT' })
await rm(join(binDir, 'setup-fails'))
await rm(join(binDir, 'setup-visited'))
await section.getByRole('button', { name: '关联飞书应用', exact: true }).click()
await page.getByText('飞书应用已关联,下一步登录飞书账号', { exact: true }).waitFor({ timeout: 20_000 })
expect(opened.map(popup => popup.url())).toEqual([SETUP_URL, SETUP_RETRY_URL])
await section.getByRole('button', { name: '登录飞书账号', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
expect(opened.map(popup => popup.url())).toEqual([SETUP_URL, SETUP_RETRY_URL, SIGN_IN_URL])
await section.getByText('已登录为 测试用户。可以在对话中直接请 Agent 使用飞书。', { exact: true }).waitFor({ timeout: 10_000 })
await page.getByText('飞书已连接', { exact: true }).waitFor({ timeout: 10_000 })
await section.getByRole('button', { name: '退出登录', exact: true }).click()
await page.getByRole('dialog', { name: '退出飞书登录?' }).getByRole('button', { name: '退出登录', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
await page.getByText('已退出飞书登录', { exact: true }).waitFor({ timeout: 10_000 })
expect(tripwire.pageErrors).toEqual([])
})
})
+8
View File
@@ -1142,6 +1142,14 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
await captureStableAria(page, '[data-composer-input]', scaffold.workspaceCwd), MODE)
expect((await readPersistedEvents(scaffold, sessionId)).some(event => event.type === 'user/message'
&& event.data.content.some(block => block.type === 'text' && block.text.includes('## User Comment')))).toBe(false)
// Removing a reference card leaves its quote in the composer, and the notice's Undo puts the card back at its line.
const extra = local.locator('[data-forge-diff-file="src/extra.ts"]')
await extra.getByRole('button', { name: '评论 R1 的操作', exact: true }).click()
await page.getByRole('menuitem', { name: '移除', exact: true }).click()
await expect.poll(() => extra.locator('[data-forge-review-thread]').count()).toBe(0)
expect(await page.locator('[data-composer-input]').first().innerText()).toContain('请检查这项修改')
await page.getByRole('alert').filter({ hasText: '已移除' }).getByRole('button', { name: '撤销', exact: true }).click()
await extra.locator('[data-forge-review-thread="agent"]').getByText('请检查这项修改', { exact: true }).waitFor()
const reviewed = scaffold.whenTurnSettled()
await page.locator('[data-composer-input]').first().press('Enter')
await reviewed
+77
View File
@@ -0,0 +1,77 @@
// Web e2e scenario: connecting the Linear plugin from its page on the Plugins
// page. The section reads the MCP manager's real entry, the browser opens the
// loopback authorization server's page, the Host callback answers with its
// completion page, the connection reaches the manager, and sign-out returns the
// section to disconnected. Zero model calls.
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, BrowserContext, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { startLinearOAuthFixture, type LinearOAuthFixture } from './linear-oauth-fixture.ts'
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const LINEAR_DIR = fileURLToPath(new URL('../../../packages/connector/linear', import.meta.url))
describe('web e2e: Linear plugin connection', () => {
let fixture: LinearOAuthFixture
let overlayDir: string
let scaffold: WebScaffold
let browser: Browser
let context: BrowserContext
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
fixture = await startLinearOAuthFixture()
overlayDir = await mkdtemp(join(tmpdir(), 'dsh-linear-e2e-'))
const overlay = join(overlayDir, 'linear.overlay.yml')
await writeFile(overlay, `- id: linear\n config:\n url: ${fixture.origin}/mcp\n`)
scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
profile: { packages: [{ dir: LINEAR_DIR, enabled: true }] },
})
browser = await chromium.launch()
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
page = await context.newPage()
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
await fixture?.close()
if (overlayDir !== undefined) await rm(overlayDir, { recursive: true, force: true })
})
it('connects the account from the plugin page and signs out after confirmation', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-linear-connection'))
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const panel = page.locator('[data-plugin-panel]')
await panel.getByRole('button', { name: '查看 Linear 插件', exact: true }).click({ timeout: 20_000 })
const section = panel.locator('[data-connector-account]')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
const opened = context.waitForEvent('page')
await section.getByRole('button', { name: '连接 Linear', exact: true }).click()
const authorization = await opened
await expect.poll(async () => await authorization.locator('body').textContent(), { timeout: 20_000 })
.toContain('已收到授权。可以关闭此页,回到 DSH 查看连接结果。')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
await page.getByText('Linear 已连接', { exact: true }).waitFor({ timeout: 10_000 })
expect(fixture.authorizations()).toBe(1)
await authorization.close()
await section.getByRole('button', { name: '退出登录', exact: true }).click()
await page.getByRole('dialog', { name: '退出 Linear 登录?' }).getByRole('button', { name: '退出登录', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(tripwire.pageErrors).toEqual([])
expect(fixture.failures()).toEqual([])
})
})
+118
View File
@@ -0,0 +1,118 @@
/**
* Loopback stand-in for Linear's hosted MCP server: OAuth protected-resource
* and authorization-server metadata, dynamic client registration, an
* authorization endpoint that approves every request by redirecting straight
* back to the caller, a token endpoint, and a Streamable HTTP MCP endpoint
* that requires a bearer token this fixture issued and answers JSON-RPC with
* plain JSON. The `initialize`, `tools/list`, and `ping` answers are written
* by hand because `apps/web` carries no MCP SDK dependency; the scenario only
* needs the handshake and the tool listing to succeed.
*/
import { once } from 'node:events'
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
/** The running fixture and what the browser and Host asked of it. */
export interface LinearOAuthFixture {
/** `http://127.0.0.1:<port>`; the MCP endpoint is `<origin>/mcp`. */
readonly origin: string
/** Authorization pages the browser opened. */
authorizations(): number
/** Errors thrown while answering requests, each answered with a 500; the scenario expects none. */
failures(): readonly unknown[]
/** Stop listening and close open connections. */
close(): Promise<void>
}
/**
* Listen on an OS-assigned loopback port.
* @returns the running fixture.
*/
export async function startLinearOAuthFixture(): Promise<LinearOAuthFixture> {
let origin = '', authorizations = 0, tokens = 0, registrations = 0
const issued = new Set<string>()
const failures: unknown[] = []
const json =(response: ServerResponse, value: unknown, status = 200): void => {
response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(value))
}
async function text(request: IncomingMessage): Promise<string> {
const chunks: Buffer[] = []
for await (const chunk of request) {
if (!(chunk instanceof Uint8Array)) throw new Error('Expected request bytes')
chunks.push(Buffer.from(chunk))
}
return Buffer.concat(chunks).toString()
}
async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
const url = new URL(request.url!, origin)
if (url.pathname.startsWith('/.well-known/oauth-protected-resource')) {
json(response, { resource: origin + '/mcp', authorization_servers: [origin] })
} else if (url.pathname === '/.well-known/oauth-authorization-server') {
json(response, {
issuer: origin, authorization_endpoint: origin + '/authorize', token_endpoint: origin + '/token',
registration_endpoint: origin + '/register', response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'],
token_endpoint_auth_methods_supported: ['none'], authorization_response_iss_parameter_supported: true,
})
} else if (url.pathname === '/register') {
registrations++
const metadata = JSON.parse(await text(request)) as Record<string, unknown>
json(response, { ...metadata, client_id: 'linear-client-' + String(registrations), token_endpoint_auth_method: 'none' }, 201)
} else if (url.pathname === '/authorize') {
authorizations++
const callback = new URL(url.searchParams.get('redirect_uri')!)
callback.searchParams.set('code', 'linear-code-' + String(authorizations))
callback.searchParams.set('state', url.searchParams.get('state')!)
callback.searchParams.set('iss', origin)
response.writeHead(302, { location: callback.href }).end()
} else if (url.pathname === '/token') {
await text(request)
tokens++
const token = 'linear-access-' + String(tokens)
issued.add(token)
json(response, { access_token: token, refresh_token: 'linear-refresh-' + String(tokens), token_type: 'Bearer', expires_in: 3600 })
} else if (url.pathname === '/mcp') {
const token = request.headers.authorization?.replace(/^Bearer /u, '')
if (token === undefined || !issued.has(token)) {
response.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"` }).end()
} else await answerMcp(request, response)
} else response.writeHead(404).end()
}
async function answerMcp(request: IncomingMessage, response: ServerResponse): Promise<void> {
if (request.method !== 'POST') { response.writeHead(405).end(); return }
const message = JSON.parse(await text(request)) as { id?: number | string; method: string; params?: { protocolVersion?: string } }
if (message.id === undefined) { response.writeHead(202).end(); return }
const reply = (result: unknown): void => { json(response, { jsonrpc: '2.0', id: message.id, result }) }
switch (message.method) {
case 'initialize':
reply({ protocolVersion: message.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'linear-fixture', version: '1.0.0' } })
break
case 'tools/list':
reply({ tools: [{ name: 'linear-search', description: 'Search the fixture workspace.', inputSchema: { type: 'object', properties: {} } }] })
break
case 'ping': reply({}); break
default: json(response, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } })
}
}
const server = createServer((request, response) => {
handle(request, response).catch((error: unknown) => {
failures.push(error)
if (!response.headersSent) response.writeHead(500).end()
})
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('Linear OAuth fixture did not bind TCP')
origin = `http://127.0.0.1:${String(address.port)}`
return {
origin,
authorizations: () => authorizations,
failures: () => failures,
close: async () => {
await new Promise<void>((resolve, reject) => {
server.close((error) => { if (error === undefined) resolve(); else reject(error) })
server.closeAllConnections()
})
},
}
}
+76
View File
@@ -0,0 +1,76 @@
// Web e2e scenario: connecting the Notion plugin from its page on the Plugins
// page. The section reads the MCP manager's real entry, the browser opens the
// loopback authorization server's page, the Host callback answers with its
// completion page, the connection reaches the manager, and sign-out returns the
// section to disconnected. Zero model calls.
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, BrowserContext, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { startNotionOAuthFixture, type NotionOAuthFixture } from './notion-oauth-fixture.ts'
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const NOTION_DIR = fileURLToPath(new URL('../../../packages/connector/notion', import.meta.url))
describe('web e2e: Notion plugin connection', () => {
let fixture: NotionOAuthFixture
let overlayDir: string
let scaffold: WebScaffold
let browser: Browser
let context: BrowserContext
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
fixture = await startNotionOAuthFixture()
overlayDir = await mkdtemp(join(tmpdir(), 'dsh-notion-e2e-'))
const overlay = join(overlayDir, 'notion.overlay.yml')
await writeFile(overlay, `- id: notion\n config:\n url: ${fixture.origin}/mcp\n`)
scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
profile: { packages: [{ dir: NOTION_DIR, enabled: true }] },
})
browser = await chromium.launch()
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
page = await context.newPage()
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
await fixture?.close()
if (overlayDir !== undefined) await rm(overlayDir, { recursive: true, force: true })
})
it('connects the account from the plugin page and signs out after confirmation', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-notion-connection'))
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const panel = page.locator('[data-plugin-panel]')
await panel.getByRole('button', { name: '查看 Notion 插件', exact: true }).click({ timeout: 20_000 })
const section = panel.locator('[data-connector-account]')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
const opened = context.waitForEvent('page')
await section.getByRole('button', { name: '连接 Notion', exact: true }).click()
const authorization = await opened
await expect.poll(async () => await authorization.locator('body').textContent(), { timeout: 20_000 })
.toContain('已收到授权。可以关闭此页,回到 DSH 查看连接结果。')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
await page.getByText('Notion 已连接', { exact: true }).waitFor({ timeout: 10_000 })
expect(fixture.authorizations()).toBe(1)
await authorization.close()
await section.getByRole('button', { name: '退出登录', exact: true }).click()
await page.getByRole('dialog', { name: '退出 Notion 登录?' }).getByRole('button', { name: '退出登录', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(tripwire.pageErrors).toEqual([])
})
})
+104
View File
@@ -0,0 +1,104 @@
/**
* Loopback stand-in for Notion's hosted MCP server: OAuth protected-resource
* and authorization-server metadata, dynamic client registration, an
* authorization endpoint that approves every request by redirecting straight
* back to the caller, a token endpoint, and a Streamable HTTP MCP endpoint
* that requires the issued bearer token and answers JSON-RPC with plain JSON.
*/
import { once } from 'node:events'
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
/** The running fixture and what the browser and Host asked of it. */
export interface NotionOAuthFixture {
/** `http://127.0.0.1:<port>`; the MCP endpoint is `<origin>/mcp`. */
readonly origin: string
/** Authorization pages the browser opened. */
authorizations(): number
/** Stop listening and close open connections. */
close(): Promise<void>
}
/**
* Listen on an OS-assigned loopback port.
* @returns the running fixture.
*/
export async function startNotionOAuthFixture(): Promise<NotionOAuthFixture> {
let origin = '', authorizations = 0, tokens = 0, registrations = 0
const json = (response: ServerResponse, value: unknown, status = 200): void => {
response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(value))
}
async function text(request: IncomingMessage): Promise<string> {
const chunks: Buffer[] = []
for await (const chunk of request) {
if (!(chunk instanceof Uint8Array)) throw new Error('Expected request bytes')
chunks.push(Buffer.from(chunk))
}
return Buffer.concat(chunks).toString()
}
async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
const url = new URL(request.url!, origin)
if (url.pathname.startsWith('/.well-known/oauth-protected-resource')) {
json(response, { resource: origin + '/mcp', authorization_servers: [origin] })
} else if (url.pathname === '/.well-known/oauth-authorization-server') {
json(response, {
issuer: origin, authorization_endpoint: origin + '/authorize', token_endpoint: origin + '/token',
registration_endpoint: origin + '/register', response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'],
token_endpoint_auth_methods_supported: ['none'], authorization_response_iss_parameter_supported: true,
})
} else if (url.pathname === '/register') {
registrations++
const metadata = JSON.parse(await text(request)) as Record<string, unknown>
json(response, { ...metadata, client_id: 'notion-client-' + String(registrations), token_endpoint_auth_method: 'none' }, 201)
} else if (url.pathname === '/authorize') {
authorizations++
const callback = new URL(url.searchParams.get('redirect_uri')!)
callback.searchParams.set('code', 'notion-code-' + String(authorizations))
callback.searchParams.set('state', url.searchParams.get('state')!)
callback.searchParams.set('iss', origin)
response.writeHead(302, { location: callback.href }).end()
} else if (url.pathname === '/token') {
await text(request)
tokens++
json(response, { access_token: 'notion-access-' + String(tokens), refresh_token: 'notion-refresh-' + String(tokens), token_type: 'Bearer', expires_in: 3600 })
} else if (url.pathname === '/mcp') {
if (request.headers.authorization === undefined) {
response.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"` }).end()
} else await answerMcp(request, response)
} else response.writeHead(404).end()
}
async function answerMcp(request: IncomingMessage, response: ServerResponse): Promise<void> {
if (request.method !== 'POST') { response.writeHead(405).end(); return }
const message = JSON.parse(await text(request)) as { id?: number | string; method: string; params?: { protocolVersion?: string } }
if (message.id === undefined) { response.writeHead(202).end(); return }
const reply = (result: unknown): void => { json(response, { jsonrpc: '2.0', id: message.id, result }) }
switch (message.method) {
case 'initialize':
reply({ protocolVersion: message.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'notion-fixture', version: '1.0.0' } })
break
case 'tools/list':
reply({ tools: [{ name: 'notion-search', description: 'Search the fixture workspace.', inputSchema: { type: 'object', properties: {} } }] })
break
case 'ping': reply({}); break
default: json(response, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } })
}
}
const server = createServer((request, response) => {
handle(request, response).catch(() => { if (!response.headersSent) response.writeHead(500).end() })
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('Notion OAuth fixture did not bind TCP')
origin = `http://127.0.0.1:${String(address.port)}`
return {
origin,
authorizations: () => authorizations,
close: async () => {
await new Promise<void>((resolve, reject) => {
server.close((error) => { if (error === undefined) resolve(); else reject(error) })
server.closeAllConnections()
})
},
}
}
+29 -8
View File
@@ -167,18 +167,33 @@ describe('web e2e: plugin configuration pages', () => {
await expect.poll(() => page.getByRole('menuitem').count()).toBe(0)
return items
}
// The shipped composition selects the DeepSeek Search API and local fetch, and the page writes nothing on mount.
expect(await searchMenu.textContent()).toBe('DeepSeek Search API')
// The shipped composition selects no search provider and local fetch, and the page writes nothing on mount.
expect(await searchMenu.textContent()).toBe('自动选择')
expect(await fetchMenu.textContent()).toBe('本机直接获取')
expect(await panel.getByRole('button', { name: '网页搜索提供方 DeepSeek Search API', exact: true }).count()).toBe(1)
expect(await panel.getByRole('button', { name: '网页搜索提供方 自动选择', exact: true }).count()).toBe(1)
expect(await panel.getByRole('button', { name: '网页获取提供方 本机直接获取', exact: true }).count()).toBe(1)
expect(await entries(searchMenu)).toEqual(['DeepSeek Search API', 'DeepSeek(旧版)'])
expect(await entries(searchMenu)).toEqual(['自动选择', 'DeepSeek Search API', 'DeepSeek 服务端搜索'])
expect(await entries(fetchMenu)).toEqual(['本机直接获取', 'DeepSeek Fetch API'])
expect(await settingsDocument()).not.toContain('searchProvider:')
// The page fixes the menu order itself; the Loader imports plugins concurrently, so the
// Host's registration order is not the YAML row order and only its membership is checked here.
const hostWeb = scaffold.ctx.get('web') as { listProviders(): Record<'search' | 'fetch', { id: string }[]> } | undefined
expect(hostWeb?.listProviders().search.map(provider => provider.id).sort()).toEqual(['deepseek-official', 'deepseek-search-api'])
// Automatic selection states which provider the Host runs for each model and shows no provider panel.
expect(await searchSection.getByText(
'跟随当前会话的模型:DeepSeek 模型使用 DeepSeek 服务端搜索,搜索不按次收费;其他模型使用 DeepSeek Search API。', { exact: true },
).count()).toBe(1)
expect(await searchSection.getByRole('link', { name: '网页搜索与获取指南', exact: true }).getAttribute('href'))
.toBe('https://api-docs.deepseek.com/zh-cn/guides/search')
expect(await searchSection.getByRole('textbox').count()).toBe(0)
expect(await save.isDisabled()).toBe(true)
// The composition names no search provider, so a selected one is stored.
await choose(searchMenu, 'DeepSeek Search API')
await save.click()
await expect.poll(() => save.isDisabled()).toBe(true)
await expect.poll(settingsDocument).toContain('searchProvider: deepseek-search-api')
expect(await panel.getByRole('button', { name: '网页搜索提供方 DeepSeek Search API', exact: true }).count()).toBe(1)
expect(await panel.getByRole('link', { name: '网页搜索与获取指南', exact: true }).getAttribute('href'))
.toBe('https://api-docs.deepseek.com/zh-cn/guides/search')
// Each section shows the description its selected provider registered with the Host, in the active language.
@@ -230,7 +245,7 @@ describe('web e2e: plugin configuration pages', () => {
await expect.poll(() => save.isDisabled()).toBe(true)
await expect.poll(settingsDocument).not.toContain('fetchProvider: deepseek-fetch-api')
await choose(searchMenu, 'DeepSeek(旧版)')
await choose(searchMenu, 'DeepSeek 服务端搜索')
const messagesEndpoint = panel.locator('#plugin-config-web-search-endpoint')
expect(await panel.getByLabel('单次请求最多搜索次数', { exact: true }).inputValue()).toBe('5')
await messagesEndpoint.fill('https://messages.test/anthropic/v1')
@@ -241,17 +256,23 @@ describe('web e2e: plugin configuration pages', () => {
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
await openPlugins()
await openPage(panel, '网页搜索与获取')
expect(await searchMenu.textContent()).toBe('DeepSeek(旧版)')
expect(await searchMenu.textContent()).toBe('DeepSeek 服务端搜索')
expect(await messagesEndpoint.inputValue()).toBe('https://messages.test/anthropic/v1')
expect(await entries(searchMenu)).toEqual(['DeepSeek Search API', 'DeepSeek(旧版)'])
expect(await entries(searchMenu)).toEqual(['自动选择', 'DeepSeek Search API', 'DeepSeek 服务端搜索'])
expect(await save.isDisabled()).toBe(true)
expect(await settingsDocument()).toContain('searchProvider: deepseek-official')
await choose(searchMenu, 'DeepSeek Search API')
await count.fill('20')
await save.click()
await expect.poll(() => save.isDisabled()).toBe(true)
await expect.poll(settingsDocument).not.toContain('searchProvider:')
await expect.poll(settingsDocument).toContain('searchProvider: deepseek-search-api')
expect(await settingsDocument()).toContain('count: 20')
// Automatic selection clears the stored provider.
await choose(searchMenu, '自动选择')
await save.click()
await expect.poll(() => save.isDisabled()).toBe(true)
await expect.poll(settingsDocument).not.toContain('searchProvider:')
expect(await searchMenu.textContent()).toBe('自动选择')
expect(await settingsDocument()).not.toMatch(/ApiKeyEnv:|searchBaseURL:|fetchBaseURL:/)
expect(tripwire.pageErrors).toEqual([])
})
+7 -2
View File
@@ -23,6 +23,7 @@ import {
const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/plugin-manager', import.meta.url))
const MANAGER_EXPECTED = join(SNAPSHOT_DIR, 'manager.expected.md')
const TERMINAL_EXPECTED = join(SNAPSHOT_DIR, 'terminal.expected.md')
const LIVE_EXPECTED = join(SNAPSHOT_DIR, 'live-enabled.expected.md')
const EXPORTS_EXPECTED = join(SNAPSHOT_DIR, 'exports.expected.md')
const EXPORTS_EN_EXPECTED = join(SNAPSHOT_DIR, 'exports-en.expected.md')
@@ -849,7 +850,10 @@ describe('web e2e: plugin manager', () => {
expect(await panel.getByText(experimentalBundleDescription('inspector-profile', 'zh'), { exact: true }).count()).toBe(1)
const bundles = await scaffold.ctx.pluginManager.listBundles()
expect(bundles.some(bundle => bundle.name === '@deepseek-ai/dsh-experimental-terminal-bundle')).toBe(true)
expect(await panel.getByRole('switch', { name: '启用 持久终端', exact: true }).count()).toBe(0)
expect(await panel.getByRole('switch', { name: '启用 持久终端', exact: true }).getAttribute('aria-checked')).toBe('false')
await compareOrRefreshGolden(TERMINAL_EXPECTED, await captureStableAria(
page, '[data-plugin-group="more"] [data-plugin-package="@deepseek-ai/dsh-experimental-terminal-bundle"]', scaffold.workspaceCwd,
), MODE)
// The More list also omits LiveShare until its rows run, so the offered count is one lower than
// the eligible installed optional-bundle list.
expect(await panel.locator('[data-plugin-group="more"] [data-plugin-package="@deepseek-ai/dsh-experimental-liveshare"]').count()).toBe(0)
@@ -881,6 +885,7 @@ describe('web e2e: plugin manager', () => {
['@deepseek-ai/dsh-experimental-inspector-profile', 1],
...cuaSupported ? [['@deepseek-ai/dsh-cua-bundle', 1]] : [],
['@deepseek-ai/dsh-timeline', 1],
['@deepseek-ai/dsh-experimental-terminal-bundle', 1],
['@deepseek-ai/dsh-experimental-cot-translation-bundle', 1],
['@deepseek-ai/dsh-experimental-session-titles-bundle', 1],
['@deepseek-ai/dsh-experimental-badge-skill-bundle', 1],
@@ -1665,7 +1670,7 @@ describe('web e2e: plugin manager', () => {
it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
expect(tripwire.warnings).toEqual([])
await assertFixtureInventory(SNAPSHOT_DIR, [
'manager.expected.md', 'live-enabled.expected.md', 'missing-bundle.expected.md', 'exports.expected.md', 'exports-en.expected.md', 'icons.expected.md', 'loading.expected.md', 'refresh.expected.md',
'manager.expected.md', 'terminal.expected.md', 'live-enabled.expected.md', 'missing-bundle.expected.md', 'exports.expected.md', 'exports-en.expected.md', 'icons.expected.md', 'loading.expected.md', 'refresh.expected.md',
'ime-enter.expected.md', 'header-responsive.expected.md', 'header-natural-motion.expected.md', 'preview.expected.md',
'touch-tooltips.expected.md', 'forge-preview.expected.md', 'timeline-tracking.expected.md',
])
@@ -0,0 +1,6 @@
# The replayed conversation runs on a DeepSeek model route, where an unconfigured search selects
# legacy Messages search. This scenario exercises the DeepSeek Search API.
- id: web
config:
searchProvider: deepseek-search-api
fetchProvider: http
+10 -6
View File
@@ -89,17 +89,21 @@ describe('web e2e: session drag scrolling', () => {
// Drop onto a row that was out of view when the drag started.
const middle = (await listEdges()).top + 200
await page.mouse.move(x, middle, { steps: 3 })
await page.mouse.move(x + 1, middle)
await page.mouse.move(x, middle)
const target = await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)!
.closest('[role="treeitem"]')!.querySelector('[class*="title"]')!.textContent, { x, y: middle })
expect(target).toMatch(/^Conversation (\d{2}|[89])$/)
// The point can rest on the gap between rows while the drop indicator settles, so read again until it names a row.
let target = ''
await expect.poll(async () => {
await page.mouse.move(x + 1, middle)
await page.mouse.move(x, middle)
target = await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)
?.closest('[role="treeitem"]')?.querySelector('[class*="title"]')?.textContent ?? '', { x, y: middle })
return target
}, { timeout: 15_000 }).toMatch(/^Conversation (\d{2}|[89])$/)
await page.mouse.up()
const titles = () => rows.locator('[class*="title"]').allTextContents()
await expect.poll(async () => {
const order = await titles()
return Math.abs(order.indexOf('Conversation 0') - order.indexOf(target))
}).toBe(1)
}, { timeout: 10_000 }).toBe(1)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
})
+2 -1
View File
@@ -247,7 +247,7 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => {
expect(tripwire.pageErrors).toEqual([])
})
it('starts in the current directory while earlier terminals and sandbox roots stay independent', async () => {
it('starts in the current directory while earlier terminals keep theirs and the sandbox root follows the directory', async () => {
onTestFailed(() => saveFailureShot(page, 'sidebar-terminal-directory'))
const agent = scaffold.ctx.agents.list()[0]!
const directories = agent.ctx.get('workingDirectory')
@@ -262,6 +262,7 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => {
if (sandbox === undefined) throw new Error('Session sandbox provider is missing')
const confine = vi.spyOn(sandbox, 'confine')
const selected = await directories.set(agent, child)
expect(sandboxPolicy.resolve({ session: agent.session })).toEqual({ ...policy, workspaceRoot: selected })
await openTerminal(page)
const firstProcess = processIdentity(0)
@@ -0,0 +1,79 @@
// Web e2e scenario: connecting the Tencent Docs plugin from its page on the Plugins
// page. The section reads the MCP manager's real entry, the browser opens the
// loopback authorization server's page with the `docs:*` scopes and the
// endpoint's own query, the Host callback answers with its
// completion page, the connection reaches the manager, and sign-out returns the
// section to disconnected. Zero model calls.
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, BrowserContext, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { startTencentDocsOAuthFixture, type TencentDocsOAuthFixture } from './tencent-docs-oauth-fixture.ts'
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const TENCENT_DOCS_DIR = fileURLToPath(new URL('../../../packages/connector/tencent-docs', import.meta.url))
describe('web e2e: Tencent Docs plugin connection', () => {
let fixture: TencentDocsOAuthFixture
let overlayDir: string
let scaffold: WebScaffold
let browser: Browser
let context: BrowserContext
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
fixture = await startTencentDocsOAuthFixture()
overlayDir = await mkdtemp(join(tmpdir(), 'dsh-tencent-docs-e2e-'))
const overlay = join(overlayDir, 'tencent-docs.overlay.yml')
await writeFile(overlay, `- id: tencent-docs\n config:\n url: ${fixture.origin}/mcp\n`)
scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
profile: { packages: [{ dir: TENCENT_DOCS_DIR, enabled: true }] },
})
browser = await chromium.launch()
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
page = await context.newPage()
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
await fixture?.close()
if (overlayDir !== undefined) await rm(overlayDir, { recursive: true, force: true })
})
it('connects the account from the plugin page and signs out after confirmation', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-tencent-docs-connection'))
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const panel = page.locator('[data-plugin-panel]')
await panel.getByRole('button', { name: '查看 腾讯文档插件', exact: true }).click({ timeout: 20_000 })
const section = panel.locator('[data-connector-account]')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
const opened = context.waitForEvent('page')
await section.getByRole('button', { name: '连接腾讯文档', exact: true }).click()
const authorization = await opened
await expect.poll(async () => await authorization.locator('body').textContent(), { timeout: 20_000 })
.toContain('已收到授权。可以关闭此页,回到 DSH 查看连接结果。')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
await page.getByText('腾讯文档已连接', { exact: true }).waitFor({ timeout: 10_000 })
expect(fixture.authorizations()).toBe(1)
expect(fixture.authorizationQuery()?.get('authType')).toBe('2')
expect(fixture.authorizationQuery()?.get('scope')).toBe('docs:read docs:write docs:manage')
await authorization.close()
await section.getByRole('button', { name: '退出登录', exact: true }).click()
await page.getByRole('dialog', { name: '退出腾讯文档登录?' }).getByRole('button', { name: '退出登录', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(tripwire.pageErrors).toEqual([])
})
})
@@ -0,0 +1,113 @@
/**
* Loopback stand-in for Tencent Docs' hosted MCP server, laid out like the
* hosted metadata: the 401 challenge names protected-resource metadata under
* the MCP path, that metadata lists the `docs:*` scopes, and the
* authorization endpoint already carries a query string. Dynamic client
* registration, an authorization endpoint that approves every request by
* redirecting straight back without an `iss` parameter, a token endpoint, and
* a Streamable HTTP MCP endpoint that requires the issued bearer token and
* answers JSON-RPC with plain JSON complete the flow.
*/
import { once } from 'node:events'
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
const SCOPES = ['docs:read', 'docs:write', 'docs:manage']
/** The running fixture and what the browser and Host asked of it. */
export interface TencentDocsOAuthFixture {
/** `http://127.0.0.1:<port>`; the MCP endpoint is `<origin>/mcp`. */
readonly origin: string
/** Authorization pages the browser opened. */
authorizations(): number
/** Query of the latest authorization page the browser opened. */
authorizationQuery(): URLSearchParams | undefined
/** Stop listening and close open connections. */
close(): Promise<void>
}
/**
* Listen on an OS-assigned loopback port.
* @returns the running fixture.
*/
export async function startTencentDocsOAuthFixture(): Promise<TencentDocsOAuthFixture> {
let origin = '', authorizations = 0, tokens = 0, registrations = 0
let authorizationQuery: URLSearchParams | undefined
const json = (response: ServerResponse, value: unknown, status = 200): void => {
response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(value))
}
async function text(request: IncomingMessage): Promise<string> {
const chunks: Buffer[] = []
for await (const chunk of request) {
if (!(chunk instanceof Uint8Array)) throw new Error('Expected request bytes')
chunks.push(Buffer.from(chunk))
}
return Buffer.concat(chunks).toString()
}
async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
const url = new URL(request.url!, origin)
if (url.pathname === '/mcp/.well-known/oauth-protected-resource') {
json(response, { resource: origin + '/mcp', authorization_servers: [origin], scopes_supported: SCOPES, bearer_methods_supported: ['header'] })
} else if (url.pathname === '/.well-known/oauth-authorization-server') {
json(response, {
issuer: origin, authorization_endpoint: origin + '/authorize?authType=2', token_endpoint: origin + '/token',
registration_endpoint: origin + '/register', scopes_supported: SCOPES, response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'],
token_endpoint_auth_methods_supported: ['none'],
})
} else if (url.pathname === '/register') {
registrations++
const metadata = JSON.parse(await text(request)) as Record<string, unknown>
json(response, { ...metadata, client_id: 'tencent-docs-client-' + String(registrations), token_endpoint_auth_method: 'none' }, 201)
} else if (url.pathname === '/authorize') {
authorizations++
authorizationQuery = url.searchParams
const callback = new URL(url.searchParams.get('redirect_uri')!)
callback.searchParams.set('code', 'tencent-docs-code-' + String(authorizations))
callback.searchParams.set('state', url.searchParams.get('state')!)
response.writeHead(302, { location: callback.href }).end()
} else if (url.pathname === '/token') {
await text(request)
tokens++
json(response, { access_token: 'tencent-docs-access-' + String(tokens), refresh_token: 'tencent-docs-refresh-' + String(tokens), token_type: 'Bearer', expires_in: 31535999, scope: SCOPES.join(' ') })
} else if (url.pathname === '/mcp') {
if (request.headers.authorization === undefined) {
response.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${origin}/mcp/.well-known/oauth-protected-resource"` }).end()
} else await answerMcp(request, response)
} else response.writeHead(404).end()
}
async function answerMcp(request: IncomingMessage, response: ServerResponse): Promise<void> {
if (request.method !== 'POST') { response.writeHead(405).end(); return }
const message = JSON.parse(await text(request)) as { id?: number | string; method: string; params?: { protocolVersion?: string } }
if (message.id === undefined) { response.writeHead(202).end(); return }
const reply = (result: unknown): void => { json(response, { jsonrpc: '2.0', id: message.id, result }) }
switch (message.method) {
case 'initialize':
reply({ protocolVersion: message.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'tencent-docs-fixture', version: '1.0.0' } })
break
case 'tools/list':
reply({ tools: [{ name: 'search', description: 'Search the fixture documents.', inputSchema: { type: 'object', properties: {} } }] })
break
case 'ping': reply({}); break
default: json(response, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } })
}
}
const server = createServer((request, response) => {
handle(request, response).catch(() => { if (!response.headersSent) response.writeHead(500).end() })
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('Tencent Docs OAuth fixture did not bind TCP')
origin = `http://127.0.0.1:${String(address.port)}`
return {
origin,
authorizations: () => authorizations,
authorizationQuery: () => authorizationQuery,
close: async () => {
await new Promise<void>((resolve, reject) => {
server.close((error) => { if (error === undefined) resolve(); else reject(error) })
server.closeAllConnections()
})
},
}
}
@@ -0,0 +1,128 @@
// Tencent Meeting sign-in, failure, and sign-out through the real Host/Remote/browser composition.
// A stand-in CLI waits for each authorization page visit and keeps the sign-in on disk.
import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, BrowserContext, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const TENCENT_MEETING_DIR = fileURLToPath(new URL('../../../packages/connector/tencent-meeting', import.meta.url))
const AUTH_PAGE = 'https://meeting.tencent.com/marketplace/tencentmeeting-cli-auth.html'
const authUrl = (attempt: number) => `${AUTH_PAGE}?e2e=${String(attempt)}&code=fixture-code`
// The stand-in keeps its sign-in in state.json beside itself; auth login prints
// a new authorization link on its `authorize url:` line for each attempt and
// waits until the test marks the page visited.
const TMEET = `#!/usr/bin/env node
const { existsSync, readFileSync, writeFileSync } = require('node:fs')
const { join } = require('node:path')
const dir = __dirname
const statePath = join(dir, 'state.json')
const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { signedIn: false, attempts: 0 }
const save = () => { writeFileSync(statePath, JSON.stringify(state)) }
switch (process.argv.slice(2).join(' ')) {
case 'auth status':
process.stdout.write(state.signedIn
? 'Logged in\\n OpenId: ou_e2e\\n UserName: 测试用户\\n'
: "Not logged in. Please use 'tmeet auth login' to authenticate.\\n")
break
case 'auth login --no-browser': {
state.attempts += 1
save()
process.stdout.write('\\nPlease open the following URL in your browser to authorize\\n\\nauthorize url: ${AUTH_PAGE}?e2e=' + state.attempts + '&code=fixture-code\\n\\nwaiting for authorization...\\n')
const poll = setInterval(() => {
if (!existsSync(join(dir, 'auth-visited'))) return
clearInterval(poll)
if (existsSync(join(dir, 'login-fails'))) {
process.stderr.write('Error: authorization failed; code=fixture-code\\n')
process.exitCode = 1
} else {
state.signedIn = true
save()
process.stdout.write('Login successful. Start managing your meetings using tmeet.\\n')
}
}, 50)
break
}
case 'auth logout': state.signedIn = false; save(); process.stdout.write('Logout success, welcome to use it again.\\n'); break
default:
process.stderr.write('unexpected tmeet arguments: ' + process.argv.slice(2).join(' ') + '\\n')
process.exitCode = 1
}
`
// The stand-in runs through its shebang, which Windows cannot execute.
describe.skipIf(process.platform === 'win32')('web e2e: Tencent Meeting plugin account', () => {
let binDir: string
let scaffold: WebScaffold
let browser: Browser
let context: BrowserContext
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
binDir = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-e2e-'))
await writeFile(join(binDir, 'tmeet'), TMEET)
await chmod(join(binDir, 'tmeet'), 0o755)
await mkdir(join(binDir, 'skills'))
const overlay = join(binDir, 'tencent-meeting.overlay.yml')
await writeFile(overlay, `- id: tencent-meeting\n config:\n binDir: ${JSON.stringify(binDir)}\n skillsDir: ${JSON.stringify(join(binDir, 'skills'))}\n`)
scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
profile: { packages: [{ dir: TENCENT_MEETING_DIR, enabled: true }] },
})
browser = await chromium.launch()
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
await context.route(url => url.href.startsWith(AUTH_PAGE), async (route) => {
await writeFile(join(binDir, 'auth-visited'), '')
await route.fulfill({ contentType: 'text/html; charset=utf-8', body: '<!doctype html><title>Tencent Meeting</title><p>Tencent Meeting stand-in page</p>' })
})
page = await context.newPage()
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
if (binDir !== undefined) await rm(binDir, { recursive: true, force: true })
})
it('reports a failed sign-in without its output, signs in, and signs out after confirmation', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-tencent-meeting-connection'))
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const panel = page.locator('[data-plugin-panel]')
await panel.getByRole('button', { name: '查看 腾讯会议插件', exact: true }).click({ timeout: 20_000 })
const section = panel.locator('[data-connector-account-key="@deepseek-ai/dsh-tencent-meeting"]')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
const opened: Page[] = []
context.on('page', (popup) => { opened.push(popup) })
await writeFile(join(binDir, 'login-fails'), '')
await section.getByRole('button', { name: '连接腾讯会议', exact: true }).click()
await section.getByRole('alert').waitFor({ timeout: 20_000 })
expect(await section.getAttribute('data-connector-account')).toBe('disconnected')
expect(await section.getByRole('alert').innerText()).toContain('auth-login · exit 1')
expect(await section.innerText()).not.toContain('fixture-code')
await rm(join(binDir, 'login-fails'))
await rm(join(binDir, 'auth-visited'))
await section.getByRole('button', { name: '连接腾讯会议', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
expect(opened.map(popup => popup.url())).toEqual([authUrl(1), authUrl(2)])
await section.getByText('已登录为 测试用户。可以在对话中直接请 Agent 使用腾讯会议。', { exact: true }).waitFor({ timeout: 10_000 })
await page.getByText('腾讯会议已连接', { exact: true }).waitFor({ timeout: 10_000 })
await section.getByRole('button', { name: '退出登录', exact: true }).click()
await page.getByRole('dialog').getByRole('button', { name: '退出登录', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
await page.getByText('已退出腾讯会议登录', { exact: true }).waitFor({ timeout: 10_000 })
expect(tripwire.pageErrors).toEqual([])
})
})
+5 -4
View File
@@ -1,5 +1,5 @@
// Web e2e scenario for the shipped default search provider, the DeepSeek
// Search API, with no provider selection patched. A real browser drives
// Web e2e scenario for the DeepSeek Search API, selected for a conversation
// on a DeepSeek model route. A real browser drives
// `web_search`; the model stream is replayed while the real DeepSeek provider
// calls a deterministic local Search API endpoint through the real
// credentials service.
@@ -141,7 +141,7 @@ async function startSearchServer(captured: CapturedSearchRequest[]): Promise<{ s
return { server, baseURL: `http://127.0.0.1:${address.port}` }
}
describe('web e2e: default Search API web search', () => {
describe('web e2e: Search API web search', () => {
let scaffold: WebScaffold
let browser: Browser
let page: Page
@@ -154,7 +154,8 @@ describe('web e2e: default Search API web search', () => {
const search = await startSearchServer(searchRequests)
searchServer = search.server
scaffold = await launchWebScaffold({
extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
extraOverlayPath: ['./pin-browse-picker.overlay.yml', './search-api-provider.overlay.yml']
.map(path => fileURLToPath(new URL(path, import.meta.url))),
compareReplaySession: true,
// Own YAML endpoint settings pin Search to the local endpoint and a dedicated key.
deepSeekWebApi: {
+123
View File
@@ -0,0 +1,123 @@
// WeCom QR-code authorization failures and recovery through the real Host/Remote/browser composition.
// A stand-in CLI waits for each QR-code page visit and keeps the authorization on disk.
import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, BrowserContext, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const WECOM_DIR = fileURLToPath(new URL('../../../packages/connector/wecom', import.meta.url))
const QR_PAGE = 'https://work.weixin.qq.com/ai/qc/gen'
const qrUrl = (attempt: number) => `${QR_PAGE}?e2e=${String(attempt)}&scode=fixture-scode`
// The stand-in keeps its authorization in state.json beside itself; auth init
// prints a new QR-code link alone on its third stdout line for each attempt and
// waits until the test marks the page visited.
const WECOM_CLI = `#!/usr/bin/env node
const { existsSync, readFileSync, writeFileSync } = require('node:fs')
const { join } = require('node:path')
const dir = __dirname
const statePath = join(dir, 'state.json')
const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { authorized: false, attempts: 0, bots: 0 }
const save = () => { writeFileSync(statePath, JSON.stringify(state)) }
switch (process.argv.slice(2).join(' ')) {
case 'auth show': process.stdout.write(state.authorized ? 'Status: authorized\\nBot ID: bot-e2e-' + state.bots + '\\n' : 'Status: unauthorized\\n'); break
case 'auth init --noninteractive --no-browser': {
state.attempts += 1
save()
process.stdout.write('Scan the QR code with WeCom to bind a bot.\\nOpen this link if the QR code does not display:\\n${QR_PAGE}?e2e=' + state.attempts + '&scode=fixture-scode\\n')
const poll = setInterval(() => {
if (!existsSync(join(dir, 'qr-visited'))) return
clearInterval(poll)
if (existsSync(join(dir, 'init-fails'))) {
process.stdout.write('bind failed; scode=fixture-scode\\n')
process.exitCode = 4
} else { state.authorized = true; state.bots += 1; save() }
}, 50)
break
}
default:
process.stderr.write('unexpected wecom-cli arguments: ' + process.argv.slice(2).join(' ') + '\\n')
process.exitCode = 1
}
`
// The stand-in runs through its shebang, which Windows cannot execute.
describe.skipIf(process.platform === 'win32')('web e2e: WeCom plugin authorization', () => {
let binDir: string
let scaffold: WebScaffold
let browser: Browser
let context: BrowserContext
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
binDir = await mkdtemp(join(tmpdir(), 'dsh-wecom-e2e-'))
await writeFile(join(binDir, 'wecom-cli'), WECOM_CLI)
await chmod(join(binDir, 'wecom-cli'), 0o755)
await mkdir(join(binDir, 'skills'))
const overlay = join(binDir, 'wecom.overlay.yml')
await writeFile(overlay, `- id: wecom\n config:\n binDir: ${JSON.stringify(binDir)}\n skillsDir: ${JSON.stringify(join(binDir, 'skills'))}\n`)
scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
profile: { packages: [{ dir: WECOM_DIR, enabled: true }] },
})
browser = await chromium.launch()
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
await context.route(url => url.href.startsWith(QR_PAGE), async (route) => {
await writeFile(join(binDir, 'qr-visited'), '')
await route.fulfill({ contentType: 'text/html; charset=utf-8', body: '<!doctype html><title>WeCom</title><p>WeCom stand-in page</p>' })
})
page = await context.newPage()
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
if (binDir !== undefined) await rm(binDir, { recursive: true, force: true })
})
it('reports a failed QR-code authorization without its output, connects, and changes the bot after confirmation', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-wecom-connection'))
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const panel = page.locator('[data-plugin-panel]')
await panel.getByRole('button', { name: '查看 企业微信插件', exact: true }).click({ timeout: 20_000 })
const section = panel.locator('[data-connector-account-key="@deepseek-ai/dsh-wecom"]')
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
expect(await panel.locator('[data-plugin-detail]').getByText('未授权', { exact: true }).count()).toBe(2)
const opened: Page[] = []
context.on('page', (popup) => { opened.push(popup) })
await writeFile(join(binDir, 'init-fails'), '')
await section.getByRole('button', { name: '连接企业微信', exact: true }).click()
await section.getByRole('alert').waitFor({ timeout: 20_000 })
expect(await section.getAttribute('data-connector-account')).toBe('disconnected')
expect(await section.getByRole('alert').innerText()).toContain('auth-init · exit 4')
expect(await section.innerText()).not.toContain('fixture-scode')
await rm(join(binDir, 'init-fails'))
await rm(join(binDir, 'qr-visited'))
await section.getByRole('button', { name: '连接企业微信', exact: true }).click()
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
expect(opened.map(popup => popup.url())).toEqual([qrUrl(1), qrUrl(2)])
await section.getByText('可以在对话中直接请 Agent 使用企业微信。', { exact: true }).waitFor({ timeout: 10_000 })
await page.getByText('企业微信已授权', { exact: true }).waitFor({ timeout: 10_000 })
await section.getByText('已绑定机器人:bot-e2e-1', { exact: true }).waitFor({ timeout: 10_000 })
// Changing the bot asks first, then runs the same QR-code binding; the stand-in reports the next bot afterwards.
await rm(join(binDir, 'qr-visited'))
await section.getByRole('button', { name: '更换机器人', exact: true }).click()
await page.getByRole('dialog', { name: '更换机器人?' }).getByRole('button', { name: '更换机器人', exact: true }).click()
await section.getByText('已绑定机器人:bot-e2e-2', { exact: true }).waitFor({ timeout: 20_000 })
expect(await section.getAttribute('data-connector-account')).toBe('connected')
expect(opened.map(popup => popup.url())).toEqual([qrUrl(1), qrUrl(2), qrUrl(3)])
expect(tripwire.pageErrors).toEqual([])
})
})
+10 -1
View File
@@ -271,7 +271,16 @@
"tests/complex-history.perf.ts",
"tests/dingtalk-connection.e2e.ts",
"tests/pwsh-terminal.e2e.ts",
"tests/workflow-run.e2e.ts"
"tests/wecom-connection.e2e.ts",
"tests/tencent-meeting-connection.e2e.ts",
"tests/workflow-run.e2e.ts",
"tests/linear-connection.e2e.ts",
"tests/linear-oauth-fixture.ts",
"tests/notion-connection.e2e.ts",
"tests/notion-oauth-fixture.ts",
"tests/tencent-docs-connection.e2e.ts",
"tests/tencent-docs-oauth-fixture.ts",
"tests/feishu-connection.e2e.ts"
],
"references": [
{ "path": "../../packages/experimental/auto-review" },
+2 -2
View File
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
en: b8a43c17719d548b
zh: 3335f8c8fa696bae
en: e9a1a23c885fbae2
zh: 95137339b7fe8268
+17 -8
View File
@@ -62,6 +62,14 @@ flowchart LR
pkg_tool_pwsh["tool-pwsh"]
pkg_subagent["subagent"]
pkg_sdk_jsonrpc_server["sdk-jsonrpc-server"]
pkg_sandbox_policy["sandbox-policy"]
pkg_api_workspace_files["api-workspace-files"]
pkg_api_terminal_controller["api-terminal-controller"]
pkg_workspace_changes["workspace-changes"]
pkg_file_reference_local["file-reference-local"]
pkg_tool_skill["tool-skill"]
pkg_agent_instructions["agent-instructions"]
pkg_tool_lsp["tool-lsp"]
pkg_mcp_resources["mcp-resources"]
svc_mcpResources["ctx.mcpResources<br/>Scoped MCP resource access"]
pkg_mcp_client["mcp-client"]
@@ -123,11 +131,8 @@ flowchart LR
pkg_api_settings_controller["api-settings-controller"]
svc_credentialsController["ctx.credentialsController<br/>Host credential-surface Remote controller"]
svc_settingsController["ctx.settingsController<br/>Host settings-surface Remote controller"]
pkg_api_workspace_files["api-workspace-files"]
svc_workspaceFiles["ctx.workspaceFiles<br/>Host workspace file Remote service"]
pkg_workspace_changes["workspace-changes"]
svc_workspaceChanges["ctx.workspaceChanges<br/>Host per-turn changed-file summaries"]
pkg_api_terminal_controller["api-terminal-controller"]
svc_terminalController["ctx.terminalController<br/>Session interactive terminal Remote controller"]
pkg_api_workspace_controller["api-workspace-controller"]
svc_workspaceController["ctx.workspaceController<br/>Host Workspace Remote controller"]
@@ -187,7 +192,6 @@ flowchart LR
pkg_tool_session_query["tool-session-query"]
pkg_file_reference["file-reference"]
svc_fileReferences["ctx.fileReferences<br/>File reference discovery"]
pkg_file_reference_local["file-reference-local"]
svc_sessionReferenceResolver["ctx.sessionReferenceResolver<br/>Cross-session snapshot preparation"]
pkg_session_title["session-title"]
svc_sessionTitle["ctx.sessionTitle<br/>Log-backed session titles"]
@@ -201,7 +205,6 @@ flowchart LR
svc_tools["ctx.tools<br/>Scoped tool registry and executor selection"]
pkg_tool_ask_user["tool-ask-user"]
pkg_tool_cordis["tool-cordis"]
pkg_tool_skill["tool-skill"]
pkg_tool_todo["tool-todo"]
pkg_user_questions["user-questions"]
svc_userQuestions["ctx.userQuestions<br/>Human question/answer seam"]
@@ -264,7 +267,6 @@ flowchart LR
pkg_sandbox["sandbox"]
svc_sandbox["ctx.sandbox<br/>Process-sandbox seam"]
pkg_sandbox_local["sandbox-local"]
pkg_sandbox_policy["sandbox-policy"]
svc_sandboxPolicy["ctx.sandboxPolicy<br/>Sandbox policy home"]
pkg_fs_sandbox["fs-sandbox"]
pkg_user_approval["user-approval"]
@@ -331,7 +333,6 @@ flowchart LR
pkg_webhook_github["webhook-github"]
pkg_lsp["lsp"]
svc_lsp["ctx.lsp<br/>Language-server navigation seam"]
pkg_tool_lsp["tool-lsp"]
pkg_cordis_host_runner["cordis-host-runner"]
svc_dynamicCordisRunner["ctx.dynamicCordisRunner<br/>Dynamic Cordis package host runner"]
svc_cordisInspect["ctx.cordisInspect<br/>Dynamic Cordis inspect registry"]
@@ -681,11 +682,19 @@ flowchart LR
svc_webhookRuntime --> pkg_webhook_github
svc_workflowEngine --> pkg_tool_ralph
svc_workflowEngine --> pkg_tool_workflow
svc_workingDirectory --> pkg_agent_instructions
svc_workingDirectory --> pkg_api_terminal_controller
svc_workingDirectory --> pkg_api_workspace_files
svc_workingDirectory --> pkg_file_reference_local
svc_workingDirectory --> pkg_sandbox_policy
svc_workingDirectory --> pkg_sdk_jsonrpc_server
svc_workingDirectory --> pkg_subagent
svc_workingDirectory --> pkg_tool_bash
svc_workingDirectory --> pkg_tool_fs
svc_workingDirectory --> pkg_tool_lsp
svc_workingDirectory --> pkg_tool_pwsh
svc_workingDirectory --> pkg_tool_skill
svc_workingDirectory --> pkg_workspace_changes
svc_workspaceRegistry --> pkg_api_session_controller
svc_workspaceRegistry --> pkg_api_workspace_controller
svc_worktrees --> pkg_experimental_tool_worktree
@@ -713,7 +722,7 @@ flowchart LR
| `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | A Session projection derives bindings from shell results and binding records and publishes their URLs without status to clients; push results trigger head-branch discovery, and Session watchers poll bound change requests through the forge registry. |
| `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | Streams one panel state per followed Session: Git inspection using Session permissions, the recognized code host and its sign-in, and the bound change requests with polled status. |
| `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | Explicit experimental creation from a pinned local commit. Existing write permissions govern checkout and shared Git metadata; the working-directory service owns the resulting Session directory. |
| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | One Session projection owns the effective execution directory, which only Host operations move. The filesystem validates changes; user context reports them while original metadata and write grants stay fixed. |
| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`api-workspace-files`](../packages/api/workspace-files), [`api-terminal-controller`](../packages/api/terminal-controller), [`workspace-changes`](../packages/deliverables/workspace-changes), [`file-reference-local`](../packages/context/file-reference-local), [`tool-skill`](../packages/skill/tool-skill), [`agent-instructions`](../packages/context/agent-instructions), [`tool-lsp`](../packages/lsp/tool-lsp) | - | One Session projection owns the effective execution directory, which only Host operations move. The filesystem validates changes and user context reports them; model tools resolve paths from the directory, the sandbox boundary, file views, and discovery follow it, and original metadata stays fixed. |
| `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | Connection-owned providers serve shared resource tools in the calling agent scope. |
| `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | One provider-owned name per service instance. Providers own their tools and browser resources per live Session; the shared service has no browser operation API. |
| `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | One provider-owned name per service instance. Each provider also owns its model tools; the service has no common action API, runtime selection, or Session workflow lock. |
+17 -8
View File
@@ -64,6 +64,14 @@ flowchart LR
pkg_tool_pwsh["tool-pwsh"]
pkg_subagent["subagent"]
pkg_sdk_jsonrpc_server["sdk-jsonrpc-server"]
pkg_sandbox_policy["sandbox-policy"]
pkg_api_workspace_files["api-workspace-files"]
pkg_api_terminal_controller["api-terminal-controller"]
pkg_workspace_changes["workspace-changes"]
pkg_file_reference_local["file-reference-local"]
pkg_tool_skill["tool-skill"]
pkg_agent_instructions["agent-instructions"]
pkg_tool_lsp["tool-lsp"]
pkg_mcp_resources["mcp-resources"]
svc_mcpResources["ctx.mcpResources<br/>Scoped MCP resource access"]
pkg_mcp_client["mcp-client"]
@@ -125,11 +133,8 @@ flowchart LR
pkg_api_settings_controller["api-settings-controller"]
svc_credentialsController["ctx.credentialsController<br/>Host credential-surface Remote controller"]
svc_settingsController["ctx.settingsController<br/>Host settings-surface Remote controller"]
pkg_api_workspace_files["api-workspace-files"]
svc_workspaceFiles["ctx.workspaceFiles<br/>Host workspace file Remote service"]
pkg_workspace_changes["workspace-changes"]
svc_workspaceChanges["ctx.workspaceChanges<br/>Host per-turn changed-file summaries"]
pkg_api_terminal_controller["api-terminal-controller"]
svc_terminalController["ctx.terminalController<br/>Session interactive terminal Remote controller"]
pkg_api_workspace_controller["api-workspace-controller"]
svc_workspaceController["ctx.workspaceController<br/>Host Workspace Remote controller"]
@@ -189,7 +194,6 @@ flowchart LR
pkg_tool_session_query["tool-session-query"]
pkg_file_reference["file-reference"]
svc_fileReferences["ctx.fileReferences<br/>File reference discovery"]
pkg_file_reference_local["file-reference-local"]
svc_sessionReferenceResolver["ctx.sessionReferenceResolver<br/>Cross-session snapshot preparation"]
pkg_session_title["session-title"]
svc_sessionTitle["ctx.sessionTitle<br/>Log-backed session titles"]
@@ -203,7 +207,6 @@ flowchart LR
svc_tools["ctx.tools<br/>Scoped tool registry and executor selection"]
pkg_tool_ask_user["tool-ask-user"]
pkg_tool_cordis["tool-cordis"]
pkg_tool_skill["tool-skill"]
pkg_tool_todo["tool-todo"]
pkg_user_questions["user-questions"]
svc_userQuestions["ctx.userQuestions<br/>Human question/answer seam"]
@@ -266,7 +269,6 @@ flowchart LR
pkg_sandbox["sandbox"]
svc_sandbox["ctx.sandbox<br/>Process-sandbox seam"]
pkg_sandbox_local["sandbox-local"]
pkg_sandbox_policy["sandbox-policy"]
svc_sandboxPolicy["ctx.sandboxPolicy<br/>Sandbox policy home"]
pkg_fs_sandbox["fs-sandbox"]
pkg_user_approval["user-approval"]
@@ -333,7 +335,6 @@ flowchart LR
pkg_webhook_github["webhook-github"]
pkg_lsp["lsp"]
svc_lsp["ctx.lsp<br/>Language-server navigation seam"]
pkg_tool_lsp["tool-lsp"]
pkg_cordis_host_runner["cordis-host-runner"]
svc_dynamicCordisRunner["ctx.dynamicCordisRunner<br/>Dynamic Cordis package host runner"]
svc_cordisInspect["ctx.cordisInspect<br/>Dynamic Cordis inspect registry"]
@@ -683,11 +684,19 @@ flowchart LR
svc_webhookRuntime --> pkg_webhook_github
svc_workflowEngine --> pkg_tool_ralph
svc_workflowEngine --> pkg_tool_workflow
svc_workingDirectory --> pkg_agent_instructions
svc_workingDirectory --> pkg_api_terminal_controller
svc_workingDirectory --> pkg_api_workspace_files
svc_workingDirectory --> pkg_file_reference_local
svc_workingDirectory --> pkg_sandbox_policy
svc_workingDirectory --> pkg_sdk_jsonrpc_server
svc_workingDirectory --> pkg_subagent
svc_workingDirectory --> pkg_tool_bash
svc_workingDirectory --> pkg_tool_fs
svc_workingDirectory --> pkg_tool_lsp
svc_workingDirectory --> pkg_tool_pwsh
svc_workingDirectory --> pkg_tool_skill
svc_workingDirectory --> pkg_workspace_changes
svc_workspaceRegistry --> pkg_api_session_controller
svc_workspaceRegistry --> pkg_api_workspace_controller
svc_worktrees --> pkg_experimental_tool_worktree
@@ -715,7 +724,7 @@ flowchart LR
| `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Session 投影从 shell 结果与绑定记录派生绑定,并把不含状态的 URL 发布给客户端;推送结果触发按 head 分支的发现,Session 监听方通过 forge 注册表轮询已绑定的变更请求。 |
| `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | 为每个被跟随的 Session 推送一份面板状态:使用 Session 权限进行的 Git 检查、识别出的代码托管平台及其登录状态,以及带轮询状态的已绑定变更请求。 |
| `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | 显式实验组合从固定的本地提交创建工作树。检出目录与共享 Git 元数据受现有写权限约束;工作目录服务拥有创建后的 Session 目录。 |
| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | 两个 Session 投影拥有有效执行目录与工作区根;Host 操作让两者一起移动。文件系统验证变更,用户上下文报告目录信息,原始元数据与写入授权保持不变。 |
| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`api-workspace-files`](../packages/api/workspace-files), [`api-terminal-controller`](../packages/api/terminal-controller), [`workspace-changes`](../packages/deliverables/workspace-changes), [`file-reference-local`](../packages/context/file-reference-local), [`tool-skill`](../packages/skill/tool-skill), [`agent-instructions`](../packages/context/agent-instructions), [`tool-lsp`](../packages/lsp/tool-lsp) | - | 两个 Session 投影拥有有效执行目录与工作区根;Host 操作让两者一起移动。文件系统验证变更,用户上下文报告目录信息;模型工具从目录解析路径,沙箱边界、文件视图与发现跟随根,原始元数据保持不变。 |
| `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | 连接所有者提供的操作在调用 agent 的作用域内服务于共享资源工具。 |
| `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | 每个服务实例注册一个提供方拥有的名称。提供方按实时 Session 拥有自己的工具与浏览器资源;共享服务不提供浏览器操作 API。 |
| `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | 每个服务实例只注册一个提供方自定的名称。各提供方也拥有自己的模型工具;服务不提供通用操作 API、运行时选择或 Session 流程锁。 |
+136 -10
View File
@@ -357,7 +357,7 @@ export interface Config {
## `@deepseek-ai/dsh-api-workspace-files`
- `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert`
- `source`: [`packages/api/workspace-files/src/index.ts:74`](../packages/api/workspace-files/src/index.ts)
- `source`: [`packages/api/workspace-files/src/index.ts:100`](../packages/api/workspace-files/src/index.ts)
```ts config-catalog
/** Deployment caps on one page, one listing, or one search. */
@@ -1255,7 +1255,7 @@ export interface CotTranslationPreferences {
## `@deepseek-ai/dsh-experimental-client-ui-forge`
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts)
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:587`](../packages/experimental/client-ui-forge/src/types.ts)
```ts config-catalog
/** Host settings of the forge panel Remote. */
@@ -1310,6 +1310,14 @@ export interface Config {
maxCachedLensBytes?: number
/** Most line annotations a changes view shows in one file, across every annotation source. */
maxAnnotationsPerFile?: number
/** Milliseconds between two reads of the review page's lists while the page is open. */
reviewListIntervalMs?: number
/** Milliseconds between two reads of the review page's navigation count while it is shown. */
reviewCountIntervalMs?: number
/** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */
reviewMaxBackoffMs?: number
/** Most change requests one review page list shows, capped by each provider's own limit. */
reviewPageSize?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-client-ui-forge -->
@@ -1343,7 +1351,7 @@ export interface Config {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:638`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:767`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1388,6 +1396,8 @@ export interface Config {
maxCommits?: number
/** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
maxViewedFiles?: number
/** Most pull requests one viewer list read returns, at most 100, the size of one GitHub search page. */
maxViewerItems?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-forge-github -->
@@ -1681,6 +1691,23 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-worktree -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-feishu -->
<a id="deepseek-aidsh-feishu"></a>
## `@deepseek-ai/dsh-feishu`
- `inject`: `cliAccounts` · `skills`
- `source`: [`packages/connector/feishu/src/index.ts:30`](../packages/connector/feishu/src/index.ts)
```ts config-catalog
/** Where lark-cli is. */
export interface Config {
/** Absolute directory holding the `lark-cli` executable; defaults to the installed `@larksuite/cli` package. */
binDir?: string
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-feishu -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-file-reference-local -->
<a id="deepseek-aidsh-file-reference-local"></a>
@@ -2127,6 +2154,25 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-jobs-local -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-linear -->
<a id="deepseek-aidsh-linear"></a>
## `@deepseek-ai/dsh-linear`
- `inject`: `mcpManager` · `systemPrompt`
- `source`: [`packages/connector/linear/src/index.ts:29`](../packages/connector/linear/src/index.ts)
```ts config-catalog
/** Linear MCP endpoint and tool loading for the managed server entry. */
export interface Config {
/** Streamable HTTP MCP endpoint; defaults to Linear's hosted server. */
url: string
/** `on-demand` (default) keeps Linear's tools hidden from each agent until it loads them; `eager` sends all of them. */
toolLoading: 'eager' | 'on-demand'
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-linear -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-llm-deepseek-account -->
<a id="deepseek-aidsh-llm-deepseek-account"></a>
@@ -2776,6 +2822,25 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-message-feedback -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-notion -->
<a id="deepseek-aidsh-notion"></a>
## `@deepseek-ai/dsh-notion`
- `inject`: `mcpManager` · `systemPrompt`
- `source`: [`packages/connector/notion/src/index.ts:29`](../packages/connector/notion/src/index.ts)
```ts config-catalog
/** Notion MCP endpoint and tool loading for the managed server entry. */
export interface Config {
/** Streamable HTTP MCP endpoint; defaults to Notion's hosted server. */
url: string
/** `on-demand` (default) keeps Notion's tools hidden from each agent until it loads them; `eager` sends all of them. */
toolLoading: 'eager' | 'on-demand'
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-notion -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-office-kit -->
<a id="deepseek-aidsh-office-kit"></a>
@@ -3219,7 +3284,7 @@ export interface Config {
- `inject`: `sessionProjections`
- `refs`: [`SandboxMode`](subsystems/sandbox.md)
- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:95`](../packages/sandbox/sandbox-policy/src/index.ts)
- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:96`](../packages/sandbox/sandbox-policy/src/index.ts)
```ts config-catalog
/**
@@ -3233,8 +3298,9 @@ export interface Config {
/** File-sandbox mode a session starts from (default: `read-only`). */
mode?: SandboxMode
/**
* Absolute fallback root for agentless calls and sessions without a cwd (default:
* `process.cwd()`). Normal agent calls use their session cwd instead.
* Absolute fallback root for agentless calls and, without the working-directory
* service, sessions without a header directory (default: `process.cwd()`).
* Normal agent calls use their session's working directory instead.
*/
workspaceRoot?: string
/**
@@ -4159,6 +4225,44 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-system-prompt -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-tencent-docs -->
<a id="deepseek-aidsh-tencent-docs"></a>
## `@deepseek-ai/dsh-tencent-docs`
- `inject`: `mcpManager` · `systemPrompt`
- `source`: [`packages/connector/tencent-docs/src/index.ts:30`](../packages/connector/tencent-docs/src/index.ts)
```ts config-catalog
/** Tencent Docs MCP endpoint and tool loading for the managed server entry. */
export interface Config {
/** Streamable HTTP MCP endpoint; defaults to Tencent Docs' hosted server. */
url: string
/** `on-demand` (default) keeps Tencent Docs' tools hidden from each agent until it loads them; `eager` sends all of them. */
toolLoading: 'eager' | 'on-demand'
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-tencent-docs -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-tencent-meeting -->
<a id="deepseek-aidsh-tencent-meeting"></a>
## `@deepseek-ai/dsh-tencent-meeting`
- `inject`: `cliAccounts` · `upstreamSkills`
- `source`: [`packages/connector/tencent-meeting/src/index.ts:28`](../packages/connector/tencent-meeting/src/index.ts)
```ts config-catalog
/** Where tmeet and the upstream guide are. */
export interface Config {
/** Absolute directory holding the `tmeet` executable; defaults to the installed `@tencentcloud/tmeet` executable for this platform. */
binDir?: string
/** Absolute directory holding the upstream guide at its repository paths; when set, nothing is downloaded. */
skillsDir?: string
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-tencent-meeting -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-terminal-bash -->
<a id="deepseek-aidsh-terminal-bash"></a>
@@ -5053,7 +5157,7 @@ export interface Config {
## `@deepseek-ai/dsh-upstream-skills`
- `inject`: `skills`
- `source`: [`packages/connector/upstream-skills/src/index.ts:32`](../packages/connector/upstream-skills/src/index.ts)
- `source`: [`packages/connector/upstream-skills/src/index.ts:35`](../packages/connector/upstream-skills/src/index.ts)
```ts config-catalog
/** Where every registered plugin's upstream files are downloaded from. */
@@ -5106,7 +5210,7 @@ export type ApprovalPolicy = 'ask' | 'never'
## `@deepseek-ai/dsh-web`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/web/web/src/index.ts:62`](../packages/web/web/src/index.ts)
- `source`: [`packages/web/web/src/index.ts:77`](../packages/web/web/src/index.ts)
```ts config-catalog
/**
@@ -5118,7 +5222,10 @@ export type ApprovalPolicy = 'ask' | 'never'
* fields rather than introduce a hidden priority chain.
*/
export interface WebRuntimeConfig {
/** Explicit search provider id. Omitted = auto-select when exactly one usable. */
/**
* Explicit search provider id. Omitted = the usable DeepSeek provider assigned to the route of the model
* request, and otherwise auto-select when exactly one usable.
*/
readonly searchProvider: Volatile<string | undefined>
/** Explicit fetch provider id. Omitted = auto-select when exactly one usable. */
readonly fetchProvider: Volatile<string | undefined>
@@ -5289,6 +5396,25 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-webhook-github -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-wecom -->
<a id="deepseek-aidsh-wecom"></a>
## `@deepseek-ai/dsh-wecom`
- `inject`: `cliAccounts` · `upstreamSkills`
- `source`: [`packages/connector/wecom/src/index.ts:28`](../packages/connector/wecom/src/index.ts)
```ts config-catalog
/** Where wecom-cli and the upstream guides are. */
export interface Config {
/** Absolute directory holding the `wecom-cli` executable; defaults to the installed platform package of `@wecom/cli`. */
binDir?: string
/** Absolute directory holding the upstream guides at their repository paths; when set, nothing is downloaded. */
skillsDir?: string
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-wecom -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-workflow-ptc -->
<a id="deepseek-aidsh-workflow-ptc"></a>
@@ -5337,7 +5463,7 @@ export interface Config {
## `@deepseek-ai/dsh-workspace-changes`
- `inject`: `subprocess` · `fs`
- `source`: [`packages/deliverables/workspace-changes/src/index.ts:34`](../packages/deliverables/workspace-changes/src/index.ts)
- `source`: [`packages/deliverables/workspace-changes/src/index.ts:35`](../packages/deliverables/workspace-changes/src/index.ts)
```ts config-catalog
/** Snapshot, capture, and comparison bounds. Invalid values fail plugin load. */
+136 -10
View File
@@ -359,7 +359,7 @@ export interface Config {
## `@deepseek-ai/dsh-api-workspace-files`
- `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert`
- `source`: [`packages/api/workspace-files/src/index.ts:74`](../packages/api/workspace-files/src/index.ts)
- `source`: [`packages/api/workspace-files/src/index.ts:100`](../packages/api/workspace-files/src/index.ts)
```ts config-catalog
/** Deployment caps on one page, one listing, or one search. */
@@ -1257,7 +1257,7 @@ export interface CotTranslationPreferences {
## `@deepseek-ai/dsh-experimental-client-ui-forge`
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts)
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:587`](../packages/experimental/client-ui-forge/src/types.ts)
```ts config-catalog
/** Host settings of the forge panel Remote. */
@@ -1312,6 +1312,14 @@ export interface Config {
maxCachedLensBytes?: number
/** Most line annotations a changes view shows in one file, across every annotation source. */
maxAnnotationsPerFile?: number
/** Milliseconds between two reads of the review page's lists while the page is open. */
reviewListIntervalMs?: number
/** Milliseconds between two reads of the review page's navigation count while it is shown. */
reviewCountIntervalMs?: number
/** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */
reviewMaxBackoffMs?: number
/** Most change requests one review page list shows, capped by each provider's own limit. */
reviewPageSize?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-client-ui-forge -->
@@ -1345,7 +1353,7 @@ export interface Config {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:638`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:767`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1390,6 +1398,8 @@ export interface Config {
maxCommits?: number
/** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */
maxViewedFiles?: number
/** Most pull requests one viewer list read returns, at most 100, the size of one GitHub search page. */
maxViewerItems?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-forge-github -->
@@ -1683,6 +1693,23 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-experimental-worktree -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-feishu -->
<a id="deepseek-aidsh-feishu"></a>
## `@deepseek-ai/dsh-feishu`
- `inject`: `cliAccounts` · `skills`
- `source`: [`packages/connector/feishu/src/index.ts:30`](../packages/connector/feishu/src/index.ts)
```ts config-catalog
/** Where lark-cli is. */
export interface Config {
/** Absolute directory holding the `lark-cli` executable; defaults to the installed `@larksuite/cli` package. */
binDir?: string
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-feishu -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-file-reference-local -->
<a id="deepseek-aidsh-file-reference-local"></a>
@@ -2129,6 +2156,25 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-jobs-local -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-linear -->
<a id="deepseek-aidsh-linear"></a>
## `@deepseek-ai/dsh-linear`
- `inject`: `mcpManager` · `systemPrompt`
- `source`: [`packages/connector/linear/src/index.ts:29`](../packages/connector/linear/src/index.ts)
```ts config-catalog
/** Linear MCP endpoint and tool loading for the managed server entry. */
export interface Config {
/** Streamable HTTP MCP endpoint; defaults to Linear's hosted server. */
url: string
/** `on-demand` (default) keeps Linear's tools hidden from each agent until it loads them; `eager` sends all of them. */
toolLoading: 'eager' | 'on-demand'
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-linear -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-llm-deepseek-account -->
<a id="deepseek-aidsh-llm-deepseek-account"></a>
@@ -2778,6 +2824,25 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-message-feedback -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-notion -->
<a id="deepseek-aidsh-notion"></a>
## `@deepseek-ai/dsh-notion`
- `inject`: `mcpManager` · `systemPrompt`
- `source`: [`packages/connector/notion/src/index.ts:29`](../packages/connector/notion/src/index.ts)
```ts config-catalog
/** Notion MCP endpoint and tool loading for the managed server entry. */
export interface Config {
/** Streamable HTTP MCP endpoint; defaults to Notion's hosted server. */
url: string
/** `on-demand` (default) keeps Notion's tools hidden from each agent until it loads them; `eager` sends all of them. */
toolLoading: 'eager' | 'on-demand'
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-notion -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-office-kit -->
<a id="deepseek-aidsh-office-kit"></a>
@@ -3221,7 +3286,7 @@ export interface Config {
- `inject`: `sessionProjections`
- `refs`: [`SandboxMode`](subsystems/sandbox.zh.md)
- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:95`](../packages/sandbox/sandbox-policy/src/index.ts)
- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:96`](../packages/sandbox/sandbox-policy/src/index.ts)
```ts config-catalog
/**
@@ -3235,8 +3300,9 @@ export interface Config {
/** File-sandbox mode a session starts from (default: `read-only`). */
mode?: SandboxMode
/**
* Absolute fallback root for agentless calls and sessions without a cwd (default:
* `process.cwd()`). Normal agent calls use their session cwd instead.
* Absolute fallback root for agentless calls and, without the working-directory
* service, sessions without a header directory (default: `process.cwd()`).
* Normal agent calls use their session's working directory instead.
*/
workspaceRoot?: string
/**
@@ -4161,6 +4227,44 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-system-prompt -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-tencent-docs -->
<a id="deepseek-aidsh-tencent-docs"></a>
## `@deepseek-ai/dsh-tencent-docs`
- `inject`: `mcpManager` · `systemPrompt`
- `source`: [`packages/connector/tencent-docs/src/index.ts:30`](../packages/connector/tencent-docs/src/index.ts)
```ts config-catalog
/** Tencent Docs MCP endpoint and tool loading for the managed server entry. */
export interface Config {
/** Streamable HTTP MCP endpoint; defaults to Tencent Docs' hosted server. */
url: string
/** `on-demand` (default) keeps Tencent Docs' tools hidden from each agent until it loads them; `eager` sends all of them. */
toolLoading: 'eager' | 'on-demand'
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-tencent-docs -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-tencent-meeting -->
<a id="deepseek-aidsh-tencent-meeting"></a>
## `@deepseek-ai/dsh-tencent-meeting`
- `inject`: `cliAccounts` · `upstreamSkills`
- `source`: [`packages/connector/tencent-meeting/src/index.ts:28`](../packages/connector/tencent-meeting/src/index.ts)
```ts config-catalog
/** Where tmeet and the upstream guide are. */
export interface Config {
/** Absolute directory holding the `tmeet` executable; defaults to the installed `@tencentcloud/tmeet` executable for this platform. */
binDir?: string
/** Absolute directory holding the upstream guide at its repository paths; when set, nothing is downloaded. */
skillsDir?: string
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-tencent-meeting -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-terminal-bash -->
<a id="deepseek-aidsh-terminal-bash"></a>
@@ -5055,7 +5159,7 @@ export interface Config {
## `@deepseek-ai/dsh-upstream-skills`
- `inject`: `skills`
- `source`: [`packages/connector/upstream-skills/src/index.ts:32`](../packages/connector/upstream-skills/src/index.ts)
- `source`: [`packages/connector/upstream-skills/src/index.ts:35`](../packages/connector/upstream-skills/src/index.ts)
```ts config-catalog
/** Where every registered plugin's upstream files are downloaded from. */
@@ -5108,7 +5212,7 @@ export type ApprovalPolicy = 'ask' | 'never'
## `@deepseek-ai/dsh-web`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/web/web/src/index.ts:62`](../packages/web/web/src/index.ts)
- `source`: [`packages/web/web/src/index.ts:77`](../packages/web/web/src/index.ts)
```ts config-catalog
/**
@@ -5120,7 +5224,10 @@ export type ApprovalPolicy = 'ask' | 'never'
* fields rather than introduce a hidden priority chain.
*/
export interface WebRuntimeConfig {
/** Explicit search provider id. Omitted = auto-select when exactly one usable. */
/**
* Explicit search provider id. Omitted = the usable DeepSeek provider assigned to the route of the model
* request, and otherwise auto-select when exactly one usable.
*/
readonly searchProvider: Volatile<string | undefined>
/** Explicit fetch provider id. Omitted = auto-select when exactly one usable. */
readonly fetchProvider: Volatile<string | undefined>
@@ -5291,6 +5398,25 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-webhook-github -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-wecom -->
<a id="deepseek-aidsh-wecom"></a>
## `@deepseek-ai/dsh-wecom`
- `inject`: `cliAccounts` · `upstreamSkills`
- `source`: [`packages/connector/wecom/src/index.ts:28`](../packages/connector/wecom/src/index.ts)
```ts config-catalog
/** Where wecom-cli and the upstream guides are. */
export interface Config {
/** Absolute directory holding the `wecom-cli` executable; defaults to the installed platform package of `@wecom/cli`. */
binDir?: string
/** Absolute directory holding the upstream guides at their repository paths; when set, nothing is downloaded. */
skillsDir?: string
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-wecom -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-workflow-ptc -->
<a id="deepseek-aidsh-workflow-ptc"></a>
@@ -5339,7 +5465,7 @@ export interface Config {
## `@deepseek-ai/dsh-workspace-changes`
- `inject`: `subprocess` · `fs`
- `source`: [`packages/deliverables/workspace-changes/src/index.ts:34`](../packages/deliverables/workspace-changes/src/index.ts)
- `source`: [`packages/deliverables/workspace-changes/src/index.ts:35`](../packages/deliverables/workspace-changes/src/index.ts)
```ts config-catalog
/** Snapshot, capture, and comparison bounds. Invalid values fail plugin load. */
Loaded 100 of 1227 files, more files were not shown because too many files have changed in this diff. Show more