Merge master into plugin installation recovery

This commit is contained in:
ZiyaZhang committed 2026-09-22 08:03:27 -07:00
commit 4bf9d2e0c0
123 files changed
+2698 -364

No files matched your search

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-15-desktop-native-fatal-recovery.md
2026-09-15-desktop-native-fatal-recovery.md: 94ead425f5483ba3e6ed5d9d595edb4483254c27
2026-09-15-desktop-native-fatal-recovery.zh.md: 2138fb11405d00d51775350bf60d2702621aaa19
2026-09-15-desktop-native-fatal-recovery.md: fc1564b02e2f7b707d2b6f6d8e0947b1a78f142d
2026-09-15-desktop-native-fatal-recovery.zh.md: ceda54b4141c5fe58e6b385c86e6c1e4958dd261
@@ -12,7 +12,7 @@ A recovery document depends on the renderer and preload whose failure can preven
Electron owns one native fatal dialog per application process. Explicit main-window creation, document-load, preload, renderer, Web initialization, and backend failures enter this path. Ordinary requests retain local error handling, and the shared Web plugin manager owns package-operation failures. Expected cancellation and shutdown do not enter recovery. No elapsed-time heuristic classifies a slow startup as fatal.
The first report claims presentation before awaiting the dialog. Later reports remain in logs. The Electron console retains the complete reported diagnostic. The dialog bounds the first diagnostic to its final eight lines and limits the complete detail to 1,200 UTF-16 code units, including truncation notice and reinstall advice, because native dialogs cannot scroll. The dialog offers exit, restart, or disabling third-party bundles followed by a whole-application restart. Recovery calls the shared app-boot `sanitizeProfile` function under the existing profile lock after Host shutdown. The function restores caller-supplied bundles and renames the profile patch to a unique backup without parsing it, requiring runtime initialization, or deleting installed files. Callers own profile shutdown and write exclusion; Desktop is the current production caller. The home-level patch remains unchanged. An explicit recovery-operation failure is presented separately and does not count as another automatic fatal report.
The first report claims presentation before awaiting the dialog. Later reports remain in logs. A crash report file under the application logs directory retains the complete reported diagnostic, and the dialog names it on its own line ([fatal diagnostics and crash reports](2026-09-22-fatal-diagnostics-and-crash-reports.md)). The dialog bounds the first diagnostic to its final eight lines and limits the complete detail to 1,200 UTF-16 code units, including truncation notice, report path, and reinstall advice, because native dialogs cannot scroll. The dialog offers exit, restart, or disabling third-party bundles followed by a whole-application restart. Recovery calls the shared app-boot `sanitizeProfile` function under the existing profile lock after Host shutdown. The function restores caller-supplied bundles and renames the profile patch to a unique backup without parsing it, requiring runtime initialization, or deleting installed files. Callers own profile shutdown and write exclusion; Desktop is the current production caller. The home-level patch remains unchanged. An explicit recovery-operation failure is presented separately and does not count as another automatic fatal report.
The Web document stays in place. A carrier callback owns startup failure presentation while the shared boot page retains its spinner; ordinary browser boot still renders its own failure report. Only the primary application frame may report a Web boot failure. Backend state remains in the main process, and native recovery directly owns disabling all third-party bundles. Desktop has no profile reset or emergency recovery document. A fatal backend failure requires one of the native recovery actions rather than an in-process retry.
@@ -12,7 +12,7 @@ Status: implemented
Electron 在每个应用进程中提供一次原生致命错误对话框。明确的主窗口创建、文档加载、preload、渲染器、Web 初始化和后端失败进入此路径。普通请求保留局部错误处理,共享 Web 插件管理器负责包操作失败。预期取消和关闭不进入恢复。不通过耗时推断慢启动为致命故障。
首次报告在等待对话框前取得展示权。后续报告保留在日志中。Electron 控制台保留完整的已报告诊断。原生对话框无法滚动,因此仅显示首次诊断末尾八行,并将包含截断提示和重装建议的完整详情限制为 1,200 个 UTF-16 代码单元。对话框提供退出、重启或禁用第三方 bundle 后重启整个应用。恢复操作等待 Host 关闭后,在已有 profile 锁内调用共享 app-boot `sanitizeProfile` 函数。该函数恢复调用方指定的 bundle,并将 profile patch 重命名为唯一备份,无需解析 patch、初始化运行时或删除安装文件。调用方负责 profile 关闭并排除并发写入;当前生产调用方是 Desktop。home 级 patch 保持不变。显式恢复操作失败会单独展示,不计为另一次自动致命报告。
首次报告在等待对话框前取得展示权。后续报告保留在日志中。应用日志目录下的崩溃报告文件保留完整的已报告诊断,对话框单独一行标明该文件([致命诊断与崩溃报告](2026-09-22-fatal-diagnostics-and-crash-reports.zh.md))。原生对话框无法滚动,因此仅显示首次诊断末尾八行,并将包含截断提示、报告路径和重装建议的完整详情限制为 1,200 个 UTF-16 代码单元。对话框提供退出、重启或禁用第三方 bundle 后重启整个应用。恢复操作等待 Host 关闭后,在已有 profile 锁内调用共享 app-boot `sanitizeProfile` 函数。该函数恢复调用方指定的 bundle,并将 profile patch 重命名为唯一备份,无需解析 patch、初始化运行时或删除安装文件。调用方负责 profile 关闭并排除并发写入;当前生产调用方是 Desktop。home 级 patch 保持不变。显式恢复操作失败会单独展示,不计为另一次自动致命报告。
Web 文档保留在原位。宿主回调负责启动失败展示,共享启动页保留加载动画;普通浏览器启动仍显示自身的失败报告。只有主应用框架可以上报 Web 启动失败。后端状态保留在主进程中,原生恢复直接负责禁用全部第三方 bundle。Desktop 不提供 profile 重置或应急恢复文档。后端致命故障必须通过原生恢复操作处理,不在当前进程中重试。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-22-fatal-diagnostics-and-crash-reports.md
2026-09-22-fatal-diagnostics-and-crash-reports.md: 01cbb24fc84b19465a15e9f82c03ae87621b5fe9
2026-09-22-fatal-diagnostics-and-crash-reports.zh.md: 38f6a6802b61b128ab6b8ffda0465691c5244523
@@ -0,0 +1,61 @@
# Agent Note: Fatal diagnostics and Desktop crash reports
Status: implemented
English | [中文](2026-09-22-fatal-diagnostics-and-crash-reports.zh.md)
## Problem
Two field failures of the Desktop application were diagnosed from screenshots of the fatal recovery dialog, which shows the last eight lines of the error and used to promise that the full diagnostic was in the Electron console. A packaged installation never surfaces that console.
On Windows, `OutputCollector.spillAll` in `dsh-subprocess-local` opened its spill file inside the child's stdout `'data'` listener. The `openSync` with `'wx'` threw `ENOENT`, which for that flag means the private per-process spill directory was gone (it is created once and never recreated; what removed it was not observed), and because no process-level handler existed the Desktop Host died with Node's default uncaught-exception output. The `path:` property happened to land in the eight visible lines; nothing else about the failure was recoverable.
On macOS, the boot audit listed a set of Web client rows as `import failed (see console for the import error)` while the real import error stayed in the renderer console. The eight visible names match exactly the rows that depend on one application batch, so a single failed load of that batch script explains the screenshot; whether the failure was a transport error, a stale-URL 404, or a truncated response was not determinable. A batch was requested exactly once, so any transient failure was final.
Both cases shared three gaps: fatal diagnostics were not persisted, the Host had no `uncaughtException` policy, and a single fallible step was allowed to fail a whole feature.
## Decision
Four decisions ship together.
**Uncaught exceptions are fatal and reported; the failed operation is never resumed.** `installFailLoud` in `dsh-app-boot` registers the same handler for `'uncaughtException'` as for `'unhandledRejection'`: write one labelled `util.inspect` diagnostic to stderr, await the surface's release hook under the existing timeout, exit 1. Control never returns to the failed operation and the event loop runs only until the release settles or times out, because only the throw site knows which state is intact; a `'data'` listener that threw mid-update has already dropped a chunk and half-set its own fields, and resuming would turn a visible crash into silently wrong output. `util.inspect` replaces `err.stack` because a `node:fs` error's `code`, `syscall`, and `path`, and any `cause` chain, are enumerable properties the stack line omits. The rejection label `fatal load failure` is unchanged because the Web profile expected-output e2e tests match it; exceptions use `fatal uncaught exception`.
**Spill files are best-effort at every step.** `spillPath` was already optional and a failed final close already withheld it. `spillAll` now contains every filesystem failure while opening or appending: it discards the spill, reports once through the owner's logger (`SpillOptions.onFailure`, wired to `ctx.logger.error` by the runtime and the SSH helper), and leaves the in-memory tail collecting. The removed directory is not recreated: the security of the design rests on a random name created once by this process, and recreating a known name would give that up. A fresh random directory on `ENOENT` is deferred work.
**A fatal Desktop failure writes a crash report before its dialog.** Every `reportFatal` caller names its source (`host`, `web-boot`, `renderer`, `main`). `DesktopFatalRecovery.report` awaits `writeCrashReport` for at most one second, then shows the dialog with the file path on its own line, independent of whether the error was shortened and in the listener-conflict variant too. The report holds the source, whether the backend had reached ready, application and runtime versions, the complete inspected error (the backend state carries the original failure object, and a Host startup failure carries the Host's own inspected error over the fatal IPC event, because the Host's stderr and that message race and the shell reports the first failure it sees), and the primary window's recent error-level console output captured from `webContents` `'console-message'` (a 64 KiB tail). Reports live under `app.getPath('logs')`, are owner-only where the platform allows, and startup keeps the ten newest. A fatal failure during shutdown writes a report without a dialog. Buttons and recovery actions are unchanged.
**A failed batch script is a per-row problem, not a boot failure.** In `ClientModuleSystem.arrive`, a transport failure (the script `error` event; nothing executed) is retried once on the same URL, shared by every row waiting on that batch. A script that loaded without registering a row is never re-executed: the batch registers packages in sequence and `register()` rejects duplicates, so a replay would stop at the first package the original run did register. Every executed batch URL is remembered, so this holds even when the first importer from the batch was a row it did register and a later row finds itself missing. Either way each still-missing row then loads its own one-resource combo URL, which the Host serves for every package; a failed batch URL is remembered so later rows skip to their fallback, while a one-resource URL stays retryable across imports (within one boot the Loader imports each entry once, so a missing row gets one fallback attempt). Dependency failures are wrapped with the consumer and dependency names. The module system records the last `import()` or `prefetch()` failure per row at the outer operation, so factory execution errors are captured as well as arrival errors, and `assertEntriesActive` reports that text per fiberless entry.
## Relationship to earlier decisions
This partially supersedes the [native Desktop fatal recovery](2026-09-15-desktop-native-fatal-recovery.md) note: the crash report file, not the Electron console, is now the record the dialog points to, and the dialog detail carries the report-path line; that note's dialog ownership, button set, and profile recovery remain active. The `uncaughtException` handling extends the release mechanism of the [fail-loud release](../bug-fix/2026-07-31-fail-loud-releases-the-terminal.md) note to synchronous throws.
## Relationship to the Desktop logging design
The Desktop local logging design (a Worker-owned rolling JSONL log with a closed event vocabulary, redaction, and rate limits) is a continuous-log design and remains future work. It stated that Host stderr and renderer console output are never persisted and that errors reach the log only as fixed categories. This decision carves out one exception: the one-time crash report of a fatal failure keeps the raw error and the retained stderr and console tails, because that raw content is what both field diagnoses needed and the report is bounded (the error section is cut at 256 KiB, the Host diagnostic at 64 KiB, the renderer console tail at 64 KiB), local, owner-only, and written only when the application is already showing its fatal dialog. The dialog names the file so a user knows what they would be sharing. The continuous-log privacy posture is unchanged for anything that is not a crash report.
## Testing
- `dsh-app-boot`: uncaught exceptions produce the labelled diagnostic with enumerable properties and the cause chain, share the exit latch and release timeout with rejections, and both handlers uninstall.
- `dsh-subprocess-local`: `ENOENT` on open (removed directory), `ENOTDIR` on open, and `ENOSPC` on append after the file exists each leave the tail byte-exact, withdraw the spill file, report once, and never throw.
- `dsh-client-modules`: a transport failure retries once and shares the retry; a persistent failure falls back per missing row without re-fetching the batch per row; a batch that registered nothing or only some rows is not re-executed; a one-resource URL stays retryable; the final error lists every attempt; import errors are recorded for transport, factory, and dependency failures and cleared by success and invalidation.
- `dsh-client-web`: the boot audit names the recorded import error when the module system is supplied.
- Desktop: `crash-report` unit tests cover rendering, owner-only writing, write failure, pruning that leaves other files alone, and the console tail; `fatal-recovery` tests pin the dialog text with and without a report path in both locales, the one-second bound, and a single write per fatal; the startup harness asserts the report input for a running-phase Host exit including the captured renderer console.
## Consequences
The Host now exits through one path for both failure kinds, up to the release timeout later than Node's immediate default exit, so a fatal dialog can appear up to two seconds after the failure, and plugin stderr written during that release window can push the fail-loud line out of the dialog's eight-line excerpt (the report file keeps the 64 KiB tail). Spill failures are no longer visible to the user beyond a truncated result with no path; the plugin logger line is the only trace, which the Host-side continuous log design would persist. Crash reports persist raw stderr and console tails, accepted for the reasons above. A batch load failure now costs up to three requests per missing row and never fails registered rows; the shared-batch memory means a later import of a row from a failed batch goes straight to its one-resource URL for the life of the page.
## Alternatives considered
**Catch the uncaught exception and keep the Host running.** Rejected: the state after a listener throws is unknown to anything but the throw site. In the Windows case, continuing would have dropped the chunk, advertised a spill path to a file that did not exist, and thrown again on every following chunk.
**Recreate the spill directory on `ENOENT`.** Rejected for this change: recreating a known name gives up the random-directory property the design exists for. A fresh `mkdtemp` on failure needs the collector to hold a directory provider rather than a string and is deferred.
**Write the crash report synchronously so the dialog stays synchronous.** Rejected: a hung write on a slow or network-mounted profile directory would freeze the shell with no dialog at all. The asynchronous write with a one-second bound shows the dialog either way.
**Persist only classified error categories in the crash report, as the continuous-log design prescribes.** Rejected for crash reports: the `path:` property and the renderer's `bundle script … failed to load` line were the load-bearing evidence in both diagnoses and would have been reduced to `UNCLASSIFIED`.
**Retry the batch URL for every failure kind.** Rejected: re-executing a batch that already registered some packages throws `duplicate factory registration` inside the script, the `load` event still fires, and the caller sees the same "loaded without registering" it started with, unable to tell that the retry caused it.
**Keep more generations of Host batch URLs so a recomposed graph does not 404 an in-flight boot.** Deferred rather than shipped: no production trigger for a post-ready graph change was found, `lazyBody` caches response buffers so retention has a real memory cost, and the generation and age limits are deployment tunables that need `Config` fields.
@@ -0,0 +1,61 @@
# Agent Note: 致命诊断与 Desktop 崩溃报告
Status: implemented
[English](2026-09-22-fatal-diagnostics-and-crash-reports.md) | 中文
## Problem
Desktop 应用的两起用户侧故障都是靠致命恢复对话框的截图定位的。该对话框只显示错误的最后八行,并且当时声称完整诊断已写入 Electron 控制台,而打包安装的应用从不暴露那个控制台。
Windows 上,`dsh-subprocess-local` 的 `OutputCollector.spillAll` 在子进程 stdout 的 `'data'` 监听器内打开 spill 文件。带 `'wx'` 的 `openSync` 抛出 `ENOENT`,对该标志而言这意味着每进程私有 spill 目录已不存在(它只创建一次、从不重建;是什么删除了它没有被观测到),由于没有任何进程级 handler,Desktop Host 以 Node 默认的未捕获异常输出退出。`path:` 属性恰好落在可见的八行里;此外关于该故障的信息一无所获。
macOS 上,启动审计把一组 Web 客户端行列为 `import failed (see console for the import error)`,而真正的 import 错误只留在渲染进程 console 中。可见的八个名字与依赖同一个 application batch 的行完全吻合,因此该 batch 脚本的一次加载失败可以解释截图;失败是传输错误、过期 URL 的 404 还是响应截断,无法判定。batch 只请求一次,因此任何瞬态失败都是最终结果。
两起事故共享三个缺口:致命诊断没有持久化、Host 没有 `uncaughtException` 策略、一个可失败步骤被允许拖垮整个功能。
## Decision
四条决定一并交付。
**未捕获异常是致命的并会被报告;失败的操作绝不恢复。** `dsh-app-boot` 的 `installFailLoud` 为 `'uncaughtException'` 注册与 `'unhandledRejection'` 相同的 handler:向 stderr 写一条带标签的 `util.inspect` 诊断,在既有超时内等待界面的 release 钩子,以 1 退出。控制流不会回到失败的操作,事件循环只运行到 release 结束或超时,因为只有抛出点知道哪些状态仍然完整;在更新过程中抛出的 `'data'` 监听器已经丢掉了一块数据并只设置了一半自己的字段,恢复运行会把可见的崩溃变成静默错误的输出。用 `util.inspect` 替代 `err.stack`,因为 `node:fs` 错误的 `code`、`syscall`、`path` 以及 `cause` 链都是堆栈行省略的可枚举属性。rejection 的标签 `fatal load failure` 保持不变,因为 Web profile 的 expected-output e2e 测试匹配它;异常使用 `fatal uncaught exception`。
**spill 文件在每一步都是尽力而为。** `spillPath` 本来就是可选的,最终关闭失败时已经会撤回它。`spillAll` 现在包住打开或追加过程中的每一种文件系统失败:丢弃该 spill,通过所有者的 logger 报告一次(`SpillOptions.onFailure`,由运行时和 SSH helper 接到 `ctx.logger.error`),并让内存尾部继续收集。被删除的目录不会重建:该设计的安全性依赖于由本进程一次性创建的随机名称,重建一个已知名称就放弃了这一点。在 `ENOENT` 时新建随机目录是待办工作。
**Desktop 致命失败在弹窗前写入崩溃报告。** 每个 `reportFatal` 调用方都标明来源(`host`、`web-boot`、`renderer`、`main`)。`DesktopFatalRecovery.report` 最多等待 `writeCrashReport` 一秒,然后弹出对话框并把文件路径单独占一行——与错误是否被截短无关,端口占用变体同样如此。报告包含来源、后端是否已就绪、应用与运行时版本、完整的 inspect 错误(backend 状态携带原始错误对象;Host 启动失败通过 fatal IPC 事件携带 Host 自己的 inspect 错误,因为 Host 的 stderr 与该消息存在竞争,而壳只报告它看到的第一个失败),以及从 `webContents` 的 `'console-message'` 捕获的主窗口最近 error 级 console 输出(64 KiB 尾部)。报告位于 `app.getPath('logs')` 下,平台允许时仅所有者可读,启动时保留最新十份。关闭过程中的致命失败只写报告、不弹窗。按钮与恢复操作不变。
**batch 脚本失败是按行的问题,不是启动失败。** 在 `ClientModuleSystem.arrive` 中,传输失败(脚本 `error` 事件;什么都没执行)在同一 URL 上重试一次,等待该 batch 的所有行共享这次重试。加载成功但没有注册某行的脚本绝不重新执行:batch 按顺序注册各包,`register()` 拒绝重复,重放会在原次运行已注册的第一个包处停止。每个已执行的 batch URL 都会被记住,因此即使首个从该 batch 导入的是它已注册的行、之后另一行发现自己缺失,这一点仍然成立。两种情况下每条仍缺失的行随后加载自己的单资源 combo URL,Host 为每个包都提供该 URL;失败的 batch URL 会被记住,后续行直接走回退,而单资源 URL 跨 import 保持可重试(一次启动内 Loader 对每个条目只 import 一次,因此缺失行只有一次回退尝试)。依赖失败用消费者与依赖的名字包装。模块系统在最外层操作按行记录最后一次 `import()` 或 `prefetch()` 失败,因此 factory 执行错误与到达错误一样被捕获,`assertEntriesActive` 按无 fiber 的条目报告该文本。
## 与既有决定的关系
本 note 部分取代 [Desktop 原生致命恢复](2026-09-15-desktop-native-fatal-recovery.zh.md):对话框指向的记录现在是崩溃报告文件而非 Electron 控制台,对话框详情多出报告路径一行;该 note 对对话框归属、按钮集合与 profile 恢复的决定仍然有效。`uncaughtException` 的处理把 [fail-loud release](../bug-fix/2026-07-31-fail-loud-releases-the-terminal.zh.md) note 的 release 机制扩展到同步抛出。
## 与 Desktop 日志体系设计的关系
Desktop 本地日志设计(Worker 独占写入的滚动 JSONL 日志、封闭事件词汇、脱敏与限流)是持续日志设计,仍是未来工作。它规定 Host stderr 与渲染进程 console 输出永不持久化、错误只以固定分类进入日志。本决定划出一个例外:致命失败的一次性崩溃报告保留原始错误以及保留的 stderr 与 console 尾部,因为两次现场定位需要的正是这些原始内容,而报告有界(error 段截至 256 KiB、Host 诊断 64 KiB、渲染进程 console 尾部 64 KiB)、本地、仅所有者可读,且只在应用已经弹出致命对话框时写入。对话框标明文件名,用户知道自己会分享什么。任何非崩溃报告的内容仍遵循持续日志的隐私姿态。
## Testing
- `dsh-app-boot`:未捕获异常产生带可枚举属性与 cause 链的带标签诊断,与 rejection 共享退出闩锁和 release 超时,两个 handler 都能卸载。
- `dsh-subprocess-local`:打开时 `ENOENT`(目录被删)、打开时 `ENOTDIR`、文件已存在后追加时 `ENOSPC`,三者都保持尾部逐字节一致、撤回 spill 文件、报告一次且不抛出。
- `dsh-client-modules`:传输失败重试一次并共享重试;持续失败按缺失行回退且不重复请求 batch;零注册或部分注册的 batch 不重新执行;单资源 URL 保持可重试;最终错误列出每次尝试;传输、factory 与依赖失败都被记录,成功和失效会清除记录。
- `dsh-client-web`:提供模块系统时启动审计写出记录的 import 错误。
- Desktop:`crash-report` 单测覆盖渲染、仅所有者可读的写入、写入失败、不触碰其他文件的清理以及 console 尾部;`fatal-recovery` 测试在两种语言下钉住带与不带报告路径的对话框文本、一秒上限以及每次致命失败只写一次;启动夹具断言运行阶段 Host 退出的报告输入,包括捕获的渲染进程 console。
## Consequences
Host 现在对两种失败走同一条退出路径,比 Node 立即退出的默认行为最多晚 release 超时的时间,因此致命对话框可能在失败后最多两秒才出现,且 release 窗口内插件写到 stderr 的内容可能把 fail-loud 那一行挤出对话框的八行摘录(报告文件保留 64 KiB 尾部)。spill 失败对用户不再可见,只剩一个带截断标记且没有路径的结果;插件 logger 那一行是唯一痕迹,Host 侧持续日志设计将来会持久化它。崩溃报告持久化原始 stderr 与 console 尾部,理由如上。batch 加载失败现在对每条缺失行最多花费三次请求,且绝不让已注册的行失败;共享的 batch 记忆意味着页面生命周期内,失败 batch 中某行的后续 import 会直接走其单资源 URL。
## Alternatives considered
**捕获未捕获异常并让 Host 继续运行。** 否决:监听器抛出后的状态除抛出点外无人知晓。在 Windows 案例中,继续运行会丢掉该块数据、向模型宣告一个不存在文件的 spill 路径,并在之后每一块上再次抛出。
**在 `ENOENT` 时重建 spill 目录。** 本次否决:重建已知名称放弃了该设计赖以存在的随机目录属性。失败时新建 `mkdtemp` 需要收集器持有目录提供函数而非字符串,作为待办。
**同步写崩溃报告以保持对话框同步。** 否决:在缓慢或网络挂载的 profile 目录上,一次挂起的写入会让壳冻结且完全没有对话框。带一秒上限的异步写入无论如何都会弹出对话框。
**按持续日志设计的规定,崩溃报告只持久化分类后的错误类别。** 对崩溃报告否决:`path:` 属性和渲染进程的 `bundle script … failed to load` 那一行是两次定位的关键证据,按该规则会被抹成 `UNCLASSIFIED`。
**对每种失败都重试 batch URL。** 否决:重新执行一个已注册部分包的 batch 会在脚本内抛出 `duplicate factory registration`,`load` 事件照常触发,调用方看到的还是最初那个「loaded without registering」,无法分辨是重试造成的。
**保留更多代 Host batch URL,使重组的 graph 不会让进行中的启动收到 404。** 推迟而非交付:没有找到 ready 之后改动 graph 的生产触发者,`lazyBody` 缓存响应 Buffer 使保留有实际内存成本,代数与时限是需要 `Config` 字段的部署可调项。
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-07-31-fail-loud-releases-the-terminal.md
2026-07-31-fail-loud-releases-the-terminal.md: a6b8ccc5a0ad885a349b32707face7bfce9d7bed
2026-07-31-fail-loud-releases-the-terminal.zh.md: 728fca424d2622af6222d51a3240eafd0e117986
2026-07-31-fail-loud-releases-the-terminal.md: 9c8aa41e960764c6d9311c49a8757a25b3996b78
2026-07-31-fail-loud-releases-the-terminal.zh.md: e44d4672dcf768c33d94b801809cf7aa653aa62f
@@ -29,6 +29,7 @@ The `/exit` path was never affected, because it disposes the tree and reaches th
- A latch, not an uninstall, keeps the first rejection the reported one. Removing the listener during teardown would let a second concurrent rejection become uncaught, and Node would kill the process mid-teardown — stranding exactly the terminal state this restores. Later rejections, including the release's own, fall through to the pending exit.
- The release is bounded by `FAIL_LOUD_RELEASE_TIMEOUT_MS` (2s) and its rejection is swallowed. A wedged or failing disposer delays the fatal exit; it never cancels it. That timer stays **referenced**: an `unref()`ed one lets Node reach an empty event loop and exit 0 on the very failure being reported, because an `unhandledRejection` listener suppresses the default fatal exit.
- Omitting `release` keeps the previous behavior exactly, so the ACP, JSON-RPC, and demo bins are unchanged.
- The same handler, latch, and release run for `uncaughtException` since the [fatal diagnostics and crash reports](../architecture/2026-09-22-fatal-diagnostics-and-crash-reports.md) decision, which also switched the diagnostic to `util.inspect`.
`dsh`'s TUI launcher passes a release that disposes the root context, which runs the TUI's existing `shutdown()` and hands the terminal back.
@@ -29,6 +29,7 @@ Loader 并发挂载各个条目,因此条目失败的顺序并不等于启动
- 使用闩锁(latch)而非卸载监听器,来保证被报告的始终是第一个 rejection。若在拆卸期间移除监听器,第二个并发 rejection 就会变成未捕获错误,Node 会在拆卸中途杀死进程——恰好残留下本次要恢复的终端状态。后续 rejection(包括 release 自身的)都会落入已挂起的退出流程。
- release 以 `FAIL_LOUD_RELEASE_TIMEOUT_MS`(2 秒)为上限,且其 rejection 被吞掉。卡住或失败的 disposer 只会延迟致命退出,绝不会取消它。该定时器保持 **referenced**:一旦 `unref()`,Node 就会在事件循环清空后、恰恰在报告这次失败时以 0 退出,因为 `unhandledRejection` 监听器抑制了默认的致命退出。
- 不传 `release` 时行为与此前完全一致,因此 ACP(Agent Client Protocol)、JSON-RPC 和各 demo bin 均无变化。
- 自[致命诊断与崩溃报告](../architecture/2026-09-22-fatal-diagnostics-and-crash-reports.zh.md)决定起,同一 handler、闩锁与 release 也对 `uncaughtException` 生效,诊断同时改为 `util.inspect`。
`dsh` 的 TUI 启动器传入的 release 会释放根上下文,从而执行 TUI 已有的 `shutdown()` 并把终端交还。
+9 -1
View File
@@ -1,6 +1,7 @@
/** Launch the Desktop profile through the Web application and report its URL to Electron. */
import { delimiter, join } from 'node:path'
import { inspect } from 'node:util'
import { loadLayeredEnv, loadProfileDirectory } from '@deepseek-ai/dsh-app-boot'
import { runProfile } from '@deepseek-ai/dsh/profile-boot'
import type {} from '@deepseek-ai/dsh-client-connection'
@@ -80,10 +81,17 @@ async function main(): Promise<void> {
if (process.connected) process.send?.({ type: 'ready', url, injections: ctx.webServer.collectIndexInjections() }, (error) => { if (error !== null) console.error(error) })
}
/** Upper bound of the startup diagnostic carried over IPC; the head holds the message and stack. */
const MAX_FATAL_DIAGNOSTIC_CHARS = 64 * 1024
if (import.meta.main) {
main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error)
if (process.connected) process.send?.({ type: 'fatal', message }, (error) => { if (error !== null) console.error(error) })
// The shell receives the complete inspected error here, not through stderr:
// stderr bytes and this IPC message race, and the shell reports the first
// failure it sees.
const diagnostic = inspect(error, { depth: 4, maxArrayLength: 50 }).slice(0, MAX_FATAL_DIAGNOSTIC_CHARS)
if (process.connected) process.send?.({ type: 'fatal', message, diagnostic }, (error) => { if (error !== null) console.error(error) })
console.error(error)
process.exitCode = 1
if (process.connected) process.disconnect()
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/desktop/README.md
README.md: df95691f20d434baaeed7f0062989bd28df2b35e
README.zh.md: ceefff9cc7d0aaac68f1dd86dcaadad99cfcbdcf
README.md: 2b07b2b9d95c3d16a3aaa58b6d52f55cb1242e2e
README.zh.md: 4ebae34332b1d622a35d0bf857f1f3252736512c
+4 -2
View File
@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop defaults to port `19387`, separate from Web’s `3080`; a `webserver.config.port` patch can override it.
The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host, dropping connection-level response headers (`transfer-encoding`, `connection`, `keep-alive`) that describe the Node fetch rather than the resource, and marking plugin bundle responses `no-store` because their per-launch revisions would only accumulate in Chromium's disk cache; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop defaults to port `19387`, separate from Web’s `3080`; a `webserver.config.port` patch can override it.
The first application-menu command, **About DeepSeek Harness**, opens Electron's native About panel with the application icon, product name, and installed release version. The menu follows the Desktop shell locale. On macOS, Hide, Hide Others, Show All, and Quit use localized labels; Hide and Quit include the DeepSeek Harness product name. These commands retain their native actions and shortcuts. macOS reads the icon from its application bundle, so an unpackaged development launch displays Electron's icon; Windows receives the packaged PNG.
@@ -82,7 +82,9 @@ The [Web plugin UI](../../packages/client/ui-plugin-manager/README.md) owns the
Fatal main-window creation, main-document loading, preload, renderer, Web initialization, or backend failures open one native recovery dialog per application process. It shows a bounded tail of the first error, notes any truncation, and offers Exit, Restart, and Disable third-party plugins, back up profile patch, and restart. Startup failures retain the Web loading page and spinner; runtime failures retain the current page. Expected shutdowns, cancelled navigation, and ordinary requests do not trigger recovery. The shared Web plugin manager reports package-operation errors; Host startup failures after plugin changes enter native recovery. There is no startup timeout heuristic. A listener failure containing `listen EADDRINUSE` replaces the diagnostics and reinstall advice with guidance to quit other running DSH instances, and offers only Exit and Restart.
Native dialog details include at most 1,200 UTF-16 code units and eight diagnostic lines; the complete reported error is written to the Electron console. Host error diagnostics retain only the last 64 Ki characters written to stderr. Earlier output is discarded so a long-running Host does not grow the shell’s diagnostic buffer indefinitely.
Native dialog details include at most 1,200 UTF-16 code units and eight diagnostic lines, plus the path of the crash report described below when one was written. Host error diagnostics retain only the last 64 Ki characters written to stderr. Earlier output is discarded so a long-running Host does not grow the shell’s diagnostic buffer indefinitely.
Before the first fatal dialog opens, Electron writes a crash report to the platform logs directory (`app.getPath('logs')`: `~/Library/Logs/DeepSeek Harness` on macOS, `logs` under the application’s `userData` directory on Windows and Linux), waiting at most one second for the write; a slow or failed write shows the dialog without a path. The file `crash-<UTC time>-<source>.log` records the source (`host` for a Host exit, `web-boot` for a renderer boot failure, `renderer` for a renderer or document failure, `main` for a shell error), whether the backend had reached ready, application and runtime versions, the error with its enumerable properties and cause chain (cut at 256 KiB), the Host’s own inspected error (at most 64 KiB) when the Host reported a startup failure over IPC before exiting, and the primary window’s recent error-level console output (at most 64 KiB). A Host exit report therefore contains the retained stderr tail, which may include plugin output. A fatal failure during shutdown writes a report without opening a dialog. Files are owner-only where the platform supports it; startup keeps the ten newest reports and removes older ones without touching other files in the directory.
Recovery waits for Host shutdown before changing plugin activation. The native recovery action calls the shared app-boot recovery function under the profile transaction lock. It disables third-party bundles and renames the profile’s `cordis.patch.yml` to `cordis.patch.yml.bak-<timestamp>` (with an ordinal on collisions) without parsing it; the next startup creates an empty patch. Installed packages and earlier backups remain. The home-level patch is unchanged. The Electron console records the backup path (or its absence) and the unchanged home-level patch. Invalid profile data, rename failures, or write failures are reported as recovery-operation errors; completed changes remain, and Desktop does not restart as though recovery succeeded. Desktop has no profile-reset action or emergency HTML document.
+4 -2
View File
@@ -2,7 +2,7 @@
[English](README.md) | 中文
桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认使用端口 `19387`,与 Web 的 `3080` 分开;可通过 `webserver.config.port` patch 覆盖。
桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host,转发时丢弃描述 Node fetch 连接而非资源本身的响应头(`transfer-encoding`、`connection`、`keep-alive`),并把插件 bundle 响应标记为 `no-store`,因为其每次启动都变化的 revision 只会在 Chromium 磁盘缓存中累积;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认使用端口 `19387`,与 Web 的 `3080` 分开;可通过 `webserver.config.port` patch 覆盖。
应用菜单第一项“**关于 DeepSeek Harness**”打开 Electron 原生关于面板,展示应用图标、产品名称和当前安装的发布版本。菜单文案跟随桌面壳的语言。macOS 的隐藏、隐藏其他、显示全部和退出条目使用本地化文案,隐藏和退出条目包含 DeepSeek Harness 产品名称。这些条目保留原生动作和快捷键。macOS 从应用包读取图标,因此未打包的开发启动会显示 Electron 图标;Windows 使用随包分发的 PNG。
@@ -82,7 +82,9 @@ macOS 上自定义应用菜单还会声明标准的 File、Window 和应用菜
主窗口创建、主文档加载、preload、渲染器、Web 初始化或后端的致命失败,会在每个应用进程中打开一次原生恢复对话框。对话框显示首次错误末尾的限长摘要,标明截断情况,并提供退出、重启、禁用第三方插件、备份 profile patch 并重启。启动失败保留 Web 加载页和动画;运行中失败保留当前页面。预期关闭、取消导航和普通请求错误不会触发恢复。共享 Web 插件管理器报告包操作错误;插件变更后的 Host 启动失败会进入原生恢复。不通过启动超时推断故障。 包含 `listen EADDRINUSE` 的监听失败以退出其他正在运行的 DSH 实例的提示替代诊断和重装建议,仅提供退出和重启。
原生弹窗详情最多包含 1,200 个 UTF-16 代码单元和八行诊断;完整的已报告错误写入 Electron 控制台。Host 错误诊断仅保留 stderr 输出的最后 64 Ki 个字符。更早的输出会被丢弃,避免长期运行的 Host 使壳的诊断缓冲区无限增长。
原生弹窗详情最多包含 1,200 个 UTF-16 代码单元和八行诊断,若已写入下述崩溃报告则附上其路径。Host 错误诊断仅保留 stderr 输出的最后 64 Ki 个字符。更早的输出会被丢弃,避免长期运行的 Host 使壳的诊断缓冲区无限增长。
首个致命弹窗打开前,Electron 会向平台日志目录(`app.getPath('logs')`:macOS 为 `~/Library/Logs/DeepSeek Harness`,Windows 与 Linux 为应用 `userData` 目录下的 `logs`)写入一份崩溃报告,最多等待写入一秒;写入缓慢或失败时弹窗不带路径。文件 `crash-<UTC 时间>-<source>.log` 记录来源(`host` 为 Host 退出、`web-boot` 为渲染进程启动失败、`renderer` 为渲染进程或文档失败、`main` 为壳自身错误)、后端是否已就绪、应用与运行时版本、包含可枚举属性与 cause 链的错误(截至 256 KiB)、Host 在退出前通过 IPC 报告启动失败时自己的 inspect 错误(最多 64 KiB),以及主窗口最近的 error 级 console 输出(最多 64 KiB)。因此 Host 退出报告包含保留的 stderr 尾部,其中可能含有插件输出。关闭过程中的致命失败只写报告、不弹窗。平台支持时文件仅所有者可读;启动时保留最新十份报告并删除更早的,不触碰目录中的其他文件。
恢复操作等待 Host 关闭后才修改插件启用状态。原生恢复操作在 profile 事务锁内调用共享 app-boot 恢复函数。它禁用第三方 bundle,并将 profile 的 `cordis.patch.yml` 重命名为 `cordis.patch.yml.bak-<timestamp>`(重名时追加序号),无需解析;下次启动创建空 patch。已安装包和已有备份保留。home 级 patch 不变。Electron 控制台记录备份路径(或原文件不存在)以及 home 级 patch 未修改。profile 数据无效、重命名失败或写入失败会作为恢复操作错误报告;已完成的修改保留,Desktop 不会假装恢复成功后重启。Desktop 不提供 profile 重置操作或应急 HTML 文档。
+13 -4
View File
@@ -3,7 +3,16 @@
import { desktopErrorState } from './startup-error.ts'
/** Backend availability presented by the desktop window. */
export type DesktopBackendState = { readonly phase: 'starting' } | { readonly phase: 'ready' } | { readonly phase: 'error'; readonly message: string }
export type DesktopBackendState =
| { readonly phase: 'starting' }
| { readonly phase: 'ready' }
/** `message` is the rendered text; `failure` is the original error so a crash report keeps its stack, properties, and cause. */
| { readonly phase: 'error'; readonly message: string; readonly failure: unknown }
/** The error state for one failure: rendered message plus the failure itself. */
function errorState(failure: unknown): DesktopBackendState {
return { ...desktopErrorState(failure), failure }
}
/** Child lifecycle owned by the desktop backend controller. */
export interface DesktopBackendHost {
@@ -80,7 +89,7 @@ export class DesktopBackendController<Host extends DesktopBackendHost> {
try { await this.cleanup(attempt) } catch (cleanupError) {
if (cleanupError !== error) failure = new AggregateError([error, cleanupError], 'desktop backend startup and cleanup failed')
}
if (!cancelled) this.update(desktopErrorState(failure))
if (!cancelled) this.update(errorState(failure))
throw failure
}
}).finally(() => { if (this.pending === pending) this.pending = undefined })
@@ -132,9 +141,9 @@ export class DesktopBackendController<Host extends DesktopBackendHost> {
if (this.current.phase !== 'ready') return
attempt.cancelled = true
const cleanup = this.cleanup(attempt)
this.update(desktopErrorState(error))
this.update(errorState(error))
void cleanup.catch((cleanupError: unknown) => {
if (this.attempt === attempt) this.update(desktopErrorState(new AggregateError([error, cleanupError], 'Desktop backend failed and could not stop')))
if (this.attempt === attempt) this.update(errorState(new AggregateError([error, cleanupError], 'Desktop backend failed and could not stop')))
})
}
+184
View File
@@ -0,0 +1,184 @@
/**
* Crash report files: the complete diagnostic of one fatal Desktop failure,
* written before the recovery dialog so the dialog can name the file. The
* dialog itself shows only the last lines of the error; the file holds the
* whole error, its enumerable properties and cause chain, the process facts,
* and the renderer's recent error-level console output.
*/
import { mkdir, readdir, unlink, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { inspect } from 'node:util'
/** Where a fatal failure surfaced. */
export type CrashReportSource = 'host' | 'web-boot' | 'renderer' | 'main'
/** Whether the backend had reached ready when the failure surfaced. */
export type CrashReportPhase = 'startup' | 'running'
/** Facts about the running application recorded in every report header. */
export interface CrashReportApp {
readonly name: string
readonly version: string
readonly platform: string
readonly arch: string
readonly electron: string
readonly node: string
readonly locale: string
}
/** Inputs of {@link renderCrashReport} and {@link writeCrashReport}. */
export interface CrashReportInput {
readonly source: CrashReportSource
readonly phase: CrashReportPhase
readonly error: unknown
/** The Host's own inspected error when it reported the failure over IPC before exiting. */
readonly hostDiagnostic?: string
/** Recent renderer console lines at error level, oldest first. */
readonly rendererConsole: readonly string[]
readonly app: CrashReportApp
readonly time: Date
}
/** File name prefix every report shares. */
export const CRASH_REPORT_PREFIX = 'crash-'
/** The exact generated file name syntax; pruning touches only files that match it. */
const CRASH_REPORT_NAME = /^crash-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-(?:host|web-boot|renderer|main)\.log$/u
/** Reports kept after pruning, newest first by file name. */
export const CRASH_REPORTS_RETAINED = 10
/** Retained bytes of renderer error-level console output. */
export const RENDERER_CONSOLE_MAX_BYTES = 64 * 1024
/** Upper bound of the rendered error section; a Host exit error already carries a 64 KiB stderr tail in its message. */
export const ERROR_SECTION_MAX_CHARS = 256 * 1024
/**
* Bounded tail of renderer error-level console lines. Lines are dropped from
* the head once the retained byte total exceeds the cap; one oversized line is
* kept whole so a long stack is never cut mid-line.
*/
export class RendererConsoleTail {
private readonly lines: string[] = []
private bytes = 0
/** @param maxBytes - retained byte cap across all lines. */
constructor(private readonly maxBytes = RENDERER_CONSOLE_MAX_BYTES) {}
/**
* Append one console line.
* @param line - the formatted console message.
*/
push(line: string): void {
this.lines.push(line)
this.bytes += Buffer.byteLength(line)
while (this.lines.length > 1 && this.bytes > this.maxBytes) {
this.bytes -= Buffer.byteLength(this.lines.shift() as string)
}
}
/** @returns the retained lines, oldest first. */
snapshot(): readonly string[] {
return [...this.lines]
}
}
/**
* The report file name: sortable by time, then the source.
* @param time - failure time.
* @param source - where the failure surfaced.
* @returns `crash-<ISO time with ':' and '.' as '-'>-<source>.log`.
*/
export function crashReportFileName(time: Date, source: CrashReportSource): string {
return `${CRASH_REPORT_PREFIX}${time.toISOString().replaceAll(/[:.]/gu, '-')}-${source}.log`
}
/**
* Render one report as plain text: a header of facts, the inspected error,
* the Host's own diagnostic when it reported one, and the renderer console tail.
* @param input - the failure and its context.
* @returns the complete file content.
*/
export function renderCrashReport(input: CrashReportInput): string {
const header = [
`time: ${input.time.toISOString()}`,
`source: ${input.source}`,
`phase: ${input.phase}`,
`app: ${input.app.name} ${input.app.version}`,
`platform: ${input.app.platform} ${input.app.arch}`,
`electron: ${input.app.electron}`,
`node: ${input.app.node}`,
`locale: ${input.app.locale}`,
`shell pid: ${String(process.pid)}`,
]
const consoleSection = input.rendererConsole.length === 0
? '(no error-level renderer console output was captured)'
: input.rendererConsole.join('\n')
return [
header.join('\n'),
'',
'--- error ---',
boundedErrorSection(input.error),
'',
...(input.hostDiagnostic === undefined ? [] : ['--- host diagnostic (as reported by the Host process) ---', input.hostDiagnostic, '']),
'--- renderer console (error level, oldest first) ---',
consoleSection,
'',
].join('\n')
}
function boundedErrorSection(error: unknown): string {
const rendered = inspect(error, { depth: 6, maxStringLength: 64 * 1024, maxArrayLength: 100, breakLength: 120 })
return rendered.length <= ERROR_SECTION_MAX_CHARS
? rendered
: `${rendered.slice(0, ERROR_SECTION_MAX_CHARS)}\n… (error section cut at ${String(ERROR_SECTION_MAX_CHARS)} characters)`
}
/**
* Write one report into `directory`, creating it when absent. Failure is
* reported to `console.error` and yields `undefined`: the recovery dialog
* proceeds without a file rather than failing over a diagnostic aid.
* @param directory - the application logs directory.
* @param input - the failure and its context.
* @returns the written file path, or `undefined` when writing failed.
*/
export async function writeCrashReport(directory: string, input: CrashReportInput): Promise<string | undefined> {
const path = join(directory, crashReportFileName(input.time, input.source))
try {
await mkdir(directory, { recursive: true, mode: 0o700 })
await writeFile(path, renderCrashReport(input), { mode: 0o600, flag: 'wx' })
return path
} catch (error) {
console.error('dsh desktop: crash report could not be written', path, error)
return undefined
}
}
/**
* Delete the oldest reports beyond `retained`, judged by file name order, and
* leave every other file in the directory alone. Failure is reported to
* `console.error`; a missing directory is not a failure.
* @param directory - the application logs directory.
* @param retained - reports to keep.
*/
export async function pruneCrashReports(directory: string, retained = CRASH_REPORTS_RETAINED): Promise<void> {
let names: string[]
try {
names = await readdir(directory)
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
console.error('dsh desktop: crash report directory could not be listed', directory, error)
return
}
const reports = names.filter(name => CRASH_REPORT_NAME.test(name)).sort()
const excess = reports.slice(0, Math.max(0, reports.length - retained))
for (const name of excess) {
try {
await unlink(join(directory, name))
} catch (error) {
console.error('dsh desktop: stale crash report could not be removed', join(directory, name), error)
}
}
}
+52 -8
View File
@@ -1,7 +1,8 @@
/** Native recovery for the first fatal failure in one Desktop process. */
import type { MessageBoxOptions, MessageBoxReturnValue } from 'electron'
import type { DesktopMessages } from './locale.ts'
import type { CrashReportSource } from './crash-report.ts'
import { formatDesktopMessage, type DesktopMessages } from './locale.ts'
import { desktopErrorState } from './startup-error.ts'
interface RecoveryOperations {
@@ -11,21 +12,43 @@ interface RecoveryOperations {
disablePlugins(): Promise<void>
exit(): void
restart(): void
/** Persist the complete diagnostic; resolves with the file path, or `undefined` when nothing was written. */
writeReport(error: unknown, source: CrashReportSource): Promise<string | undefined>
}
function dialogDetail(error: string, messages: DesktopMessages): string {
/** Upper bound on waiting for the crash report before the dialog opens. */
export const CRASH_REPORT_WAIT_MS = 1_000
/** The dialog's `detail` budget in characters, within which the native message box stays readable. */
const DETAIL_BUDGET = 1200
/** Tail lines of the error kept in the dialog; the report file holds the rest. */
const DETAIL_TAIL_LINES = 8
/**
* Compose the dialog detail: the error's last lines (prefixed by the
* shortening notice when they are not the whole error), then the report path
* when one was written, then the reinstall advice. The report line does not
* depend on shortening: a short error that was persisted names its file too.
*/
function dialogDetail(error: string, messages: DesktopMessages, reportPath: string | undefined): string {
const advice = `\n\n${messages.startupReinstallAdvice}`
const tail = error.split(/\r\n|[\n\r\u2028\u2029]/u).slice(-8).join('\n')
const budget = 1200 - advice.length - messages.diagnosticTruncated.length - 1
const report = reportLine(messages, reportPath)
const tail = error.split(/\r\n|[\n\r\u2028\u2029]/u).slice(-DETAIL_TAIL_LINES).join('\n')
const budget = DETAIL_BUDGET - advice.length - report.length - messages.diagnosticTruncated.length - 1
const shortened = tail.slice(-budget).replace(/^[\uDC00-\uDFFF]/u, '')
return `${shortened === error ? error : `${messages.diagnosticTruncated}\n${shortened}`}${advice}`
return `${shortened === error ? error : `${messages.diagnosticTruncated}\n${shortened}`}${report}${advice}`
}
function reportLine(messages: DesktopMessages, reportPath: string | undefined): string {
return reportPath === undefined ? '' : `\n${formatDesktopMessage(messages.reportWrittenTo, { path: reportPath })}`
}
/** Deduplicates fatal reports while keeping explicit recovery-operation failures actionable. */
export class DesktopFatalRecovery {
private reported = false
/** @param operations - Native presentation and application-owned shutdown operations. */
/** @param operations - Native presentation, report persistence, and application-owned shutdown operations. */
constructor(private readonly operations: RecoveryOperations) {}
/** Whether this process requires a native recovery action before further plugin changes. */
@@ -33,13 +56,17 @@ export class DesktopFatalRecovery {
/**
* Show the first fatal error; later reports cannot replace it or open another dialog.
* The crash report is written first, bounded by {@link CRASH_REPORT_WAIT_MS}, so the dialog can name it;
* a slow or failed write shows the dialog without a path.
* @param error - Fatal failure, including nested diagnostic causes.
* @param source - Where the failure surfaced, recorded in the report.
* @returns Completion of the user's recovery action; duplicate reports resolve immediately.
*/
async report(error: unknown): Promise<void> {
async report(error: unknown, source: CrashReportSource): Promise<void> {
if (this.reported) return
this.reported = true
const messages = this.operations.messages()
const reportPath = await this.persist(error, source)
let detail = desktopErrorState(error).message
let message = messages.fatalSummary
for (;;) {
@@ -48,7 +75,9 @@ export class DesktopFatalRecovery {
type: 'error',
title: messages.startupFailed,
message,
detail: addressInUse ? messages.startupAddressInUse : dialogDetail(detail, messages),
detail: addressInUse
? `${messages.startupAddressInUse}${reportLine(messages, reportPath)}`
: dialogDetail(detail, messages, reportPath),
buttons: addressInUse
? [messages.exitApplication, messages.restartApplication]
: [messages.exitApplication, messages.restartApplication, messages.disableThirdPartyPlugins],
@@ -73,4 +102,19 @@ export class DesktopFatalRecovery {
}
}
}
private async persist(error: unknown, source: CrashReportSource): Promise<string | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined
try {
return await Promise.race([
this.operations.writeReport(error, source),
new Promise<undefined>((resolve) => { timer = setTimeout(() => { resolve(undefined) }, CRASH_REPORT_WAIT_MS) }),
])
} catch (failure) {
console.error('dsh desktop: crash report failed', failure)
return undefined
} finally {
clearTimeout(timer)
}
}
}
+26 -2
View File
@@ -14,6 +14,8 @@ interface ReadyEvent {
interface FatalEvent {
readonly type: 'fatal'
readonly message: string
/** The Host's complete inspected error: stack, enumerable properties, cause chain. */
readonly diagnostic?: string
}
interface PlatformSessionEvent {
@@ -56,7 +58,7 @@ function isDesktopHostEvent(message: unknown): message is DesktopHostEvent {
} catch { return false }
}
case 'fatal':
return typeof candidate.message === 'string'
return typeof candidate.message === 'string' && (candidate.diagnostic === undefined || typeof candidate.diagnostic === 'string')
case 'update-tasks':
return Number.isSafeInteger(candidate.requestId) && typeof candidate.active === 'boolean'
&& (candidate.error === undefined || typeof candidate.error === 'string')
@@ -87,6 +89,28 @@ export interface DesktopHostReady {
/** The child has exited, but task teardown did not finish successfully. */
export class DesktopHostUncleanExitError extends Error {}
/**
* A Host failure reported over IPC before the process exited. `message` is what
* the Host chose to show; `diagnostic` is its complete inspected error, kept
* separately so a crash report can print it verbatim instead of a string escaped
* inside another error's properties.
*/
export class DesktopHostFatalError extends Error {
readonly #diagnostic: string | undefined
/**
* @param message - The Host's failure message.
* @param diagnostic - The Host's inspected error, when the Host supplied one.
*/
constructor(message: string, diagnostic: string | undefined) {
super(message)
this.#diagnostic = diagnostic
}
/** The Host's inspected error; a getter so `util.inspect` of this error does not repeat it as an escaped property. */
get diagnostic(): string | undefined { return this.#diagnostic }
}
/** One Web backend running under the Electron executable in Node mode. */
export class DesktopHostProcess {
private child: ChildProcess | undefined
@@ -165,7 +189,7 @@ export class DesktopHostProcess {
if (this.stopping) this.shutdownCompleted = true
else this.fail(new Error('dsh desktop host acknowledged an unrequested shutdown'))
}
else if (message.type === 'fatal') this.fail(new Error(message.message))
else if (message.type === 'fatal') this.fail(new DesktopHostFatalError(message.message, message.diagnostic))
else {
const query = this.taskQueries.get(message.requestId)
if (message.error === undefined) query?.resolve(message.active)
+4 -2
View File
@@ -21,7 +21,8 @@ export const en = {
startupFailed: 'DeepSeek Harness is unavailable',
fatalSummary: 'The application could not start or stopped unexpectedly.',
startupAddressInUse: 'Another DSH instance (such as dsh web or the desktop app) is running. They cannot start at the same time. Quit the other running DSH instance, then restart.',
diagnosticTruncated: '… Error details shortened. The full diagnostic was written to the Electron console.',
diagnosticTruncated: '… Error details shortened.',
reportWrittenTo: 'Diagnostic report: {path}',
startupReinstallAdvice: 'If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.',
exitApplication: 'Exit',
restartApplication: 'Restart',
@@ -150,7 +151,8 @@ export const zh = {
startupFailed: 'DeepSeek Harness 无法使用',
fatalSummary: '应用无法启动或已意外停止。',
startupAddressInUse: '有其他正在运行的 DSH(如其他 dsh web、桌面端),无法同时启动,请退出其他正在运行的 DSH 后重启。',
diagnosticTruncated: '… 错误详情已截短,完整诊断已写入 Electron 控制台。',
diagnosticTruncated: '… 错误详情已截短。',
reportWrittenTo: '诊断报告:{path}',
startupReinstallAdvice: '如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。',
exitApplication: '退出',
restartApplication: '重启',
+53 -14
View File
@@ -22,7 +22,7 @@ import {
} from 'electron'
import { resolveDesktopPaths } from './paths.ts'
import { DesktopProjectManager } from './project-manager.ts'
import { DesktopHostProcess, DesktopHostUncleanExitError } from './host-process.ts'
import { DesktopHostFatalError, DesktopHostProcess, DesktopHostUncleanExitError } from './host-process.ts'
import { DesktopPlatformView, PLATFORM_IPC, platformBounds } from './platform-view.ts'
import { installDesktopDirectoryPicker } from './directory-picker.ts'
import { installMicrophonePermissions } from './microphone-permissions.ts'
@@ -33,6 +33,7 @@ import { claimDesktopSingleInstance } from './single-instance.ts'
import { DesktopUpdateCoordinator } from './update-coordinator.ts'
import { serveWebDocument, authenticateWebHost, forwardWebRequest } from './web-document.ts'
import { DesktopFatalRecovery } from './fatal-recovery.ts'
import { pruneCrashReports, RendererConsoleTail, writeCrashReport, type CrashReportSource } from './crash-report.ts'
import { openWelcomeWindow } from './welcome-window.ts'
import { WELCOME_IPC, needsWelcome } from './welcome-api.ts'
import { connectDesktopWelcome, type DesktopWelcomeBackend } from './welcome-backend.ts'
@@ -52,6 +53,18 @@ let focusPrimaryWindow = (): void => {}
let stopForRecovery = async (): Promise<void> => {}
let shuttingDown = false
let windowsLanguage: string | undefined
/**
* Whether the backend has reached ready: false until the first ready, back to
* false when a restart returns it to starting, frozen during shutdown so a
* failure while tearing down a ready backend still reads as `running`.
*/
let backendReady = false
/** Error-level console output of the primary window, attached to crash reports. */
const rendererConsole = new RendererConsoleTail()
// Platform-conventional logs directory (macOS ~/Library/Logs/<name>, otherwise under userData);
// set before ready so the first fatal report already resolves under it.
app.setAppLogsPath()
function currentDesktopLocale(): ReturnType<typeof resolveDesktopLocale> {
return resolveDesktopLocale(windowsLanguage ?? app.getLocale())
@@ -67,12 +80,32 @@ const recovery = new DesktopFatalRecovery({
},
exit: () => { app.quit() },
restart: () => { app.relaunch(); app.quit() },
writeReport: (error, source) => persistCrashReport(error, source),
})
function reportFatal(error: unknown): void {
function persistCrashReport(error: unknown, source: CrashReportSource): Promise<string | undefined> {
return writeCrashReport(app.getPath('logs'), {
source,
phase: backendReady ? 'running' : 'startup',
error,
...(error instanceof DesktopHostFatalError && error.diagnostic !== undefined ? { hostDiagnostic: error.diagnostic } : {}),
rendererConsole: rendererConsole.snapshot(),
app: {
name: app.name, version: app.getVersion(), platform: process.platform, arch: process.arch,
electron: process.versions.electron, node: process.versions.node, locale: currentDesktopLocale().id,
},
time: new Date(),
})
}
function reportFatal(error: unknown, source: CrashReportSource): void {
console.error(error)
if (shuttingDown) return
void recovery.report(error).catch((failure: unknown) => { console.error(failure); app.exit(1) })
if (shuttingDown) {
// No dialog during shutdown, but the report still records what failed on the way out.
void persistCrashReport(error, source)
return
}
void recovery.report(error, source).catch((failure: unknown) => { console.error(failure); app.exit(1) })
}
protocol.registerSchemesAsPrivileged([{
@@ -250,6 +283,7 @@ function createWindow(preload: string, show = false, primary = false): BrowserWi
}
async function main(): Promise<void> {
void pruneCrashReports(app.getPath('logs'))
const journalDirectory = process.env.DSH_DESKTOP_UPDATE_JOURNAL_DIR
const updateJournal = journalDirectory === undefined ? undefined : new DesktopUpdateJournal(journalDirectory, app.getVersion())
const resources = runtimeResources()
@@ -383,7 +417,8 @@ async function main(): Promise<void> {
updateTasks: (action: 'inspect' | 'lock' | 'unlock') => host.updateTasks(action),
}
}, (state) => {
if (state.phase === 'error') reportFatal(new Error(state.message))
if (state.phase === 'error') reportFatal(state.failure, 'host')
else if (!shuttingDown) backendReady = state.phase === 'ready'
})
const updateErrors = new WeakMap<DesktopUpdateState, Promise<void>>()
@@ -422,7 +457,7 @@ async function main(): Promise<void> {
if (backend.host !== undefined) updateJournal?.action('workspace-ready')
})
workspaceRecovery = recovery
void recovery.catch(reportFatal).finally(() => {
void recovery.catch((error: unknown) => { reportFatal(error, 'main') }).finally(() => {
if (startup === hostReady) startup = undefined
if (workspaceRecovery === recovery) workspaceRecovery = undefined
})
@@ -449,7 +484,7 @@ async function main(): Promise<void> {
// The existing Web document resumes through the boot IPC response.
})().catch((error: unknown) => {
updateJournal?.action('workspace-failed')
reportFatal(error)
reportFatal(error, 'main')
throw error
}).finally(() => { startup = undefined })
return startup
@@ -546,7 +581,7 @@ async function main(): Promise<void> {
throw new Error('dsh desktop: rejected startup failure from a non-primary frame')
}
if (typeof message !== 'string') throw new Error('dsh desktop: startup failure must be text')
reportFatal(new Error(message))
reportFatal(new Error(message), 'web-boot')
})
ipcMain.handle(DESKTOP_IPC.browserAcquire, (event, workspace: unknown) => {
@@ -863,18 +898,22 @@ async function main(): Promise<void> {
browserGuests.bind(window)
window.on('focus', automaticCheck)
window.on('closed', () => { if (mainWindow === window) mainWindow = undefined })
window.webContents.on('console-message', (details) => {
if (details.level !== 'error') return
rendererConsole.push(`${details.sourceId}:${String(details.lineNumber)} ${details.message}`)
})
window.webContents.on('did-fail-load', (_event, code, description, url, isMainFrame) => {
if (isMainFrame && code !== -3 && !quitting && !window.isDestroyed()) {
reportFatal(new Error(`Desktop page failed to load: ${url} (${String(code)}: ${description})`))
reportFatal(new Error(`Desktop page failed to load: ${url} (${String(code)}: ${description})`), 'renderer')
}
})
window.webContents.on('preload-error', (_event, _path, error) => {
if (!quitting && !window.isDestroyed()) reportFatal(error)
if (!quitting && !window.isDestroyed()) reportFatal(error, 'renderer')
})
window.webContents.on('render-process-gone', (_event, details) => {
navigation = undefined
if (!quitting && !window.isDestroyed() && details.reason !== 'clean-exit') {
reportFatal(new Error(`Desktop renderer exited: ${details.reason}`))
reportFatal(new Error(`Desktop renderer exited: ${details.reason}`), 'renderer')
}
})
return window
@@ -963,8 +1002,8 @@ async function main(): Promise<void> {
if (isMandatory()) { mandatoryUI?.focus(); return }
const window = welcomeWindow ?? mainWindow
if (window === undefined || window.isDestroyed()) {
try { createMainWindow() } catch (error) { reportFatal(error); return }
void (backend.state.phase === 'ready' ? openInitialWindow() : navigateMain(applicationUrl)).catch(reportFatal)
try { createMainWindow() } catch (error) { reportFatal(error, 'main'); return }
void (backend.state.phase === 'ready' ? openInitialWindow() : navigateMain(applicationUrl)).catch((error: unknown) => { reportFatal(error, 'main') })
return
}
// Startup and sign-out select the visible window before activation may reveal the workspace.
@@ -1073,7 +1112,7 @@ if (ownsDesktopInstance) void app.whenReady().then(main).catch(async (error: unk
if (diagnosticFile !== undefined) {
await writeFile(diagnosticFile, `${error instanceof Error ? error.stack ?? message : message}\n`).catch(() => undefined)
}
reportFatal(error)
reportFatal(error, 'main')
}).catch((error: unknown) => {
console.error(error)
app.exit(1)
+21 -2
View File
@@ -49,12 +49,30 @@ export async function authenticateWebHost(url: string): Promise<string> {
return end < 0 ? cookie : cookie.slice(0, end)
}
/**
* Response headers not relayed to the renderer. `set-cookie` would hand the
* Host's authentication cookie to the page's cookie jar, which the shell owns
* instead; the rest describe the Node `fetch` connection (its encoding, length,
* and hop-by-hop transport), which Chromium never sees.
*/
const WITHHELD_RESPONSE_HEADERS = [
'set-cookie',
'content-encoding', 'content-length',
'transfer-encoding', 'connection', 'keep-alive', 'te', 'trailer', 'upgrade', 'proxy-authenticate', 'proxy-authorization',
]
/** Host routes whose responses carry immutable cache headers keyed by a per-process revision. */
const PLUGIN_BUNDLE_PATH = /^\/plugins\//u
/**
* Forward local application requests to its authenticated Host, preserving streaming and cancellation.
* Plugin bundle responses lose their `cache-control` for `no-store`: the Host marks them immutable
* under a revision that changes every launch, so Chromium's disk cache would only accumulate bundles
* no later launch can reuse.
* @param request - Request from the application origin.
* @param host - Owned Host URL.
* @param cookie - Host-issued authentication cookie.
* @returns Host response without network-only encoding headers.
* @returns Host response without connection-level headers.
*/
export async function forwardWebRequest(request: Request, host: string, cookie: string): Promise<Response> {
const source = new URL(request.url)
@@ -69,6 +87,7 @@ export async function forwardWebRequest(request: Request, host: string, cookie:
const init = { method: request.method, headers, body: request.body, signal: request.signal, duplex: 'half', redirect: 'manual' as const }
const response = await fetch(target, init)
const outgoing = new Headers(response.headers)
for (const name of ['content-encoding', 'content-length', 'set-cookie']) outgoing.delete(name)
for (const name of WITHHELD_RESPONSE_HEADERS) outgoing.delete(name)
if (PLUGIN_BUNDLE_PATH.test(source.pathname)) outgoing.set('cache-control', 'no-store')
return new Response(response.body, { status: response.status, headers: outgoing })
}
+13 -8
View File
@@ -82,8 +82,9 @@ describe('desktop backend controller', () => {
it('publishes preparation errors and permits retry', async () => {
const f = fixture()
await expect(f.controller.start(async () => { throw new Error('invalid profile') })).rejects.toThrow('invalid profile')
expect(f.controller.state).toEqual({ phase: 'error', message: 'invalid profile' })
const invalid = new Error('invalid profile')
await expect(f.controller.start(async () => { throw invalid })).rejects.toThrow('invalid profile')
expect(f.controller.state).toEqual({ phase: 'error', message: 'invalid profile', failure: invalid })
expect(f.create).not.toHaveBeenCalled()
f.ready.resolve()
await f.controller.start(async () => {})
@@ -97,11 +98,13 @@ describe('desktop backend controller', () => {
const start = f.controller.start(async () => {})
const rejected = expect(start).rejects.toThrow('plugin failed')
await f.started.promise
f.ready.reject(new Error('plugin failed'))
const pluginFailure = new Error('plugin failed')
f.ready.reject(pluginFailure)
await f.stopping.promise
f.exited.resolve()
await rejected
expect(f.controller.state).toEqual({ phase: 'error', message: 'plugin failed' })
// The original error object travels with the state so a crash report keeps its stack and properties.
expect(f.controller.state).toEqual({ phase: 'error', message: 'plugin failed', failure: pluginFailure })
expect(f.host.stop).toHaveBeenCalledTimes(1)
await f.controller.close()
})
@@ -110,8 +113,9 @@ describe('desktop backend controller', () => {
const f = fixture()
f.ready.resolve()
await f.controller.start(async () => {})
f.fail(new Error('transport failed'))
expect(f.controller.state).toEqual({ phase: 'error', message: 'transport failed' })
const transportFailure = new Error('transport failed')
f.fail(transportFailure)
expect(f.controller.state).toEqual({ phase: 'error', message: 'transport failed', failure: transportFailure })
expect(f.controller.host).toBeUndefined()
await f.stopping.promise
const prepare = vi.fn(async () => {})
@@ -131,11 +135,12 @@ describe('desktop backend controller', () => {
const rejected = expect(start).rejects.toThrow('immediate failure')
await f.started.promise
f.ready.resolve()
f.fail(new Error('immediate failure'))
const immediate = new Error('immediate failure')
f.fail(immediate)
await f.stopping.promise
f.exited.resolve()
await rejected
expect(f.states).toEqual([{ phase: 'starting' }, { phase: 'error', message: 'immediate failure' }])
expect(f.states).toEqual([{ phase: 'starting' }, { phase: 'error', message: 'immediate failure', failure: immediate }])
await f.controller.close()
})
+117
View File
@@ -0,0 +1,117 @@
import { mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
import {
CRASH_REPORTS_RETAINED, crashReportFileName, ERROR_SECTION_MAX_CHARS, pruneCrashReports, renderCrashReport, RendererConsoleTail,
writeCrashReport,
type CrashReportInput,
} from '../src/crash-report.ts'
const roots: string[] = []
afterEach(async () => {
vi.restoreAllMocks()
await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })))
})
async function scratch(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'desktop-crash-'))
roots.push(root)
return root
}
const input = (overrides: Partial<CrashReportInput> = {}): CrashReportInput => ({
source: 'host',
phase: 'running',
error: Object.assign(new Error("ENOENT: no such file or directory, open 'C:\\\\Temp\\\\dsh-subprocess-x\\\\out.log'"), {
errno: -4058, code: 'ENOENT', syscall: 'open', path: 'C:\\Temp\\dsh-subprocess-x\\out.log',
}),
rendererConsole: [],
app: { name: 'DeepSeek Harness', version: '0.1.7', platform: 'win32', arch: 'x64', electron: '44.0.0', node: '24.18.1', locale: 'zh_CN' },
time: new Date('2026-09-22T10:30:00.123Z'),
...overrides,
})
it('names files by sortable time and source', () => {
expect(crashReportFileName(new Date('2026-09-22T10:30:00.123Z'), 'web-boot')).toBe('crash-2026-09-22T10-30-00-123Z-web-boot.log')
})
it('renders the facts header, the inspected error with its properties and cause, and the renderer console', () => {
const text = renderCrashReport(input({
error: new Error('wrapper', { cause: input().error }),
rendererConsole: ['dsh-app://app/assets/entry.js:12 client-modules: bundle script plugins/??a/client.js&rev=1 failed to load'],
}))
expect(text).toContain('time: 2026-09-22T10:30:00.123Z\nsource: host\nphase: running\napp: DeepSeek Harness 0.1.7\nplatform: win32 x64\nelectron: 44.0.0\nnode: 24.18.1\nlocale: zh_CN\n')
expect(text).toContain('--- error ---\nError: wrapper')
expect(text).toContain("syscall: 'open'")
expect(text).toContain("path: 'C:\\\\Temp\\\\dsh-subprocess-x\\\\out.log'")
expect(text).toContain('[cause]: Error: ENOENT')
expect(text).toContain('--- renderer console (error level, oldest first) ---\ndsh-app://app/assets/entry.js:12 client-modules: bundle script')
expect(text.endsWith('\n')).toBe(true)
})
it('prints the Host diagnostic verbatim in its own section when the Host reported one', () => {
const diagnostic = "Error: profile has no cordis.yml\n at load (index.js:1:1) {\n code: 'ENOENT'\n}"
const text = renderCrashReport(input({ error: new Error('profile has no cordis.yml'), hostDiagnostic: diagnostic }))
expect(text).toContain(`--- host diagnostic (as reported by the Host process) ---\n${diagnostic}\n\n--- renderer console`)
expect(renderCrashReport(input())).not.toContain('--- host diagnostic')
})
it('says so when no renderer console output was captured and keeps a long error message whole', () => {
const text = renderCrashReport(input({ error: new Error('x'.repeat(20_000)) }))
expect(text).toContain('(no error-level renderer console output was captured)')
expect(text).toContain('x'.repeat(20_000))
})
it('writes an owner-only report into a directory it creates and returns its path', async () => {
const root = await scratch()
const directory = join(root, 'logs')
const path = await writeCrashReport(directory, input())
expect(path).toBe(join(directory, 'crash-2026-09-22T10-30-00-123Z-host.log'))
expect(await readFile(path!, 'utf8')).toContain('source: host')
if (process.platform !== 'win32') expect((await stat(path!)).mode & 0o777).toBe(0o600)
})
it('returns undefined and logs when the report cannot be written', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const root = await scratch()
const blocked = join(root, 'not-a-directory')
await writeFile(blocked, '')
expect(await writeCrashReport(blocked, input())).toBeUndefined()
expect(error).toHaveBeenCalledWith('dsh desktop: crash report could not be written', expect.stringContaining('crash-'), expect.anything())
})
it('prunes only the oldest crash reports and leaves other files alone', async () => {
const root = await scratch()
const names = Array.from({ length: CRASH_REPORTS_RETAINED + 3 }, (_, index) =>
crashReportFileName(new Date(Date.UTC(2026, 8, 1 + index)), 'main'))
for (const name of names) await writeFile(join(root, name), '')
const foreign = ['crash-notes.txt', 'crash-notes.log', 'crash-2026-09-01T00-00-00-000Z-unknown.log', 'update-journal.jsonl']
for (const name of foreign) await writeFile(join(root, name), '')
await pruneCrashReports(root)
const remaining = (await readdir(root)).sort()
expect(remaining).toEqual([...names.slice(3), ...foreign].sort())
})
it('cuts an oversized error section and says so', () => {
const text = renderCrashReport(input({ error: new Error('y'.repeat(300 * 1024)) }))
const section = text.slice(text.indexOf('--- error ---'), text.indexOf('--- renderer console'))
expect(section.length).toBeLessThan(ERROR_SECTION_MAX_CHARS + 200)
expect(section).toContain(`… (error section cut at ${String(ERROR_SECTION_MAX_CHARS)} characters)`)
})
it('treats a missing logs directory as nothing to prune', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
await pruneCrashReports(join(await scratch(), 'absent'))
expect(error).not.toHaveBeenCalled()
})
it('keeps the newest renderer console lines within the byte cap, never cutting a line', () => {
const tail = new RendererConsoleTail(20)
tail.push('a'.repeat(8))
tail.push('b'.repeat(8))
tail.push('c'.repeat(8))
expect(tail.snapshot()).toEqual(['b'.repeat(8), 'c'.repeat(8)])
tail.push('d'.repeat(40))
expect(tail.snapshot()).toEqual(['d'.repeat(40)])
})
@@ -0,0 +1,10 @@
DeepSeek Harness is unavailable
The application could not start or stopped unexpectedly.
Desktop Host failed
Plugin initialization failed
Diagnostic report: C:\Users\someone\AppData\Roaming\DeepSeek Harness\logs\crash-2026-09-22T10-30-00-000Z-host.log
If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.
Exit
Restart
Disable third-party plugins, back up profile patch, and restart
@@ -0,0 +1,10 @@
DeepSeek Harness 无法使用
应用无法启动或已意外停止。
Desktop Host failed
Plugin initialization failed
诊断报告:C:\Users\someone\AppData\Roaming\DeepSeek Harness\logs\crash-2026-09-22T10-30-00-000Z-host.log
如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。
退出
重启
禁用第三方插件、备份 profile patch 并重启
+120 -12
View File
@@ -1,9 +1,13 @@
import { afterEach, expect, it, vi } from 'vitest'
import type { MessageBoxOptions } from 'electron'
import { DesktopFatalRecovery } from '../src/fatal-recovery.ts'
import { CRASH_REPORT_WAIT_MS, DesktopFatalRecovery } from '../src/fatal-recovery.ts'
import type { CrashReportSource } from '../src/crash-report.ts'
import { resolveDesktopLocale } from '../src/locale.ts'
function fixture(locale = 'en') {
function fixture(
locale = 'en',
writeReport: (error: unknown, source: CrashReportSource) => Promise<string | undefined> = async () => undefined,
) {
const choice = Promise.withResolvers<{ response: number; checkboxChecked: boolean }>()
const stopped = Promise.withResolvers<undefined>()
const operations = {
@@ -13,17 +17,26 @@ function fixture(locale = 'en') {
disablePlugins: vi.fn(async () => {}),
exit: vi.fn(),
restart: vi.fn(),
writeReport: vi.fn(writeReport),
}
return { operations, choice, stopped, recovery: new DesktopFatalRecovery(operations) }
}
/** The dialog opens only after the report write settles, so tests wait for the first show() call. */
async function shown(operations: { show: ReturnType<typeof vi.fn> }): Promise<void> {
await vi.waitFor(() => { expect(operations.show).toHaveBeenCalled() })
}
const REPORT_PATH = 'C:\\Users\\someone\\AppData\\Roaming\\DeepSeek Harness\\logs\\crash-2026-09-22T10-30-00-000Z-host.log'
afterEach(() => { vi.restoreAllMocks() })
it.each(['en', 'zh-CN'])('offers only exit and restart for a listener conflict in %s', async (locale) => {
const { operations, choice, stopped, recovery } = fixture(locale)
const pending = recovery.report(new AggregateError([
new Error('webserver (@deepseek-ai/dsh-host-webserver): Error: listen EADDRINUSE: address already in use 127.0.0.1:19387'),
], 'required startup failure'))
], 'required startup failure'), 'host')
await shown(operations)
const options = operations.show.mock.calls[0]![0]
expect(options.buttons).toEqual([operations.messages().exitApplication, operations.messages().restartApplication])
await expect([options.title, options.message, options.detail, ...options.buttons!].join('\n') + '\n')
@@ -38,7 +51,8 @@ it.each(['en', 'zh-CN'])('offers only exit and restart for a listener conflict i
it.each(['win32', 'darwin', 'linux'] as const)('offers the same listener conflict recovery on %s', async (platform) => {
vi.spyOn(process, 'platform', 'get').mockReturnValue(platform)
const { operations, choice, stopped, recovery } = fixture()
const pending = recovery.report(new Error('listen EADDRINUSE: address already in use'))
const pending = recovery.report(new Error('listen EADDRINUSE: address already in use'), 'main')
await shown(operations)
expect(operations.show.mock.calls[0]![0].buttons).toEqual([
operations.messages().exitApplication, operations.messages().restartApplication,
])
@@ -50,7 +64,8 @@ it.each(['win32', 'darwin', 'linux'] as const)('offers the same listener conflic
it.each(['en', 'zh-CN'])('records the %s native recovery dialog', async (locale) => {
const { operations, choice, stopped, recovery } = fixture(locale)
const pending = recovery.report(new AggregateError([new Error('Plugin initialization failed')], 'Desktop Host failed'))
const pending = recovery.report(new AggregateError([new Error('Plugin initialization failed')], 'Desktop Host failed'), 'main')
await shown(operations)
const options = operations.show.mock.calls[0]![0]
await expect([options.title, options.message, options.detail, ...options.buttons!].join('\n') + '\n')
.toMatchFileSnapshot(`expected/fatal-dialog-${locale}.txt`)
@@ -61,14 +76,15 @@ it.each(['en', 'zh-CN'])('records the %s native recovery dialog', async (locale)
it('locks the first report before the dialog settles and never resets after an action', async () => {
const { operations, choice, stopped, recovery } = fixture()
const pending = recovery.report(new Error('first failure'))
await recovery.report(new Error('second failure'))
const pending = recovery.report(new Error('first failure'), 'main')
await shown(operations)
await recovery.report(new Error('second failure'), 'main')
expect(operations.show).toHaveBeenCalledOnce()
expect(operations.show.mock.calls[0]![0].detail).toContain('first failure')
choice.resolve({ response: 1, checkboxChecked: false })
stopped.resolve(undefined)
await pending
await recovery.report(new Error('third failure'))
await recovery.report(new Error('third failure'), 'main')
expect(operations.show).toHaveBeenCalledOnce()
})
@@ -76,7 +92,7 @@ it.each([0, 1, 2])('waits for shutdown before executing choice %s', async (respo
const { operations, choice, stopped, recovery } = fixture()
const stopping = Promise.withResolvers<undefined>()
operations.stop.mockImplementation(() => { stopping.resolve(undefined); return stopped.promise })
const pending = recovery.report(new Error('fatal'))
const pending = recovery.report(new Error('fatal'), 'main')
choice.resolve({ response, checkboxChecked: false })
await stopping.promise
expect(operations.exit).not.toHaveBeenCalled()
@@ -96,7 +112,7 @@ it('reports a user-requested disable failure and allows exit without restarting'
.mockResolvedValueOnce({ response: 0, checkboxChecked: false })
operations.disablePlugins.mockRejectedValueOnce(new Error('profile is read-only'))
stopped.resolve(undefined)
await recovery.report(new Error('fatal'))
await recovery.report(new Error('fatal'), 'main')
expect(operations.show).toHaveBeenCalledTimes(2)
expect(operations.show.mock.calls[1]![0].detail).toContain('profile is read-only')
expect(operations.restart).not.toHaveBeenCalled()
@@ -106,7 +122,7 @@ it('reports a user-requested disable failure and allows exit without restarting'
it('allows exit after shutdown cleanup fails', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const { operations, choice, stopped, recovery } = fixture()
const pending = recovery.report(new Error('fatal'))
const pending = recovery.report(new Error('fatal'), 'main')
choice.resolve({ response: 0, checkboxChecked: false })
stopped.reject(new Error('cleanup failed'))
await pending
@@ -120,7 +136,7 @@ it.each(['en', 'zh-CN'])('bounds long diagnostics and recovery-operation errors
.mockResolvedValueOnce({ response: 0, checkboxChecked: false })
operations.disablePlugins.mockRejectedValueOnce(new Error('read-only\n'.repeat(5000) + 'final write failure'))
stopped.resolve(undefined)
await recovery.report(new Error('😀'.repeat(32768) + '\nfinal backend failure'))
await recovery.report(new Error('😀'.repeat(32768) + '\nfinal backend failure'), 'main')
for (const [options] of operations.show.mock.calls) {
expect(options.detail!.length).toBeLessThanOrEqual(1200)
expect(options.detail!.split('\n').length).toBeLessThanOrEqual(12)
@@ -131,3 +147,95 @@ it.each(['en', 'zh-CN'])('bounds long diagnostics and recovery-operation errors
expect(operations.show.mock.calls[0]![0].detail).toContain('final backend failure')
expect(operations.show.mock.calls[1]![0].detail).toContain('final write failure')
})
it.each(['en', 'zh-CN'])('names the report file even when the error is short enough to show whole, in %s', async (locale) => {
const { operations, choice, stopped, recovery } = fixture(locale, async () => REPORT_PATH)
const pending = recovery.report(new Error('Desktop Host failed\nPlugin initialization failed'), 'host')
await shown(operations)
await vi.waitFor(() => { expect(operations.show).toHaveBeenCalledOnce() })
expect(operations.writeReport).toHaveBeenCalledWith(expect.any(Error), 'host')
const options = operations.show.mock.calls[0]![0]
expect(options.detail).not.toContain(operations.messages().diagnosticTruncated)
expect(options.detail).toContain(REPORT_PATH)
await expect([options.title, options.message, options.detail, ...options.buttons!].join('\n') + '\n')
.toMatchFileSnapshot(`expected/fatal-dialog-with-report-${locale}.txt`)
choice.resolve({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
await pending
})
it('keeps the report line inside the detail budget when the error is long', async () => {
const { operations, choice, stopped, recovery } = fixture('en', async () => REPORT_PATH)
const pending = recovery.report(new Error('😀'.repeat(32768) + '\nfinal backend failure'), 'web-boot')
await shown(operations)
await vi.waitFor(() => { expect(operations.show).toHaveBeenCalledOnce() })
const detail = operations.show.mock.calls[0]![0].detail!
expect(detail.length).toBeLessThanOrEqual(1200)
expect(detail.split('\n').length).toBeLessThanOrEqual(12)
expect(detail.isWellFormed()).toBe(true)
expect(detail).toContain(operations.messages().diagnosticTruncated)
expect(detail).toContain('final backend failure')
expect(detail).toContain(REPORT_PATH)
expect(detail.indexOf(REPORT_PATH)).toBeLessThan(detail.indexOf(operations.messages().startupReinstallAdvice))
choice.resolve({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
await pending
})
it('names the report file in the listener-conflict dialog too', async () => {
const { operations, choice, stopped, recovery } = fixture('en', async () => REPORT_PATH)
const pending = recovery.report(new Error('listen EADDRINUSE: address already in use 127.0.0.1:19387'), 'host')
await shown(operations)
await vi.waitFor(() => { expect(operations.show).toHaveBeenCalledOnce() })
const options = operations.show.mock.calls[0]![0]
expect(options.buttons).toHaveLength(2)
expect(options.detail).toBe(`${operations.messages().startupAddressInUse}\n${operations.messages().reportWrittenTo.replace('{path}', REPORT_PATH)}`)
choice.resolve({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
await pending
})
it('shows the dialog without a path when the report write fails or returns nothing', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
for (const writeReport of [async () => undefined, async () => { throw new Error('disk full') }]) {
const { operations, choice, stopped, recovery } = fixture('en', writeReport)
const pending = recovery.report(new Error('fatal'), 'main')
await shown(operations)
await vi.waitFor(() => { expect(operations.show).toHaveBeenCalledOnce() })
expect(operations.show.mock.calls[0]![0].detail).toBe(`fatal\n\n${operations.messages().startupReinstallAdvice}`)
choice.resolve({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
await pending
}
})
it('does not wait longer than the report deadline before showing the dialog', async () => {
vi.useFakeTimers()
try {
const { operations, choice, stopped, recovery } = fixture('en', () => new Promise<string>(() => {}))
const pending = recovery.report(new Error('fatal'), 'main')
await vi.advanceTimersByTimeAsync(CRASH_REPORT_WAIT_MS - 1)
expect(operations.show).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(1)
expect(operations.show).toHaveBeenCalledOnce()
expect(operations.show.mock.calls[0]![0].detail).not.toContain('crash-')
choice.resolve({ response: 0, checkboxChecked: false })
stopped.resolve(undefined)
await pending
} finally {
vi.useRealTimers()
}
})
it('writes the report once for the first fatal failure and not for the recovery-failure redisplay', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const { operations, stopped, recovery } = fixture('en', async () => REPORT_PATH)
operations.show.mockResolvedValueOnce({ response: 2, checkboxChecked: false })
.mockResolvedValueOnce({ response: 0, checkboxChecked: false })
operations.disablePlugins.mockRejectedValueOnce(new Error('profile is read-only'))
stopped.resolve(undefined)
await recovery.report(new Error('fatal'), 'host')
expect(operations.show).toHaveBeenCalledTimes(2)
expect(operations.writeReport).toHaveBeenCalledOnce()
expect(operations.show.mock.calls[1]![0].detail).toContain(REPORT_PATH)
})
+15 -1
View File
@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { DesktopHostProcess, DesktopHostUncleanExitError } from '../src/host-process.ts'
import { DesktopHostFatalError, DesktopHostProcess, DesktopHostUncleanExitError } from '../src/host-process.ts'
const roots: string[] = []
const hosts: DesktopHostProcess[] = []
@@ -176,11 +176,25 @@ describe('desktop host process', () => {
it.each([
["process.send({ type: 'fatal', message: 'startup failed' }); process.disconnect()", 'startup failed'],
["process.send({ type: 'ready', url: 4 })", 'invalid IPC event'],
["process.send({ type: 'fatal', message: 'startup failed', diagnostic: 42 })", 'invalid IPC event'],
['process.exit(0)', 'host stopped'],
])('rejects startup when the child fails before readiness: %s', async (source, message) => {
const host = hostProcess(projectWithHost(source))
await expect(host.start()).rejects.toThrow(message)
})
it('keeps the Host\'s inspected error separate from the message it reports', async () => {
const diagnostic = "Error: startup failed\\n at boot (lib/index.js:3:9) {\\n code: 'ENOENT',\\n path: '/profile/cordis.yml'\\n}"
const failures: Error[] = []
const host = hostProcess(projectWithHost(
`process.send({ type: 'fatal', message: 'startup failed', diagnostic: ${JSON.stringify(diagnostic)} }); process.disconnect()`,
), undefined, (error) => { failures.push(error) })
await expect(host.start()).rejects.toThrow('startup failed')
const [failure] = failures
expect(failure).toBeInstanceOf(DesktopHostFatalError)
expect((failure as DesktopHostFatalError).diagnostic).toBe(diagnostic)
expect(Object.keys(failure!)).not.toContain('diagnostic')
})
})
it('carries Platform credentials over private IPC and clears them on shutdown', async () => {
+70 -1
View File
@@ -8,14 +8,22 @@ import { tmpdir } from 'node:os'
import type { MenuItemConstructorOptions, MessageBoxOptions } from 'electron'
import { DESKTOP_IPC, type DesktopUpdateState } from '../src/ipc.ts'
import { MANDATORY_IPC } from '../src/mandatory-update-ipc.ts'
import { DesktopHostUncleanExitError } from '../src/host-process.ts'
import { DesktopHostFatalError, DesktopHostUncleanExitError } from '../src/host-process.ts'
import { en } from '../src/locale.ts'
import { DesktopUpdatePreparationError } from '../src/update-error.ts'
import { writeCrashReport } from '../src/crash-report.ts'
type InvokeEvent = { sender?: unknown; senderFrame: { url: string } }
type InvokeHandler = (event: InvokeEvent, ...args: unknown[]) => unknown
vi.mock('../src/web-document.ts', () => ({ authenticateWebHost: async () => 'test-cookie', serveWebDocument: vi.fn(), forwardWebRequest: vi.fn() }))
// Report persistence has its own unit tests; here it resolves within microtasks so the fatal
// dialog never outlives the test that triggered it.
vi.mock('../src/crash-report.ts', async importOriginal => ({
...await importOriginal<typeof import('../src/crash-report.ts')>(),
writeCrashReport: vi.fn(async () => 'desktop-test-logs/crash-test.log'),
pruneCrashReports: vi.fn(async () => {}),
}))
const harness = await vi.hoisted(async () => {
const { EventEmitter } = await import('node:events')
@@ -131,6 +139,8 @@ const harness = await vi.hoisted(async () => {
getPreferredSystemLanguages: () => ['en-US'],
getVersion: () => '1.0.0',
getAppPath: (): string => 'desktop-test-app',
setAppLogsPath: vi.fn(),
getPath: (name: string): string => `desktop-test-${name}`,
setAboutPanelOptions: vi.fn<(options: Electron.AboutPanelOptionsOptions) => void>(),
requestSingleInstanceLock: () => true,
setAsDefaultProtocolClient: vi.fn(),
@@ -1426,7 +1436,10 @@ describe('desktop main startup', () => {
expect(() => { handler(event, {}) }).toThrow('must be text')
expect(harness.dialog.showMessageBox).not.toHaveBeenCalled()
handler(event, 'client mount failed')
await harness.dialogShown.promise
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('client mount failed')
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('desktop-test-logs/crash-test.log')
expect(writeCrashReport).toHaveBeenCalledWith('desktop-test-logs', expect.objectContaining({ source: 'web-boot', phase: 'startup' }))
expect(window.urls).toEqual(['dsh-app://app/'])
})
@@ -1438,7 +1451,9 @@ describe('desktop main startup', () => {
window.webContents.emit('did-fail-load', {}, -3, 'aborted', 'dsh-app://app/', true)
expect(harness.dialog.showMessageBox).not.toHaveBeenCalled()
window.webContents.emit('did-fail-load', {}, -2, 'failed', 'dsh-app://app/', true)
await harness.dialogShown.promise
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('Desktop page failed to load')
expect(writeCrashReport).toHaveBeenCalledWith('desktop-test-logs', expect.objectContaining({ source: 'renderer' }))
})
it('offers all recovery choices when resources fail before the Host starts', async () => {
@@ -1486,6 +1501,60 @@ describe('desktop main startup', () => {
expect(harness.hosts).toHaveLength(0)
})
it('writes the Host\'s own diagnostic into a startup-phase crash report when the Host reports a fatal error before ready', async () => {
await import('../src/main.ts')
await harness.preparing.promise
harness.prepared.resolve()
await harness.hostStarted.promise
const host = harness.hosts[0]!
const diagnostic = "Error: profile has no cordis.yml\n at loadProfileDirectory (app-boot/lib/index.js:12:3) {\n code: 'ENOENT',\n path: '/profiles/desktop/cordis.yml'\n}"
// DesktopHostProcess.fail() rejects start() and calls onFailure with the same error object.
const failure = new DesktopHostFatalError('profile has no cordis.yml', diagnostic)
host.onFailure!(failure)
host.ready.reject(failure)
await host.stopping.promise
host.exited.resolve()
await harness.dialogShown.promise
const [directory, report] = vi.mocked(writeCrashReport).mock.calls[0]!
expect(directory).toBe('desktop-test-logs')
expect(report.source).toBe('host')
expect(report.phase).toBe('startup')
expect(report.error).toBeInstanceOf(DesktopHostFatalError)
expect(report.hostDiagnostic).toBe(diagnostic)
expect((harness.dialog.showMessageBox.mock.calls[0]![0] as MessageBoxOptions).detail).toContain('profile has no cordis.yml')
})
it('attaches the primary window\'s error-level console output to a running-phase Host crash report', async () => {
harness.dialog.showMessageBox.mockResolvedValue({ response: 0, checkboxChecked: false })
await import('../src/main.ts')
await harness.preparing.promise
harness.prepared.resolve()
await harness.hostStarted.promise
const host = harness.hosts[0]!
host.ready.resolve()
await Promise.resolve(invoke(DESKTOP_IPC.boot))
const window = harness.windows[0]!
window.webContents.emit('console-message', { level: 'info', message: 'boot ok', sourceId: 'dsh-app://app/assets/entry.js', lineNumber: 1 })
window.webContents.emit('console-message', {
level: 'error', message: 'client-modules: bundle script plugins/??a/client.js&rev=1 failed to load',
sourceId: 'dsh-app://app/assets/entry.js', lineNumber: 12,
})
host.onFailure!(new Error('dsh desktop host exited with 1: fatal uncaught exception: ENOENT'))
await host.stopping.promise
expect(writeCrashReport).toHaveBeenCalledOnce()
const [directory, report] = vi.mocked(writeCrashReport).mock.calls[0]!
expect(directory).toBe('desktop-test-logs')
expect(report.source).toBe('host')
expect(report.phase).toBe('running')
expect(report.error).toBeInstanceOf(Error)
expect((report.error as Error).message).toContain('fatal uncaught exception: ENOENT')
expect(report.rendererConsole).toEqual(['dsh-app://app/assets/entry.js:12 client-modules: bundle script plugins/??a/client.js&rev=1 failed to load'])
expect(report.app).toMatchObject({ name: 'Desktop test', version: '1.0.0', platform: process.platform, locale: 'en' })
expect(report.time).toBeInstanceOf(Date)
host.exited.resolve()
await harness.quitCompleted.promise
})
it.each([0, 1, 2])('waits for Host exit before recovery action %s', async (response) => {
harness.dialog.showMessageBox.mockResolvedValue({ response, checkboxChecked: false })
await import('../src/main.ts')
+25
View File
@@ -54,6 +54,31 @@ it('forwards upload bytes and cancellation with Host credentials while keeping t
expect(await response.text()).toBe('stream')
})
it('drops connection-level headers the Host wrote for its own transport', async () => {
const fetch = vi.fn().mockResolvedValue(new Response('body', { headers: {
'transfer-encoding': 'chunked', connection: 'keep-alive', 'keep-alive': 'timeout=5', trailer: 'x', te: 'trailers',
'content-type': 'text/plain', 'cache-control': 'no-cache', etag: '"1"',
} }))
vi.stubGlobal('fetch', fetch)
const response = await forwardWebRequest(new Request('dsh-app://app/api/read'), 'http://127.0.0.1:1234/', 'session=owned')
for (const name of ['transfer-encoding', 'connection', 'keep-alive', 'trailer', 'te']) expect(response.headers.get(name)).toBeNull()
expect(response.headers.get('content-type')).toBe('text/plain')
expect(response.headers.get('cache-control')).toBe('no-cache')
expect(response.headers.get('etag')).toBe('"1"')
})
it('replaces the immutable cache header of plugin bundles with no-store and leaves other routes alone', async () => {
const immutable = 'public, max-age=31536000, immutable'
const fetch = vi.fn().mockImplementation(async () => new Response('js', { headers: { 'cache-control': immutable } }))
vi.stubGlobal('fetch', fetch)
const bundle = await forwardWebRequest(new Request('dsh-app://app/plugins/??a/client.js&rev=1'), 'http://127.0.0.1:1234/', 'c')
expect(bundle.headers.get('cache-control')).toBe('no-store')
const chunk = await forwardWebRequest(new Request('dsh-app://app/plugins/a/client.x.js?rev=1'), 'http://127.0.0.1:1234/', 'c')
expect(chunk.headers.get('cache-control')).toBe('no-store')
const asset = await forwardWebRequest(new Request('dsh-app://app/api/plugins/list'), 'http://127.0.0.1:1234/', 'c')
expect(asset.headers.get('cache-control')).toBe(immutable)
})
it('refuses another page origin without forwarding its request', async () => {
const fetch = vi.fn()
vi.stubGlobal('fetch', fetch)
@@ -34,6 +34,11 @@ const state = vi.hoisted(() => ({
nativeTheme: { themeSource: 'system', shouldUseDarkColors: false },
}))
vi.mock('../src/crash-report.ts', async importOriginal => ({
...await importOriginal<typeof import('../src/crash-report.ts')>(),
writeCrashReport: vi.fn(async () => undefined),
pruneCrashReports: vi.fn(async () => {}),
}))
vi.mock('electron', () => ({
clipboard: { writeText: state.copy },
app: {
@@ -46,6 +51,8 @@ vi.mock('electron', () => ({
getVersion: () => '1.0.0',
setAboutPanelOptions: vi.fn(),
getAppPath: () => '/development-app',
getPath: (name: string) => `/development-${name}`,
setAppLogsPath: vi.fn(),
getPreferredSystemLanguages: () => ['en-US'],
on: (name: string, callback: (...args: unknown[]) => void) => { state.appListeners.set(name, callback) },
quit: state.quit,
@@ -0,0 +1,10 @@
- group "从哪个 npm 源下载插件":
- radio "默认安装源(registry.npmjs.org)"
- text: 默认安装源(registry.npmjs.org)
- radio "中国大陆镜像源(registry.npmmirror.com)" [checked]
- text: 中国大陆镜像源(registry.npmmirror.com)
- radio "自定义地址"
- text: 自定义地址
- textbox "自定义地址" [disabled]:
- /placeholder: https://npm.example.com/
- text: 公司内网或私有 npm 源;需要登录的源,把凭据放在本机的 ~/.npmrc 里
@@ -0,0 +1,10 @@
- group "从哪个 npm 源下载插件":
- radio "默认安装源(registry.npmjs.org)" [checked]
- text: 默认安装源(registry.npmjs.org)
- radio "中国大陆镜像源(registry.npmmirror.com)"
- text: 中国大陆镜像源(registry.npmmirror.com)
- radio "自定义地址"
- text: 自定义地址
- textbox "自定义地址" [disabled]:
- /placeholder: https://npm.example.com/
- text: 公司内网或私有 npm 源;需要登录的源,把凭据放在本机的 ~/.npmrc 里
+30
View File
@@ -0,0 +1,30 @@
/** Controlled public-registry responses inside one isolated Web-test Host. */
import { appendFileSync } from 'node:fs'
export const name = 'registry-ping-fixture'
/** Replace only npm registry ping requests and restore the Host transport on unload. */
export function apply(ctx, config) {
ctx.effect(() => {
const original = globalThis.fetch
const lifetime = new AbortController()
const pending = new Set()
const endpoints = ['https://registry.npmjs.org/-/ping', 'https://registry.npmmirror.com/-/ping']
globalThis.fetch = (input, init) => {
if (typeof input !== 'string' || !endpoints.includes(input)) return original(input, init)
appendFileSync(config.requestLog, JSON.stringify(input) + '\n')
if (input === `${config.winner}-/ping`) return Promise.resolve(new Response('{}'))
const signal = AbortSignal.any([init.signal, lifetime.signal])
const request = new Promise((_resolve, reject) => {
if (signal.aborted) reject(signal.reason)
else signal.addEventListener('abort', () => { reject(signal.reason) }, { once: true })
})
pending.add(request)
return request.finally(() => { pending.delete(request) })
}
return async () => {
globalThis.fetch = original
lifetime.abort()
await Promise.allSettled(pending)
}
})
}
+30
View File
@@ -0,0 +1,30 @@
/** Hold one Host service until the restart test releases application startup. */
export const name = 'web-restart-startup'
/** Keep the carrier services available while Session Controller startup is held. */
export const inject = ['typertGateway', 'connection', 'webServer']
/**
* Provide the test-only dependency after startup has been released.
* @param {import('@deepseek-ai/cordis').Context} ctx - Host plugin context.
* @returns {Promise<void>} Once the barrier is released or the plugin is disposed.
*/
export async function apply(ctx) {
if (process.env.DSH_WEB_RESTART_HOLD_STARTUP === '1') {
if (typeof process.send !== 'function') throw new Error('web restart startup fixture requires an IPC channel')
const released = Promise.withResolvers()
const resume = (message) => {
if (message === 'resume-startup') released.resolve(true)
}
ctx.effect(() => {
process.on('message', resume)
return () => {
process.off('message', resume)
released.resolve(false)
}
}, 'web-restart: startup barrier')
process.send('startup-blocked')
if (!await released.promise) return
}
ctx.reflect.provide('webRestartReady', {})
}
+5
View File
@@ -0,0 +1,5 @@
- id: session-controller
inject: [webRestartReady]
- insert:
- id: web-restart-startup
name: ./restart-startup.js
+1 -1
View File
@@ -397,7 +397,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
const picker = page.getByRole('dialog', { name: '选择要添加的模型' })
await picker.getByRole('button', { name: '取消全选' }).click()
await picker.getByRole('searchbox', { name: '搜索模型' }).fill('gpt-6-astra')
await picker.getByRole('checkbox', { name: 'gpt-6-astra', exact: true }).check()
await picker.getByRole('checkbox', { name: 'GPT-6 Astra', exact: true }).check()
await picker.getByRole('button', { name: '添加所选' }).click()
await dialog.getByRole('button', { name: '模型选项 1' }).click()
expect(await image.isChecked()).toBe(true)
+28 -6
View File
@@ -6,16 +6,22 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium } from 'playwright'
import { expect, it } from 'vitest'
import { expect, it, onTestFinished } from 'vitest'
import { launchWebScaffold, captureStableAria, compareOrRefreshGolden, webSnapshotMode, watchConsole, type WebScaffold } from './scaffold.ts'
import { ZH_BROWSER_LOCALE } from './support.ts'
const MIRROR = 'https://registry.npmmirror.com/'
it('offers the registries, remembers the one picked, and moves an install on to the next when a run loses its registry', async () => {
it.each(['https://registry.npmjs.org/', MIRROR])('selects the fastest responding registry %s, remembers it, and falls back after a registry failure', async (winner) => {
const scratch = await mkdtemp(join(tmpdir(), 'dsh-install-registry-'))
onTestFinished(() => rm(scratch, { recursive: true, force: true }))
const requestLog = join(scratch, 'registry-pings.jsonl')
await writeFile(requestLog, '')
const overlay = join(scratch, 'cordis.patch.yml')
await writeFile(overlay, `- id: plugin-manager\n config: ${JSON.stringify({ pnpmCommand: process.execPath })}\n`)
const fixture = new URL('./fixtures/registry-ping.mjs', import.meta.url).href
await writeFile(overlay, `- id: plugin-manager\n config: ${JSON.stringify({ pnpmCommand: process.execPath })}\n`
+ `- insert:\n - id: registry-ping-fixture\n name: ${JSON.stringify(fixture)}\n config: ${JSON.stringify({ winner, requestLog })}\n`
+ `- id: ui-plugin-manager\n config: ${JSON.stringify({ registryProbeEnabled: true })}\n`)
let scaffold: WebScaffold | undefined
try {
scaffold = await launchWebScaffold({ profile: { packages: [] }, extraOverlayPath: overlay })
@@ -29,6 +35,7 @@ it('offers the registries, remembers the one picked, and moves an install on to
// it is asked, naming the registry, and installs the package on the next; the Host moves it on to the next registry.
await writeFile(join(profile, 'config'), 'console.log("https://registry.npmjs.org/")\n')
await writeFile(join(profile, 'view'), `
require('node:fs').appendFileSync('.registry-lookups', JSON.stringify(process.argv) + '\\n');
if (!process.argv.includes('--registry=${MIRROR}')) {
console.log(JSON.stringify({ error: { code: 'ERR_PNPM_META_FETCH_FAIL', message: 'GET https://registry.npmjs.org/mirrored-package: request timed out (ETIMEDOUT)' } }));
process.exitCode = 1;
@@ -63,12 +70,25 @@ it('offers the registries, remembers the one picked, and moves an install on to
const dialog = page.getByRole('dialog')
// Folded, the registry control names pnpm's own registry; unfolded, its options float from it and offer the configured
// mirror and a typed address.
const registryToggle = dialog.getByRole('button', { name: '安装源 默认安装源', exact: true })
const registryToggle = dialog.getByRole('button', { name: winner === MIRROR ? '安装源 中国大陆镜像源' : '安装源 默认安装源', exact: true })
await registryToggle.waitFor()
expect(await page.getByRole('radio').count()).toBe(0)
await registryToggle.click()
const options = page.getByRole('group', { name: '从哪个 npm 源下载插件', exact: true })
await options.getByRole('radio', { name: '中国大陆镜像源(registry.npmmirror.com)', exact: true }).click()
const mirror = options.getByRole('radio', { name: '中国大陆镜像源(registry.npmmirror.com)', exact: true })
await expect.poll(async () => (await readFile(requestLog, 'utf8')).trim().split('\n').filter(Boolean)).toHaveLength(2)
const pingUrls = (await readFile(requestLog, 'utf8')).trim().split('\n').sort()
expect(pingUrls).toEqual(['https://registry.npmjs.org/-/ping', 'https://registry.npmmirror.com/-/ping'].map(url => JSON.stringify(url)))
if (winner === MIRROR) {
expect(await mirror.isChecked()).toBe(true)
await compareOrRefreshGolden(fileURLToPath(new URL('./expected/plugin-install-registry/fastest-default.expected.md', import.meta.url)),
await captureStableAria(page, '[data-install-registry]', scaffold.workspaceCwd), webSnapshotMode())
} else {
expect(await options.getByRole('radio', { name: '默认安装源(registry.npmjs.org)', exact: true }).isChecked()).toBe(true)
await compareOrRefreshGolden(fileURLToPath(new URL('./expected/plugin-install-registry/official-default.expected.md', import.meta.url)),
await captureStableAria(page, '[data-install-registry]', scaffold.workspaceCwd), webSnapshotMode())
await mirror.click()
}
expect(await options.getByRole('radio').count()).toBe(3)
await dialog.getByRole('button', { name: '安装源 中国大陆镜像源', exact: true }).waitFor()
await dialog.getByRole('textbox', { name: '包名或地址' }).fill('mirrored-package')
@@ -86,6 +106,9 @@ it('offers the registries, remembers the one picked, and moves an install on to
// the registry after it, which finished it. Each run shows behind the details with the registry it asked.
await dialog.getByRole('button', { name: '立即启用', exact: true }).waitFor({ timeout: 20_000 })
await dialog.getByText('版本 2.0.0', { exact: true }).waitFor()
const lookups = (await readFile(join(profile, '.registry-lookups'), 'utf8')).trim().split('\n')
expect(lookups).toHaveLength(1)
expect(JSON.parse(lookups[0]!)).toContain('--registry=' + MIRROR)
await dialog.getByRole('button', { name: '查看安装详情', exact: true }).click()
await dialog.getByText('Installed from the registry pnpm names', { exact: true }).waitFor()
await dialog.getByText('第 1 次 · 中国大陆镜像源', { exact: true }).waitFor()
@@ -103,6 +126,5 @@ it('offers the registries, remembers the one picked, and moves an install on to
} finally { await browser.close() }
} finally {
await scaffold?.close()
await rm(scratch, { recursive: true, force: true })
}
})
+1
View File
@@ -565,6 +565,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
// Without HMR the profile applies configuration changes at its next start.
...options.profile?.hmr === false ? [{ id: 'hmr', disabled: true }] : [],
{ id: 'session-log-deepseek', config: { enabled: false } },
{ id: 'ui-plugin-manager', config: { registryProbeEnabled: false } },
...mode === 'record' || options.deepSeekMissingCredential === true
? []
: [{ id: 'agent-default-model', config: { provider: 'deepseek-official', model: 'deepseek-v4-flash' } }],
+44 -7
View File
@@ -14,16 +14,18 @@ class RestartableServer {
private child: ChildProcess | undefined
private closed: Promise<void> | undefined
private output = ''
readonly startupBlocked = Promise.withResolvers<undefined>()
constructor(private readonly world: string, private readonly modelUrl: string) {}
async start(port: number): Promise<string> {
async start(port: number, holdStartup = false): Promise<string> {
if (this.child !== undefined) throw new Error('Server is already running')
this.output = ''
const ready = Promise.withResolvers<string>()
const child = spawn(process.execPath, [
join(REPO_ROOT, 'apps/cli/lib/bin.js'), '--profile', 'web',
'--patch', fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
'--patch', fileURLToPath(new URL('./fixtures/restart-startup.overlay.yml', import.meta.url)),
'--no-open', '--port', String(port),
], {
cwd: this.world,
@@ -32,8 +34,9 @@ class RestartableServer {
DSH_HOME: join(this.world, 'home'), DSH_AGENTS_HOME: join(this.world, 'agents'),
DSH_TELEMETRY_DISABLED: '1', DEEPSEEK_API_KEY: 'keyless-server-restart-fixture',
DEEPSEEK_BASE_URL: this.modelUrl,
DSH_WEB_RESTART_HOLD_STARTUP: holdStartup ? '1' : '0',
},
stdio: ['ignore', 'pipe', 'pipe'],
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
})
this.child = child
const receive = (data: Buffer): void => {
@@ -43,6 +46,9 @@ class RestartableServer {
}
child.stdout?.on('data', receive)
child.stderr?.on('data', receive)
child.on('message', (message) => {
if (message === 'startup-blocked') this.startupBlocked.resolve(undefined)
})
child.once('error', (error) => { ready.reject(error) })
this.closed = new Promise((resolve) => {
child.once('close', (code, signal) => {
@@ -58,6 +64,7 @@ class RestartableServer {
async stop(): Promise<void> {
const child = this.child
if (child === undefined) return
this.resumeStartup()
let forced = false
const timer = setTimeout(() => { forced = true; child.kill('SIGKILL') }, 15_000)
try {
@@ -70,10 +77,14 @@ class RestartableServer {
if (forced) throw new Error('Server did not stop after SIGTERM\n' + this.logs())
}
resumeStartup(): void {
if (this.child?.connected) this.child.send('resume-startup')
}
logs(): string { return this.output.replace(/([?&]token=)[A-Za-z0-9_-]+/gu, '$1<redacted>') }
}
it('keeps an opened Session and draft when the server restarts on the same port', async () => {
it.each([false, true])('keeps the same revision, Session and page across a server restart (delayed startup: %s)', async (holdStartup) => {
const world = await mkdtemp(join(tmpdir(), 'dsh-server-restart-'))
onTestFinished(() => rm(world, { recursive: true, force: true }))
const model = createServer((request, response) => {
@@ -126,6 +137,7 @@ it('keeps an opened Session and draft when the server restarts on the same port'
onTestFinished(() => browser.close())
const page = await newEnglishPage(browser)
const errors: string[] = []
const streamErrors: unknown[] = []
const graphs: { rev: string; entries: { id: string; rev: string }[] }[] = []
let readyFrames = 0
let sessionBaselines = 0
@@ -140,7 +152,8 @@ it('keeps an opened Session and draft when the server restarts on the same port'
})
socket.on('framereceived', ({ payload }) => {
if (typeof payload !== 'string') return
const message = JSON.parse(payload) as { type?: string; streamId: string; value?: { type?: string } }
const message = JSON.parse(payload) as { type?: string; streamId: string; value?: { type?: string }; error?: unknown }
if (message.type === 'error') streamErrors.push(message.error)
if (message.type === 'item' && message.value?.type === 'ready') readyFrames++
if (message.type === 'item' && endpoints.get(message.streamId) === 'session/follow'
&& message.value?.type === 'snapshot') sessionBaselines++
@@ -154,7 +167,7 @@ it('keeps an opened Session and draft when the server restarts on the same port'
})
onTestFailed(async () => {
await saveFailureShot(page, 'web-server-restart-' + scenarioId)
await writeFile(join(REPO_ROOT, '.artifacts', 'server-restart-' + scenarioId + '.json'), JSON.stringify({ errors, graphs, server: server.logs() }, null, 2))
await writeFile(join(REPO_ROOT, '.artifacts', 'server-restart-' + scenarioId + '.json'), JSON.stringify({ errors, streamErrors, graphs, server: server.logs() }, null, 2))
})
await page.goto(url, { waitUntil: 'load' })
await page.locator('[data-slot="root"]').waitFor({ state: 'attached', timeout: 20_000 })
@@ -177,7 +190,29 @@ it('keeps an opened Session and draft when the server restarts on the same port'
page.on('framenavigated', () => { navigations++ })
await server.stop()
const restarted = await server.start(port)
let restarted: string
const restarting = server.start(port, holdStartup)
try {
if (holdStartup) {
await Promise.race([
server.startupBlocked.promise,
restarting.then(() => { throw new Error('the restarted Host did not hold controller startup') }),
])
const opened = await page.evaluate(() => new Promise<boolean>((resolve) => {
const endpoint = new URL('api/remote.mux', location.href)
endpoint.protocol = 'ws:'
const socket = new WebSocket(endpoint)
let accepted = false
socket.addEventListener('open', () => { accepted = true; socket.close() })
socket.addEventListener('close', () => { resolve(accepted) })
}))
expect(opened).toBe(false)
expect(readyFrames).toBe(beforeReady)
}
} finally {
server.resumeStartup()
restarted = await restarting
}
expect(new URL(restarted).origin).toBe(new URL(url).origin)
await expect.poll(() => readyFrames, { timeout: 30_000 }).toBeGreaterThan(beforeReady)
await expect.poll(() => sessionBaselines, { timeout: 30_000 }).toBeGreaterThan(beforeBaseline)
@@ -187,7 +222,8 @@ it('keeps an opened Session and draft when the server restarts on the same port'
}))
expect(errors).toEqual([])
expect(graphs.at(-1)).toEqual(graphs[beforeGraphs - 1])
expect(streamErrors).toEqual([])
for (const graph of graphs.slice(beforeGraphs)) expect(graph).toEqual(graphs[beforeGraphs - 1])
expect(await originalRoot!.evaluate(element => element.isConnected)).toBe(true)
expect(await composer.textContent()).toBe(draft)
expect(await response.isVisible()).toBe(true)
@@ -195,5 +231,6 @@ it('keeps an opened Session and draft when the server restarts on the same port'
await composer.press('Enter')
await expect.poll(() => response.count(), { timeout: 20_000 }).toBe(2)
expect(errors).toEqual([])
expect(streamErrors).toEqual([])
expect(navigations).toBe(0)
})
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/capability-seams.md
capability-seams.md: aac4813e5c375af311a36c10820909f85641ca4e
capability-seams.zh.md: f0e584f92658efb7cb34601aeb88494aa8085293
capability-seams.md: 6550250f0cc89ea5ca1c67c07894bc04385f93f6
capability-seams.zh.md: f71f021a32f07eec129e892f8d65445ad7b8d264
+5
View File
@@ -10,6 +10,8 @@ flowchart LR
pkg_hmr["hmr"]
svc_hmr["ctx.hmr<br/>Serialized module and configuration reloads"]
pkg_app_boot["app-boot"]
pkg_client_ui_plugin_manager["client-ui-plugin-manager"]
svc_pluginRegistryProbe["ctx.pluginRegistryProbe<br/>Host registry response comparison"]
pkg_plugin_manager["plugin-manager"]
svc_pluginManager["ctx.pluginManager<br/>Current-profile plugin and bundle management"]
pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"]
@@ -293,6 +295,7 @@ flowchart LR
pkg_client_connection --> svc_connection
pkg_client_file_upload --> svc_fileUploads
pkg_client_modules --> svc_clientModules
pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe
pkg_command_feedback --> svc_sessionFeedback
pkg_commands --> svc_commands
pkg_compaction --> svc_compaction
@@ -470,6 +473,7 @@ flowchart LR
svc_officeToPdf --> pkg_client_ui_sidebar_documentpreview
svc_pluginManager --> pkg_plugin_manager
svc_pluginManager --> pkg_ui_settings_plugin_inventory
svc_pluginRegistryProbe --> pkg_client_ui_plugin_manager
svc_profileContext --> pkg_plugin_manager
svc_ptcRuntime --> pkg_tools
svc_ptcRuntime --> pkg_workflow_ptc
@@ -564,6 +568,7 @@ flowchart LR
| ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note |
| --- | --- | --- | --- | --- | --- | --- |
| `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | Owns module and exact configuration watchers; application mutations share its queue and automatic reloads await the application file lock. |
| `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | Races public registry responses on the Host; the Client owns the initial registry recommendation. |
| `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. |
| `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr. |
| `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams. |
+5
View File
@@ -12,6 +12,8 @@ flowchart LR
pkg_hmr["hmr"]
svc_hmr["ctx.hmr<br/>Serialized module and configuration reloads"]
pkg_app_boot["app-boot"]
pkg_client_ui_plugin_manager["client-ui-plugin-manager"]
svc_pluginRegistryProbe["ctx.pluginRegistryProbe<br/>Host registry response comparison"]
pkg_plugin_manager["plugin-manager"]
svc_pluginManager["ctx.pluginManager<br/>Current-profile plugin and bundle management"]
pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"]
@@ -295,6 +297,7 @@ flowchart LR
pkg_client_connection --> svc_connection
pkg_client_file_upload --> svc_fileUploads
pkg_client_modules --> svc_clientModules
pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe
pkg_command_feedback --> svc_sessionFeedback
pkg_commands --> svc_commands
pkg_compaction --> svc_compaction
@@ -472,6 +475,7 @@ flowchart LR
svc_officeToPdf --> pkg_client_ui_sidebar_documentpreview
svc_pluginManager --> pkg_plugin_manager
svc_pluginManager --> pkg_ui_settings_plugin_inventory
svc_pluginRegistryProbe --> pkg_client_ui_plugin_manager
svc_profileContext --> pkg_plugin_manager
svc_ptcRuntime --> pkg_tools
svc_ptcRuntime --> pkg_workflow_ptc
@@ -566,6 +570,7 @@ flowchart LR
| ctx 键 | 角色 | 所属包 | 实现 | 直接消费方 | 配套插件 | 说明 |
| --- | --- | --- | --- | --- | --- | --- |
| `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | 负责模块和精确配置监听;应用修改共用其队列,自动重载等待应用文件锁。 |
| `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | 在 Host 上并发比较公共安装源响应;初始安装源推荐由 Client 负责。 |
| `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 |
| `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | dsh launcher 提供纯数据形式的 profile 位置与组合输入;重载调度由 dsh-hmr 负责。 |
| `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 负责浏览器认证与共享 HTTP 请求分发;API 适配器注册端点和流。 |
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/config-catalog.md
config-catalog.md: fc5a8e12cf94715934d484121dfbbccc7ffc4252
config-catalog.zh.md: 26c7807c997c41a208e047965eec59eeec925a9c
config-catalog.md: b9e75f6679d43aef41808a30ed370e26070c1331
config-catalog.zh.md: d76c88fb806998abee414347822a3d11c3b2b7de
+19 -2
View File
@@ -194,7 +194,7 @@ export interface Config {
}
```
Source: [`packages/api/gateway/src/index.ts:144`](../packages/api/gateway/src/index.ts)
Source: [`packages/api/gateway/src/index.ts:145`](../packages/api/gateway/src/index.ts)
<a id="deepseek-aidsh-api-job-controller"></a>
@@ -481,6 +481,24 @@ export interface Config {
Source: [`packages/client/hmr/src/index.ts:30`](../packages/client/hmr/src/index.ts)
<a id="deepseek-aidsh-client-ui-plugin-manager"></a>
## `@deepseek-ai/dsh-client-ui-plugin-manager`
```ts config-catalog
/** Registry-probe deadline and process-local cache policy. */
export interface Config {
/** Whether the dialog can compare the public npm registries. */
registryProbeEnabled: boolean
/** Deadline for the parallel HTTPS probes, including response cleanup. */
registryProbeTimeoutMs: number
/** Lifetime of a winning registry or unavailable result. */
registryProbeCacheTtlMs: number
}
```
Source: [`packages/client/ui-plugin-manager/src/index.ts:15`](../packages/client/ui-plugin-manager/src/index.ts)
<a id="deepseek-aidsh-client-ui-settings-account"></a>
## `@deepseek-ai/dsh-client-ui-settings-account`
@@ -4112,7 +4130,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
- `@deepseek-ai/dsh-client-ui-open-in-app` ([`packages/client/ui-open-in-app/src/index.ts`](../packages/client/ui-open-in-app/src/index.ts))
- `@deepseek-ai/dsh-client-ui-permission-presets` ([`packages/client/ui-permission-presets/src/index.ts`](../packages/client/ui-permission-presets/src/index.ts))
- `@deepseek-ai/dsh-client-ui-plan` ([`packages/client/ui-plan/src/index.ts`](../packages/client/ui-plan/src/index.ts))
- `@deepseek-ai/dsh-client-ui-plugin-manager` ([`packages/client/ui-plugin-manager/src/index.ts`](../packages/client/ui-plugin-manager/src/index.ts))
- `@deepseek-ai/dsh-client-ui-reference` ([`packages/client/ui-reference/src/index.ts`](../packages/client/ui-reference/src/index.ts))
- `@deepseek-ai/dsh-client-ui-renderer` ([`packages/client/ui-renderer/src/index.ts`](../packages/client/ui-renderer/src/index.ts))
- `@deepseek-ai/dsh-client-ui-schedule` ([`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts))
+19 -2
View File
@@ -196,7 +196,7 @@ export interface Config {
}
```
来源:[`packages/api/gateway/src/index.ts:144`](../packages/api/gateway/src/index.ts)
来源:[`packages/api/gateway/src/index.ts:145`](../packages/api/gateway/src/index.ts)
<a id="deepseek-aidsh-api-job-controller"></a>
@@ -483,6 +483,24 @@ export interface Config {
来源: [`packages/client/hmr/src/index.ts:30`](../packages/client/hmr/src/index.ts)
<a id="deepseek-aidsh-client-ui-plugin-manager"></a>
## `@deepseek-ai/dsh-client-ui-plugin-manager`
```ts config-catalog
/** Registry-probe deadline and process-local cache policy. */
export interface Config {
/** Whether the dialog can compare the public npm registries. */
registryProbeEnabled: boolean
/** Deadline for the parallel HTTPS probes, including response cleanup. */
registryProbeTimeoutMs: number
/** Lifetime of a winning registry or unavailable result. */
registryProbeCacheTtlMs: number
}
```
来源: [`packages/client/ui-plugin-manager/src/index.ts:15`](../packages/client/ui-plugin-manager/src/index.ts)
<a id="deepseek-aidsh-client-ui-settings-account"></a>
## `@deepseek-ai/dsh-client-ui-settings-account`
@@ -4114,7 +4132,6 @@ export interface Config {
- `@deepseek-ai/dsh-client-ui-open-in-app`([`packages/client/ui-open-in-app/src/index.ts`](../packages/client/ui-open-in-app/src/index.ts))
- `@deepseek-ai/dsh-client-ui-permission-presets`([`packages/client/ui-permission-presets/src/index.ts`](../packages/client/ui-permission-presets/src/index.ts))
- `@deepseek-ai/dsh-client-ui-plan`([`packages/client/ui-plan/src/index.ts`](../packages/client/ui-plan/src/index.ts))
- `@deepseek-ai/dsh-client-ui-plugin-manager`([`packages/client/ui-plugin-manager/src/index.ts`](../packages/client/ui-plugin-manager/src/index.ts))
- `@deepseek-ai/dsh-client-ui-reference`([`packages/client/ui-reference/src/index.ts`](../packages/client/ui-reference/src/index.ts))
- `@deepseek-ai/dsh-client-ui-renderer`([`packages/client/ui-renderer/src/index.ts`](../packages/client/ui-renderer/src/index.ts))
- `@deepseek-ai/dsh-client-ui-schedule`([`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts))
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/subsystems/boot.md
boot.md: a52c362aef1c61f9087da7c1abfce8d4671d9e92
boot.zh.md: 5933e206127bd5ca4aa0b8888cf81f0e1aeb9eb7
boot.md: a1e8917adaf80315d871081740e5a76e5cd1e6dd
boot.zh.md: 1ba455d6ba9ff0053ff9d6f6d1313e7ae871a2a1
+18
View File
@@ -162,6 +162,24 @@ Manage profile files and apply their declared reload lifecycle.
Source: [`packages/boot/plugin-manager/src/index.ts`](../../packages/boot/plugin-manager/src/index.ts)
<a id="ctxpluginregistryprobe--pluginregistryprobe"></a>
### `ctx.pluginRegistryProbe` — `PluginRegistryProbe`
Compares public registry responses on the Host; the Client owns the initial selection.
```ts cordis-catalog
/**
* Race npm and npmmirror HTTPS ping responses through the Host's fetch proxy.
* Concurrent readers share a probe; a winner cancels and awaits the other request.
* @returns the first registry with a successful response, or null when disabled or neither responds successfully; results are cached.
* @throws rejects when the service has been unloaded.
*/
@Remote async fastest(): Promise<string | null>
```
Source: [`packages/client/ui-plugin-manager/src/index.ts`](../../packages/client/ui-plugin-manager/src/index.ts)
<a id="ctxprofilecontext--profilecontext"></a>
### `ctx.profileContext` — `ProfileContext`
+18
View File
@@ -162,6 +162,24 @@ Manage profile files and apply their declared reload lifecycle.
Source: [`packages/boot/plugin-manager/src/index.ts`](../../packages/boot/plugin-manager/src/index.ts)
<a id="ctxpluginregistryprobe--pluginregistryprobe"></a>
### `ctx.pluginRegistryProbe` — `PluginRegistryProbe`
Compares public registry responses on the Host; the Client owns the initial selection.
```ts cordis-catalog
/**
* Race npm and npmmirror HTTPS ping responses through the Host's fetch proxy.
* Concurrent readers share a probe; a winner cancels and awaits the other request.
* @returns the first registry with a successful response, or null when disabled or neither responds successfully; results are cached.
* @throws rejects when the service has been unloaded.
*/
@Remote async fastest(): Promise<string | null>
```
Source: [`packages/client/ui-plugin-manager/src/index.ts`](../../packages/client/ui-plugin-manager/src/index.ts)
<a id="ctxprofilecontext--profilecontext"></a>
### `ctx.profileContext` — `ProfileContext`
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/api/gateway/README.md
README.md: b5b64d3fa073c4f992529b63bc2e02117a28cecf
README.zh.md: 87919703fdb2a1f9e32603bf6a1d152d4cc5404e
README.md: 1a746a83eb966fba6ae40b61061d42bf478e1c84
README.zh.md: 7b37548f6ad894b761457df80278eeed7aa6ca7b
+2
View File
@@ -34,6 +34,8 @@ A cancellation-aware Remote method declares `signal: AbortSignal` as its final H
A stream Remote uses `@Remote({ mode: 'stream' })` and returns an `Iterable` or `AsyncIterable`. `ctx.typertGateway.stream()` applies the same endpoint, argument, lookup, and cancellation checks as unary invocation, then returns a cancellation-aware iterable over the business items. The Client opens the Gateway-owned `/api/remote.mux` WebSocket when its plugin activates and keeps it connected while idle. Connection owns the retry schedule; before each retry it asks the mux to cancel any candidate or active socket and make exactly one fresh physical attempt. The Host sends Ping control frames at the configured `websocketHeartbeatIntervalMs` interval (two seconds by default), and the browser answers Pong at the WebSocket protocol layer, so idle network intermediaries see traffic without any Remote stream frame. A socket that has not answered the previous Ping is terminated at the next interval. Independently cancellable logical streams share that socket; an in-process Connection carrier provides equivalent streams directly without opening it.
When the launcher supplies `ctx.appReady`, Gateway registers the WebSocket upgrade route only after successful application startup. Earlier connection attempts remain carrier failures handled by Connection's retry policy, so a restarting Host cannot accept streams while its controllers are still initializing. Unloading cancels a pending readiness subscription and closes any registered carrier. Embedded Hosts without `appReady` register immediately and own their startup ordering; in-process invocation is unchanged.
Every stream also carries a Client-to-Host uplink on the same logical stream. A method declares the uplink item type as the second type argument of its return type, `RemoteStream<Out, In>` from [`dsh-typert-protocol`](../../typert/protocol/README.md); `In` defaults to `never`, and a method that returns `Iterable`, `AsyncIterable`, or `RemoteStream<Out>` declares that it reads none. The running method reads its call as `this.ctx.invocation`: the Gateway derives the receiver from a Context carrying that `RemoteInvocation` — `request`, `service`, `peer`, `signal`, and `uplink()` — so nothing enters the parameter list, and `ctx.invocation` is `undefined` on a Context no Remote call derived. `uplink()` is available once per call. With a descriptor codec it decodes every item before delivery; without one — an SRC method, or a method whose `In` is `never` — it delivers JSON-safe `unknown` values. The Client sends each item as an `item` frame on the open logical stream, a top-level `undefined` item as an `item` frame without `value`, and its half-close as an `end` frame; the method observes the half-close as the end of the `uplink()` iteration and cancellation through `signal`. A rejected item fails the whole stream with `gateway/input-invalid` (field `uplink`). Uplink items are validated one by one at the Host because they arrive from the browser; downlink items are values the Host method produced and pass through unchecked. When the method finishes its downlink the Gateway returns the uplink iterator and drops unread items; items sent to a method that never takes its uplink wait in the inbox until then. Each logical stream buffers at most `streamInboxBytes` (262144 by default) of uplink frame bytes; overflow fails the stream with `gateway/uplink-overflow`, and an item after `end` fails it with `gateway/protocol`, in both cases without closing the socket. `item`, `end`, and `cancel` frames for a stream id the Host has already finished are dropped; only a duplicate `open` closes the socket. Gateway-owned streams such as `$events` return their uplink as soon as they open, so their `item` frames are dropped instead of buffered. A unary method may also call `uplink()`; its items are readable only while the method runs. Every stream speaks for the operator Peer: a WebSocket's streams for the Peer Connection admitted at upgrade, whose scope disposal closes the socket, and an in-process carrier's for the operator directly.
Host composition can register one application event source through `registerRemoteEvents()`. Gateway reserves the internal `$events` logical endpoint for that source, accepts only empty `args`, and aborts streams opened by the registration when the source is withdrawn. API Remotes owns the event selection, argument validation, per-Client queues, and the Host home sent in the opening `{ type: 'ready', clientId, host: { home } }` frame. Its source factory attaches incremental listeners synchronously, so the Client publishes the generation and starts baseline reads only after incremental delivery is ready.
+2
View File
@@ -34,6 +34,8 @@ Connection 可用时,Host 入口会在 Connection 共享的 `/api` FetchHandle
流式 Remote 使用 `@Remote({ mode: 'stream' })` 并返回 `Iterable` 或 `AsyncIterable`。`ctx.typertGateway.stream()` 执行与一元调用相同的 endpoint、参数、lookup 和取消校验,再返回可取消的业务项 iterable。Client 插件激活时打开 Gateway 自有的 `/api/remote.mux` WebSocket,并让它在空闲时保持连接。Connection 拥有重试调度;每次 retry 前,它要求 mux 取消候选或活动 socket,并且只做一次全新的物理连接尝试。Host 按配置的 `websocketHeartbeatIntervalMs` 间隔(默认 2 秒)发送 Ping 控制帧,浏览器在 WebSocket 协议层自动回复 Pong,使空闲网络中间层持续看到流量,而不新增 Remote 流帧。若 socket 尚未回复上一次 Ping,Host 会在下一间隔终止它。可独立取消的逻辑流共享这条连接;进程内 Connection 载体直接提供等价的流,不打开该 WebSocket。
启动器提供 `ctx.appReady` 时,Gateway 仅在应用成功启动后注册 WebSocket 升级路由。此前的连接尝试仍属于载体故障,由 Connection 的重试策略处理,因此重启中的 Host 不会在控制器仍在初始化时接受流。卸载会取消尚未触发的就绪订阅,并关闭已注册的载体。不提供 `appReady` 的嵌入式 Host 会立即注册,并自行负责启动顺序;进程内调用不变。
每条流还在同一条逻辑流上携带从 Client 到 Host 的上行。方法把上行项类型声明为返回类型的第二个类型参数——来自 [`dsh-typert-protocol`](../../typert/protocol/README.zh.md) 的 `RemoteStream<Out, In>`;`In` 缺省为 `never`,返回 `Iterable`、`AsyncIterable` 或 `RemoteStream<Out>` 的方法即声明自己不读上行。运行中的方法通过 `this.ctx.invocation` 读取本次调用:Gateway 从携带该 `RemoteInvocation`(`request`、`service`、`peer`、`signal` 与 `uplink()`)的 Context 派生接收者,因此没有任何东西进入参数列表,而非 Remote 调用派生的 Context 上 `ctx.invocation` 为 `undefined`。`uplink()` 每次调用只能取一次。描述符带 codec 时它在交付前逐项解码;不带时——SRC 方法,或 `In` 为 `never` 的方法——它交付经 JSON 安全校验的 `unknown` 值。Client 在已打开的逻辑流上把每一项作为 `item` 帧发送(顶层 `undefined` 项是不带 `value` 的 `item` 帧),以 `end` 帧表示半关闭;方法通过 `uplink()` 迭代结束感知半关闭,通过 `signal` 感知取消。被拒绝的项使整条流以 `gateway/input-invalid`(字段 `uplink`)失败。上行项在 Host 逐项校验,因为它们来自浏览器;下行项是 Host 方法产出的值,不经校验原样透传。方法结束下行时 Gateway 调用 uplink 迭代器的 return 并丢弃未读的项;发给从未取用 uplink 的方法的项在 inbox 里等到那时为止。每条逻辑流最多缓冲 `streamInboxBytes`(默认 262144)字节的上行帧;超限使流以 `gateway/uplink-overflow` 失败,`end` 之后的项使流以 `gateway/protocol` 失败,两种情况都不关闭 socket。发给 Host 已结束的流 id 的 `item`、`end` 与 `cancel` 帧被丢弃;只有重复的 `open` 会关闭 socket。`$events` 这类 Gateway 自有的流在打开时立即 return 其 uplink,因此它们的 `item` 帧被丢弃而不缓冲。一元方法也可以调用 `uplink()`;其项只在方法运行期间可读。每条流都代表操作者 Peer:WebSocket 上的流代表 Connection 在升级时接纳的 Peer,该 scope 释放时 socket 关闭;进程内载体的流直接代表操作者。
Host 组合可通过 `registerRemoteEvents()` 注册唯一的应用事件 source。Gateway 为它保留内部 `$events` logical endpoint,只接受空 `args`,并在 source 撤回时中止该注册打开的流。事件名单、参数校验、每个 Client 的队列及 opening `{ type: 'ready', clientId, host: { home } }` frame 中的 Host home 由 API Remotes 拥有。source factory 在返回 iterable 前同步挂好增量 listener,因此 Client 只在增量投递就绪后发布 generation 并开始 baseline 读取。
+1
View File
@@ -67,6 +67,7 @@
},
"devDependencies": {
"@deepseek-ai/dsh-brand": "workspace:^",
"@deepseek-ai/dsh-cmdline": "workspace:^",
"@deepseek-ai/dsh-client-connection": "workspace:^",
"@deepseek-ai/dsh-host-webserver": "workspace:^",
"@deepseek-ai/dsh-remote-mock": "workspace:^",
+38 -24
View File
@@ -15,6 +15,7 @@ import {
import { Deque } from '@deepseek-ai/dsh-deque'
import type { WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
import type {} from '@deepseek-ai/dsh-cmdline'
import z from '@deepseek-ai/schemastery'
export type { TypertGatewayFaultDetails } from './remote-error-codes.ts'
import {
@@ -217,6 +218,8 @@ export class TypertGatewayService extends Service implements TypertGateway {
/**
* Register the Gateway against the active Typert registry.
* WebSocket admission waits for launcher-owned application readiness when supplied;
* direct invocation and in-process streams remain available independently.
* @param ctx - owning Host Context with Typert registry access.
* @param config - validated Gateway transport configuration.
*/
@@ -234,31 +237,42 @@ export class TypertGatewayService extends Service implements TypertGateway {
)
})
ctx.inject(['connection', 'webServer'], (webCtx) => {
const mux = new RemoteStreamMuxServer(
(endpoint, payload, uplink, peer, control) =>
this.openWireStream(endpoint, payload, uplink, peer, control.signal, control),
this.wireStream.failure,
resolved.websocketHeartbeatIntervalMs,
resolved.streamInboxBytes,
)
webCtx.effect(() => {
const route: WebUpgradeRoute = {
path: REMOTE_STREAM_MUX_PATH,
handler: (req, socket, head) => {
const admission = webCtx.connection.admit(req)
if ('rejection' in admission) {
rejectRemoteStreamUpgrade(socket, admission.rejection)
return
}
mux.handleUpgrade(req, socket, head, admission.peer)
},
const listen = (): void => {
const mux = new RemoteStreamMuxServer(
(endpoint, payload, uplink, peer, control) =>
this.openWireStream(endpoint, payload, uplink, peer, control.signal, control),
this.wireStream.failure,
resolved.websocketHeartbeatIntervalMs,
resolved.streamInboxBytes,
)
webCtx.effect(function* () {
yield () => mux.close()
const route: WebUpgradeRoute = {
path: REMOTE_STREAM_MUX_PATH,
handler: (req, socket, head) => {
const admission = webCtx.connection.admit(req)
if ('rejection' in admission) {
rejectRemoteStreamUpgrade(socket, admission.rejection)
return
}
mux.handleUpgrade(req, socket, head, admission.peer)
},
}
yield webCtx.webServer.registerUpgrade(route)
}, `api-gateway: ${REMOTE_STREAM_MUX_PATH} WebSocket`)
}
// Existing pages reconnect before the new Host prints its URL. No stream
// may enter until the launcher has activated and audited its controllers.
const ready = webCtx.get('appReady')
if (ready === undefined) listen()
else webCtx.effect(() => {
let closed = false
const cancel = ready.onReady(() => { if (!closed) listen() })
return () => {
closed = true
cancel()
}
const unregister = webCtx.webServer.registerUpgrade(route)
return async () => {
unregister()
await mux.close()
}
}, `api-gateway: ${REMOTE_STREAM_MUX_PATH} WebSocket`)
}, 'api-gateway: application readiness')
})
}
@@ -6,6 +6,7 @@ import { Context, symbols } from '@deepseek-ai/cordis'
import { apply as applyConnection, inject as connectionInject } from '@deepseek-ai/dsh-client-connection'
import WebServer from '@deepseek-ai/dsh-host-webserver'
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
import type { AppReady } from '@deepseek-ai/dsh-cmdline'
import {
Remote,
remoteErrorOf,
@@ -229,6 +230,30 @@ class FeedService extends TypertRemoteService {
const roots: Context[] = []
class StartupProbe implements AppReady {
private ready = false
private readonly listeners = new Set<() => void>()
lastListener: (() => void) | undefined
get pending(): number { return this.listeners.size }
onReady(listener: () => void): () => void {
this.lastListener = listener
if (this.ready) {
listener()
return () => {}
}
this.listeners.add(listener)
return () => { this.listeners.delete(listener) }
}
commit(): void {
this.ready = true
for (const listener of this.listeners) listener()
this.listeners.clear()
}
}
class RemoteEventSourceProbe {
readonly source = (signal: AbortSignal): AsyncIterable<TypertRemoteEventDispatch> => {
this.signal = signal
@@ -307,6 +332,30 @@ afterEach(async () => {
})
describe('Typert Remote streams', () => {
it.each([false, true])('accepts WebSockets only after application readiness (already ready: %s)', async (alreadyReady) => {
const startup = new StartupProbe()
if (alreadyReady) startup.commit()
const { ctx } = await setup(true, {}, startup)
if (!alreadyReady) {
expect(startup.pending).toBe(1)
expect(await acceptsSocket(ctx)).toBe(false)
startup.commit()
}
expect(await acceptsSocket(ctx)).toBe(true)
expect(startup.pending).toBe(0)
})
it('withdraws a pending WebSocket startup subscription when the Gateway unloads', async () => {
const startup = new StartupProbe()
const { ctx } = await setup(true, {}, startup)
expect(startup.pending).toBe(1)
await ctx.fiber.dispose()
expect(startup.pending).toBe(0)
// A launcher commit can already hold a copy of the cancelled listener.
expect(() => { startup.lastListener?.() }).not.toThrow()
expect(() => { startup.commit() }).not.toThrow()
})
it('validates the WebSocket heartbeat timer range and the stream inbox bound', () => {
expect(TypertGatewayService.Config({})).toEqual({ websocketHeartbeatIntervalMs: 2_000, streamInboxBytes: 262_144 })
expect(TypertGatewayService.Config({ websocketHeartbeatIntervalMs: MAX_TIMER_DELAY_MS, streamInboxBytes: 1 }))
@@ -1341,9 +1390,11 @@ describe('Typert Remote streams', () => {
async function setup(
transport: boolean,
gatewayConfig: GatewayConfig = {},
ready?: AppReady,
): Promise<{ readonly ctx: Context; readonly service: FeedService }> {
const ctx = new Context()
roots.push(ctx)
if (ready !== undefined) ctx.provide('appReady', ready)
if (transport) {
await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 })
provideBrowserCredentials(ctx)
@@ -1365,6 +1416,17 @@ async function setup(
return { ctx, service: receiver[symbols.original] ?? receiver }
}
async function acceptsSocket(ctx: Context): Promise<boolean> {
const socket = new WebSocket(`ws://127.0.0.1:${String(ctx.webServer.port)}/api/remote.mux`, {
headers: { cookie: browserCookie(ctx) },
})
const closed = new Promise<void>((resolve) => { socket.once('close', () => { resolve() }) })
const opened = await once(socket, 'open').then(() => true, () => false)
if (opened) socket.close()
await closed
return opened
}
function descriptors(): InvocationDescriptor[] {
const label = {
name: 'label',
+3
View File
@@ -13,6 +13,9 @@
"src/types.ts"
],
"references": [
{
"path": "../../boot/cmdline"
},
{
"path": "../../../vendor/cosmokit"
},
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/api/remotes/README.md
README.md: 74e1595bfbe852605e5d5a7c6930c113e63a92bd
README.zh.md: b8974b0987d5be4ebee2a2886d3cbce321638d4d
README.md: 493418fbceed15c96a5b0e6339e1114c715e9c89
README.zh.md: 69190cf2ce318fea3dee7be20aef047ff999ef84
+1 -1
View File
@@ -27,7 +27,7 @@ Two-sided BFF for Host Remote capabilities selected by this application. The Hos
[`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.md) owns Agent and Session identity policy, including the Typert lookup resolvers used by other namespaces. This package only selects and mounts that generated Session contribution; it does not duplicate activation policy.
The Client assembly mounts Office conversion, Commands, credentials, settings, Goal, dynamic Cordis, file and Session references, read-only Host plugin inventory, message feedback, permission presets, Session Controller, subagents, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation.
The Client assembly mounts Office conversion, Commands, credentials, settings, Goal, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, message feedback, permission presets, Session Controller, subagents, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation.
This facade is also the front door for the wire type vocabulary a Client package names. It re-exports, type-only, the Remote failure vocabulary (`RemoteResult`, `RemoteFailure`, `RemoteErrorCode`, `RemoteErrorDetailsMap`), the Host facts (`RemoteHostFacts`), and each selected domain's client-safe payload types, so a Client feature package imports one specifier instead of reaching into `dsh-typert-protocol`, the Gateway, or an owner's Host entry. Two kinds of package deliberately skip this door: the API-layer packages this assembly itself selects — importing it back would close a dependency cycle — and their tests, which take the failure vocabulary from `dsh-typert-protocol` directly. A UI package's tests instead take the `RemoteError` constructor from [`dsh-client-test-runtime`](../../test-support/client-runtime/README.md).
+1 -1
View File
@@ -27,7 +27,7 @@ kind: "package-reference"
[`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.zh.md) 拥有 agent(智能体)与会话身份策略,包括供其他 namespace 使用的 Typert lookup 解析器。本包只选择并挂载生成的会话 contribution,不复制激活策略。
Client 组合挂载 Office 转换、Commands、凭据、settings、Goal、动态 Cordis、文件与会话引用、只读 Host 插件清单、消息反馈、权限预设、会话控制器、subagents 和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。
Client 组合挂载 Office 转换、Commands、凭据、settings、Goal、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、消息反馈、权限预设、会话控制器、subagents 和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。
本 facade 同时是 Client 包指称 wire 类型词汇的正门。它以 type-only 方式转出 Remote 失败词汇(`RemoteResult`、`RemoteFailure`、`RemoteErrorCode`、`RemoteErrorDetailsMap`)、Host 事实(`RemoteHostFacts`),以及各已选领域对 Client 安全的载荷类型,因此 Client 功能包只 import 一个 specifier,不必伸手进 `dsh-typert-protocol`、Gateway 或某个拥有方的 Host 入口。有两类包刻意不走这道门:本装配自己选中的 API 层包——反向 import 会形成依赖环——以及它们的测试,后者直接从 `dsh-typert-protocol` 取失败词汇。UI 包的测试则从 [`dsh-client-test-runtime`](../../test-support/client-runtime/README.zh.md) 取 `RemoteError` 构造器。
+1
View File
@@ -95,6 +95,7 @@
"@deepseek-ai/dsh-command-feedback": "workspace:^",
"@deepseek-ai/dsh-api-terminal-controller": "workspace:^",
"@deepseek-ai/dsh-plugin-manager": "workspace:^",
"@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:^",
"@deepseek-ai/dsh-office-to-pdf": "workspace:^",
"@deepseek-ai/dsh-api-account-controller": "workspace:^"
}
+4 -1
View File
@@ -10,6 +10,7 @@ import goalsRemote from '@deepseek-ai/dsh-goal/remote'
import llmRemote from '@deepseek-ai/dsh-llm/remote'
import dynamicRemote from '@deepseek-ai/dsh-cordis-host-runner/remote'
import pluginManagerRemote from '@deepseek-ai/dsh-plugin-manager/remote'
import pluginRegistryProbeRemote from '@deepseek-ai/dsh-client-ui-plugin-manager/remote'
import pluginInventoryRemote from '@deepseek-ai/dsh-host-plugin-inventory/remote'
import messageFeedbackRemote from '@deepseek-ai/dsh-message-feedback/remote'
import permissionPresetsRemote from '@deepseek-ai/dsh-permission-presets/remote'
@@ -31,6 +32,7 @@ export type {
PluginInstallLogChunk, PluginInstallProgress, PluginInstallRequestId, PluginRegistries, PluginSpecInspection, ReadOnlyReason, Registry,
} from '@deepseek-ai/dsh-plugin-manager/types'
export type {} from '@deepseek-ai/dsh-plugin-manager/remote'
export type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/remote'
export type { PluginInventorySnapshot } from '@deepseek-ai/dsh-host-plugin-inventory/types'
export type {} from '@deepseek-ai/dsh-agent-preset-registry/remote'
export type {} from '@deepseek-ai/dsh-commands/remote'
@@ -171,7 +173,8 @@ export async function apply(ctx: Context): Promise<() => Promise<void>> {
try {
for (const contribution of [
agentPresetsRemote, commandsRemote, settingsControllerRemote, accountRemote, goalsRemote, llmRemote, dynamicRemote,
pluginInventoryRemote, pluginManagerRemote, messageFeedbackRemote, sessionFeedbackRemote, fileUploadsRemote, sessionReferencesRemote,
pluginInventoryRemote, pluginManagerRemote, pluginRegistryProbeRemote, messageFeedbackRemote, sessionFeedbackRemote,
fileUploadsRemote, sessionReferencesRemote,
permissionPresetsRemote, subagentsRemote, sessionRemote, jobRemote, workspaceRemote, workspaceFilesRemote, terminalRemote,
officeToPdfRemote,
]) {
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/boot/app-boot/README.md
README.md: 5bbe75d641eeeaf3b87c31221b3491ad1408934e
README.zh.md: b3ac89c1cb082880622175b494d540888b19e804
README.md: 70a8e235ac5846061ea47e79e7dc575881110a50
README.zh.md: 9849b033e01827a4c50a22b72ea20deebb0fdd85
+2 -1
View File
@@ -40,7 +40,7 @@ installFailLoud('dsh')
const ctx = await boot('dsh', resolveConfigPath(argv[2], process.env.DSH_SNAPSHOT))
```
With that entry point, startup keeps every plugin that can activate. An enabled failed plugin produces a labelled warning. A failed required entry makes startup dispose the whole app and exit nonzero; required ids absent from a profile and disabled required entries do not affect startup. The global required list covers shared Agent execution, application endpoints, and Web bootstrap/transport: `agent-loop`, `webserver`, `modules`, `connection`, `headless-runner`, `acp`, and `sdk-jsonrpc-server`.
`installFailLoud` writes one labelled `util.inspect` diagnostic to stderr for an unhandled rejection or an uncaught exception, awaits the surface's release hook under a fixed timeout, and exits 1; control never returns to the failed operation, because only the throw site knows which state is intact, and the event loop runs only until the release settles or times out. With that entry point, startup keeps every plugin that can activate. An enabled failed plugin produces a labelled warning. A failed required entry makes startup dispose the whole app and exit nonzero; required ids absent from a profile and disabled required entries do not affect startup. The global required list covers shared Agent execution, application endpoints, and Web bootstrap/transport: `agent-loop`, `webserver`, `modules`, `connection`, `headless-runner`, `acp`, and `sdk-jsonrpc-server`.
<a id="profiles"></a>
### Profiles
@@ -97,6 +97,7 @@ After the Loader settles, app-boot warns when only optional entries are inactive
| An injected service is unavailable | Warn; continue while the entry waits for its dependencies | Stop startup | Keep the entry waiting; adding the missing provider can activate it |
| HTTP port binding fails | Warn; continue without that endpoint | Stop startup | Keep the process running without the failed endpoint; corrected config can restore it |
| Detached asynchronous work outside the `apply()` return Promise produces an unhandled rejection | Fatal: dispose the app and exit nonzero | Fatal: dispose the app and exit nonzero | Fatal: dispose the app and exit nonzero, regardless of entry id |
| A synchronous callback (a stream `'data'` listener, a timer) throws an uncaught exception at any point in the process lifetime | Fatal: dispose the app and exit nonzero; the failed operation is not resumed | Fatal: dispose the app and exit nonzero; the failed operation is not resumed | Fatal: dispose the app and exit nonzero, regardless of entry id |
| Entry is absent or explicitly disabled | Ignore it | Ignore it | Do not activate it; no required-startup audit |
The required list above includes `modules` and `connection`; Web startup cannot succeed when either enabled entry fails. Failure of an optional provider can also prevent a required consumer from activating. Schema rejection before an existing entry updates is not a transactional rollback of sibling changes.
+2 -1
View File
@@ -40,7 +40,7 @@ installFailLoud('dsh')
const ctx = await boot('dsh', resolveConfigPath(argv[2], process.env.DSH_SNAPSHOT))
```
有了这个入口,启动会保留所有能够激活的插件。启用但失败的插件会产生带标签的警告。required entry 失败时,启动会拆卸整个应用并以非零码退出;profile 中不存在的 required id 和已禁用的 required entry 不影响启动。全局 required list 覆盖共享 Agent 执行、应用 endpoint,以及 Web 启动与传输:`agent-loop`、`webserver`、`modules`、`connection`、`headless-runner`、`acp` 和 `sdk-jsonrpc-server`。
`installFailLoud` 会为未处理 rejection 或未捕获异常向 stderr 写一条带标签的 `util.inspect` 诊断,在固定超时内等待界面的 release 钩子,然后以 1 退出;控制流不会回到失败的操作,因为只有抛出点知道哪些状态仍然完整,事件循环只运行到 release 结束或超时。有了这个入口,启动会保留所有能够激活的插件。启用但失败的插件会产生带标签的警告。required entry 失败时,启动会拆卸整个应用并以非零码退出;profile 中不存在的 required id 和已禁用的 required entry 不影响启动。全局 required list 覆盖共享 Agent 执行、应用 endpoint,以及 Web 启动与传输:`agent-loop`、`webserver`、`modules`、`connection`、`headless-runner`、`acp` 和 `sdk-jsonrpc-server`。
<a id="profiles"></a>
### Profile
@@ -97,6 +97,7 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如
| 注入的服务不可用 | 警告;继续,条目等待依赖 | 终止启动 | 条目继续等待;补上缺失的提供方后可以激活 |
| HTTP 端口绑定失败 | 警告;继续,但该端点不可用 | 终止启动 | 进程继续运行,但失败的端点不可用;修正配置后可以恢复 |
| 脱离 `apply()` 返回 Promise 的异步任务产生未处理 rejection | 致命错误:释放应用并以非零码退出 | 致命错误:释放应用并以非零码退出 | 致命错误:释放应用并以非零码退出,与条目 id 无关 |
| 同步回调(流的 `'data'` 监听器、定时器)在进程生命周期任一时刻抛出未捕获异常 | 致命错误:释放应用并以非零码退出;失败的操作不会被恢复 | 致命错误:释放应用并以非零码退出;失败的操作不会被恢复 | 致命错误:释放应用并以非零码退出,与条目 id 无关 |
| 条目缺失或被显式禁用 | 忽略 | 忽略 | 不激活该条目;不执行 required 启动审计 |
上面的 required 列表包含 `modules` 与 `connection`;只要其中一个已启用条目失败,Web 就无法成功启动。Optional 提供方失败也可能使 required 消费方无法激活。现有条目的新配置在更新前被 schema 校验拒绝,并不等于对兄弟插件的变更做事务回滚。
+38 -15
View File
@@ -8,7 +8,7 @@
import { pathToFileURL } from 'node:url'
import { readFileSync } from 'node:fs'
import { parseEnv } from 'node:util'
import { inspect, parseEnv } from 'node:util'
import { basename, dirname, isAbsolute, resolve } from 'node:path'
import * as yaml from 'js-yaml'
import { Context, type FiberState } from '@deepseek-ai/cordis'
@@ -566,13 +566,16 @@ export async function mountRootInclude(
return entry
}
/** The two process events {@link installFailLoud} turns into a fatal exit. */
export type FailLoudEvent = 'unhandledRejection' | 'uncaughtException'
/**
* The slice of `process` {@link installFailLoud} needs — injectable so tests
* exercise the handler without registering on (or exiting) the real process.
*/
export interface FailLoudProcess {
on(event: 'unhandledRejection', handler: (err: unknown) => void): unknown
off(event: 'unhandledRejection', handler: (err: unknown) => void): unknown
on(event: FailLoudEvent, handler: (err: unknown) => void): unknown
off(event: FailLoudEvent, handler: (err: unknown) => void): unknown
stderr: { write(chunk: string): unknown }
/**
* Terminate the process. Callers treat this as the end of the run, as
@@ -616,11 +619,22 @@ async function observeLoaderRejectionCheckpoint(reasons: readonly unknown[]): Pr
export const FAIL_LOUD_RELEASE_TIMEOUT_MS = 2_000
/**
* Install before boot to turn a late unhandled plugin-init rejection into one
* labelled stderr diagnostic and `exit(1)`. A rejection already included by
* {@link auditStartupEntries} is ignored during its process checkpoint;
* every other rejection remains fatal. Stdout remains untouched for ACP; the
* returned function removes the handler.
* Install before boot to turn an unhandled rejection or an uncaught exception,
* at any point in the process lifetime, into one labelled stderr diagnostic and
* `exit(1)`. A rejection already included by {@link auditStartupEntries} is
* ignored during its process checkpoint; every other rejection and every
* uncaught exception remains fatal. Control never returns to the failed
* operation after either: only the throw site knows which state is intact, and
* a listener that threw mid-update (a stream `'data'` handler, a half-applied
* registry write) leaves silently wrong results behind if it were resumed. The
* event loop keeps running only until the release hook settles or times out.
* Stdout remains untouched for ACP; the returned function removes both handlers.
*
* The diagnostic is `util.inspect(err)`, not `err.stack`: a `node:fs` error's
* `code`, `syscall`, and `path` and any `cause` chain are enumerable properties
* that the stack line omits, and they are what a crash report needs. Once a
* handler is installed Node prints nothing of its own, so this line is the
* only record of the failure.
*
* The Loader mounts entries concurrently, so a surface that owns the terminal
* can already hold it when a sibling entry rejects. Exiting straight from the
@@ -642,7 +656,7 @@ export const FAIL_LOUD_RELEASE_TIMEOUT_MS = 2_000
* @param release - optional teardown awaited before exit, used by a
* terminal-owning surface to restore the terminal. Its own failure is
* swallowed because the pending fatal exit already owns the outcome.
* @returns the uninstaller that removes the rejection handler.
* @returns the uninstaller that removes both handlers.
*/
export function installFailLoud(
binName: string,
@@ -650,14 +664,13 @@ export function installFailLoud(
release?: () => Promise<void> | void,
): () => void {
let exiting = false
const handler = (err: unknown): void => {
if (assembledActivationRejections.has(err)) return
// A release in flight already owns the exit. Swallow later rejections
const report = (err: unknown, label: string): void => {
// A release in flight already owns the exit. Swallow later failures
// (teardown's own included) rather than reporting a second failure over the
// real one or letting Node kill the process before the terminal is back.
if (exiting) return
exiting = true
proc.stderr.write(`${binName}: fatal load failure: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`)
proc.stderr.write(`${binName}: ${label}: ${inspect(err, { depth: 4, maxArrayLength: 50 })}\n`)
if (release === undefined) {
proc.exit(1)
return
@@ -681,8 +694,18 @@ export function installFailLoud(
proc.exit(1)
})()
}
const uninstall = (): void => void proc.off('unhandledRejection', handler)
proc.on('unhandledRejection', handler)
const onRejection = (err: unknown): void => {
if (assembledActivationRejections.has(err)) return
// Label kept stable: the Web profile expected-output e2e tests match it.
report(err, 'fatal load failure')
}
const onException = (err: unknown): void => { report(err, 'fatal uncaught exception') }
const uninstall = (): void => {
proc.off('unhandledRejection', onRejection)
proc.off('uncaughtException', onException)
}
proc.on('unhandledRejection', onRejection)
proc.on('uncaughtException', onException)
return uninstall
}
+70 -20
View File
@@ -9,7 +9,7 @@ import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
import {
addHarnessSourceSection, auditStartupEntries, boot, StartupError,
FAIL_LOUD_RELEASE_TIMEOUT_MS, HARNESS_SOURCE_SECTION,
installFailLoud, loadEnv, loadLayeredEnv, loadOverlayPatches, resolveConfigPath, type FailLoudProcess,
installFailLoud, loadEnv, loadLayeredEnv, loadOverlayPatches, resolveConfigPath, type FailLoudEvent, type FailLoudProcess,
} from '../src/index.ts'
const NAME = 'dsh-test-bin'
@@ -360,14 +360,24 @@ describe('loadLayeredEnv', () => {
})
describe('installFailLoud', () => {
function fakeProc(): FailLoudProcess & { handlers: Array<(err: unknown) => void>; written: string[]; exits: number[] } {
const handlers: Array<(err: unknown) => void> = []
type Handler = (err: unknown) => void
function fakeProc(): FailLoudProcess & {
handlers: Handler[]
rejection: Handler
exception: Handler
written: string[]
exits: number[]
} {
const handlers: Handler[] = []
const registered = new Map<FailLoudEvent, Handler>()
const written: string[] = []
const exits: number[] = []
return {
handlers, written, exits,
on: (_event, handler) => { handlers.push(handler) },
off: (_event, handler) => { handlers.splice(handlers.indexOf(handler), 1) },
get rejection() { return registered.get('unhandledRejection')! },
get exception() { return registered.get('uncaughtException')! },
on: (event, handler) => { handlers.push(handler); registered.set(event, handler) },
off: (event, handler) => { handlers.splice(handlers.indexOf(handler), 1); registered.delete(event) },
stderr: { write: (chunk: string) => { written.push(chunk) } },
exit: (code: number) => { exits.push(code) },
}
@@ -377,7 +387,7 @@ describe('installFailLoud', () => {
const proc = fakeProc()
installFailLoud(NAME, proc)
const error = new Error('boom')
proc.handlers[0]!(error)
proc.rejection(error)
expect(proc.written[0]).toContain(`${NAME}: fatal load failure: `)
expect(proc.written[0]).toContain(error.stack)
expect(proc.exits).toEqual([1])
@@ -388,7 +398,7 @@ describe('installFailLoud', () => {
it('stringifies a non-Error rejection and an Error without a stack falls back to its message', () => {
const plain = fakeProc()
installFailLoud(NAME, plain)
plain.handlers[0]!('plain failure')
plain.rejection('plain failure')
expect(plain.written[0]).toContain('plain failure')
expect(plain.exits).toEqual([1])
@@ -396,7 +406,7 @@ describe('installFailLoud', () => {
delete (stackless as { stack?: string }).stack
const bare = fakeProc()
installFailLoud(NAME, bare)
bare.handlers[0]!(stackless)
bare.rejection(stackless)
expect(bare.written[0]).toContain('no stack')
expect(bare.exits).toEqual([1])
})
@@ -404,16 +414,18 @@ describe('installFailLoud', () => {
it('returns an uninstaller that removes the handler (and defaults to the real process)', () => {
const proc = fakeProc()
const uninstall = installFailLoud(NAME, proc)
expect(proc.handlers).toHaveLength(1)
expect(proc.handlers).toHaveLength(2)
uninstall()
expect(proc.handlers).toHaveLength(0)
// Default-proc arm: install on the real process, then immediately uninstall
// so the suite leaks no handler and can never exit the runner.
const before = process.listenerCount('unhandledRejection')
const before = [process.listenerCount('unhandledRejection'), process.listenerCount('uncaughtException')]
const uninstallReal = installFailLoud(NAME)
expect(process.listenerCount('unhandledRejection')).toBe(before + 1)
expect(process.listenerCount('unhandledRejection')).toBe(before[0]! + 1)
expect(process.listenerCount('uncaughtException')).toBe(before[1]! + 1)
uninstallReal()
expect(process.listenerCount('unhandledRejection')).toBe(before)
expect(process.listenerCount('unhandledRejection')).toBe(before[0])
expect(process.listenerCount('uncaughtException')).toBe(before[1])
})
it('does not report an activation rejection shared by entries in the boot audit', async () => {
@@ -436,12 +448,12 @@ describe('installFailLoud', () => {
} as unknown as Context, NAME, warn)
await Promise.resolve()
await Promise.resolve()
proc.handlers[0]!(error)
proc.rejection(error)
expect(proc.written).toEqual([])
expect(proc.exits).toEqual([])
await audit
expect(warn).toHaveBeenCalledWith(expect.stringContaining('assembled activation failure'))
proc.handlers[0]!(error)
proc.rejection(error)
expect(proc.exits).toEqual([1])
})
@@ -455,7 +467,7 @@ describe('installFailLoud', () => {
await Promise.resolve()
order.push('released')
})
proc.handlers[0]!(new Error('sibling entry rejected'))
proc.rejection(new Error('sibling entry rejected'))
expect(proc.written[0]).toContain(`${NAME}: fatal load failure: `)
// The release is in flight, so the exit has not committed yet.
expect(proc.exits).toEqual([])
@@ -466,7 +478,7 @@ describe('installFailLoud', () => {
it('still exits when the release hook rejects', async () => {
const proc = fakeProc()
installFailLoud(NAME, proc, () => Promise.reject(new Error('terminal stop failed')))
proc.handlers[0]!(new Error('boom'))
proc.rejection(new Error('boom'))
await vi.waitFor(() => { expect(proc.exits).toEqual([1]) })
})
@@ -475,7 +487,7 @@ describe('installFailLoud', () => {
try {
const proc = fakeProc()
installFailLoud(NAME, proc, () => new Promise<void>(() => {}))
proc.handlers[0]!(new Error('boom'))
proc.rejection(new Error('boom'))
expect(proc.exits).toEqual([])
await vi.advanceTimersByTimeAsync(FAIL_LOUD_RELEASE_TIMEOUT_MS)
expect(proc.exits).toEqual([1])
@@ -494,14 +506,52 @@ describe('installFailLoud', () => {
await Promise.resolve()
released = true
})
proc.handlers[0]!(new Error('first rejection'))
proc.handlers[0]!(new Error('second rejection'))
expect(proc.handlers).toHaveLength(1)
proc.rejection(new Error('first rejection'))
proc.rejection(new Error('second rejection'))
proc.exception(new Error('exception during teardown'))
expect(proc.handlers).toHaveLength(2)
expect(proc.written).toHaveLength(1)
expect(proc.written[0]).toContain('first rejection')
await vi.waitFor(() => { expect(proc.exits).toEqual([1]) })
expect(released).toBe(true)
})
it('turns an uncaught exception into a labelled diagnostic with its enumerable properties and exits 1', () => {
const proc = fakeProc()
installFailLoud(NAME, proc)
const error = Object.assign(new Error("ENOENT: no such file or directory, open '/tmp/dsh-subprocess-x/out.log'"), {
errno: -2, code: 'ENOENT', syscall: 'open', path: '/tmp/dsh-subprocess-x/out.log',
})
proc.exception(error)
expect(proc.written).toHaveLength(1)
expect(proc.written[0]).toContain(`${NAME}: fatal uncaught exception: `)
expect(proc.written[0]).toContain(error.stack)
expect(proc.written[0]).toContain("syscall: 'open'")
expect(proc.written[0]).toContain("path: '/tmp/dsh-subprocess-x/out.log'")
expect(proc.exits).toEqual([1])
})
it('includes the cause chain in the diagnostic', () => {
const proc = fakeProc()
installFailLoud(NAME, proc)
proc.exception(new Error('wrapper', { cause: new Error('root cause') }))
expect(proc.written[0]).toContain('[cause]: Error: root cause')
expect(proc.exits).toEqual([1])
})
it('awaits the release hook for an uncaught exception as it does for a rejection', async () => {
const proc = fakeProc()
let released = false
installFailLoud(NAME, proc, async () => {
await Promise.resolve()
released = true
})
proc.exception(new Error('listener threw'))
expect(proc.written[0]).toContain('fatal uncaught exception')
expect(proc.exits).toEqual([])
await vi.waitFor(() => { expect(proc.exits).toEqual([1]) })
expect(released).toBe(true)
})
})
describe('auditStartupEntries', () => {
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/boot/plugin-manager/README.md
README.md: d937d265a7942f824f5f4a02c0a5eaba62208994
README.zh.md: 388a2e249613299753ae63c3c20d2ca89311dc4f
README.md: 1de9c9d78e421d44eb006f1ab7fd82656f006a2a
README.zh.md: f7502aab64738ad1feccf58b84ff945213df2eff
+2
View File
@@ -47,6 +47,8 @@ A selected bundle that cannot load remains in `listBundles` with an `error`; `en
Registries are asked in turn. The plan starts at `options.registry`, else the configured `registry` (`null` is the one pnpm's own configuration names), and continues through `fallbackRegistries` while a registry is unreachable, times out, or answers that it has no such package or version, which a mirror not yet synced does. A registry outside the configured set is asked alone, so a private registry never falls through to a public one; pnpm's own registry counts as part of the set only while what it names, read through `pnpm config get registry` before each plan, is npm's own registry or one of the fallbacks, and is otherwise asked alone as a private one. A registry pnpm's own configuration already names is asked once. The lookup runs `pnpm view` with `--registry` and without pnpm's own retries, so a dead registry is reported within `inspectTimeoutMs` and the next one is asked; pnpm prints its refusal as JSON on stdout, which is read like stderr. The install keeps pnpm's retry settings. `registries()` answers the configured set and what pnpm names, for a picker. The [registry Agent Note](../../../.agents/notes/implemented/architecture/2026-09-18-plugin-install-registries.md) owns the rationale.
The browser-safe `@deepseek-ai/dsh-plugin-manager/registry` entry exports `OFFICIAL_NPM_REGISTRY` and `NPMMIRROR_REGISTRY` for consumers that identify those public registries.
`installBundle` accepts a caller-generated `requestId`, under which `plugin-manager/install-log` streams each pnpm run's output and `plugin-manager/install-state` announces `installing`, `cancelling`, and `applying`; `installing` is announced once per registry asked, with the `attempt`'s registry, position, and the plan's length. The install asks the same plan as the lookup, from `options.registry`, running `pnpm add` with `--registry` and restoring the profile files between attempts; it moves on for the failures another registry can change and stops at any other, and at a failure whose error line names the host a git or tarball spec is fetched from, which no registry stands in for; `failedAt` says which of the two the last failed run could not reach. `cancelInstall(requestId)` stops the run and answers `cancelled` only after pnpm exited and the files are back, `too-late` once the bundle is being applied, and `not-running` for any other id; the install call then reports `application: 'cancelled'`. A run that fails, is cancelled, or adds a package without a bundle patch restores `package.json` and `pnpm-lock.yaml` as they were; `packageResult.kind` classifies the last run from its exit and output, `registries` names every registry asked, and `bundle` names the package a finished run added. `listBundles` carries each bundle's one-liner (the package `description`), the rows its patch declares with their live entries, and the built-in rows it overrides; it lists the profile's own bundles, the bundles the installation supplies, and a selected name without a bundle patch as a `not-bundle` problem, while an unselected plain dependency is left out. A bundle the launcher's `OPTIONAL_BUNDLES` names is `optional`: shipped switched off for the person to turn on, never removable, and selected by no shipped template ([rationale](../../../.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md)). Every completed operation emits `plugin-manager/changed`; a patch generation applied outside the manager, by HMR's watcher after a CLI or hand edit, announces nothing, so the page learns of it on its next read.
`waitForInstall(requestId)` lets a client recover a lost response by waiting for the active installation, including its non-cancellable application phase. It returns the same outcome as the original call, or `null` if the request is not active. Completed results are not retained; `null` establishes neither success nor cancellation.
@@ -47,6 +47,8 @@ kind: "package-reference"
注册表按顺序询问。计划从 `options.registry` 开始,否则从配置的 `registry`(`null` 即 pnpm 自身配置指定的那个)开始,并在一个注册表不可达、超时或答复没有这个包或版本(尚未同步的镜像会如此)时继续问 `fallbackRegistries`。配置集合之外的注册表只问它自己,因而私有源永远不会落到公共源;pnpm 自身的注册表只在它指向的地址(每次做计划前经 `pnpm config get registry` 读出)是 npm 官方源或某个备选源时才算集合成员,否则视为私有源只问它自己。pnpm 自身配置已经指向的注册表只问一次。查询以 `--registry` 运行 `pnpm view` 且不带 pnpm 自身的重试,所以死掉的注册表会在 `inspectTimeoutMs` 内报告并转问下一个;pnpm 把拒绝以 JSON 打印在 stdout,读法与 stderr 相同。安装保留 pnpm 的重试设置。`registries()` 把配置集合和 pnpm 指向的地址答复给选择器。[注册表 Agent Note](../../../.agents/notes/implemented/architecture/2026-09-18-plugin-install-registries.zh.md) 拥有理由。
可在浏览器使用的 `@deepseek-ai/dsh-plugin-manager/registry` 入口导出 `OFFICIAL_NPM_REGISTRY` 和 `NPMMIRROR_REGISTRY`,供消费方识别这两个公共注册表。
`installBundle` 接受调用方生成的 `requestId`,`plugin-manager/install-log` 在其下流式转发每次 pnpm 运行的输出,`plugin-manager/install-state` 通告 `installing`、`cancelling` 与 `applying`;每问一个注册表通告一次 `installing`,`attempt` 带上这次的注册表、序号和计划长度。安装沿用查询的计划,从 `options.registry` 开始,以 `--registry` 运行 `pnpm add`,两次尝试之间恢复 profile 文件;换一个注册表能改变的失败才转问下一个,其他失败即停,错误行点名 git 或 tarball spec 自身拉取主机的失败也停,因为没有注册表能替代那台主机;`failedAt` 说明最后一次失败的运行连不上的是二者中的哪一个。`cancelInstall(requestId)` 停止运行,只在 pnpm 退出且文件恢复后答复 `cancelled`,组合包已在应用时答复 `too-late`,其他 id 答复 `not-running`;安装调用随后报告 `application: 'cancelled'`。失败、被取消或装入了没有组合包 patch 的包的运行,会把 `package.json` 与 `pnpm-lock.yaml` 恢复原样;`packageResult.kind` 按退出方式与输出对最后一次运行分类,`registries` 列出问过的每个注册表,`bundle` 给出完成的运行新增的包。`listBundles` 携带每个组合包的一句话简介(包的 `description`)、其 patch 声明的行及其存活条目,以及它覆盖的内置行;它列出 profile 自己的组合包、安装提供的组合包,以及被选中却没有组合包 patch 的名字(作为 `not-bundle` 问题),未选中的普通依赖不列出。启动器的 `OPTIONAL_BUNDLES` 点名的组合包是 `optional`:随安装提供、默认关闭、由用户开启,永不可卸载,也不被任何随附模板选中([理由](../../../.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md))。每个完成的操作都会发出 `plugin-manager/changed`;在管理器之外应用的一代 patch(HMR 监视到 CLI 或手工编辑后)不发通知,页面要到下一次读取才知道。
`waitForInstall(requestId)` 让客户端在响应丢失后等待活动安装的结果,包括不可取消的应用阶段。它返回与原调用相同的结果,请求不在活动中时返回 `null`。已完成的结果不保留;`null` 不表示成功或已取消。
+2 -2
View File
@@ -20,7 +20,7 @@ import type { ProfileContext, ProfileManifest } from '@deepseek-ai/dsh-app-boot'
import { bundleManifest, readProfileRegistry, registryArguments, runProfilePnpm, saveManifest, viewProfilePackage } from './operations.ts'
import { classifyInstallFailure } from './install-failure.ts'
import { InvalidInstallSpecError, parseInstallSpec, type ParsedInstallSpec } from './install-spec.ts'
import { attributeFailure, normalizeRegistry, registryPlan } from './registry.ts'
import { attributeFailure, normalizeRegistry, NPMMIRROR_REGISTRY, registryPlan } from './registry.ts'
import { writePluginEnabled } from './patch.ts'
import { ManagementFailure } from './failure.ts'
import { approveBuilds, readPendingBuilds } from './build-approval.ts'
@@ -173,7 +173,7 @@ export class PluginManager extends TypertRemoteService {
lockWaitMs: z.number().step(1).min(0).default(120000),
inspectTimeoutMs: z.number().step(1).min(1000).default(20000),
registry: z.string().pattern(REGISTRY_URL),
fallbackRegistries: z.array(z.string().pattern(REGISTRY_URL)).default(['https://registry.npmmirror.com/']),
fallbackRegistries: z.array(z.string().pattern(REGISTRY_URL)).default([NPMMIRROR_REGISTRY]),
})
/** Management bundles remain protected if their files become unreadable. */
private readonly managementBundles = new Set<string>()
@@ -13,6 +13,9 @@ import type { PluginInstallFailureKind, PluginRegistries, Registry } from './typ
/** npm's own registry: what pnpm names without any configuration, and the one public registry a plan trusts as such. */
export const OFFICIAL_NPM_REGISTRY = 'https://registry.npmjs.org/'
/** Public npmmirror URL shared by the fallback configuration and public-registry comparison. */
export const NPMMIRROR_REGISTRY = 'https://registry.npmmirror.com/'
/** An http(s) URL, as pnpm's `--registry` takes it. */
export const REGISTRY_URL = /^https?:\/\/\S+$/
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/modules/README.md
README.md: c99293b1f7a26a86279c4d71d9d6f41c6452b13e
README.zh.md: f6057204e1a039cecb824a3c355f4d7b906abac9
README.md: 3388eb2ae421b303df6709f0bfc656fe67e3a866
README.zh.md: 3cbc600ee5ed211640070773efb72f58b91d4669
+1 -1
View File
@@ -35,7 +35,7 @@ A browser plugin package declares `dsh.client` in its `package.json` with `platf
### What the browser loads
The application combo scripts carry only each plugin's `client.js` entry and register those factories once during boot; module bodies remain lazy and run only at first import or materialization. A source `import()` split by tsdown compiles to `require.async("./client.<name>.js")`; its versioned sibling script arrives only when that expression runs. Rows that share a combo URL share one in-flight script task. HMR switches one changed row to its revisioned one-resource combo URL. `<id>/client` and the bare id resolve to the same exports, because a plugin bundle is its package's client half.
The application combo scripts carry only each plugin's `client.js` entry and register those factories once during boot; module bodies remain lazy and run only at first import or materialization. A source `import()` split by tsdown compiles to `require.async("./client.<name>.js")`; its versioned sibling script arrives only when that expression runs. Rows that share a combo URL share one in-flight script task. A combo whose `<script>` fails to load is requested once more; a combo that loads without registering a row is never re-executed, because the batch script registers its packages in sequence and a replay would stop at the first duplicate registration. In both cases each still-missing row then loads its own one-resource combo URL, so one failed batch costs at most three requests per missing row and leaves the rows it did register untouched. The module system records the last import failure per row (transport, registration, dependency cascade, or factory execution); the Web boot audit reports that text per entry. HMR switches one changed row to its revisioned one-resource combo URL. `<id>/client` and the bare id resolve to the same exports, because a plugin bundle is its package's client half.
### Live plugin composition
+1 -1
View File
@@ -35,7 +35,7 @@ kind: "package-reference"
### 浏览器加载什么
application combo 脚本只携带每个插件的 `client.js` 入口,并在启动时仅注册一次这些 factory;模块主体仍保持惰性,只在首次 import 或物化时运行。经 tsdown 拆分的源码 `import()` 会编译为 `require.async("./client.<name>.js")`;只有执行该表达式时,对应的带版本同级脚本才会到达。共享 combo URL 的 row 共用一个进行中的脚本任务。HMR(热模块替换)会让一条发生变化的 row 改用带 revision 的单资源 combo URL。`<id>/client` 与裸 id 解析到同一组导出,因为插件 bundle 就是其包的客户端半侧。
application combo 脚本只携带每个插件的 `client.js` 入口,并在启动时仅注册一次这些 factory;模块主体仍保持惰性,只在首次 import 或物化时运行。经 tsdown 拆分的源码 `import()` 会编译为 `require.async("./client.<name>.js")`;只有执行该表达式时,对应的带版本同级脚本才会到达。共享 combo URL 的 row 共用一个进行中的脚本任务。`<script>` 加载失败的 combo 会再请求一次;加载成功但没有注册某条 row 的 combo 绝不会重新执行,因为批量脚本按顺序注册各个包,重放会在第一个重复注册处停止。两种情况下,每条仍缺失的 row 随后加载自己的单资源 combo URL,因此一个失败的 batch 对每条缺失 row 最多花费三次请求,且不影响它已经注册的 row。模块系统按 row 记录最后一次 import 失败(传输、注册、依赖级联或 factory 执行);Web 启动审计按条目报告该文本。HMR(热模块替换)会让一条发生变化的 row 改用带 revision 的单资源 combo URL。`<id>/client` 与裸 id 解析到同一组导出,因为插件 bundle 就是其包的客户端半侧。
### 插件动态组合
+10 -1
View File
@@ -100,7 +100,7 @@ export interface WebBootGraph {
export interface BootModuleRow {
/** Entry name == package name (module-table key). */
id: string
/** Revisioned single-resource combo reference used after HMR invalidation. */
/** Revisioned single-resource combo reference: the fallback when the row's batch fails and the reload target after HMR invalidation. */
url: string
/** Content-addressed combo reference used before the first HMR invalidation. */
initialUrl: string
@@ -412,6 +412,15 @@ export interface ClientModuleLoader {
* @param id - graph entry name.
*/
prefetch(id: string): Promise<void>
/**
* The last failure of {@link import} or {@link prefetch} for one graph row:
* transport, registration, dependency cascade, or factory execution. Cleared
* by a later success and by {@link invalidate}. The boot audit reads it to
* report why a Loader entry has no fiber.
* @param id - graph entry name.
* @returns the recorded failure, or `undefined` when the row never failed or succeeded since.
*/
importError(id: string): Error | undefined
/**
* Full reset of one non-bootstrap package: drop its entry and chunk factories
* and materialized records so the next prefetch/import loads its one-resource
+123 -21
View File
@@ -38,6 +38,11 @@ function atRevision(url: string, rev: string): string {
const CLIENT_CHUNK = /^client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js$/
/** The message of a thrown value: an Error's message, anything else stringified. */
function describeError(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
/** Internal module-table key for one package-local chunk. */
function chunkId(ownerId: string, fileName: string): string {
return `${ownerId}/${fileName}`
@@ -101,6 +106,12 @@ export class ClientModuleSystem implements ClientModuleLoader {
private readonly materializing = new Set<string>()
private readonly graphRows = new Map<string, BootModuleRow>()
private readonly loadBundle: (url: string) => Promise<void>
/** Last import or prefetch failure per graph row, cleared by a later success or invalidation. */
private readonly importErrors = new Map<string, Error>()
/** Batch URLs whose transport or execution already failed; rows still missing from them go straight to their one-resource URL. */
private readonly failedBundleUrls = new Set<string>()
/** Every URL whose script has executed once; a batch among them is never requested again. */
private readonly executedBundleUrls = new Set<string>()
/**
* Build the module system over the parsed boot rows.
@@ -161,25 +172,75 @@ export class ClientModuleSystem implements ClientModuleLoader {
})
}
/** Load one graph row so its factory is registered (idempotent per in-flight arrival). */
private arrive(row: BootModuleRow): Promise<void> {
const { id } = row
if (this.loadCache.has(id) || this.factories.has(id)) return Promise.resolve()
const reload = this.reloadTargets.get(id)
const url = reload?.url ?? row.initialUrl
/** Run one bundle transport per URL; every row waiting on the same URL shares the in-flight request. */
private loadShared(url: string): Promise<void> {
let transport = this.pendingArrival.get(url)
if (transport === undefined) {
transport = this.loadBundle(url).finally(() => { this.pendingArrival.delete(url) })
transport = this.loadBundle(url)
.then(() => { this.executedBundleUrls.add(url) })
.finally(() => { this.pendingArrival.delete(url) })
this.pendingArrival.set(url, transport)
}
return transport.then(() => {
if (!this.factories.has(id)) {
throw new Error(`client-modules: bundle ${url} loaded without registering "${id}" via __ModuleLoader__.load`)
return transport
}
/**
* Load one graph row so its factory is registered (idempotent per in-flight
* arrival). A batch script is one classic script that registers every
* package in sequence, and {@link register} rejects a second registration,
* so the two failure kinds differ: a transport failure (`error` event, nothing
* executed) is retried once on the same URL; a script that loaded without
* registering this row (a parse error registered nothing, or a runtime throw
* stopped it after registering others) is never re-executed, because a replay
* would stop again at the first duplicate registration; that holds even when
* the row that first imports from the batch is one it did register, because
* every executed batch URL is remembered. Either way the row then falls back
* to its own one-resource URL, which the Host serves for every package, so one
* failed batch costs at most three requests per missing row and never fails
* the rows that were registered.
*/
private async arrive(row: BootModuleRow): Promise<void> {
const { id } = row
if (this.loadCache.has(id) || this.factories.has(id)) return
const reload = this.reloadTargets.get(id)
const preferred = reload?.url ?? row.initialUrl
const fallback = reload === undefined && row.url !== preferred ? row.url : undefined
const failures: string[] = []
const attempt = async (url: string): Promise<'registered' | 'transport-failed' | 'not-registered'> => {
try {
await this.loadShared(url)
} catch (error) {
failures.push(`${url}: ${describeError(error)}`)
return 'transport-failed'
}
if (reload !== undefined && this.reloadTargets.get(id) === reload) {
this.reloadTargets.delete(id)
}
})
if (this.factories.has(id)) return 'registered'
failures.push(`${url}: loaded without registering "${id}" via __ModuleLoader__.load`)
return 'not-registered'
}
let outcome: Awaited<ReturnType<typeof attempt>> = 'transport-failed'
if (this.failedBundleUrls.has(preferred)) {
failures.push(`${preferred}: skipped after an earlier failure of this bundle`)
} else if (fallback !== undefined && this.executedBundleUrls.has(preferred)) {
// The batch already ran (an earlier importer was a row it did register)
// and this row is still missing: a replay would stop at the first
// duplicate registration.
failures.push(`${preferred}: already executed without registering "${id}"`)
outcome = 'not-registered'
this.failedBundleUrls.add(preferred)
} else {
outcome = await attempt(preferred)
if (outcome === 'transport-failed') outcome = await attempt(preferred)
// Only a batch URL is remembered: a one-resource URL has no fallback and
// stays retryable on the next import, as before.
if (outcome !== 'registered' && fallback !== undefined) this.failedBundleUrls.add(preferred)
}
if (outcome !== 'registered' && fallback !== undefined) outcome = await attempt(fallback)
if (outcome !== 'registered') {
throw new Error(`client-modules: could not load "${id}": ${failures.join('; ')}`)
}
if (reload !== undefined && this.reloadTargets.get(id) === reload) {
this.reloadTargets.delete(id)
}
}
/** Register each injected package and unresolved dynamic request before its consumer. */
@@ -202,15 +263,32 @@ export class ClientModuleSystem implements ClientModuleLoader {
const id = stripClientSuffix(request)
if (this.seed.has(request) || this.loadCache.has(id)) continue
const dependency = this.graphRows.get(id)
if (dependency !== undefined) await this.arriveGraphRow(dependency, next, visited)
if (dependency !== undefined) await this.arriveDependency(row.id, dependency, next, visited)
}
for (const packageName of row.inject) {
const dependency = this.graphRows.get(packageName)
if (dependency !== undefined) await this.arriveGraphRow(dependency, [], visited)
if (dependency !== undefined) await this.arriveDependency(row.id, dependency, [], visited)
}
await this.arrive(row)
}
/** Arrive one dependency, naming the consumer it failed for so a cascade reads as a chain, not as 44 unrelated failures. */
private async arriveDependency(
consumerId: string,
dependency: BootModuleRow,
open: readonly string[],
visited: Set<string>,
): Promise<void> {
try {
await this.arriveGraphRow(dependency, open, visited)
} catch (error) {
throw new Error(
`client-modules: "${consumerId}" not loaded because dependency "${dependency.id}" failed: ${describeError(error)}`,
{ cause: error },
)
}
}
/** Materialize a registered factory (synchronous; memoized in loadCache). */
private materialize(id: string, ownerId = id): ClientModuleRecord {
const existing = this.loadCache.get(id)
@@ -298,15 +376,17 @@ export class ClientModuleSystem implements ClientModuleLoader {
const existing = this.loadCache.get(id)
if (existing !== undefined) return existing.exports
const row = this.graphRows.get(id)
if (row !== undefined) {
await this.arriveGraphRow(row)
} else if (!this.factories.has(id)) {
if (row === undefined) {
if (this.factories.has(id)) return this.materialize(id).exports
throw new Error(
`client-modules: cannot resolve "${specifier}" — not a seed word, not a materialized module, `
+ 'and not a row in the boot graph (the runtime mirror of the bundle purity gate)',
)
}
return this.materialize(id).exports
return this.recordingImportError(id, async () => {
await this.arriveGraphRow(row)
return this.materialize(id).exports
})
}
async prefetch(id: string): Promise<void> {
@@ -314,7 +394,28 @@ export class ClientModuleSystem implements ClientModuleLoader {
if (this.loadCache.has(normalized)) return
const row = this.graphRows.get(normalized)
if (row === undefined) throw new Error(`client-modules: prefetch("${id}") — not a graph entry`)
await this.arriveGraphRow(row)
await this.recordingImportError(normalized, () => this.arriveGraphRow(row))
}
importError(id: string): Error | undefined {
return this.importErrors.get(stripClientSuffix(id))
}
/**
* Run one graph-row operation, recording its failure for the boot audit and
* clearing the record on success. Arrival and materialization both run in
* here, so a factory that throws is recorded as well as a bundle that never
* arrived; the Loader only sees a missing fiber either way.
*/
private async recordingImportError<T>(id: string, operation: () => Promise<T>): Promise<T> {
try {
const result = await operation()
this.importErrors.delete(id)
return result
} catch (error) {
this.importErrors.set(id, error instanceof Error ? error : new Error(describeError(error)))
throw error
}
}
/** Refresh descriptors and unowned factory revisions before any entry imports its dependencies. */
@@ -361,6 +462,7 @@ export class ClientModuleSystem implements ClientModuleLoader {
invalidate(id: string, rev?: string): void {
const normalized = stripClientSuffix(id)
if (this.bootstrapIds.has(normalized)) return
this.importErrors.delete(normalized)
this.generations.set(normalized, (this.generations.get(normalized) ?? 0) + 1)
const row = this.graphRows.get(normalized)
if (row !== undefined) {
@@ -483,7 +483,8 @@ it('discards a failed arrival target when an uncreated entry receives a newer gr
expect(b.modules.entries.state.getSnapshot().failures[0]?.message).toContain('offline r1')
b.arrival(async () => {})
await b.modules.entries.sync(graph(row('a', 'r2')))
expect(b.fetched).toEqual([row('a').url, row('a', 'r1').url, row('a', 'r2').url])
// A transport failure is retried once on the same URL before the reload is reported failed.
expect(b.fetched).toEqual([row('a').url, row('a', 'r1').url, row('a', 'r1').url, row('a', 'r2').url])
})
it('uses the latest desired revision when a rebuild queues before entry creation', async () => {
@@ -76,17 +76,26 @@ function bench(
pending?: ClientBundleRegistration[]
defaultTransport?: boolean
chunks?: Record<string, Factory | null>
/** Remaining transport rejections per URL (the `<script>` error event). */
transportFailures?: Record<string, number>
/** URLs whose script loads but registers only the listed ids (a runtime throw after those registrations). */
registerOnly?: Record<string, string[]>
} = {},
): Bench {
const fetched: string[] = []
const gates = new Map<string, () => void>()
const target = registrationTarget(opts.pending)
win.__ModuleLoader__ = target
const transportFailures = { ...opts.transportFailures }
const loadBundle = async (url: string): Promise<void> => {
fetched.push(url)
if (opts.gated?.includes(url) === true) {
await new Promise<void>((resolve) => { gates.set(url, resolve) })
}
if ((transportFailures[url] ?? 0) > 0) {
transportFailures[url] = (transportFailures[url] as number) - 1
throw new Error(`client-modules: bundle script ${url} failed to load`)
}
const sibling = /^plugins\/(.+)\/(client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js)\?rev=[^&]+$/.exec(url)
if (sibling !== null) {
const id = sibling[1] as string
@@ -105,7 +114,9 @@ function bench(
const singleId = combo?.split(',').length === 1 && combo.endsWith('/client.js')
? combo.slice(0, -'/client.js'.length)
: undefined
const only = opts.registerOnly?.[url]
for (const id of batchIds ?? (singleId === undefined ? [] : [singleId])) {
if (only !== undefined && !only.includes(id)) continue
const factory = bundles[id]
if (factory != null) win.__ModuleLoader__?.load({ id, factory })
}
@@ -343,6 +354,134 @@ describe('lazy CJS arrival', () => {
})
})
describe('bundle arrival recovery', () => {
const single = (id: string): string => comboReference([id], '0')
it('retries a batch once after a transport failure and shares the retry across its rows', async () => {
const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
transportFailures: { [APPLICATION_URL]: 1 },
})
const [a, c] = await Promise.all([b.loader.import('a', '', {}), b.loader.import('b', '', {})])
expect(a).toEqual({ a: 1 })
expect(c).toEqual({ b: 2 })
expect(b.fetched).toEqual([APPLICATION_URL, APPLICATION_URL])
})
it('falls back to each missing row\'s one-resource URL when the batch keeps failing, without re-fetching the batch per row', async () => {
const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
transportFailures: { [APPLICATION_URL]: 5 },
})
const [a, c] = await Promise.all([b.loader.import('a', '', {}), b.loader.import('b', '', {})])
expect(a).toEqual({ a: 1 })
expect(c).toEqual({ b: 2 })
expect(b.fetched.filter(url => url === APPLICATION_URL)).toHaveLength(2)
expect(b.fetched.slice(2).sort()).toEqual([single('a'), single('b')].sort())
expect(b.loader.importError('a')).toBeUndefined()
})
it('does not re-execute a batch that loaded without registering; the missing row loads alone', async () => {
const b = bench([row('a')], { a: () => ({ a: 1 }) }, { registerOnly: { [APPLICATION_URL]: [] } })
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
expect(b.fetched).toEqual([APPLICATION_URL, single('a')])
})
it('after a partially registering batch, loads only the missing row and never duplicates the registered one', async () => {
const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
registerOnly: { [APPLICATION_URL]: ['a'] },
})
expect(await b.loader.import('b', '', {})).toEqual({ b: 2 })
expect(b.fetched).toEqual([APPLICATION_URL, single('b')])
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
expect(b.fetched).toHaveLength(2)
})
it('never re-executes a batch that already ran, even when its first importer was one of the rows it did register', async () => {
const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
registerOnly: { [APPLICATION_URL]: ['a'] },
})
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
expect(b.fetched).toEqual([APPLICATION_URL])
expect(await b.loader.import('b', '', {})).toEqual({ b: 2 })
expect(b.fetched).toEqual([APPLICATION_URL, single('b')])
})
it('reports every attempt when the one-resource fallback fails too', async () => {
const b = bench([row('a')], { a: () => ({ a: 1 }) }, {
transportFailures: { [APPLICATION_URL]: 2, [single('a')]: 1 },
})
const failure: unknown = await b.loader.import('a', '', {}).then(() => undefined, (error: unknown) => error)
if (!(failure instanceof Error)) throw new Error('import resolved')
expect(failure.message).toContain('could not load "a"')
const batchAttempts = failure.message.split(`${APPLICATION_URL}: client-modules: bundle script`).length - 1
expect(batchAttempts).toBe(2)
expect(failure.message).toContain(`${single('a')}: client-modules: bundle script`)
expect(b.fetched).toEqual([APPLICATION_URL, APPLICATION_URL, single('a')])
})
it('a one-resource URL that fails stays retryable on the next import instead of being remembered as a failed batch', async () => {
const reloadUrl = comboReference(['a'], '1')
const b = bench([row('a')], { a: () => ({ a: 1 }) }, { transportFailures: { [reloadUrl]: 2 } })
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
b.loader.invalidate('a', '1')
await expect(b.loader.import('a', '', {})).rejects.toThrow('could not load "a"')
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
expect(b.fetched).toEqual([APPLICATION_URL, reloadUrl, reloadUrl, reloadUrl])
})
})
describe('import error record', () => {
it('records the transport failure of a row and clears it once the row imports', async () => {
const b = bench([row('a')], { a: () => ({ a: 1 }) }, {
transportFailures: { [APPLICATION_URL]: 2, [comboReference(['a'], '0')]: 1 },
})
await expect(b.loader.import('a', '', {})).rejects.toThrow()
expect(b.loader.importError('a')?.message).toContain('could not load "a"')
expect(b.loader.importError('a/client')).toBe(b.loader.importError('a'))
expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
expect(b.loader.importError('a')).toBeUndefined()
})
it('records a factory that throws during materialization, which no arrival record could see', async () => {
const b = bench([row('a')], { a: () => { throw new Error('factory exploded') } })
await expect(b.loader.import('a', '', {})).rejects.toThrow('factory exploded')
expect(b.loader.importError('a')?.message).toBe('factory exploded')
})
it('names the failed dependency in the consumer\'s record so a cascade reads as a chain', async () => {
const b = bench([row('dep'), row('consumer', { inject: ['dep'] })], { dep: () => ({}), consumer: () => ({}) }, {
registerOnly: { [APPLICATION_URL]: ['consumer'] },
transportFailures: { [comboReference(['dep'], '0')]: 1 },
})
await expect(b.loader.import('consumer', '', {})).rejects.toThrow(
'"consumer" not loaded because dependency "dep" failed: client-modules: could not load "dep"',
)
expect(b.loader.importError('consumer')?.message).toContain('dependency "dep" failed')
expect(b.loader.importError('dep')).toBeUndefined()
expect(b.loader.importError('consumer')?.cause).toBeInstanceOf(Error)
})
it('records a non-Error thrown by a factory as an Error carrying its text', async () => {
const b = bench([row('a')], { a: () => { throw 'factory rejected a string' } })
await expect(b.loader.import('a', '', {})).rejects.toBe('factory rejected a string')
expect(b.loader.importError('a')).toBeInstanceOf(Error)
expect(b.loader.importError('a')?.message).toBe('factory rejected a string')
})
it('records a prefetch failure and invalidate clears the record', async () => {
const b = bench([row('a')], { a: null })
await expect(b.loader.prefetch('a')).rejects.toThrow('without registering "a"')
expect(b.loader.importError('a')).toBeDefined()
b.loader.invalidate('a')
expect(b.loader.importError('a')).toBeUndefined()
})
it('has no record for a row that never failed or is unknown', () => {
const b = bench([row('a')], { a: () => ({}) })
expect(b.loader.importError('a')).toBeUndefined()
expect(b.loader.importError('nope')).toBeUndefined()
})
})
describe('require resolution', () => {
it('a factory requiring a registered-but-unmaterialized module materializes it recursively', async () => {
const order: string[] = []
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-plugin-manager/README.md
README.md: c02351b1fabafa093c80078013b21276fb5ce35c
README.zh.md: 61751d18f4dcac1f4ed159e5d5baeba2fccd2b83
README.md: d89e56a1115d077865c49150ecbf4991a524cfe9
README.zh.md: 50699e47490425f34eb295bec057ea970b84b7e5
+11 -3
View File
@@ -31,7 +31,11 @@ Installed bundles and their plugin rows display their own title and description
### Installing a bundle
**Add plugin** takes a package name with an optional version, a Git address, a tarball, or an absolute local path; the dialog says a package name is what follows `dsh plugin add` in a README. **Install guide and examples** under the field opens a guide that shows the three common forms with an example each; **Use example** drops one into the field. **Registry** beside it names the registry the install asks first and unfolds the choice: the default registry, pnpm's own, titled with the host the machine's pnpm configuration names; each mirror the Host configured (`pluginManager.registries`), npmmirror as the mainland China mirror; and a typed http(s) address. The options float over the dialog from the control, so unfolding them never lengthens the card, and the card's content scrolls when the guide makes it taller than the viewport. The registry the Host asks first is the choice until one is remembered; the choice is then remembered in this browser (`localStorage`) and starts the next dialog, and a remembered address the Host no longer offers stays as a typed one. **Install** first asks the Host to read what the spec names (`pluginManager.inspect`) at the chosen registry: a name the list already shows, a name no registry has, a path without a package, a package without a bundle patch, or a spec pnpm would refuse comes back under the field as one sentence, with the spec kept for editing; when no registry could be reached, the sentence names every one asked. The install then starts at the registry that answered. An accepted spec opens the installing screen, which shows the package's name, one-liner, and version as the Host read them and folds pnpm's command and output behind **Show install details**. A finished install offers **Enable now**, which switches the new bundle on, closes the dialog, and scrolls the list to it; closing instead leaves it installed and off. While the Host moves on to another registry, the installing screen says which registry could not serve the package and which is asked now, and each pnpm run behind the details carries a badge naming its registry. A failed install says what went wrong in one line, as the Host attributed it — no registry could be reached, naming every one asked; the host a GitHub address or a tarball link is fetched from could not be reached, which no registry helps; the package was not found, the disk is full, the profile is not writable, pnpm blocked a build script — with pnpm's output behind the details and **Retry** at hand, and **Change registry** beside it when the Host laid the failure at the registry it asked, which returns to the spec with the registry options open; the Host has already put the profile files back. When pnpm blocked a dependency's install scripts, the failed screen lists the packages whose scripts wait for permission and offers **Allow these scripts and retry** in place of **Retry**; the Host saves the permission in the profile's `pnpm-workspace.yaml`, which a failed run leaves as pnpm wrote it, then runs pnpm again, and the installed screen names what was allowed. A successful installation does not certify that a module can activate.
On first use, when pnpm uses the unconfigured official npm registry and npmmirror is offered, the Host probes both registries in parallel. The first successful HTTPS ping response selects the initial source. The dialog preserves remembered choices, manual selections, explicit manager configuration, and custom or unknown pnpm registries. An install clicked during initial probing waits for that bounded operation; a late result cannot overwrite a manual choice or reopen a closed dialog.
The Host sends GET requests to `https://registry.npmjs.org/-/ping` and `https://registry.npmmirror.com/-/ping` through its normal fetch proxy. A 2xx response wins; redirects and failures do not. The remaining request is cancelled, both response bodies are discarded, and cleanup completes before the result returns. The default deadline is 1500 ms and results, including unavailable results, are cached for five minutes. Configure `registryProbeTimeoutMs` and `registryProbeCacheTtlMs` on `ui-plugin-manager`; `registryProbeEnabled: false` disables probing. If both requests fail or time out, the existing default remains selected. No IP-location service or Session content is involved.
**Add plugin** takes a package name with an optional version, a Git address, a tarball, or an absolute local path; the dialog says a package name is what follows `dsh plugin add` in a README. **Install guide and examples** under the field opens a guide that shows the three common forms with an example each; **Use example** drops one into the field. **Registry** beside it names the registry the install asks first and unfolds the choice: the default registry, pnpm's own, titled with the host the machine's pnpm configuration names; each mirror the Host configured (`pluginManager.registries`), npmmirror as the mainland China mirror; and a typed http(s) address. The options float over the dialog from the control, so unfolding them never lengthens the card, and the card's content scrolls when the guide makes it taller than the viewport. The initial choice follows the response comparison above; the choice is then remembered in this browser (`localStorage`) and starts the next dialog, and a remembered address the Host no longer offers stays as a typed one and remains the requested address when installation starts before the registry list returns. **Install** first asks the Host to read what the spec names (`pluginManager.inspect`) at the chosen registry: a name the list already shows, a name no registry has, a path without a package, a package without a bundle patch, or a spec pnpm would refuse comes back under the field as one sentence, with the spec kept for editing; when no registry could be reached, the sentence names every one asked. The install then starts at the registry that answered. An accepted spec opens the installing screen, which shows the package's name, one-liner, and version as the Host read them and folds pnpm's command and output behind **Show install details**. A finished install offers **Enable now**, which switches the new bundle on, closes the dialog, and scrolls the list to it; closing instead leaves it installed and off. While the Host moves on to another registry, the installing screen says which registry could not serve the package and which is asked now, and each pnpm run behind the details carries a badge naming its registry. A failed install says what went wrong in one line, as the Host attributed it — no registry could be reached, naming every one asked; the host a GitHub address or a tarball link is fetched from could not be reached, which no registry helps; the package was not found, the disk is full, the profile is not writable, pnpm blocked a build script — with pnpm's output behind the details and **Retry** at hand, and **Change registry** beside it when the Host laid the failure at the registry it asked, which returns to the spec with the registry options open; the Host has already put the profile files back. When pnpm blocked a dependency's install scripts, the failed screen lists the packages whose scripts wait for permission and offers **Allow these scripts and retry** in place of **Retry**; the Host saves the permission in the profile's `pnpm-workspace.yaml`, which a failed run leaves as pnpm wrote it, then runs pnpm again, and the installed screen names what was allowed. A successful installation does not certify that a module can activate.
During preparation and download, **Cancel install** asks the Host to stop the run and waits for confirmation. Loading the bundle cannot be cancelled. Closing with ×, Escape, or the backdrop hides the dialog immediately and requests cancellation when possible. **View installation** reopens the same task with its output; another installation cannot start while its outcome is pending or unconfirmed. Confirmed cancellation returns to the spec and shows a toast; the manifest and lockfile are restored, while downloaded files can remain. A lost installation response triggers a request to recover the result; **Check installation status** and reconnect retry that request. If the Host has no active request, **Installation result unavailable** allows returning to editing after checking the plugin list. A cancellation sent before acceptance waits and retries automatically; a failed cancellation can be retried manually. Hidden tasks report their outcome through toasts without reopening the dialog.
@@ -85,6 +89,8 @@ Package management uses the profile's dependency records: installed bundles can
### Registration
The Host entry exposes `pluginRegistryProbe.fastest()` through the generated Remote interface. It shares pending comparisons, expires cached results, and aborts and awaits outstanding probes on unload. Calls after unload return a rejected Promise.
The browser plugin registers the `plugins` sidebar entry and its `main` panel through `ctx.slots.inject()`, so both follow late slot declaration, locale changes and teardown. The page is global and belongs to no Session. Display text comes from package metadata and the page's dictionary.
### The store
@@ -126,6 +132,8 @@ None; this package neither assembles nor sends a provider request.
## Known Limitations and Deferred Work
- Ping response time does not measure package-download throughput. Probes use the Host fetch route, which pnpm-specific proxy settings can differ from; users can always choose the registry manually, and installation retains its existing fallback rules.
<a id="known-limitations-and-deferred-work"></a>
@@ -136,7 +144,7 @@ These limits define the reach of the management view; they are current package c
- **Rows show a phase, not a reason** — a failed row reads as failed without the Host's error text; the Host log has it.
- **One install at a time** — the dialog runs one pnpm command; a second spec waits for the first to finish.
- **No version picker** — the spec is typed as pnpm accepts it; the page neither lists registry versions nor offers upgrades.
- **The registry choice is this browser's** — it lives in `localStorage`, so another browser, the `dsh plugin` command, and the agent tool start from the Host's configured registry.
- **The registry choice is this browser's** — it lives in `localStorage`, so another browser applies its own initial recommendation; the `dsh plugin` command and the agent tool use the Host's configured registry.
- **Every registry read runs pnpm** — opening the dialog, the check, and the install each ask pnpm what its own configuration names; a machine without pnpm reads it as unknown and is offered no fallback.
<a id="dev-note"></a>
@@ -149,4 +157,4 @@ None.
</details>
**Runtime invariant:** No companion is published. This package owns a sidebar panel over Host-owned facts.
**Runtime invariant:** No companion is published. The panel reads Host-owned facts, and the registry-probe cache stores one comparison result without an independently maintained projection.
+11 -3
View File
@@ -31,7 +31,11 @@ kind: "package-reference"
### 安装一个组合包
**添加插件**接受包名(可带版本)、Git 地址、压缩包或本地绝对路径;对话框说明包名就是 README 里 `dsh plugin add` 后面的那一段。输入框下方的**插件安装引导和示例**展开一段引导,给出三种常见形式各一个示例;**填入示例**把示例填进输入框。旁边的**安装源**写着安装首先询问的注册表,展开后可选:默认安装源,即 pnpm 自身的注册表,标题带上本机 pnpm 配置指向的主机名;Host 配置的每个镜像(`pluginManager.registries`),npmmirror 显示为中国大陆镜像源;以及手动输入的 http(s) 地址。选项从控件上浮在对话框之上,展开不会拉长卡片;引导使卡片高过视口时,卡片内容可以滚动。Host 首先询问的注册表在记住选择之前就是当前选择;之后选择记在本浏览器(`localStorage`)里,下次打开对话框从它开始,Host 不再提供的已记住地址保留为手动输入的地址。**安装**先让 Host 在所选注册表读出 spec 指向什么(`pluginManager.inspect`):列表中已有的名字、所有注册表都没有的名字、没有包的路径、没有组合包 patch 的包,或 pnpm 会拒绝的 spec,都以一句话回到输入框下方,spec 保留可继续编辑;所有注册表都连不上时,这句话列出问过的每一个。随后安装从作答的那个注册表开始。通过检查的 spec 打开安装中界面,展示 Host 读到的包名、一句话简介和版本,pnpm 的命令与输出折叠在**查看安装详情**之后。安装完成后提供**立即启用**:启用新组合包、关闭对话框并把列表滚动到它;直接关闭则让它保持已安装但关闭。Host 改问另一个注册表时,安装中界面会说明哪个源没能提供这个包、现在改问哪个,详情里每次 pnpm 运行都带一个写明所用源的标记。安装失败时按 Host 的归因用一行话说明原因——所有安装源都连不上,并列出问过的每一个;GitHub 地址或压缩包链接自身的主机连不上,换源无济于事;包不存在、磁盘已满、profile 不可写、pnpm 拦下了构建脚本——pnpm 输出在详情里,**重试**就在手边,Host 把失败归于所问注册表时还在旁边提供**更换安装源**,回到 spec 输入界面并展开安装源选项;Host 已经把 profile 文件放回原样。pnpm 拦下依赖的安装脚本时,失败界面列出等待允许的包,并以**允许这些脚本并重试**取代**重试**;Host 把授权写进 profile 的 `pnpm-workspace.yaml`(失败的运行保留 pnpm 写入的这个文件)再运行 pnpm,安装完成界面会说明允许了哪些脚本。安装成功不代表模块一定能够激活。
首次使用时,如果未显式配置安装源、pnpm 使用官方 npm 源,且列表提供 npmmirror,Host 会并发探测这两个源,选择最先成功响应 HTTPS ping 的源。已记住的选择、用户手选、管理器显式配置,以及自定义或未知的 pnpm 源均保留。在初次探测期间点击安装会等待这次有时限的操作;迟到结果不会覆盖手选或重新打开已关闭的对话框。
Host 通过普通 fetch 代理向 `https://registry.npmjs.org/-/ping` 和 `https://registry.npmmirror.com/-/ping` 发送 GET 请求,以最先返回 2xx 的源为结果;重定向和失败不参与选择。随后取消另一条请求、丢弃两个响应体,并在清理完成后返回。默认时限为 1500 毫秒,包括不可用结果在内的探测结果均缓存五分钟。在 `ui-plugin-manager` 上配置 `registryProbeTimeoutMs` 和 `registryProbeCacheTtlMs`;`registryProbeEnabled: false` 关闭探测。两条请求都失败或超时时保留现有默认源。不使用 IP 地区服务,也不发送 Session 内容。
**添加插件**接受包名(可带版本)、Git 地址、压缩包或本地绝对路径;对话框说明包名就是 README 里 `dsh plugin add` 后面的那一段。输入框下方的**插件安装引导和示例**展开一段引导,给出三种常见形式各一个示例;**填入示例**把示例填进输入框。旁边的**安装源**写着安装首先询问的注册表,展开后可选:默认安装源,即 pnpm 自身的注册表,标题带上本机 pnpm 配置指向的主机名;Host 配置的每个镜像(`pluginManager.registries`),npmmirror 显示为中国大陆镜像源;以及手动输入的 http(s) 地址。选项从控件上浮在对话框之上,展开不会拉长卡片;引导使卡片高过视口时,卡片内容可以滚动。初始选择遵循上文的响应比较规则;之后选择记在本浏览器(`localStorage`)里,下次打开对话框从它开始,Host 不再提供的已记住地址保留为手动输入的地址;在安装源列表返回前开始安装,也仍请求该地址。**安装**先让 Host 在所选注册表读出 spec 指向什么(`pluginManager.inspect`):列表中已有的名字、所有注册表都没有的名字、没有包的路径、没有组合包 patch 的包,或 pnpm 会拒绝的 spec,都以一句话回到输入框下方,spec 保留可继续编辑;所有注册表都连不上时,这句话列出问过的每一个。随后安装从作答的那个注册表开始。通过检查的 spec 打开安装中界面,展示 Host 读到的包名、一句话简介和版本,pnpm 的命令与输出折叠在**查看安装详情**之后。安装完成后提供**立即启用**:启用新组合包、关闭对话框并把列表滚动到它;直接关闭则让它保持已安装但关闭。Host 改问另一个注册表时,安装中界面会说明哪个源没能提供这个包、现在改问哪个,详情里每次 pnpm 运行都带一个写明所用源的标记。安装失败时按 Host 的归因用一行话说明原因——所有安装源都连不上,并列出问过的每一个;GitHub 地址或压缩包链接自身的主机连不上,换源无济于事;包不存在、磁盘已满、profile 不可写、pnpm 拦下了构建脚本——pnpm 输出在详情里,**重试**就在手边,Host 把失败归于所问注册表时还在旁边提供**更换安装源**,回到 spec 输入界面并展开安装源选项;Host 已经把 profile 文件放回原样。pnpm 拦下依赖的安装脚本时,失败界面列出等待允许的包,并以**允许这些脚本并重试**取代**重试**;Host 把授权写进 profile 的 `pnpm-workspace.yaml`(失败的运行保留 pnpm 写入的这个文件)再运行 pnpm,安装完成界面会说明允许了哪些脚本。安装成功不代表模块一定能够激活。
准备和下载期间,**取消安装**会请求 Host 停止运行并等待确认。加载组合包的阶段不可取消。点击 ×、按 Escape 或点击遮罩会立即隐藏对话框,并在可以取消时请求取消。**查看安装任务**会重新打开同一任务并保留输出;结果待定或尚未确认时不能发起另一项安装。确认取消后回到 spec 输入界面并显示 toast;manifest 与 lockfile 已恢复,已下载文件可能保留。安装响应丢失后会请求恢复结果;**核对安装状态**和重连会重试该请求。Host 已无活动请求时,**未能获取安装结果**允许检查插件列表后返回编辑。早于接收确认的取消请求会等待并自动重试;取消失败可手动重试。隐藏的任务通过 toast 通知结果,不会重新弹出对话框。
@@ -85,6 +89,8 @@ ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({
### 注册
Host 入口通过生成的 Remote 接口暴露 `pluginRegistryProbe.fastest()`,共享进行中的比较、让缓存按时过期,并在卸载时中止和等待未完成探测。卸载后调用会返回拒绝的 Promise。
浏览器插件通过 `ctx.slots.inject()` 注册 `plugins` 侧栏入口与它的 `main` 面板,使两者跟随 slot 延迟声明、本地化变化与销毁。页面为全局页面,不属于任何 Session。显示文本来自包元信息与页面字典。
### store
@@ -126,6 +132,8 @@ ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({
## 已知限制与延期工作
- Ping 响应时间不代表包下载吞吐量。探测使用 Host fetch 的网络路径,pnpm 专用代理设置可能使用不同路径;用户始终可以手动选择安装源,安装仍遵循现有回退规则。
<a id="known-limitations-and-deferred-work"></a>
@@ -136,7 +144,7 @@ ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({
- **行只显示阶段,不显示原因**——失败的行只显示为失败,没有 Host 的错误文本;Host 日志里有。
- **一次只能安装一个**——对话框一次运行一个 pnpm 命令;第二个 spec 要等前一个完成。
- **没有版本选择器**——spec 按 pnpm 接受的写法输入;页面不列出注册表版本,也不提供升级。
- **安装源选择只属于本浏览器**——它存在 `localStorage` 里,所以另一个浏览器、`dsh plugin` 命令和 agent 工具都从 Host 配置的注册表开始。
- **安装源选择只属于本浏览器**——它存在 `localStorage` 里,所以另一个浏览器会独立计算初始推荐;`dsh plugin` 命令和 agent 工具使用 Host 配置的注册表。
- **每次读注册表都要运行 pnpm**——打开对话框、检查、安装各问一次 pnpm 自身配置指向哪里;没有 pnpm 的机器读作未知,不提供备选。
<a id="dev-note"></a>
@@ -149,4 +157,4 @@ ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({
</details>
**运行时不变式:** 不发布伴生检查。本包只拥有一个基于 Host 事实的侧栏面板。
**运行时不变式:** 不发布伴生检查。面板读取 Host 事实,安装源探测缓存只保存一次比较结果,没有独立维护的投影。
+23 -5
View File
@@ -23,7 +23,15 @@
"default": "./lib/client.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json"
"./package.json": "./package.json",
"./typert": {
"types": "./lib/typert.host.d.ts",
"default": "./lib/typert.host.js"
},
"./remote": {
"types": "./lib/typert.remote-client.d.ts",
"default": "./lib/typert.remote-client.js"
}
},
"dsh": {
"client": {
@@ -55,7 +63,6 @@
"@deepseek-ai/dsh-client-ui-renderer": "workspace:^",
"@deepseek-ai/dsh-client-ui-sidebar": "workspace:^",
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
"@deepseek-ai/dsh-plugin-manager": "workspace:^",
"@deepseek-ai/dsh-package-manifest": "workspace:^",
"@testing-library/react": "^16.1.0",
"@types/react": "~18.3.1",
@@ -64,11 +71,22 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"@deepseek-ai/dsh-util-crypto": "workspace:^",
"@deepseek-ai/dsh-client-ui-settings": "workspace:^"
"@deepseek-ai/dsh-client-ui-settings": "workspace:^",
"@deepseek-ai/dsh-plugin-manager": "workspace:^"
},
"files": [
"lib/index.js",
"lib/client.js",
"lib/types/**/*.d.ts"
]
"lib/types/**/*.d.ts",
"lib/typert.host.js",
"lib/typert.host.d.ts",
"lib/typert.remote-client.js",
"lib/typert.remote-client.d.ts"
],
"dependencies": {
"@deepseek-ai/dsh-timeout": "workspace:^",
"@deepseek-ai/schemastery": "workspace:^",
"zod": "^4.4.3",
"@deepseek-ai/dsh-typert-protocol": "workspace:^"
}
}
@@ -49,7 +49,7 @@ export const NS = 'pluginManager'
export const PANEL_ID = 'plugins' as MainPanelId
/** Services required by the sidebar registration and the Remote methods; the inventory says whether the Host manages a profile. */
export const inject = ['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'configForms']
export const inject = ['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'remote.pluginRegistryProbe', 'configForms']
/**
* Contribute the Plugins entry to the sidebar with the management page it
@@ -24,7 +24,7 @@ import type {
ReadOnlyReason,
Registry,
} from '@deepseek-ai/dsh-api-remotes/client'
import { REGISTRY_URL } from '@deepseek-ai/dsh-plugin-manager/registry'
import { normalizeRegistry, NPMMIRROR_REGISTRY, OFFICIAL_NPM_REGISTRY, REGISTRY_URL } from '@deepseek-ai/dsh-plugin-manager/registry'
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'
import type { LocalizedText, PluginLocalizedMeta } from '@deepseek-ai/dsh-package-manifest'
@@ -407,6 +407,26 @@ function reconciled(remembered: RegistryChoice | null, registries: PluginRegistr
: remembered
}
interface RegistryRead {
/** Last automatically assigned choice; a different object belongs to a manual selection. */
choice: RegistryChoice
/** Pending initial registry list and response probes; an untouched installation waits until it settles. */
done?: Promise<void>
}
/** Only the shipped public mirror can replace an unconfigured official npm default. */
function eligibleMirror(registries: PluginRegistries): string | undefined {
if (registries.registry !== null || registries.resolved === null) return undefined
let resolved: string
try { resolved = normalizeRegistry(registries.resolved) }
catch (_error) {
// An invalid pnpm registry cannot receive a public mirror recommendation.
return undefined
}
if (resolved !== OFFICIAL_NPM_REGISTRY) return undefined
return registries.fallbackRegistries.find(registry => registry === NPMMIRROR_REGISTRY)
}
/** One installation owns acceptance, response recovery, and every cancellation attempt. */
interface InstallRequest {
readonly requestId: PluginInstallRequestId
@@ -428,6 +448,7 @@ export class PluginManagerController {
private inspectAbort: AbortController | undefined
private request: InstallRequest | undefined
private noticeSeq = 0
private registryRead: RegistryRead | undefined
/** The registry last used from this browser, kept across dialogs and page loads; null until one was used. */
private readonly registryMemory: SnapshotStore<RegistryChoice | null> = createSnapshotStore<RegistryChoice | null>(null, {
persist: { name: 'dsh.plugin-manager.install-registry' },
@@ -456,6 +477,7 @@ export class PluginManagerController {
/** Stop publishing and drop every late settlement. */
dispose(): void {
this.disposed = true
this.registryRead = undefined
this.request = undefined
this.generation += 1
}
@@ -478,7 +500,9 @@ export class PluginManagerController {
if (install.requestId === undefined) {
// A new dialog starts from the registry last used here and reads what the Host offers; a hidden install reopens as it is.
this.patch({ install: { ...IDLE_INSTALL, open: true, registry: this.registryMemory.getSnapshot() ?? OFFICIAL_REGISTRY } })
void this.readRegistries()
const read: RegistryRead = { choice: this.getSnapshot().install.registry }
this.registryRead = read
read.done = this.readRegistries(read).finally(() => { delete read.done })
} else {
this.patchInstall({ open: true })
}
@@ -491,6 +515,7 @@ export class PluginManagerController {
return
}
this.abortInspect()
this.registryRead = undefined
this.patch({ install: IDLE_INSTALL })
},
editInstallSpec: (text) => {
@@ -569,12 +594,27 @@ export class PluginManagerController {
})
}
private currentRegistryRead(read: RegistryRead): boolean {
return !this.disposed && this.registryRead === read
}
/** Read the registries the Host offers, for the dialog just opened; a refused read leaves pnpm's own and a typed one. */
private async readRegistries(): Promise<void> {
private async readRegistries(read: RegistryRead): Promise<void> {
const answer = await this.ctx.remote.pluginManager.registries()
const install = this.getSnapshot().install
if (this.disposed || !install.open || !answer.ok) return
this.patchInstall({ registries: answer.value, registry: reconciled(this.registryMemory.getSnapshot(), answer.value) })
if (!this.currentRegistryRead(read) || !install.open || !answer.ok) return
const remembered = this.registryMemory.getSnapshot()
const untouched = install.registry === read.choice && (install.phase === 'idle' || install.phase === 'checking')
if (untouched) read.choice = reconciled(remembered, answer.value)
this.patchInstall({ registries: answer.value, ...untouched ? { registry: read.choice } : {} })
const mirror = eligibleMirror(answer.value)
if (!untouched || remembered !== null || mirror === undefined) return
const fastest = await this.ctx.remote.pluginRegistryProbe.fastest()
const current = this.getSnapshot().install
if (!this.currentRegistryRead(read) || !current.open || (current.phase !== 'idle' && current.phase !== 'checking')
|| current.registry !== read.choice || !fastest.ok || fastest.value !== mirror) return
read.choice = { kind: 'offered', registry: mirror }
this.patchInstall({ registry: read.choice })
}
/**
@@ -695,8 +735,6 @@ export class PluginManagerController {
this.patchInstall({ phase: 'idle', registryError: true })
return
}
const registry: Registry = typed ?? (choice as Extract<RegistryChoice, { kind: 'offered' }>).registry
this.registryMemory.set(typed === undefined ? choice : { kind: 'custom', url: typed })
this.abortInspect()
const controller = new AbortController()
this.inspectAbort = controller
@@ -704,6 +742,15 @@ export class PluginManagerController {
phase: 'checking', inputError: null, subject: null, runs: [], detailsOpen: false, attempts: null, registryOpen: false,
installed: null, restartRequired: false, failure: null, approvedBuilds: [],
})
const read = this.registryRead
if (read !== undefined && choice === read.choice && read.done !== undefined) {
await read.done
if (this.gone(controller.signal) || this.registryRead !== read) return
}
const currentChoice = this.getSnapshot().install.registry
const selected = currentChoice.kind === 'custom' ? { ...currentChoice, url: currentChoice.url.trim() } : currentChoice
const registry: Registry = selected.kind === 'custom' ? selected.url : selected.registry
this.registryMemory.set(selected)
const inspected = await this.ctx.remote.pluginManager.inspect(spec, { registry }, controller.signal)
if (this.gone(controller.signal)) return
this.inspectAbort = undefined
+85 -3
View File
@@ -1,4 +1,86 @@
/** Host loader entry for the plugin-manager tab's browser implementation exported from `./client`. */
/** Host registry-response probing for the plugin installation dialog. */
/** Host plugin body — no host-side behavior for the plugin manager tab. */
export function apply(): void {}
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
declare module '@deepseek-ai/cordis' {
interface Context {
pluginRegistryProbe: PluginRegistryProbe
}
}
/** Registry-probe deadline and process-local cache policy. */
export interface Config {
/** Whether the dialog can compare the public npm registries. */
registryProbeEnabled: boolean
/** Deadline for the parallel HTTPS probes, including response cleanup. */
registryProbeTimeoutMs: number
/** Lifetime of a winning registry or unavailable result. */
registryProbeCacheTtlMs: number
}
/** Compares public registry responses on the Host; the Client owns the initial selection. */
export default class PluginRegistryProbe extends TypertRemoteService {
static Config: z<Partial<Config>, Config> = z.object({
registryProbeEnabled: z.boolean().default(true),
registryProbeTimeoutMs: z.natural().min(1).max(MAX_TIMER_DELAY_MS).default(1500),
registryProbeCacheTtlMs: z.natural().default(300000),
})
private readonly lifetime = new AbortController()
private pending: Promise<string | null> | undefined
private cached: { registry: string | null; expiresAt: number } | undefined
constructor(ctx: Context, private readonly config: Config) {
super(ctx, 'pluginRegistryProbe')
ctx.effect(() => async () => {
this.lifetime.abort()
await this.pending
})
}
/**
* Race npm and npmmirror HTTPS ping responses through the Host's fetch proxy.
* Concurrent readers share a probe; a winner cancels and awaits the other request.
* @returns the first registry with a successful response, or null when disabled or neither responds successfully; results are cached.
* @throws rejects when the service has been unloaded.
*/
@Remote
async fastest(): Promise<string | null> {
this.lifetime.signal.throwIfAborted()
if (!this.config.registryProbeEnabled) return null
if (this.cached !== undefined && this.cached.expiresAt > Date.now()) return this.cached.registry
this.pending ??= this.probe().finally(() => { this.pending = undefined })
return this.pending
}
private async probe(): Promise<string | null> {
const finished = new AbortController()
const signal = AbortSignal.any([this.lifetime.signal, finished.signal, AbortSignal.timeout(this.config.registryProbeTimeoutMs)])
const requests = ['https://registry.npmjs.org/-/ping', 'https://registry.npmmirror.com/-/ping'].map(async endpoint => ({
registry: new URL('/', endpoint).href,
response: await fetch(endpoint, { signal, redirect: 'error' }),
}))
const successful = requests.map(async (request) => {
const { registry, response } = await request
if (!response.ok) throw new Error(`Registry ping returned HTTP ${response.status}`)
return registry
})
let registry: string | null
try {
registry = await Promise.any(successful)
} catch (_unavailableRegistries) {
registry = null
} finally {
finished.abort()
const responses = await Promise.allSettled(requests)
await Promise.allSettled(responses.map(async (result) => {
if (result.status === 'fulfilled') await result.value.response.body?.cancel()
}))
}
if (!this.lifetime.signal.aborted) this.cached = { registry, expiresAt: Date.now() + this.config.registryProbeCacheTtlMs }
return registry
}
}
@@ -11,7 +11,6 @@ import { apply, inject, NS, PANEL_ID } from '../src/client/index.ts'
import { PluginManagerPage } from '../src/client/PluginManagerPage.tsx'
import { PluginsPanelIcon } from '../src/client/PluginsPanelIcon.tsx'
import type { PluginManagerFace } from '../src/client/manager-store.ts'
import { apply as hostApply } from '../src/index.ts'
usePinnedBrowserLanguages('zh-CN')
afterEach(cleanup)
@@ -32,6 +31,7 @@ async function bench() {
const remote = new TestRemote(ctx, {
settings: { describe: vi.fn(async () => ({ ok: true as const, value: { writable: true, hasDocument: true, namespaces: [] } })) },
pluginInventory: { list },
pluginRegistryProbe: { fastest: vi.fn(async () => ({ ok: true as const, value: null })) },
pluginManager: {
listBundles: vi.fn(() => Promise.resolve({ ok: true as const, value: [] })),
listPlugins: vi.fn(() => Promise.resolve({ ok: true as const, value: [] })),
@@ -53,12 +53,8 @@ function declare(slots: SlotRegistry): () => void {
}
describe('ui-plugin-manager browser plugin', () => {
it('keeps the host Loader entry inert', () => {
expect(hostApply).not.toThrow()
})
it('declares only the services the page and its Remote methods use', () => {
expect(inject).toEqual(['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'configForms'])
expect(inject).toEqual(['slots', 'locale', 'remote', 'remote.pluginManager', 'remote.pluginInventory', 'remote.pluginRegistryProbe', 'configForms'])
})
it('registers the sidebar entry and its page, which reads the Host only once rendered and follows Host changes', async () => {
@@ -85,9 +85,10 @@ function bench(overrides: Partial<Record<string, ReturnType<typeof vi.fn>>> = {}
setPluginEnabled: vi.fn(() => Promise.resolve(ok(APPLIED))),
...overrides,
}
const probe = { fastest: overrides.fastest ?? vi.fn(() => Promise.resolve(ok(null))) }
const ctx = {
configForms: { describe: () => ({ getSnapshot: () => ({ view: { namespaces: [] } }), subscribe: () => () => {} }), get: vi.fn((id: string) => `form:${id}`) },
remote: { pluginManager: plugins, pluginInventory: inventory },
remote: { pluginManager: plugins, pluginInventory: inventory, pluginRegistryProbe: probe },
} as never
const controller = new PluginManagerController(ctx)
onTestFinished(() => { controller.dispose() })
@@ -98,7 +99,7 @@ function bench(overrides: Partial<Record<string, ReturnType<typeof vi.fn>>> = {}
await vi.waitFor(() => { expect(state().install.phase).toBe('starting') })
return state().install.requestId as PluginInstallRequestId
}
return { plugins, inventory, controller, face, state, started }
return { plugins, inventory, probe, controller, face, state, started }
}
it('hands a custom page the shared configuration form of its entry', () => {
@@ -353,7 +354,7 @@ describe('PluginManagerController', () => {
// Neither typing nor a second run reaches the Host while it checks.
face.editInstallSpec('other')
expect(state().install.spec).toBe(' dsh-new ')
expect(plugins.inspect).toHaveBeenCalledTimes(1)
await vi.waitFor(() => { expect(plugins.inspect).toHaveBeenCalledTimes(1) })
expect(plugins.inspect).toHaveBeenCalledWith('dsh-new', { registry: null }, expect.any(AbortSignal))
const requestId = await started()
expect(state().install.subject).toEqual({ spec: 'dsh-new', ...INSPECTED })
@@ -436,6 +437,7 @@ describe('PluginManagerController', () => {
face.openInstall()
face.editInstallSpec('dsh-x')
face.runInstall()
await vi.waitFor(() => { expect(plugins.inspect).toHaveBeenCalledOnce() })
const checkSignal = (plugins.inspect.mock.calls[0] as unknown[])[2] as AbortSignal
face.cancelInstall()
expect(checkSignal.aborted).toBe(true)
@@ -1196,3 +1198,131 @@ describe('PluginManagerController', () => {
expect(state().install.registry).toEqual({ kind: 'offered', registry: MIRROR })
})
})
describe('Host registry response recommendation', () => {
it('inspects the remembered registry when the offered choice becomes custom during the initial read', async () => {
const key = 'dsh.plugin-manager.install-registry'
const registry = 'https://old.example/'
const storage = new Map([[key, JSON.stringify({ kind: 'offered', registry })]])
const registries = deferred<ReturnType<typeof ok<typeof REGISTRIES>>>()
vi.stubGlobal('localStorage', {
getItem: (name: string) => storage.get(name) ?? null,
setItem: (name: string, value: string) => { storage.set(name, value) },
removeItem: (name: string) => { storage.delete(name) },
})
try {
const { face, state, plugins, probe } = bench({
registries: vi.fn(() => registries.promise),
inspect: vi.fn(async () => ok({ ...INSPECTED, registry })),
})
face.openInstall()
face.editInstallSpec('dsh-new')
face.runInstall()
expect(state().install.phase).toBe('checking')
expect(plugins.inspect).not.toHaveBeenCalled()
registries.resolve(ok(REGISTRIES))
await vi.waitFor(() => { expect(plugins.inspect).toHaveBeenCalled() })
expect(plugins.inspect).toHaveBeenCalledWith('dsh-new', { registry }, expect.any(AbortSignal))
expect(state().install.registry).toEqual({ kind: 'custom', url: registry })
expect(JSON.parse(storage.get(key)!)).toEqual({ kind: 'custom', url: registry })
expect(probe.fastest).not.toHaveBeenCalled()
await vi.waitFor(() => { expect(state().install.phase).toBe('done') })
expect(plugins.installBundle).toHaveBeenCalledWith('dsh-new', expect.objectContaining({ registry }))
} finally {
registries.resolve(ok(REGISTRIES))
vi.unstubAllGlobals()
}
})
it('selects the mainland mirror before the first inspection, even when install was clicked during lookup', async () => {
const fastest = deferred<ReturnType<typeof ok<string | null>>>()
const { face, state, plugins, probe } = bench({ fastest: vi.fn(() => fastest.promise) })
face.openInstall()
face.editInstallSpec('dsh-new')
face.runInstall()
await vi.waitFor(() => { expect(probe.fastest).toHaveBeenCalledOnce() })
expect(plugins.inspect).not.toHaveBeenCalled()
fastest.resolve(ok(MIRROR))
await vi.waitFor(() => { expect(plugins.inspect).toHaveBeenCalled() })
expect(plugins.inspect).toHaveBeenCalledWith('dsh-new', { registry: MIRROR }, expect.any(AbortSignal))
expect(state().install.registry).toEqual({ kind: 'offered', registry: MIRROR })
})
it.each([OFFICIAL, null])('keeps the default for probe result %s', async (winner) => {
const { face, state, probe } = bench({ fastest: vi.fn(() => Promise.resolve(ok(winner))) })
face.openInstall()
await vi.waitFor(() => { expect(probe.fastest).toHaveBeenCalledOnce() })
expect(state().install.registry).toEqual({ kind: 'offered', registry: null })
})
it('keeps the default when the Host lookup is unavailable', async () => {
const { face, state, probe } = bench({ fastest: vi.fn(() => Promise.resolve(refused('gateway/internal', 'offline'))) })
face.openInstall()
await vi.waitFor(() => { expect(probe.fastest).toHaveBeenCalledOnce() })
expect(state().install.registry).toEqual({ kind: 'offered', registry: null })
})
it.each([
{ registry: MIRROR, resolved: OFFICIAL, fallbackRegistries: [MIRROR] },
{ registry: null, resolved: CORP, fallbackRegistries: [MIRROR] },
{ registry: null, resolved: null, fallbackRegistries: [MIRROR] },
{ registry: null, resolved: 'invalid', fallbackRegistries: [MIRROR] },
{ registry: null, resolved: OFFICIAL, fallbackRegistries: [] },
])('does not probe registries for an ineligible registry configuration %j', async (registries) => {
const { face, state, probe } = bench({ registries: vi.fn(() => Promise.resolve(ok(registries))) })
face.openInstall()
await vi.waitFor(() => { expect(state().install.registries).toEqual(registries) })
expect(state().install.registry).toEqual({ kind: 'offered', registry: registries.registry })
expect(probe.fastest).not.toHaveBeenCalled()
})
it('preserves a manual choice made before the registry list arrives', async () => {
const registries = deferred<ReturnType<typeof ok<typeof REGISTRIES>>>()
const { face, state, probe } = bench({ registries: vi.fn(() => registries.promise) })
face.openInstall()
face.chooseRegistry({ kind: 'custom', url: CORP })
registries.resolve(ok(REGISTRIES))
await vi.waitFor(() => { expect(state().install.registries).toEqual(REGISTRIES) })
expect(state().install.registry).toEqual({ kind: 'custom', url: CORP })
expect(probe.fastest).not.toHaveBeenCalled()
})
it('does not overwrite a manual choice or wait for registry probing after that choice', async () => {
const fastest = deferred<ReturnType<typeof ok<string | null>>>()
const { face, state, plugins, probe } = bench({ fastest: vi.fn(() => fastest.promise) })
face.openInstall()
await vi.waitFor(() => { expect(probe.fastest).toHaveBeenCalledOnce() })
face.chooseRegistry({ kind: 'custom', url: CORP })
face.editInstallSpec('dsh-new')
face.runInstall()
await vi.waitFor(() => { expect(plugins.inspect).toHaveBeenCalled() })
fastest.resolve(ok(MIRROR))
await fastest.promise
expect(state().install.registry).toEqual({ kind: 'custom', url: CORP })
expect(plugins.inspect).toHaveBeenCalledWith('dsh-new', { registry: CORP }, expect.any(AbortSignal))
})
it.each(['close', 'dispose'] as const)('discards a waiting install after %s', async (action) => {
const fastest = deferred<ReturnType<typeof ok<string | null>>>()
const { face, controller, plugins, probe } = bench({ fastest: vi.fn(() => fastest.promise) })
face.openInstall()
face.editInstallSpec('dsh-new')
face.runInstall()
await vi.waitFor(() => { expect(probe.fastest).toHaveBeenCalledOnce() })
if (action === 'close') face.closeInstall()
else controller.dispose()
fastest.resolve(ok(MIRROR))
await fastest.promise
await Promise.resolve()
expect(plugins.inspect).not.toHaveBeenCalled()
})
})
it('recognizes the official registry without a trailing slash and with uppercase host letters', async () => {
const { face, state } = bench({
registries: vi.fn(async () => ok({ ...REGISTRIES, resolved: 'https://REGISTRY.NPMJS.ORG' })),
fastest: vi.fn(async () => ok(MIRROR)),
})
face.openInstall()
await vi.waitFor(() => { expect(state().install.registry).toEqual({ kind: 'offered', registry: MIRROR }) })
})
@@ -0,0 +1,136 @@
import { Context } from '@deepseek-ai/cordis'
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
import { NPMMIRROR_REGISTRY, OFFICIAL_NPM_REGISTRY } from '@deepseek-ai/dsh-plugin-manager/registry'
import PluginRegistryProbe, { type Config } from '../src/index.ts'
afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() })
async function mount(config: Partial<Config> = {}) {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
await ctx.plugin(PluginRegistryProbe, PluginRegistryProbe.Config(config))
return { ctx, probe: ctx.pluginRegistryProbe }
}
function transport() {
const requests = new Map<string, ReturnType<typeof Promise.withResolvers<Response>> & { signal: AbortSignal }>()
const fetch = vi.fn((url: string, init: RequestInit) => {
const signal = init.signal
if (!signal) throw new Error('Missing probe signal')
const pending = Promise.withResolvers<Response>()
const abort = () => { pending.reject(signal.reason) }
signal.addEventListener('abort', abort, { once: true })
requests.set(url, { ...pending, signal })
return pending.promise.finally(() => { signal.removeEventListener('abort', abort) })
})
vi.stubGlobal('fetch', fetch)
const request = (registry: string) => {
const found = requests.get(`${registry}-/ping`)
if (!found) throw new Error('Probe has not started')
return found
}
return { fetch, request }
}
it.each([OFFICIAL_NPM_REGISTRY, NPMMIRROR_REGISTRY])('shares concurrent probes and caches the first successful response from %s', async (winner) => {
vi.useFakeTimers()
const { fetch, request } = transport()
const { probe } = await mount({ registryProbeCacheTtlMs: 50 })
const first = probe.fastest()
const shared = probe.fastest()
expect(fetch).toHaveBeenCalledTimes(2)
expect(fetch).toHaveBeenCalledWith(`${winner}-/ping`, expect.objectContaining({ redirect: 'error' }))
const cancel = vi.fn()
request(winner).resolve(new Response(new ReadableStream({ cancel })))
expect(await first).toBe(winner)
expect(await shared).toBe(winner)
expect(cancel).toHaveBeenCalledOnce()
const other = winner === OFFICIAL_NPM_REGISTRY ? NPMMIRROR_REGISTRY : OFFICIAL_NPM_REGISTRY
expect(request(other).signal.aborted).toBe(true)
expect(await probe.fastest()).toBe(winner)
expect(fetch).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(50)
const refreshed = probe.fastest()
request(other).resolve(new Response(null, { status: 204 }))
expect(await refreshed).toBe(other)
expect(fetch).toHaveBeenCalledTimes(4)
})
it('performs no request when disabled', async () => {
const { fetch } = transport()
const { probe } = await mount({ registryProbeEnabled: false })
expect(await probe.fastest()).toBeNull()
expect(fetch).not.toHaveBeenCalled()
})
it('ignores a faster HTTP failure and releases both response bodies', async () => {
const { request } = transport()
const { probe } = await mount()
const result = probe.fastest()
const cancel = vi.fn()
request(OFFICIAL_NPM_REGISTRY).resolve(new Response(new ReadableStream({ cancel }), { status: 503 }))
request(NPMMIRROR_REGISTRY).resolve(new Response(null, { status: 204 }))
expect(await result).toBe(NPMMIRROR_REGISTRY)
expect(cancel).toHaveBeenCalledOnce()
})
it('caches unavailable results when both registries fail', async () => {
const { fetch, request } = transport()
const { probe } = await mount()
const result = probe.fastest()
request(OFFICIAL_NPM_REGISTRY).reject(new TypeError('offline'))
request(NPMMIRROR_REGISTRY).resolve(new Response(null, { status: 500 }))
expect(await result).toBeNull()
expect(await probe.fastest()).toBeNull()
expect(fetch).toHaveBeenCalledTimes(2)
})
it.each(['timeout', 'dispose'] as const)('settles both pending probes on %s', async (cause) => {
const { request } = transport()
const { ctx, probe } = await mount({ registryProbeTimeoutMs: 50 })
const result = probe.fastest()
if (cause === 'dispose') await ctx.fiber.dispose()
expect(await result).toBeNull()
for (const registry of [OFFICIAL_NPM_REGISTRY, NPMMIRROR_REGISTRY]) expect(request(registry).signal.aborted).toBe(true)
if (cause === 'dispose') await expect(probe.fastest()).rejects.toThrow()
})
it('chooses by response arrival and awaits response-body cleanup before settling', async () => {
const { request } = transport()
const { probe } = await mount()
const cleanup = Promise.withResolvers<undefined>()
const cancelled = Promise.withResolvers<undefined>()
const result = probe.fastest()
const settled = vi.fn()
void result.then(settled)
request(OFFICIAL_NPM_REGISTRY).resolve(new Response(new ReadableStream({
cancel() { cancelled.resolve(undefined); return cleanup.promise },
})))
request(NPMMIRROR_REGISTRY).resolve(new Response(null, { status: 204 }))
try {
await cancelled.promise
expect(settled).not.toHaveBeenCalled()
cleanup.resolve(undefined)
expect(await result).toBe(OFFICIAL_NPM_REGISTRY)
} finally {
cleanup.resolve(undefined)
await result
}
})
it('keeps a successful response when discarding its body rejects', async () => {
const { request } = transport()
const { probe } = await mount()
const result = probe.fastest()
request(NPMMIRROR_REGISTRY).resolve(new Response(new ReadableStream({
cancel() { return Promise.reject(new Error('body already aborted')) },
})))
expect(await result).toBe(NPMMIRROR_REGISTRY)
})
it.each([
{ registryProbeTimeoutMs: 0 }, { registryProbeTimeoutMs: 2_147_483_648 },
{ registryProbeCacheTtlMs: -1 },
])('rejects invalid probe limits %j', (config) => {
expect(() => PluginRegistryProbe.Config(config)).toThrow()
})
@@ -0,0 +1,56 @@
{
"extends": "../../../tsconfig.base.client.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types",
"tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo"
},
"references": [
{
"path": "../../util/package-manifest"
},
{
"path": "../../../vendor/cordis"
},
{
"path": "../../api/remotes/tsconfig.client.json"
},
{
"path": "../../boot/plugin-manager"
},
{
"path": "../../test-support/client-runtime"
},
{
"path": "../locale/tsconfig.client.json"
},
{
"path": "../store"
},
{
"path": "../ui-layout"
},
{
"path": "../ui-primitives"
},
{
"path": "../ui-renderer"
},
{
"path": "../ui-sidebar"
},
{
"path": "../ui-slots"
},
{
"path": "../../util/crypto"
},
{
"path": "../ui-settings/tsconfig.client.json"
}
],
"include": [
"src/client",
"src/css-modules.d.ts"
]
}
@@ -0,0 +1,25 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types",
"tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo"
},
"files": [
"src/index.ts"
],
"references": [
{
"path": "../../../vendor/cordis"
},
{
"path": "../../../vendor/schemastery"
},
{
"path": "../../util/timeout"
},
{
"path": "../../typert/protocol"
}
]
}
@@ -1,54 +1,11 @@
{
"extends": "../../../tsconfig.base.client.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": [
"src"
],
"files": [],
"references": [
{
"path": "../../util/package-manifest"
"path": "./tsconfig.host.json"
},
{
"path": "../../../vendor/cordis"
},
{
"path": "../../api/remotes/tsconfig.client.json"
},
{
"path": "../../boot/plugin-manager"
},
{
"path": "../../test-support/client-runtime"
},
{
"path": "../locale/tsconfig.client.json"
},
{
"path": "../store"
},
{
"path": "../ui-layout"
},
{
"path": "../ui-primitives"
},
{
"path": "../ui-renderer"
},
{
"path": "../ui-sidebar"
},
{
"path": "../ui-slots"
},
{
"path": "../../util/crypto"
},
{
"path": "../ui-settings/tsconfig.client.json"
"path": "./tsconfig.client.json"
}
]
}
@@ -1,3 +1,3 @@
import { clientBundle } from '../tsdown.client.ts'
export default clientBundle('@deepseek-ai/dsh-client-ui-plugin-manager', ['lib/types/index.js'])
export default clientBundle('@deepseek-ai/dsh-client-ui-plugin-manager', ['lib/types/index.js'], { hostPhase: true })
@@ -27,7 +27,7 @@
"path": "../ui-renderer"
},
{
"path": "../ui-plugin-manager"
"path": "../ui-plugin-manager/tsconfig.client.json"
},
{
"path": "../ui-settings/tsconfig.client.json"
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-settings-models/README.md
README.md: 8bced338559ae1609ce3816f3ea7e760dcce2da7
README.zh.md: ebb321842aa5a68b9cd3aa7355afdb249c71ee6d
README.md: e0accf787aba9d2857887773b4f1a3d703fc1fc1
README.zh.md: 39b443c2293a9da0f7a82bc70d10539a2d153aa8
+1 -1
View File
@@ -45,7 +45,7 @@ Expand **Customized settings → Model options** to edit each model. Both provid
### Adding and deleting providers
**Add model provider** is the one entry to the add card, offered while any editor-backed settings namespace is mounted and enabled while either mode below can proceed. The card opens on a segmented mode switch with a one-line purpose beneath it: **Third-party model provider** carries the dormant-directory provider select over the provider editor — a bare-mounted `llm-pi-ai` offers its whole installed catalog before any route exists — and **Custom model API** carries the create form for a route pi-ai does not ship: a relay, a self-hosted server, or any other OpenAI- or Anthropic-compatible endpoint. A mode is offered only while its namespace is mounted; with one mode the card shows that form alone under the mode's name, and a mode whose namespace has nothing left to adopt or no protocol to declare is disabled with the reason as its hover text. A panel mounts the first time its mode is shown and stays mounted, hidden, while the card is open and its mode stays offered, so switching modes discards neither draft; the switch locks while either panel has a write or an endpoint interrogation in flight, since a switch underneath one would orphan its answer. Each tab controls its panel through ids, and closing either panel forgets the catalog draft's target. The custom form asks for a unique **Provider ID**, an endpoint, a protocol, and at least one uniquely-identified model, because nothing can default those. The protocol picker names each protocol by its product name — OpenAI Chat Completions, OpenAI Responses, Anthropic Messages — while the stored value stays the schema identifier; a protocol the adapter adds before this page names it shows that identifier. The endpoint placeholder follows the selected protocol: OpenAI Chat Completions and Responses show `https://gateway.example/v1`, while Anthropic Messages shows `https://gateway.example` because its SDK appends `/v1/messages`. Changing the protocol preserves any address already entered. The endpoint must be a parseable HTTP or HTTPS URL; localhost, IPv4 and IPv6 literals, and custom ports remain valid. A syntax error blocks both discovery and creation at the field, while a request failure remains a separate provider error. **Fetch available models** asks the `llm/discoverModels` Remote about the endpoint the form shows, so adding a provider is one pass instead of save-then-return; the reply opens a searchable picker rather than being written, and nothing is written until **Add selected**. Each selected candidate copies its id, display name, context window, output-token cap, and disclosed input types into the editable row when disclosed, while an existing row retains its user-tuned values. Search matches model ids and optional display names without clearing hidden selections. **Select all** adds the visible results, while **Deselect all** clears the entire selection so hidden results cannot be adopted accidentally. A row is deletable only when the user layer alone carries it (removal restores the composition base), and its confirmation dialog names the provider.
**Add model provider** is the one entry to the add card, offered while any editor-backed settings namespace is mounted and enabled while either mode below can proceed. The card opens on a segmented mode switch with a one-line purpose beneath it: **Third-party model provider** carries the dormant-directory provider select over the provider editor — a bare-mounted `llm-pi-ai` offers its whole installed catalog before any route exists — and **Custom model API** carries the create form for a route pi-ai does not ship: a relay, a self-hosted server, or any other OpenAI- or Anthropic-compatible endpoint. A mode is offered only while its namespace is mounted; with one mode the card shows that form alone under the mode's name, and a mode whose namespace has nothing left to adopt or no protocol to declare is disabled with the reason as its hover text. A panel mounts the first time its mode is shown and stays mounted, hidden, while the card is open and its mode stays offered, so switching modes discards neither draft; the switch locks while either panel has a write or an endpoint interrogation in flight, since a switch underneath one would orphan its answer. Each tab controls its panel through ids, and closing either panel forgets the catalog draft's target. The custom form asks for a unique **Provider ID**, an endpoint, a protocol, and at least one uniquely-identified model, because nothing can default those. The protocol picker names each protocol by its product name — OpenAI Chat Completions, OpenAI Responses, Anthropic Messages — while the stored value stays the schema identifier; a protocol the adapter adds before this page names it shows that identifier. The endpoint placeholder follows the selected protocol: OpenAI Chat Completions and Responses show `https://gateway.example/v1`, while Anthropic Messages shows `https://gateway.example` because its SDK appends `/v1/messages`. Changing the protocol preserves any address already entered. The endpoint must be a parseable HTTP or HTTPS URL; localhost, IPv4 and IPv6 literals, and custom ports remain valid. A syntax error blocks both discovery and creation at the field, while a request failure remains a separate provider error. **Fetch available models** asks the `llm/discoverModels` Remote about the endpoint the form shows, so adding a provider is one pass instead of save-then-return; the reply opens a searchable picker rather than being written, and nothing is written until **Add selected**. Each candidate displays its name, falling back to its id when no name is supplied. Rows stay on one line; hovering reveals the full text when it is truncated. Selection and configuration retain the original model id. Each selected candidate copies its id, display name, context window, output-token cap, and disclosed input types into the editable row when disclosed, while an existing row retains its user-tuned values. Search matches model ids and optional display names without clearing hidden selections. **Select all** adds the visible results, while **Deselect all** clears the entire selection so hidden results cannot be adopted accidentally. A row is deletable only when the user layer alone carries it (removal restores the composition base), and its confirmation dialog names the provider.
### First-run dialogs
@@ -45,7 +45,7 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会
### 新增与删除提供商
**添加模型提供商**是新增卡片的唯一入口:只要任一带编辑器的设置 namespace 已挂载就会出现,下述两种方式任一可继续时才可点击。卡片打开后顶部是分段式的方式切换,下方一行小字说明所选方式的用途:**第三方模型提供商**承载休眠目录提供商选择框与提供商编辑器——裸挂载的 `llm-pi-ai` 在任何路由存在之前就能提供其完整的已安装 catalog;**自定义模型 API**承载为 pi-ai 不提供的路由(中转站、自部署服务或其他兼容 OpenAI / Anthropic 协议的接口)准备的创建表单。某种方式只在其 namespace 已挂载时提供;只剩一种方式时卡片以该方式为标题直接显示表单;namespace 已无可采用的提供商或没有可声明的协议时,对应方式会被禁用并把原因作为悬停提示。面板在其方式首次显示时挂载,之后在卡片打开且该方式仍被提供期间保持挂载但隐藏,因此切换方式不会丢掉任何一边的草稿;任一面板有写入或端点探测进行中时滑块锁定,因为此时切换会让结果落到看不见的面板上。每个 tab 通过 id 控制其面板,关闭任一面板都会忘记目录草稿的目标。自定义表单会索要唯一的 **Provider ID**、端点、协议与至少一个可唯一识别的模型,因为没有东西能为它们兜底。协议选择框以产品名称显示各协议——OpenAI Chat Completions、OpenAI Responses、Anthropic Messages——存储的值仍是 schema 标识符;适配器新增而本页尚未命名的协议直接显示其标识符。端点占位示例随所选协议变化:OpenAI Chat Completions 与 Responses 显示 `https://gateway.example/v1`,Anthropic Messages 显示 `https://gateway.example`,因为其 SDK 会追加 `/v1/messages`。切换协议会保留已输入的地址。端点必须是可解析的 HTTP 或 HTTPS URL;localhost、IPv4 与 IPv6 字面地址以及自定义端口仍然有效。语法错误会在字段处阻止询问与创建,请求失败则继续作为独立的提供商错误显示。**获取可用模型**通过 `llm/discoverModels` Remote 查询表单显示的端点,因此新增提供商一次即可完成,而非先保存再返回;回复打开的是可搜索选择器而非直接写入,只有点击**添加所选**才会写入。每个选中候选会在提供商公布相应信息时,把 id、显示名、上下文窗口、最大输出 token 数和已公布的输入类型复制进可编辑行;已经存在的行保留用户调整过的值。搜索会匹配模型 id 与可选显示名称,且不会清除隐藏项的勾选状态。**全选**会加入可见结果,而**取消全选**会清空全部勾选,以免意外采用隐藏结果。只有用户层单独携带某行时,该行才可删除(删除会恢复组合基线),其确认对话框会指名该提供商。
**添加模型提供商**是新增卡片的唯一入口:只要任一带编辑器的设置 namespace 已挂载就会出现,下述两种方式任一可继续时才可点击。卡片打开后顶部是分段式的方式切换,下方一行小字说明所选方式的用途:**第三方模型提供商**承载休眠目录提供商选择框与提供商编辑器——裸挂载的 `llm-pi-ai` 在任何路由存在之前就能提供其完整的已安装 catalog;**自定义模型 API**承载为 pi-ai 不提供的路由(中转站、自部署服务或其他兼容 OpenAI / Anthropic 协议的接口)准备的创建表单。某种方式只在其 namespace 已挂载时提供;只剩一种方式时卡片以该方式为标题直接显示表单;namespace 已无可采用的提供商或没有可声明的协议时,对应方式会被禁用并把原因作为悬停提示。面板在其方式首次显示时挂载,之后在卡片打开且该方式仍被提供期间保持挂载但隐藏,因此切换方式不会丢掉任何一边的草稿;任一面板有写入或端点探测进行中时滑块锁定,因为此时切换会让结果落到看不见的面板上。每个 tab 通过 id 控制其面板,关闭任一面板都会忘记目录草稿的目标。自定义表单会索要唯一的 **Provider ID**、端点、协议与至少一个可唯一识别的模型,因为没有东西能为它们兜底。协议选择框以产品名称显示各协议——OpenAI Chat Completions、OpenAI Responses、Anthropic Messages——存储的值仍是 schema 标识符;适配器新增而本页尚未命名的协议直接显示其标识符。端点占位示例随所选协议变化:OpenAI Chat Completions 与 Responses 显示 `https://gateway.example/v1`,Anthropic Messages 显示 `https://gateway.example`,因为其 SDK 会追加 `/v1/messages`。切换协议会保留已输入的地址。端点必须是可解析的 HTTP 或 HTTPS URL;localhost、IPv4 与 IPv6 字面地址以及自定义端口仍然有效。语法错误会在字段处阻止询问与创建,请求失败则继续作为独立的提供商错误显示。**获取可用模型**通过 `llm/discoverModels` Remote 查询表单显示的端点,因此新增提供商一次即可完成,而非先保存再返回;回复打开的是可搜索选择器而非直接写入,只有点击**添加所选**才会写入。候选项显示模型名称,未提供名称时回退到 id。每行保持单行,文字截断时可悬停查看完整内容。勾选与配置仍使用原始模型 id。每个选中候选会在提供商公布相应信息时,把 id、显示名、上下文窗口、最大输出 token 数和已公布的输入类型复制进可编辑行;已经存在的行保留用户调整过的值。搜索会匹配模型 id 与可选显示名称,且不会清除隐藏项的勾选状态。**全选**会加入可见结果,而**取消全选**会清空全部勾选,以免意外采用隐藏结果。只有用户层单独携带某行时,该行才可删除(删除会恢复组合基线),其确认对话框会指名该提供商。
### 首次运行弹窗
@@ -447,10 +447,9 @@ export function ModelListEditor(props: ModelListEditorProps): ReactNode {
checked={picked.has(candidate.id)}
onChange={() => { toggle(candidate.id) }}
/>
{/* The id alone: it is the string adoption writes, and the
capacities the endpoint reported are adopted with it and
editable in the row that appears. */}
<span className={styles['candidateId']}>{candidate.id}</span>
<span className={styles['candidateName']} title={candidate.name ?? candidate.id}>
{candidate.name ?? candidate.id}
</span>
</label>
</li>
))}
@@ -705,11 +705,13 @@ select.input {
cursor: pointer;
}
.candidateId {
.candidateName {
flex: 1 1 auto;
font-family: var(--ds-font-family-code);
min-width: 0;
font-size: 13px;
overflow-wrap: anywhere;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.candidateEmpty {
@@ -609,6 +609,8 @@ describe('endpoint interrogation', () => {
fireEvent.click(screen.getByText(en.fetchModels))
await screen.findByText(en.fetchTitle)
expect(screen.getByRole<HTMLInputElement>('checkbox', { name: 'Fresh' }).checked).toBe(true)
expect(screen.queryByRole('checkbox', { name: 'fresh' })).toBeNull()
// The already-configured row starts unchecked; the new one starts checked.
const boxes = [...document.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')]
expect(boxes.map(box => box.checked)).toEqual([false, true])
@@ -748,6 +750,8 @@ describe('endpoint interrogation', () => {
fireEvent.click(screen.getByText(en.fetchModels))
const dialog = await screen.findByRole('dialog')
const search = screen.getByLabelText<HTMLInputElement>(en.fetchSearch)
expect(dialog.textContent).toContain('Beta Display')
expect(dialog.textContent).not.toContain('opaque-id')
expect([...dialog.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')]
.map(box => box.checked)).toEqual([true, true, true])
@@ -755,9 +759,12 @@ describe('endpoint interrogation', () => {
expect(dialog.textContent).toContain('alpha')
expect(dialog.textContent).not.toContain('opaque-id')
// The display name is searchable even though adoption and the row use id.
fireEvent.change(search, { target: { value: 'beta' } })
expect(dialog.textContent).toContain('opaque-id')
expect(dialog.textContent).toContain('Beta Display')
expect(dialog.textContent).not.toContain('alpha')
fireEvent.change(search, { target: { value: 'opaque' } })
expect(dialog.textContent).toContain('Beta Display')
expect(dialog.textContent).not.toContain('alpha')
fireEvent.click(within_(dialog, en.fetchDeselectAll))
@@ -27,7 +27,7 @@
"path": "../ui-renderer"
},
{
"path": "../ui-plugin-manager"
"path": "../ui-plugin-manager/tsconfig.client.json"
},
{
"path": "../ui-settings/tsconfig.client.json"
@@ -27,7 +27,7 @@
"path": "../ui-renderer"
},
{
"path": "../ui-plugin-manager"
"path": "../ui-plugin-manager/tsconfig.client.json"
},
{
"path": "../ui-settings/tsconfig.client.json"
@@ -27,7 +27,7 @@
"path": "../ui-renderer"
},
{
"path": "../ui-plugin-manager"
"path": "../ui-plugin-manager/tsconfig.client.json"
},
{
"path": "../ui-settings/tsconfig.client.json"
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more