chore: adapt sidebar to DSH 0.2.1-alpha.5

This commit is contained in:
Menghuan1918 committed 2026-10-17 02:12:44 +08:00
1 parent 693b4850e3
commit 4ebd3e9bdd
73 files changed
+1512 -1593

No files matched your search

+5 -29
View File
@@ -171,38 +171,14 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
# Pin the DSH CLI the lane mounts into; the profile's bundle stack
# (dsh-base / dsh-web-app) resolves from this installation. Keep in
# step with the plugin's @deepseek-ai/* peer range when bumping.
# Write an EXACT version, never a dist-tag: when 0.1.7-rc.1 shipped, the
# npm `alpha` tag still meant 0.1.7-alpha.2, rc.1 went out on `next`, and
# `latest` was still the 0.1.5 line — `@alpha` would mount a host this
# plugin no longer supports. The 0.2.0 line repeats the pattern: its
# first candidate is `next` while `latest` is still 0.1.7-rc.2.
# The lanes speak the slash-only RPC dialect
# (tests/e2e/host-protocol.ts).
#
# The larger heap is the fix for one of the two ways this step used to
# die (runs 34490912649 and 34363627184 on the alpha line): the pinned
# version's TRANSITIVES are declared as floating `^` ranges, so while
# upstream publishes a prerelease in stages (0.1.5-rc.2 went out
# 14:43-14:57 on 2026-09-10) npm resolved a mixed peer graph —
# 3062 ERESOLVE lines, then "Ineffective mark-compacts near heap limit"
# (exit 134). The other failure mode was a hard ETARGET on a sibling
# package that appeared minutes later; pinning a version that is fully
# published (not mid-flight) is the fix for that one.
#
# Peer resolution stays ON: `--legacy-peer-deps` was tried in the first
# cut of this fix and made the install broken rather than robust — it
# skips exactly the peers a global install has to supply, and
# @deepseek-ai/dsh-app-boot requires `@deepseek-ai/cordis-plugin-group`
# (a peer, not a dependency) at boot, so the CLI died with
# ERR_MODULE_NOT_FOUND before the smoke could even start. Verified
# locally that the plain install resolves it.
# Pin the exact 0.2.1-alpha.5 host CLI; never use a dist-tag.
# Keep peer resolution ON: do not add --legacy-peer-deps; it skips boot peers.
# The lanes speak the slash-only RPC dialect (tests/e2e/host-protocol.ts).
# NODE_OPTIONS below preserves the heap budget needed for prerelease peer resolution.
- name: Install dsh CLI (pinned)
env:
NODE_OPTIONS: --max-old-space-size=4096
run: npm install -g @deepseek-ai/dsh@0.2.0-rc.2
run: npm install -g @deepseek-ai/dsh@0.2.1-alpha.5
# lib/ is gitignored; the tarball is produced from this build.
- name: Build and pack the npm tarball
+6 -5
View File
@@ -31,7 +31,7 @@
本地:`pnpm build && pnpm pack && pnpm exec playwright install chromium && pnpm test:mount`。
- **钉版写精确版本号,绝不写 dist-tag**(`alpha` / `latest` / `next` 的指向与候选版经常不一致);默认与 CI 同为 `@deepseek-ai/dsh@0.2.0-rc.2`。
- **钉版写精确版本号,绝不写 dist-tag**(`alpha` / `latest` / `next` 的指向与候选版经常不一致);默认与 CI 同为 `@deepseek-ai/dsh@0.2.1-alpha.5`。
- 该步骤需要 `NODE_OPTIONS=--max-old-space-size=4096`(浮动的传递依赖会组出混合 peer 图 → ERESOLVE 后 OOM);**不要加 `--legacy-peer-deps`**(会跳掉 boot 必需的 peer,CLI 直接 `ERR_MODULE_NOT_FOUND`)。
- 本机 npm registry 是 npmmirror、对新预发布滞后:装不到时 `pnpm install --registry https://registry.npmjs.org`。
- Windows lane 跑 `pnpm test:windows`(`--maxWorkers=1`),`vitest.config.ts` 的 `testTimeout: 30_000` 与它配套。e2e spec 命名 `*.e2e.ts` + vitest `exclude` 双保险;**改 `exclude` 必须保留默认排除项**。
@@ -40,11 +40,12 @@
## 3. DSH 版本适配
- **当前基线 DSH 0.2.0-rc.2(v0.25.0 起)**。14 条 `@deepseek-ai/dsh-*` peer 一律写 `^<基线>` 浮动 caret 范围、**绝不钉精确版本**(只有 devDependencies 精确钉);精确版本、或没有预发布子句的范围会被宿主启动预检整行静默禁用。`tests/market-manifest.spec.ts` 钉住这条形状。
- **caret 跨不过 minor**:`^0.1.7-rc.1` 对 `0.2.0-rc.1` 判定为 false → 整行 `disabled`、插件静默不加载。**抬基线必须同批抬 peer 下限。**
- 支持线(用户侧):0.2.0-rc.1 及更早(含 0.1.7 线)固定 v0.24.1;0.1.7 线的最后支持版是 **v0.22.1**(v0.23.0 从未发布到 npm)。按本仓库先例**不写运行时兼容层**。
- **抬基线动作清单**:① `pnpm peers check`,把失配的传递 peer 提升进 devDependencies;② 扫宿主包产物的**裸 import 差集**(`pnpm peers check` 看不到这类失败,0.1.7 线是 `zustand` / `immer`);③ 对消费的宿主包做类型面 diff(重点 `ui-primitives` / `dsh-session` / `sidebar-right`),确认导出只增不减;④ 复查会话格式版本、`SUBAGENT_DESCRIPTOR_VERSION`、web profile 的 inject 列表;⑤ 同批同步 CI 钉版、`scripts/e2e-common.sh`、**`scripts/install.sh`(随包发布、会直接给用户 npx 命令)** 与 README / 指南的版本行。
- **当前基线 DSH 0.2.1-alpha.5(v0.28.0-alpha.0 起)**。13 条 `@deepseek-ai/dsh-*` peer 一律写 `^<基线>` 浮动 caret 范围、**绝不钉精确版本**(只有 devDependencies 精确钉);本包不声明 `package.json#engines.dsh`,因此走 peer 兼容性检查;alpha.5 对声明了该字段的包优先且仅按它判定,不读 peer。`dsh.plugin.json#engines.dsh` 不参与这一规则。`tests/market-manifest.spec.ts` 钉住这条形状。
- **0.x caret 不跨 minor,但可跨 patch**:`^0.1.7-rc.1` 对 `0.2.0-rc.1` 判定为 false → 整行 `disabled`、插件静默不加载。**抬基线必须同批抬 peer 下限。**
- 支持线(用户侧):0.2.0-rc.2 用户固定 npm 已发布的 **v0.26.1**(v0.27.0 尚未发布);0.2.0-rc.1 用户固定 v0.24.1;0.1.7 线的最后支持版是 **v0.22.1**(v0.23.0 从未发布到 npm)。按本仓库先例**不写运行时兼容层**。
- **抬基线动作清单**:① `pnpm peers check`,把失配的传递 peer 提升进 devDependencies;② 扫宿主包产物的**裸 import 差集**(`pnpm peers check` 看不到这类失败,0.1.7 线是 `zustand` / `immer`);③ 对消费的宿主包做类型面 diff(重点 `ui-primitives` / `dsh-session` / `sidebar-right`),确认导出只增不减;④ 复查会话格式版本、`SUBAGENT_DESCRIPTOR_VERSION`、web profile 的 inject 列表;⑤ 同批同步 CI 钉版、`scripts/e2e-common.sh`、**`scripts/install.sh` / `scripts/install.ps1`(随包发布、会直接给用户 npx 命令)** 与 README / 指南的版本行。
- **用户 profile 自己的 `overrides: '@deepseek-ai/dsh-*'` 要同批抬**,否则旧包遮蔽 bundle → 预检禁用 `config-editor` → `settings` 行永久 `pending`;先看宿主日志的 `disabling profile plugin row` 与 `pending (waiting for service: …)`。
- **alpha.5 删除契约**:不再依赖 `@deepseek-ai/dsh-invariants`、`ctx.invariants` 或上游 `/invariant` 子路径,也不发布本插件的 invariant companion;HTTP/WS 准入统一调用 `ctx.connection.requestRejection(req)`,仅 `undefined` 放行,不恢复 `webRuntime` / 自建信任例外。
- 动设置面 / sidechat / 原生 tab 之前,先读 [docs/host-contracts.md](docs/host-contracts.md)(原 §3.4 的 1–12 条按原编号都在那里)。
---
+9
View File
@@ -2,6 +2,15 @@
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
### v0.28.0-alpha.0(本地验证完成,未发布)
- **支持线前移到 DSH 0.2.1-alpha.5+**:13 条 DSH peer 使用 `^0.2.1-alpha.5`,开发依赖与 CI / 安装脚本钉精确基线。0.2.0-rc.2 用户请固定 npm 已发布的 **v0.26.1**(v0.27.0 尚未发布);本 alpha 使用 `dsh-better-sidebar@0.28.0-alpha.0`,不是 `latest`。
- **宿主 Connection 准入**:HTTP/WS 路由统一调用 `ctx.connection.requestRejection(req)`,不再依赖已删除的 `webRuntime` 或插件自建信任例外。
- **移除 runtime invariants 接入**:上游删除 `@deepseek-ai/dsh-invariants` 与 `/invariant` 子路径,本插件同步移除 companion、类型与发布入口;压缩种子测试继续使用公开的 surface fold 和 seed validator。
- **当前执行目录接入**:文件 / Git / 终端与新建 sidechat 跟随会话 `working_directory`;live 读 workingDirectory,cold 用 sessionQuery all projections 并释放 lease,linked worktree 保持 base-keyed,新 sidechat seed 尾部盖章当前 cwd。
- **宿主伴随 API / 依赖**:补齐 `TerminalBlockLabels.commandLine(line)` 与 21 份词典;同步 Cordis `4.0.5`、schemastery `~3.18.5-alpha.2`、group `1.0.5-alpha.2` 与 include `1.0.10`,不直接钉 loader 或设置 override。alpha.5 优先用 package 的 `engines.dsh` 判断兼容性,本插件不新增该字段,继续用 13 条 DSH peers。
- **本地适配验证完成(未发布)**:真实 alpha.5 挂载 **13/13 通过**(2.6 min),aggregate 通过且无重复路由;typecheck、lint、build、consumer types、pack 新鲜通过,浏览器 consumer 不泄漏 Node 类型。默认 CI 入口与单 worker 全量重跑均为 **219 文件 / 2634 用例通过,17 跳过**;排查期间的并发 watch / GC 失败已不再构成阻塞,详见 [适配记录](docs/plans/2026-10-16-dsh-0.2.1-alpha.5-adaptation.md)。rg 引擎检查通过,fd 缺失与 Windows 原生验证未执行;peer 仅剩可选 better-locale 的 4 条旧 DSH 警告。
### v0.27.0
- 🌿 **Git 页面重做:VS Code Source Control 结构 + 只读提交图(同一页签)**([#941](https://github.com/omdsh-dev/DSH-better-sidebar/issues/941),贡献者 PR [#944](https://github.com/omdsh-dev/DSH-better-sidebar/pull/944) @hairyf + [#969](https://github.com/omdsh-dev/DSH-better-sidebar/pull/969) @vlln):「文件变动 > Git」的内容区改为 Source Control 结构——可折叠的 Changes(多行 Message + 仅填草稿的 Generate、Merge / Staged / Changes 三组各自独立折叠与计数、整行 hover)与 Graph 区、常驻底栏(可点击分支 + `*`/`+`/`!` 标记、upstream 的 `↓`/`↑` 与安全 Pull-then-Push);Push/Pull 与 worktree·子仓库选择移入 More Actions;提交只消费已暂存项,冲突 / 空消息 / 无暂存时禁止,草稿按会话·仓库·worktree 隔离。Graph 区由 **#969 的有界只读引擎**渲染(专用 `git.graph` 路由:子先于父的拓扑序、分支筛选、游标失效显式返回 `graph-stale`、每页 200 / 偏移 10000 / 分支 1000 / 进程 10 s / 输出 8 MiB 上限,超限报错不静默截断;泳道连线与引用徽章用主题状态色,hover 卡片与提交详情卡;**纯读取**——不 checkout / fetch / 改任何 ref)。底部预览面板改为固定三签 `提交详情 / 内容 / 差异`(有内容才有差异,读操作落在内容签)。**设计取舍与实施偏差见 [docs/plans/2026-10-16-git-page-vscode-scm-merge.md](docs/plans/2026-10-16-git-page-vscode-scm-merge.md)**(贡献者 PR [#939](https://github.com/omdsh-dev/DSH-better-sidebar/pull/939) @hairyf 的官方下划线 Tabs 镜片切换保留;第三个「提交图」镜头刻意未上线)。
+9
View File
@@ -4,6 +4,15 @@
>
> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current.
### v0.28.0-alpha.0 (locally validated; unpublished)
- **Support moves to DSH 0.2.1-alpha.5+**: 13 DSH peers use `^0.2.1-alpha.5`; development dependencies, CI and installers pin the exact baseline. DSH 0.2.0-rc.2 users should pin npm-published **v0.26.1** (v0.27.0 has not been published). Install this alpha explicitly as `dsh-better-sidebar@0.28.0-alpha.0`, not `latest`.
- **Native Connection admission**: HTTP/WS routes delegate to `ctx.connection.requestRejection(req)`, without the removed `webRuntime` service or plugin-owned trust exceptions.
- **Runtime invariants integration removed**: upstream removed `@deepseek-ai/dsh-invariants` and `/invariant` subpaths; the plugin removes its companion, types and package entry. Compaction seed coverage retains the public surface fold and seed validator.
- **Current working directory**: files, Git, terminals and new side chats follow session `working_directory`; live reads use workingDirectory, cold reads use sessionQuery all projections with lease disposal. Linked worktrees stay base-keyed; each new sidechat seed ends with a current-cwd stamp.
- **Companion API / dependencies**: supply `TerminalBlockLabels.commandLine(line)` in both consumers and synchronize all 21 dictionaries; update Cordis `4.0.5`, schemastery `~3.18.5-alpha.2`, group `1.0.5-alpha.2` and include `1.0.10`, without a direct loader pin or overrides. Alpha.5 prefers package `engines.dsh` for compatibility; this plugin leaves it absent and retains its 13 DSH peers.
- **Locally validated (unpublished)**: real alpha.5 mount **13/13 passed** (2.6 min), aggregate passed without duplicate routes; fresh typecheck, lint, build, consumer types and pack passed, without leaking Node types into the browser consumer. Both the default CI entry and single-worker full runs passed **219 files / 2634 tests, with 17 skipped**; earlier watch / GC failures under concurrency are resolved investigation history, retained in the [adaptation record](docs/plans/2026-10-16-dsh-0.2.1-alpha.5-adaptation.md). The rg engine check passed; fd was unavailable and native Windows verification was not run. Only four optional better-locale legacy DSH peer warnings remain.
### v0.27.0
- **One Git page with Source Control and a read-only commit graph**: collapsible Changes and Graph sections, independent Merge / Staged / Changes groups, commit-message drafts, and a persistent branch/sync footer. The bounded graph reader supports branch filtering, lane connections, reference badges, hover details and commit inspection without checking out branches or changing refs. The shared preview keeps three tabs: Commit details / Content / Diff. Based on [#944](https://github.com/omdsh-dev/DSH-better-sidebar/pull/944) by @hairyf and [#969](https://github.com/omdsh-dev/DSH-better-sidebar/pull/969) by @vlln; the official lens tabs from [#939](https://github.com/omdsh-dev/DSH-better-sidebar/pull/939) by @hairyf remain, with no third graph lens.
+15 -7
View File
@@ -7,7 +7,7 @@
<a href="https://github.com/omdsh-dev/DSH-better-sidebar/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/omdsh-dev/DSH-better-sidebar/actions/workflows/ci.yml/badge.svg" /></a>
<a href="https://github.com/omdsh-dev/DSH-better-sidebar/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/omdsh-dev/DSH-better-sidebar" /></a>
<a href="https://opensource.org/licenses/MIT"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" /></a>
<a href="https://www.npmjs.com/package/@deepseek-ai/dsh?activeTab=versions"><img alt="Supported DSH versions: 0.2.0-rc.2+" src="https://img.shields.io/badge/DSH-0.2.0--rc.2%2B-4d6bfe" /></a>
<a href="https://www.npmjs.com/package/@deepseek-ai/dsh?activeTab=versions"><img alt="Supported DSH versions: 0.2.1-alpha.5+" src="https://img.shields.io/badge/DSH-0.2.1--alpha.5%2B-4d6bfe" /></a>
</div>
<div align="center">
@@ -35,17 +35,19 @@ Switch to **Git Graph** at the top of the Git panel for commit nodes, forks and
## 🚀 Installation
```sh
dsh plugin --profile web add dsh-better-sidebar@latest
dsh plugin --profile web add dsh-better-sidebar@0.28.0-alpha.0
```
Then **hard-refresh the browser** (Cmd/Ctrl+Shift+R). Requires DSH **0.2.0-rc.2+**.
Then **hard-refresh the browser** (Cmd/Ctrl+Shift+R). Requires DSH **0.2.1-alpha.5+**.
<details>
<summary><b>Pick the plugin version for your DSH version</b></summary>
| Your DSH version | Install command |
| --- | --- |
| **0.2.0-rc.2+** (incl. later stable) | `dsh plugin --profile web add dsh-better-sidebar@latest` |
| **0.2.1-alpha.5+** (this alpha support line) | `dsh plugin --profile web add dsh-better-sidebar@0.28.0-alpha.0` |
| **0.2.0-rc.2** | `dsh plugin --profile web add dsh-better-sidebar@0.26.1` |
| **0.2.0-rc.1** | `dsh plugin --profile web add dsh-better-sidebar@0.24.1` |
| **0.1.7-rc.1 ~ 0.1.7 stable** | `dsh plugin --profile web add dsh-better-sidebar@0.22.1` |
| 0.1.7-alpha.x | No compatible release — upgrade DSH to rc.1 first |
| 0.1.6 and earlier (incl. the 0.1.5 line) | `dsh plugin --profile web add dsh-better-sidebar@0.19.1` |
@@ -61,12 +63,12 @@ Always pin **exact versions** for older releases (`latest` moves forward with ea
```text
Install the dsh-better-sidebar plugin (a sidebar workbench for DSH):
1. Run dsh plugin --profile web add dsh-better-sidebar@latest (latest = current stable)
1. Run dsh plugin --profile web add dsh-better-sidebar@0.28.0-alpha.0 (this alpha, not latest)
2. Remind me to hard-refresh the browser (Cmd/Ctrl+Shift+R) afterwards
If something fails, check the FAQ table in https://github.com/omdsh-dev/DSH-better-sidebar README first.
```
**One-line script** — clone this repo and run `bash scripts/install.sh` (macOS / Linux / Windows Git Bash; `install.ps1` for native Windows). It handles installation + bundle registration.
**One-line script** — clone this repo and run `bash scripts/install.sh 0.28.0-alpha.0` (macOS / Linux / Windows Git Bash; `./scripts/install.ps1 -Version 0.28.0-alpha.0` for native Windows). It handles installation + bundle registration.
**Updating**: just re-run the install command, then hard-refresh the browser.
@@ -83,12 +85,18 @@ If something fails, check the FAQ table in https://github.com/omdsh-dev/DSH-bett
| **Two sidebars** on the page | Double mounting. Remove the legacy manual mount line (`- insert: ... better-sidebar ...`) from `~/.dsh/profiles/web/cordis.patch.yml`; aggregate packages mounting this package under a different id are auto-yielded, no action needed. |
| Settings values gone after upgrade | Since DSH 0.1.7, preferences live on this plugin's mount row in the profile (default entry id `better-sidebar`). The plugin migrates your old `settings.yaml` values once on first start and never overwrites newer values. |
| Terminal unavailable | Terminals are provided by **DSH itself** (this plugin ships no PTY) — see DSH docs; "host provides no terminal capability" in the bottom terminal means this deployment has no terminal controller mounted. |
| `dsh: command not found` | Install DSH first; or use `npx -y --package @deepseek-ai/dsh dsh plugin --profile web add dsh-better-sidebar@latest`. |
| `dsh: command not found` | Install DSH first; or use `npx -y --package @deepseek-ai/dsh@0.2.1-alpha.5 dsh plugin --profile web add dsh-better-sidebar@0.28.0-alpha.0`. |
</details>
## 🆕 Recent Updates
**v0.28.0-alpha.0 (locally validated; unpublished)**
- Adapt to DSH **0.2.1-alpha.5+**: use native Connection admission for HTTP/WS and remove the retired invariant companion and dependency
- Files, Git, terminals and newly created side chats follow the session’s current working directory
- **DSH 0.2.0-rc.2 users stay on npm-published v0.26.1**; v0.27.0 has not been published. Use the explicit alpha version above, not `latest`
**v0.27.0** - full release history at [Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases) · [CHANGELOG](./CHANGELOG_EN.md)
- **Git page rebuilt**: Source Control groups, a read-only commit graph with branch filtering, and a shared Commit details / Content / Diff pane
+15 -7
View File
@@ -7,7 +7,7 @@
<a href="https://github.com/omdsh-dev/DSH-better-sidebar/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/omdsh-dev/DSH-better-sidebar/actions/workflows/ci.yml/badge.svg" /></a>
<a href="https://github.com/omdsh-dev/DSH-better-sidebar/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/omdsh-dev/DSH-better-sidebar" /></a>
<a href="https://opensource.org/licenses/MIT"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" /></a>
<a href="https://www.npmjs.com/package/@deepseek-ai/dsh?activeTab=versions"><img alt="支持的 DSH 版本:0.2.0-rc.2+" src="https://img.shields.io/badge/DSH-0.2.0--rc.2%2B-4d6bfe" /></a>
<a href="https://www.npmjs.com/package/@deepseek-ai/dsh?activeTab=versions"><img alt="支持的 DSH 版本:0.2.1-alpha.5+" src="https://img.shields.io/badge/DSH-0.2.1--alpha.5%2B-4d6bfe" /></a>
</div>
<div align="center">
@@ -35,17 +35,19 @@
## 🚀 安装
```sh
dsh plugin --profile web add dsh-better-sidebar@latest
dsh plugin --profile web add dsh-better-sidebar@0.28.0-alpha.0
```
装完**硬刷新浏览器**(Cmd/Ctrl+Shift+R)即可。要求 DSH **0.2.0-rc.2+**。
装完**硬刷新浏览器**(Cmd/Ctrl+Shift+R)即可。要求 DSH **0.2.1-alpha.5+**。
<details>
<summary><b>按 DSH 版本选插件版本</b></summary>
| 你的 DSH 版本 | 安装命令 |
| --- | --- |
| **0.2.0-rc.2+**(含之后的正式版) | `dsh plugin --profile web add dsh-better-sidebar@latest` |
| **0.2.1-alpha.5+**(本 alpha 支持线) | `dsh plugin --profile web add dsh-better-sidebar@0.28.0-alpha.0` |
| **0.2.0-rc.2** | `dsh plugin --profile web add dsh-better-sidebar@0.26.1` |
| **0.2.0-rc.1** | `dsh plugin --profile web add dsh-better-sidebar@0.24.1` |
| **0.1.7-rc.1 ~ 0.1.7 正式版** | `dsh plugin --profile web add dsh-better-sidebar@0.22.1` |
| 0.1.7-alpha.x | 没有可装版本——先升级 DSH 到 rc.1 |
| 0.1.6 及更早(含 0.1.5 线) | `dsh plugin --profile web add dsh-better-sidebar@0.19.1` |
@@ -61,12 +63,12 @@ dsh plugin --profile web add dsh-better-sidebar@latest
```text
帮我安装 dsh-better-sidebar 插件(DSH 侧边栏工作台),步骤:
1. 执行 dsh plugin --profile web add dsh-better-sidebar@latest(latest 即当前正式版)
1. 执行 dsh plugin --profile web add dsh-better-sidebar@0.28.0-alpha.0(本次 alpha,非 latest)
2. 完成后提醒我硬刷新浏览器(Cmd/Ctrl+Shift+R)
遇到报错先查 https://github.com/omdsh-dev/DSH-better-sidebar README 的常见问题表。
```
**一键脚本**——克隆本仓库后执行 `bash scripts/install.sh`(macOS / Linux / Windows Git Bash;Windows 原生用 `install.ps1`),自动完成安装 + bundle 注册。
**一键脚本**——克隆本仓库后执行 `bash scripts/install.sh 0.28.0-alpha.0`(macOS / Linux / Windows Git Bash;Windows 原生用 `./scripts/install.ps1 -Version 0.28.0-alpha.0`),自动完成安装 + bundle 注册。
**更新**:重跑一次安装命令即可,然后硬刷新浏览器。
@@ -83,12 +85,18 @@ dsh plugin --profile web add dsh-better-sidebar@latest
| 页面出现**两个侧边栏** | 双挂载。删掉 `~/.dsh/profiles/web/cordis.patch.yml` 里旧的手动挂载行(`- insert: ... better-sidebar ...`);聚合包以不同 id 挂载本包时会自动退让,无需处理。 |
| 升级后设置页的值去哪了 | DSH 0.1.7 起偏好写在 profile 里本插件的挂载行上(默认 entry id `better-sidebar`),插件首次启动会把旧 `settings.yaml` 里的配置一次性回迁,不会覆盖新设的值。 |
| 终端无法使用 | 终端由 **DSH 自身**提供(本插件不自带 PTY),请查 DSH 侧文档;底部终端显示「宿主未提供终端能力」= 这个部署没挂终端控制器。 |
| 提示 `dsh: command not found` | 先安装 DSH;或用 `npx -y --package @deepseek-ai/dsh dsh plugin --profile web add dsh-better-sidebar@latest`。 |
| 提示 `dsh: command not found` | 先安装 DSH;或用 `npx -y --package @deepseek-ai/dsh@0.2.1-alpha.5 dsh plugin --profile web add dsh-better-sidebar@0.28.0-alpha.0`。 |
</details>
## 🆕 最近更新
**v0.28.0-alpha.0(本地适配验证完成,未发布)**
- 适配 DSH **0.2.1-alpha.5+**:HTTP/WS 改用宿主 Connection admission,移除已废弃的 invariant companion 与依赖
- 会话执行目录变化时,文件 / Git / 终端与新建侧边对话跟随当前目录
- **0.2.0-rc.2 用户留在 npm 已发布的 v0.26.1**;v0.27.0 尚未发布,alpha 请用上方精确版本命令,不要用 `latest`
**v0.27.0** - 完整发布历史见 [Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases) · [CHANGELOG](./CHANGELOG.md)
- **Git 页面重做**:Source Control 分组、支持分支筛选的只读提交图,以及共用的「提交详情 / 内容 / 差异」预览区
+4 -1
View File
@@ -2,8 +2,11 @@
> 面向 **消费插件开发者**:如何让你的插件向 better-sidebar 注册新的侧边栏页面(tab)和文件类型预览器。
>
> 适用版本:**v0.4.0+**(`ctx.betterSidebar` 服务);声明式设置 **v0.4.1+**;text/number 设置行 **v0.11.0+**;badge/生命周期/定向打开/插件设置/版本探测 **v0.12.0+**;select 设置行(`settingSelect`)与外链认领(`urlTarget`)**v0.13.0+**;统一 `@deepseek-ai/cordis` 类型基底 **v0.15.2+**;路由前缀安全解析(`hostRouteUrl`)**v0.25.0+**。当前版本 **v0.27.0**(peer 下限 `^0.2.0-rc.2`,仅支持 DSH **0.2.0-rc.2+**;0.2.0-rc.1 请用 v0.24.1,0.1.7 线请用 v0.22.1——caret 范围跨 minor 不成立,`^0.1.7-rc.1` 会被 0.2.0 宿主的启动预检静默禁用)。**v0.19.0 移除了自绘右侧面板与自由窗口**(见 §0、§11);**自 v0.20.0 开发线起**(**注意:0.20.0 从未发布到 npm,这些变更全部落在 v0.21.1**)插件**移除了自带的终端**(宿主 0.1.6 的 `ui-sidebar-terminal` 取代,见 §4.4)、**移除了终端固定(pin)**,并在 0.1.7 上**把浏览器视图与只读文件预览整体让给宿主**(`ui-sidebar-browser` / `ui-sidebar-documentpreview`,见 §4.4、§5.4)、**收敛了外链接管**(见 §4.1)、**重写了设置接入面**(`SettingsForms`,见 §8.2)、**给文件树加了实时刷新**(见 §10);同时**删除了轮尾产物行接管**(DSH 0.1.6 把 `conversation.chat.turnTail` 从 chain 改成只能追加的 list,替换语义不复存在)。
> 适用版本:**v0.4.0+**(`ctx.betterSidebar` 服务);声明式设置 **v0.4.1+**;text/number 设置行 **v0.11.0+**;badge/生命周期/定向打开/插件设置/版本探测 **v0.12.0+**;select 设置行(`settingSelect`)与外链认领(`urlTarget`)**v0.13.0+**;统一 `@deepseek-ai/cordis` 类型基底 **v0.15.2+**;路由前缀安全解析(`hostRouteUrl`)**v0.25.0+**。当前版本 **v0.28.0-alpha.0**(13 条 DSH peer 下限 `^0.2.1-alpha.5`,仅支持 DSH **0.2.1-alpha.5+**;0.2.0-rc.2 请用 npm 已发布的 v0.26.1(v0.27.0 尚未发布),0.2.0-rc.1 请用 v0.24.1,0.1.7 线请用 v0.22.1——caret 范围跨 minor 不成立,`^0.1.7-rc.1` 会被 0.2.0 宿主的启动预检静默禁用)。**v0.19.0 移除了自绘右侧面板与自由窗口**(见 §0、§11);**自 v0.20.0 开发线起**(**注意:0.20.0 从未发布到 npm,这些变更全部落在 v0.21.1**)插件**移除了自带的终端**(宿主 0.1.6 的 `ui-sidebar-terminal` 取代,见 §4.4)、**移除了终端固定(pin)**,并在 0.1.7 上**把浏览器视图与只读文件预览整体让给宿主**(`ui-sidebar-browser` / `ui-sidebar-documentpreview`,见 §4.4、§5.4)、**收敛了外链接管**(见 §4.1)、**重写了设置接入面**(`SettingsForms`,见 §8.2)、**给文件树加了实时刷新**(见 §10);同时**删除了轮尾产物行接管**(DSH 0.1.6 把 `conversation.chat.turnTail` 从 chain 改成只能追加的 list,替换语义不复存在)。
> 权威代码:`src/client/service.ts`(服务实现)、`src/client/builtins/`(内置 6 tab + 3 viewer 参考实现)、`lib/types/client/service.d.ts`(类型声明)。
> alpha.5 已删除 `@deepseek-ai/dsh-invariants` 与上游 `/invariant` 子路径;本插件同步移除 invariant companion,不提供替代注册服务。HTTP/WS 准入遵循宿主 Connection(见 §6.2)。
> 当前目录语义:文件 / Git / 终端与新建 sidechat 跟随会话 `working_directory`。live 读 `ctx.workingDirectory.get(session)`;cold 通过 `ctx.sessionQuery.observeSession` 的 all projections 读取并在 `finally` 释放 lease。linked worktree 仍按 base 目录记账;新 sidechat seed 尾部盖章当前 cwd,防止继承历史目录覆盖它。
> alpha.5 的 `TerminalBlockLabels` 要求 `commandLine(line)`;两个渲染消费者与全部 21 份词典同步。宿主兼容性优先读 `package.json#engines.dsh`,缺席才读 DSH peers;本插件没有该字段,仍用 13 条 peers(第三方 `dsh.plugin.json` 不参与)。
> 仓库开发规则(硬约束 / CI / 发版)见 [AGENTS.md](../AGENTS.md)。
---
+9 -4
View File
@@ -2,7 +2,9 @@
> 从 `AGENTS.md` §3 移出的深度参考(原 §3.4 第 1–12 条与 0.1.5–0.1.7 历史线中仍然生效的部分)。
> **编号保持不变**:代码、测试与文档里写的「AGENTS.md §3.4 第 N 条」就是本文第 N 条。
> 历史版本已不在支持线内(当前基线 DSH 0.2.0-rc.2,见 [AGENTS.md](../AGENTS.md) §3);逐条适配过程见 [docs/plans/](plans/) 与 [CHANGELOG.md](../CHANGELOG.md)。
> 历史版本已不在支持线内(当前基线 DSH 0.2.1-alpha.5,见 [AGENTS.md](../AGENTS.md) §3);逐条适配过程见 [docs/plans/](plans/) 与 [CHANGELOG.md](../CHANGELOG.md)。
当前适配约束:HTTP/WS 均由 `ctx.connection.requestRejection(req)` 裁决 Host/Origin 与浏览器认证,只有 `undefined` 放行,不读取已删除的 `webRuntime`。alpha.5 同时移除了 `@deepseek-ai/dsh-invariants`、`ctx.invariants` 和上游 `/invariant` 子路径;本插件不再发布 invariant companion。
## A. 0.1.5–0.1.7 引入、至今仍是现行约束的行为
@@ -18,6 +20,9 @@
- **会话格式 v4 的两处形状**:`source.kind === 'plugin'` 被硬拒,插件侧一律用 `plugin:dsh-better-sidebar`(与 DSH 自己 v3→v4 迁移产出的 kind 逐字一致,历史 sidechat 会话不丢);tool 结果消息是 `role: 'tool'` + **顶层** `content` / `isError` / `toolCallId`,转录解析器**必须同时接受新旧形状**——旧分支不能删(历史日志里就是旧形状),只认新形状会静默返回空串。
- **客户端会话快照与宿主客户端服务**:子代理目录读 `SessionListState.projectionsBySession[sid]?.values.subagentCatalog`(`mode` 有 `'unknown'` 新值);后台任务页直接读宿主**客户端** `ctx.jobs` 服务(`src/client/jobs-client.ts`:`getSnapshot()/subscribe()` 整份快照、`watchRows(sessionId)` 按会话引用计数、`observe(...)` 非消费输出流、`kill(sessionId, jobId)`)——**不要自建 `jobs.*` 路由,也不要用事件回放去读模型已读的输出**(那会动模型的 `job_output` 游标)。
- **会话当前执行目录**:文件 / Git / 终端及新建 sidechat 跟随 `working_directory`,不把 session header cwd 当成当前值。live 读 `ctx.workingDirectory.get(session)`;cold 经 `ctx.sessionQuery.observeSession(..., { projectionMode: 'all' })` 读取,lease 在 `finally` 中释放。同一 base 的 live 目录增量通过 epoch 失效缓存;cold 外进程同 base 变化仍沿用既有 15 s TTL。linked worktree 选择仍按 base 目录记账,不把选中的 worktree 反写为 base。sidechat 继承 seed 尾部盖章当前 cwd,避免旧 seed 的目录事件覆盖新线程的初始目录。
- **终端 label**:alpha.5 的 `TerminalBlockLabels` 新增必填 `commandLine(line)`,两个消费者都要提供,21 份词典同步对应 key。
## B. 宿主契约(原 AGENTS.md §3.4 第 1–12 条)
1. **一次性 token 鉴权**:就绪行 `dsh web: http://127.0.0.1:<port>/?token=<43字符>`(导航换签名 cookie,干净 URL 401)。`e2e-mount.sh` 的 URL grep 必须延伸到空白(`[^ ]*`,否则在 `/` 截断丢 token);e2e 统一走 `tests/e2e/host.ts`(`parseLaunchUrl` 对裸 origin 直接抛错),带 stamps 导航走 `gotoPage()`(先 addCookies 再直达——token 换 cookie 的 303 会丢弃同 URL 其它 query 参数)。插件 `/sidebar/*` 路由不受影响,同源 fetch 照旧。
@@ -27,7 +32,7 @@
5. **`dsh-subagent` 的 `SUBAGENT_DESCRIPTOR_VERSION` 仍是 3**:sidechat 种子的 `subagent/descriptor` 版本由宿主包盖章,插件不硬编码;测试断言跟随常量(`tests/sidechat-routes.spec.ts`),勿钉字面量。
6. **`@deepseek-ai/dsh-client-runtime` 包已消亡**(继任 seed 是裸名 `dsh-client-store`,无 `/client` 子路径):peerDependencies、devDependencies、`dsh.client.inject`、chunk externals 白名单(`src/client/chunk-loader.ts` / `tsdown.config.ts` 各有一处说明它已移除的注释)**无活引用**。
7. **e2e scratch profile 的 `minimumReleaseAgeExclude` 含 `'@deepseek-ai/*'`**(字面配置在 `scripts/e2e-common.sh` 的 `e2e_write_profile` heredoc,`e2e-mount.sh` / `e2e-aggregate-mount.sh` 都调它;与仓库根 `pnpm-workspace.yaml` 同策):alpha 版本常在发布后 24h 内跑 lane,pnpm 11 的 `minimumReleaseAge` 默认会拒装新鲜包。
8. **插件开发树的 dsh-* 传递 peer 需提升为 devDependencies**:npm 上的宿主包把姊妹包(`dsh-attachment` / `scope` / `session-projection` / `system-prompt` / `user-approval` / `util-time` 等)声明为 peerDependencies(由宿主 bundle 树统一提供,插件仓库没有),插件若只直接依赖其中一部分,其余 peer 在 pnpm 下会解析到树上残留的旧版——测试加载即崩。因此 devDependencies 需涵盖 dev 树实际触达的全部 peer,与直接依赖同款精确钉版;**一律以 `pnpm peers check` 的实际输出为准,不要预加**(`dsh-workspace` / `dsh-agent-preset-registry` 只是 `dsh-subagent` 的 optional peer 且从不被 import)。`@deepseek-ai/cordis` peer 现要求 `^4.0.4`;`cordis-plugin-group` / `-include` 是 `dsh-app-boot` / `dsh-config-editor` 的**传递 peer**,只改 `dependencies` 不够(pnpm 会继续沿用 lockfile 里的旧副本),要**显式钉进 devDependencies** 才收敛。例外已消除:`dsh-client-locale` 与 DSH 同 tuple,不再允许落后。
8. **插件开发树的 dsh-* 传递 peer 需提升为 devDependencies**:npm 上的宿主包把姊妹包(`dsh-attachment` / `scope` / `session-projection` / `system-prompt` / `user-approval` / `util-time` 等)声明为 peerDependencies(由宿主 bundle 树统一提供,插件仓库没有),插件若只直接依赖其中一部分,其余 peer 在 pnpm 下会解析到树上残留的旧版——测试加载即崩。因此 devDependencies 需涵盖 dev 树实际触达的全部 peer,与直接依赖同款精确钉版;**一律以 `pnpm peers check` 的实际输出为准,不要预加**(`dsh-workspace` / `dsh-agent-preset-registry` 只是 `dsh-subagent` 的 optional peer 且从不被 import)。当前伴随依赖为 Cordis `4.0.5`、schemastery `~3.18.5-alpha.2`、group `1.0.5-alpha.2` 与 include `1.0.10`;不直接钉 loader、不设 override,稳定 Cordis 同时满足宿主 alpha 与稳定传递 loader 的范围;`cordis-plugin-group` / `-include` 是 `dsh-app-boot` / `dsh-config-editor` 的**传递 peer**,只改 `dependencies` 不够(pnpm 会继续沿用 lockfile 里的旧副本),要**显式钉进 devDependencies** 才收敛。例外已消除:`dsh-client-locale` 与 DSH 同 tuple,不再允许落后。
9. **右侧栏是 DSH 原生栏,插件只提供 tab 类型**(**编号提示**:旧文与代码注释里把它引用作 `§3.10` / `§3 第 10 条`——`tests/native-surface-cross-session.spec.ts` 的 `§3.10` 与指南 §10 表格里的「第 10 条」都指本条):聊天里一切文件打开(工具行 / 产物行 / 正文提及 / 行内代码路径)统一走 `ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path))`,其中文件地址语法为「一律 session 作用域、绝对路径保留前导 `/`」,`parseFileAddress` 前缀解析并去 `?`/`#`。插件的每个 `TabDescriptor` 注册成原生 tab 类型(`kind = descriptor.id`,`extension` 带)+ 原生 tab 体(`sidebar.right.pane.tab` keyed 槽,key = `dsh-better-sidebar:<id>`);`editor` 类型同时认领 `dsh-resource://file/**`(**但按本文 A 节的清单让出一部分**),并接管内置 `files` 页面 kind(`openTab('files')` 打开插件文件树,注销即复位)。`ctx.sidebarRight.openTab/openResource/close` 只对**在屏会话**写入,跨会话用具体类上的 `openTabIn/openResourceIn/closeIn`;原生 tab 的插件侧状态在 `src/client/native/tab-adapter.tsx`。几条硬事实:
- **注册必须等服务、不能等槽声明**:原生栏先声明 `sidebar.right.pane.tab` 再 `provide('sidebarRightTabs')`,真机 profile 上槽声明回调里 `ctx.get('sidebarRightTabs')` 仍是 undefined(实测 3 秒后才出现),按槽触发注册会静默什么都不注册且永不重试——用 `ctx.inject(['sidebarRightTabs'], cb)` 驱动类型注册(`tests/native-surface.spec.ts` 以「槽先触发、服务后到达」的顺序守护)。
- `SidebarRightGuideEntry.id` **必填且同 provider 内唯一**(缺它会静默清空整个承载面);同 provider 的 guide 条目是**追加**关系(`chain` 那种「替换宿主条目」的语义只存在于 `conversation.chat.turnTail` 且已被上游改成 `list`)。**指南只描述 ≤4 条条目**(`GuideBody.tsx` 的 `MAX_DESCRIBED_ENTRIES`):更长是整列丢弃而不是截断——插件默认贡献 4 个 guide 条目(文件 / Git / 任务管理 / 侧边对话),加上宿主终端条目后可能超限;插件**不恢复**旧的 `nativeGuideDesc` 通用兜底句。
@@ -35,6 +40,6 @@
- **原生注册账本的两条不变量**(`tests/native-registration.spec.ts` 守护):① `live` 里同时装着描述符类型(键 = descriptor id)与 `files` 接管(键 = `FILES_KIND`,**永远不在 `wanted` 里**),清理循环必须**跳过 `FILES_KIND`**——它只由编辑器类型的 `wantsFiles/hasFiles` 开关分支与 seat disposer 管理;否则每次通知都会把它拆掉再重建,而 teardown 期间的那次重建会把 id 孤儿化:`tabs.register` 建在**宿主** ctx 上(宿主 ctx 此时仍活着)所以照样成功,紧随的 `ctx.slots.inject` 建在**插件** ctx 上却抛 `cannot create effect on inactive context`,`live.set` 永不执行 → 该 id 在整页生命周期内不可再注册(真机表现:`native register files error: … already registered` 刷屏 + 文件树落到宿主空态,只有刷新页面才恢复;实证见 [docs/plans/2026-09-28-native-files-takeover-reload-leak.md](plans/2026-09-28-native-files-takeover-reload-leak.md))。② 因此「注册成功一半」是**可达状态**:任何在宿主取走 id **之后**失败的注册(槽位注册抛错等)必须**回滚释放该 type** 并释放已经建好的槽位,插件侧只留一个下次通知可以重试的失败,绝不留下无处释放的 id。相关断言必须写在注册表的**事件日志**上而不是「活着的 id 集合」上:孤儿 id 会让键集合看起来完全正常,键集合断言在未修复代码上同样通过。
- **原生 tab 的状态保留(已采纳 `keepMounted: true`)**:宿主因此把访问过的 body 挂住,同会话切 tab 不再卸载,组件态(树滚动、未保存草稿、chip 重命名)随之免费保留,**不需要**任何 module-level 记忆。三条必须同时成立的配套事实:(a) **记录不能随卸载删除**(只由 `surface.close` 与「会话消失」回收),而「切回会话清零」那一路(真机日志里 `DISPOSE type …:files` → `register`、同键 `drop`+`mint`)已由上面的 `FILES_KIND` 守卫挡掉(真机 e2e 现断言跨会话 `scrollTop` 复原);(b) 原生 tab id **每会话各自计数**(`tab1`…)且多会话同号并存,记录与写面一律按 `sessionId::tabId` 记账,`Surface.update/has/activate` 的 `sessionId` 缺省按 `sidebarRight.mounted` 解析,多会话同名时**拒绝而不是猜**;(c) **展开集的权威在插件 store 的会话状态里**(`attachStore` + `syncExpanded` + `getSessionStates().expanded`,由 `native/index.ts` 绑定),记录只负责**身份**与投影——两套持久化会互相打架,插件不自持「每记录的展开集」。设计过程与实测见 [docs/plans/2026-09-25-native-tab-state-retention-keepmounted.md](plans/2026-09-25-native-tab-state-retention-keepmounted.md)。
10. **自定义种子必须带 fork 标记对(`meta.isSeeded: true` + `inheritedEventCount`),且 create 后必须 `inbox.clear()`、冷恢复必须按 id 精确清扫——标记对必要但不充分**:dsh-session 契约规定「只给 seed 不标 isSeeded,种子算重放历史而非继承前缀」——缺标记时 `Session.ownEvents()` 含整个种子,子会话的 inbox 折重放种子里的 `agent/inbox/spliced`,**继承父会话切割时刻未领取的 inbox 输入**。**但运行时 inbox 不走 `ownEvents()`**:`ReactLoopInbox.current()` → `ctx.sessionProjections.stateOf()` → `SessionProjectionRegistry.cellFor` 折的是 `snapshotEvents()` **全量日志(含继承种子前缀)**,且标准 inbox 投影的 `init` 忽略 `inheritedEventCount`、注册表 `session/created` 急切初始化跳过一切种子会话(seq ≠ 0)——种子里的 `agent/inbox/spliced` 会原样重放进子会话 live inbox。因此 sidechat 宿主 `agents.create` 成功后、任何 inject/followup 之前必须 `handle.agent.inbox.clear()`(durable 补偿 splice 是 own 事件,冷恢复折存储日志同样归零)。**幽灵的来源比「父会话排队」更宽**:父会话 mid-turn 且工具有未返回调用时,种子被截断在 `turn/start` 之前,而 inbox 的「领取」splice 发生在 `turn/start` **之后** → **父会话本轮开头已领取的输入**在种子折叠里仍是 pending;`clear()` 是唯一能一次清干净的硬围栏(create 时本线程自己不可能有排队输入)。**冷恢复不能沿用 `clear()`**(会误杀「用户在线程里排队、宿主重启后尚未领取」的合法输入):改为 `dropInheritedGhosts`——`inheritedPendingIds(log, inheritedEventCount)` 只折继承前缀得到幽灵 id 集合,再逐个 `agent.inbox.remove(id)`,精确且幂等(`src/sidechat-core.ts` 纯函数,`tests/sidechat-core.spec.ts` / `tests/sidechat-routes.spec.ts` 守护)。宿主 `session.fork`(api-session-controller)的调用即规范形态(注意:宿主自己的 `fork` **没有**这一步补偿,同窗口有同样的暴露面);回归由 `tests/sidechat-seed-validation.spec.ts`(真实 `Session.create` + 对 `ownEvents()` 跑 inbox 折 + **真实 `SessionProjectionRegistry`** 折全量日志钉住上游洞与 clear 补偿)守护。**模型选择同为 agent 作用域**:`sidechat.model` 必须同时落 `session.append('model/selection', …)`(宿主 `selectForNextRequest` 的同一形状)与 `installModelSelection(agent.ctx, ref)`(`@deepseek-ai/dsh-agent` 公开导出),否则控制器缓存的 per-agent selection 永不回读投影;resume 后也要按日志里的有效选择重装(`src/sidechat-routes.ts` 的 `ensureModelSelection`)。**上游 0.2.0 新增的 `buildForkSeed` 与本插件手工的 `buildSidechatInheritance` 职责重叠,但收益不明确**(插件另有 dangling-tool-call 退回结构化快照的自有需求),暂不替换。
11. **`dsh.plugin.json` 从来不是 DSH 契约**(全树 grep 0 命中):DSH 真正读的是 `package.json` 的 `dsh.bundle.patch` + `dsh.client`(`platform`/`inject`/`immediately`/`external`)+ `exports["./client"]`。`dsh.plugin.json` 与 `lib/client-registry.js` 只服务第三方 registry(社区市场)通道,`tests/manifest-consistency.spec.ts` 守护的是这条通道的形状,不是 DSH 契约。**`dsh.manifestVersion` 与 `engines.dsh` 仍是「只声明、零读」**(DSH 自己的 package-manifest README 写明 installers / loaders 不强制它们)。`dsh.bundle.patch` 有形状校验(非法值会 `throw`,引导期跳过该 bundle),本插件是合法的单字符串。
11. **`dsh.plugin.json` 从来不是 DSH 契约**(全树 grep 0 命中):DSH 真正读的是 `package.json` 的 `dsh.bundle.patch` + `dsh.client`(`platform`/`inject`/`immediately`/`external`)+ `exports["./client"]`。`dsh.plugin.json` 与 `lib/client-registry.js` 只服务第三方 registry(社区市场)通道,`tests/manifest-consistency.spec.ts` 守护的是这条通道的形状,不是 DSH 契约。**不要混淆两个 manifest 的 `engines.dsh`**:alpha.5 的兼容性检查优先读取 `package.json#engines.dsh`,存在时由它独立裁决;本插件未声明此字段,仍由 13 条 DSH peer 决定兼容性。`dsh.plugin.json#engines.dsh` 只是第三方 registry 元数据,不能替代 package 字段;`dsh.manifestVersion` 也不是版本兼容性开关。`dsh.bundle.patch` 有形状校验(非法值会 `throw`,引导期跳过该 bundle),本插件是合法的单字符串。
**插件展示元数据**(Plugins 页与 `plugin_manager` 列表,v0.21.1 起已采纳)三条硬规则:`package.json#icon` 必须是**包内相对路径**且写进 `files`(36×36、纯填充无描边、**双色渐变**——与 DSH 自带 `PluginArtwork*` 同风格,单色版在 30px 行内尺寸下会读成一块纯色板);`locale/en.json` 是发现基线(缺它整个目录都不读,`meta.title` / `description` 在这里);`exports` 必须暴露 `./locale/*.json` 与 `./package.json`。**所有失败都是静默的**——元数据有问题只会退化成一行纯文字,没有任何报错;`tests/plugin-meta.spec.ts` 守护「声明了就必须发布出去」。plugin-manager 侧另有**多 registry 回退**(配置源 → `fallbackRegistries`,默认含 `registry.npmmirror.com`;`network`/`timeout`/`not-found`/`no-matching-version` 会自动问下一个源;`registry` 入参只存在于 Web 对话框与 `plugin_manager` 工具,**CLI 没有 registry flag**)。
12. **peer 声明是启动期硬约束(最容易静默失效的一处)**:`packages/boot/app-boot/src/plugin-compatibility.ts` 只做一件事——遍历 profile 行的 `peerDependencies`,对**名字为 `@deepseek-ai/dsh` 或以 `@deepseek-ai/dsh-` 开头**的条目跑 `semver.satisfies(宿主版本, range, { includePrerelease: true })`,不满足就把整行 `row.disabled = true`(group 行连 `group` 一起关掉),只在 stderr 留一行 `disabling profile plugin <label>: <reason>`。调用点:`dsh web --profile <p>` 的 `prepareProfileEntries`(必经路径)、`profile.ts`(bundle 行,异常被吞成 skip,该 bundle 不再贡献 patch 层)、`agent-preset-registry/src/mount.ts`(预置行),以及 plugin-manager 的安装前/安装后校验。**四个要点**:(a) 它**只读 peer,不读 `engines.dsh` / `dsh.manifestVersion`**(那两个字段仍然零读者,见第 11 条);(b) `peerDependenciesMeta.optional` **没有任何豁免**(我们那条 optional 的 `@deepseek-ai/dsh-client-ui-sidebar-right` 照样参与判定);(c) `includePrerelease` 被强制打开,判定比 npm 宽松(`^0.1.6-alpha.2` 也能满足 `0.1.7-rc.1`),但**精确版本号、或没有预发布子句的范围(如 `^0.1.7`)一定不过**——且这条宽松只在**同一 minor 内**成立(AGENTS.md §3);(d) 豁免只能写 profile 自己的 `compatibility.json`(`dsh plugin allow-version <pkg@ver> --dsh-version <exact> --accept-risk`),没有全局开关也没有环境变量。**`pnpm peers check` 看不到这个失败模式**:它校验的是解析出来的 dev 树,不是宿主会读的范围形状。
12. **宿主版本兼容性是启动期硬约束**:alpha.5 先读插件 `package.json#engines.dsh`;字段存在时只按该范围判定,DSH peer 不再拓宽或收窄结果。字段缺席时回退检查名字为 `@deepseek-ai/dsh` 或以 `@deepseek-ai/dsh-` 开头的 peer,按 `semver.satisfies(宿主版本, range, { includePrerelease: true })` 判定。本插件刻意不新增该字段,仍由 13 条 DSH peer 的 `^0.2.1-alpha.5` 支持线约束,optional peer 没有豁免。`engines` 非对象或 `engines.dsh` 非字符串会导致兼容性清单不可读并拒绝加载;`workspace:` 仅在 peer 中有效。安装与 profile 启动拒绝可能禁用整行,需读 `disabling profile plugin` 日志;拒绝记录字段已由 `peers` 改为 `requirements`,其中 key 为 `engines.dsh` 或回退检查的 peer 包名。`pnpm peers check` 校验的是 dev 依赖树,不能证明宿主启动预检通过。[官方升级指南](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.1-alpha.5/docs/upgrade-guide/v0.2.1-alpha.3/plugin-engines-dsh/guide.md)。
@@ -0,0 +1,62 @@
# DSH 0.2.1-alpha.5 适配记录(v0.28.0-alpha.0)
> 状态:本地适配验证完成,未发布。以下结果由主线程执行并确认;未修改 DSH 源码或升级真实用户 profile。
## 1. 已批准范围
- 宿主精确目标:DSH `0.2.1-alpha.5`;插件版本:`0.28.0-alpha.0`。
- 单支持线:13 条 DSH peer 下限为 `^0.2.1-alpha.5`,开发依赖与 CI / 安装脚本钉精确宿主版本;不写旧版运行时兼容层。
- DSH `0.2.0-rc.2` 用户继续使用 npm 已发布的插件 `0.26.1`;`0.27.0` 尚未发布到 npm。`0.2.0-rc.1` 用 `0.24.1`,`0.1.7` 线用 `0.22.1`。
- alpha 发布后使用 `dsh plugin --profile web add dsh-better-sidebar@0.28.0-alpha.0`;`latest` 不是本 alpha 的安装目标。
- 不修改 DSH 源码,不升级真实用户 profile,不发布 npm。
## 2. 两项删除型迁移
### Connection admission
alpha.5 删除 `webRuntime`。插件注入改为 `connection`;所有 `/sidebar` HTTP/WS 路由调用 `ctx.connection.requestRejection(req)`,仅返回 `undefined` 才继续。Host/Origin 与浏览器认证由宿主裁决,不复制 trusted-host 列表或恢复插件自建例外;拒绝应发生在读取请求体或升级之前。
### Runtime invariants
[官方升级指南](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.1-alpha.5/docs/upgrade-guide/v0.2.0-rc.2/remove-runtime-invariants/guide.md) 明确移除 `@deepseek-ai/dsh-invariants`、`ctx.invariants` 与各宿主包的 `/invariant` 子路径,无替代包。不能把不存在的版本钉成 alpha.5,也不保留 rc.2 包混入新支持线。
本插件同步移除 invariant companion、类型、包导出与打包清单。压缩种子回归移除上游 `/invariant` 导入,继续以公开 surface fold、seed validator 和事件结构断言覆盖原行为,不自建 invariant 框架。
## 3. 当前执行目录、labels 与兼容性判定
用户已选择文件 / Git / 终端与新建 sidechat 跟随会话 `working_directory`。live 读 `ctx.workingDirectory.get(session)`;cold 通过 `ctx.sessionQuery.observeSession` 的 `projectionMode: 'all'` 读取当前目录,lease 在 `finally` 释放。linked worktree 仍按 base 目录记账;sidechat seed 尾部 stamp 当前 cwd,避免历史 seed 目录覆盖新线程当前目录。
alpha.5 的 `TerminalBlockLabels` 新增必填 `commandLine(line)`,两个消费者已补,全 21 份词典 key 同步。伴随更新 Cordis `4.0.5`、schemastery `~3.18.5-alpha.2`、group `1.0.5-alpha.2`、include `1.0.10`。稳定 Cordis 同时满足 alpha 宿主与稳定传递 loader 的范围,无需 override;剩余 4 条 peer 警告仅来自可选 better-locale 的旧 DSH 支持线。
[官方兼容性升级指南](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.1-alpha.5/docs/upgrade-guide/v0.2.1-alpha.3/plugin-engines-dsh/guide.md) 描述 alpha.3 之后的规则变化:package 自有 `engines.dsh` 存在时独立决定兼容性,否则才读 DSH peers;拒绝记录由 `peers` 更名 `requirements`。本插件不新增 `package.json#engines.dsh`,仍用 13 peers;第三方 `dsh.plugin.json#engines.dsh` 不参与宿主判定。
## 4. 同步面
- 依赖、lockfile、插件版本与 manifest。
- Connection 注入、路由准入、结构化类型及测试夹具。
- CI、e2e 默认/预期宿主版本、两个安装脚本。
- 当前 README、接入指南、宿主契约、开发规则及本次 CHANGELOG 新条目;历史记录不改写。
## 5. 验证矩阵(主线程执行并确认)
| 检查 | 状态 |
| --- | --- |
| 安装 alpha.5 依赖并检查 lockfile 收敛 | 已执行;最终伴随版本见上文 |
| `pnpm peers check` | 仅可选 better-locale 的 4 条旧 DSH peer 警告,无 loader 未定项 |
| 消费宿主包类型面与裸 import 差集 | 已审计 74 个 primitives 消费符号与 27 个宿主包;必填变化为 commandLine;新增裸 import 均由宿主包或平台模块表提供 |
| 会话格式、子代理描述符版本、web profile inject | 主线程实跑常量仍为 4 / 3;surface 与 sidebar-right 的 6 份消费声明逐字节相同;独立 tag 审计确认客户端 roster 只增不减,真实挂载通过 |
| `pnpm typecheck` / `pnpm lint` | 新鲜通过 |
| `pnpm test`(默认 CI 入口) | 219 文件全部通过;2634 passed / 17 skipped,20.29 s,无 unhandled errors |
| `pnpm test --maxWorkers=1` | 219 文件全部通过;2634 passed / 17 skipped(共 2651),96.1 s |
| `pnpm build` / `pnpm check:consumer-types` | 新鲜通过;浏览器 consumer 不泄漏 Node 类型 |
| `pnpm check:engines` | rg 通过;fd 缺失,未执行 fd 检查 |
| `pnpm pack` 与 tarball 内容检查 | 通过:467 项、版本 0.28.0-alpha.0;废弃 invariant / trust-fence 源码、产物与声明均 0 项 |
| 精确 alpha.5 宿主的 `pnpm test:mount` | 最终交付 tarball 重跑 13/13 通过,2.5 min;此前一轮亦为 13/13 |
| 精确 alpha.5 宿主的 `pnpm test:mount:aggregate` | 通过:settings.get 返回 ok:true,未知路由 404,无重复路由 |
| Windows 原生运行验证 | 未执行 |
排查期间默认并发曾出现 watch / GC 相关失败,保留为历史而非当前阻塞;最终默认入口与单 worker 完整重跑均通过。默认入口日志为 `/tmp/bsb-alpha-tests-default-final.log`,单 worker 日志为 `/tmp/bsb-alpha-tests-final.log`。默认目录、同 base live 增量 epoch 与 sidechat seed cwd stamp 真实测试均通过;cold 外进程同 base 更新仍受既有 15 s TTL 约束。
消费类型通过 `/// <reference lib="esnext.disposable" preserve="true" />` 保留 disposal 标准类型引用,浏览器 consumer 验证不引入 Node 类型。
真实挂载必须使用隔离 scratch profile 与精确 `@deepseek-ai/dsh@0.2.1-alpha.5`,不使用会覆盖 `DSH_HOME` 的桌面 shim。网络或安装失败应记录原始失败,不以旧宿主测试替代 alpha.5 证据。
+2 -2
View File
@@ -1,10 +1,10 @@
{
"id": "dsh-external/dsh-better-sidebar",
"version": "0.27.0",
"version": "0.28.0-alpha.0",
"main": "./lib/index.js",
"description": "更好用的右侧边栏——文件树、编辑器、文件变动、任务和侧边对话都收在这一栏里,每个会话互不干扰。暴露服务供其他插件注册侧边栏页面与文件预览器",
"engines": {
"dsh": ">=0.2.0-rc.2"
"dsh": ">=0.2.1-alpha.5"
},
"contributes": {
"tools": [],
+47 -53
View File
@@ -1,6 +1,6 @@
{
"name": "dsh-better-sidebar",
"version": "0.27.0",
"version": "0.28.0-alpha.0",
"description": "Better Sidebar for DSH — file tree, editor, changes, tasks and side chat in one column, separate for every conversation. Also exposes a service other plugins use to register sidebar tabs and file viewers.",
"type": "module",
"repository": {
@@ -17,10 +17,6 @@
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./invariant": {
"types": "./lib/types/invariant.d.ts",
"default": "./lib/invariant.js"
},
"./client": {
"types": "./lib/types/client/index.d.ts",
"default": "./lib/client.js"
@@ -59,7 +55,6 @@
},
"files": [
"lib/index.js",
"lib/invariant.js",
"lib/client.js",
"lib/client-registry.js",
"lib/client-editor.js",
@@ -95,21 +90,20 @@
},
"license": "MIT",
"peerDependencies": {
"@deepseek-ai/cordis": "^4.0.4",
"@deepseek-ai/dsh-agent": "^0.2.0-rc.2",
"@deepseek-ai/dsh-client-locale": "^0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-conversation": "^0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-primitives": "^0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-settings": "^0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-sidebar-right": "^0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-slots": "^0.2.0-rc.2",
"@deepseek-ai/dsh-host-webserver": "^0.2.0-rc.2",
"@deepseek-ai/dsh-invariants": "^0.2.0-rc.2",
"@deepseek-ai/dsh-llm": "^0.2.0-rc.2",
"@deepseek-ai/dsh-session": "^0.2.0-rc.2",
"@deepseek-ai/dsh-settings": "^0.2.0-rc.2",
"@deepseek-ai/dsh-subagent": "^0.2.0-rc.2",
"@deepseek-ai/dsh-tools": "^0.2.0-rc.2",
"@deepseek-ai/cordis": "^4.0.5-alpha.2",
"@deepseek-ai/dsh-agent": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-client-locale": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-conversation": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-primitives": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-settings": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-sidebar-right": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-slots": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-host-webserver": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-llm": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-session": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-settings": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-subagent": "^0.2.1-alpha.5",
"@deepseek-ai/dsh-tools": "^0.2.1-alpha.5",
"@huanlin/dsh-plugin-better-locale": "^0.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
@@ -144,7 +138,7 @@
"@codemirror/search": "^6.7.1",
"@codemirror/state": "^6.7.1",
"@codemirror/view": "^6.43.8",
"@deepseek-ai/schemastery": "^3.18.4",
"@deepseek-ai/schemastery": "~3.18.5-alpha.2",
"@formkit/auto-animate": "^0.10.0",
"@lezer/highlight": "^1.2.3",
"@xterm/addon-fit": "^0.11.0",
@@ -159,37 +153,37 @@
},
"devDependencies": {
"@cordisjs/plugin-loader": "^1.0.0-rc.5",
"@deepseek-ai/cordis": "4.0.4",
"@deepseek-ai/cordis-plugin-group": "1.0.4",
"@deepseek-ai/cordis-plugin-include": "1.0.9",
"@deepseek-ai/dsh-agent": "0.2.0-rc.2",
"@deepseek-ai/dsh-agent-loop": "0.2.0-rc.2",
"@deepseek-ai/dsh-attachment": "0.2.0-rc.2",
"@deepseek-ai/dsh-client-locale": "0.2.0-rc.2",
"@deepseek-ai/dsh-client-store": "0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-conversation": "0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-primitives": "0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-settings": "0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-sidebar-right": "0.2.0-rc.2",
"@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
"@deepseek-ai/dsh-host-webserver": "0.2.0-rc.2",
"@deepseek-ai/dsh-invariants": "0.2.0-rc.2",
"@deepseek-ai/dsh-llm": "0.2.0-rc.2",
"@deepseek-ai/dsh-ptc-runtime": "0.2.0-rc.2",
"@deepseek-ai/dsh-sandbox": "0.2.0-rc.2",
"@deepseek-ai/dsh-sandbox-policy": "0.2.0-rc.2",
"@deepseek-ai/dsh-scope": "0.2.0-rc.2",
"@deepseek-ai/dsh-session": "0.2.0-rc.2",
"@deepseek-ai/dsh-session-persistence": "0.2.0-rc.2",
"@deepseek-ai/dsh-session-projection": "0.2.0-rc.2",
"@deepseek-ai/dsh-settings": "0.2.0-rc.2",
"@deepseek-ai/dsh-subagent": "0.2.0-rc.2",
"@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2",
"@deepseek-ai/dsh-tools": "0.2.0-rc.2",
"@deepseek-ai/dsh-user-approval": "0.2.0-rc.2",
"@deepseek-ai/dsh-util-code-language": "0.2.0-rc.2",
"@deepseek-ai/dsh-util-time": "0.2.0-rc.2",
"@deepseek-ai/dsh-util-workspace-path": "0.2.0-rc.2",
"@deepseek-ai/cordis": "4.0.5",
"@deepseek-ai/cordis-plugin-group": "1.0.5-alpha.2",
"@deepseek-ai/cordis-plugin-include": "1.0.10",
"@deepseek-ai/dsh-agent": "0.2.1-alpha.5",
"@deepseek-ai/dsh-agent-loop": "0.2.1-alpha.5",
"@deepseek-ai/dsh-attachment": "0.2.1-alpha.5",
"@deepseek-ai/dsh-client-locale": "0.2.1-alpha.5",
"@deepseek-ai/dsh-client-store": "0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-conversation": "0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-primitives": "0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-settings": "0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-sidebar-right": "0.2.1-alpha.5",
"@deepseek-ai/dsh-client-ui-slots": "0.2.1-alpha.5",
"@deepseek-ai/dsh-host-webserver": "0.2.1-alpha.5",
"@deepseek-ai/dsh-llm": "0.2.1-alpha.5",
"@deepseek-ai/dsh-ptc-runtime": "0.2.1-alpha.5",
"@deepseek-ai/dsh-sandbox": "0.2.1-alpha.5",
"@deepseek-ai/dsh-sandbox-policy": "0.2.1-alpha.5",
"@deepseek-ai/dsh-scope": "0.2.1-alpha.5",
"@deepseek-ai/dsh-session": "0.2.1-alpha.5",
"@deepseek-ai/dsh-session-persistence": "0.2.1-alpha.5",
"@deepseek-ai/dsh-session-projection": "0.2.1-alpha.5",
"@deepseek-ai/dsh-settings": "0.2.1-alpha.5",
"@deepseek-ai/dsh-subagent": "0.2.1-alpha.5",
"@deepseek-ai/dsh-system-prompt": "0.2.1-alpha.5",
"@deepseek-ai/dsh-tools": "0.2.1-alpha.5",
"@deepseek-ai/dsh-user-approval": "0.2.1-alpha.5",
"@deepseek-ai/dsh-util-code-language": "0.2.1-alpha.5",
"@deepseek-ai/dsh-util-time": "0.2.1-alpha.5",
"@deepseek-ai/dsh-util-workspace-path": "0.2.1-alpha.5",
"@deepseek-ai/dsh-working-directory": "0.2.1-alpha.5",
"@eslint/js": "^10.0.1",
"@huanlin/dsh-plugin-better-locale": "^0.1.0",
"@playwright/test": "^1.62.1",
+615 -577
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -38,7 +38,6 @@ minimumReleaseAgeExclude:
- '@deepseek-ai/dsh-host-apiproxy@0.0.1-rc.1'
- '@deepseek-ai/dsh-host-directory-picker@0.0.1-rc.1'
- '@deepseek-ai/dsh-host-webserver@0.0.1-rc.1'
- '@deepseek-ai/dsh-invariants@0.0.1-rc.1'
- '@deepseek-ai/dsh-llm-retry@0.0.1-rc.1'
- '@deepseek-ai/dsh-llm@0.0.1-rc.1'
- '@deepseek-ai/dsh-native-command@0.0.1-rc.1'
+5 -8
View File
@@ -41,13 +41,10 @@ e2e_require_cmd() {
# PATH 上的 dsh 优先,否则 npx 拉官方包(同 scripts/install.sh)。DSH_CMD
# 缺省值(`dsh`)由调用方从环境变量取好传入。
#
# 回退的 npx 版本是显式钉死的:不钉就会解析 npm 的 `latest` dist-tag,而
# 0.2.0 线目前只有预发布(`latest` 仍是 0.1.7-rc.2,0.2.0-rc.2 走 `next`),
# 冒烟会静静地挂到一个插件已不支持的宿主上。**必须写精确版本,不能写
# `@next`/`@alpha` 之类的 dist-tag**:0.1.7-rc.1 上线时 `alpha` 指的是
# 0.1.7-alpha.2,0.2.0-rc.2 又只挂在 `next` 上。钉版必须与 package.json 的
# peer 下限同步(caret 跨 minor 不成立:`^0.1.7-rc.1` 实测不满足 0.2.0-rc.2)。
DSH_NPX_SPEC="${DSH_NPX_SPEC:-@deepseek-ai/dsh@0.2.0-rc.2}"
# 回退的 npx 版本是显式钉死的:不钉就会解析 npm 的 dist-tag,可能静默挂到
# 插件不支持的宿主上。**必须写精确版本,不能写 `@next`/`@alpha` 等 dist-tag**。
# 该版本必须与 package.json 的 DSH peer 基线同步。
DSH_NPX_SPEC="${DSH_NPX_SPEC:-@deepseek-ai/dsh@0.2.1-alpha.5}"
e2e_resolve_dsh_cmd() {
local explicit="${DSH_CMD}"
if ! command -v "$DSH_CMD" >/dev/null 2>&1; then
@@ -69,7 +66,7 @@ e2e_resolve_dsh_cmd() {
# 己在挂什么),只告警。
e2e_check_dsh_version() {
local explicit="$1" actual expected
expected="${DSH_EXPECT_VERSION:-0.2.0-rc.2}"
expected="${DSH_EXPECT_VERSION:-0.2.1-alpha.5}"
# `dsh --version` 冷启动要走 npx,给足预算;拿不到版本就只告警。
actual="$($DSH_CMD --version 2>/dev/null | tr -d '[:space:]' | head -c 64 || true)"
case "$actual" in
+2 -2
View File
@@ -28,7 +28,7 @@
# 环境变量(均可省略):
# DSH_HOME 默认 %USERPROFILE%\.dsh
# REGISTRY 默认 https://registry.npmjs.org
# DSH_CMD 默认优先 PATH 上的 dsh,缺省回退 npx -y --package @deepseek-ai/dsh
# DSH_CMD 默认优先 PATH 上的 dsh,缺省回退 npx -y --package @deepseek-ai/dsh@0.2.1-alpha.5
#
# 说明:
# - pnpm 11 的 minimumReleaseAge 会拒绝发布 <24h 的新版本。脚本会预写
@@ -173,7 +173,7 @@ Ensure-WorkspaceSettings
if ($CLI -eq 'dsh') {
$cliArgs = @('plugin', '--profile', $Profile, 'add', "$PKG@$SPEC")
} else {
$cliArgs = @('-y', '--package', '@deepseek-ai/dsh', 'dsh', 'plugin', '--profile', $Profile, 'add', "$PKG@$SPEC")
$cliArgs = @('-y', '--package', '@deepseek-ai/dsh@0.2.1-alpha.5', 'dsh', 'plugin', '--profile', $Profile, 'add', "$PKG@$SPEC")
}
Say "执行 $CLI plugin --profile $Profile add $PKG@$SPEC ..."
$addOut = & $CLI @cliArgs 2>&1
+2 -2
View File
@@ -24,7 +24,7 @@
# 环境(均可省略,脚本会自动探测):
# DSH_HOME 默认 ~/.dsh(Windows Git Bash 下回退 $USERPROFILE/.dsh)
# REGISTRY 默认 https://registry.npmjs.org(发布源;装依赖仍走 pnpm 配置)
# DSH_CMD 默认优先用 PATH 上的 `dsh`,缺省回退 npx -y --package @deepseek-ai/dsh
# DSH_CMD 默认优先用 PATH 上的 `dsh`,缺省回退 npx -y --package @deepseek-ai/dsh@0.2.1-alpha.5
#
# 说明:
# - pnpm 11 的 minimumReleaseAge 会拒绝发布 <24h 的新版本。脚本会预写
@@ -140,7 +140,7 @@ dsh_cli() {
if command -v "$DSH_CMD" >/dev/null 2>&1; then
printf '%s' "$DSH_CMD"
elif command -v npx >/dev/null 2>&1; then
printf 'npx -y --package @deepseek-ai/dsh@0.1.7-alpha.1 dsh'
printf 'npx -y --package @deepseek-ai/dsh@0.2.1-alpha.5 dsh'
else
die "未找到 dsh 或 npx。请先安装 DSH(并确保 Node/npm 可用),或用 DSH_CMD 指定 dsh 路径。"
fi
-1
View File
@@ -26,7 +26,6 @@ const out = join(root, 'registry')
const files = [
'dsh.plugin.json',
'lib/index.js',
'lib/invariant.js',
'lib/client-registry.js',
'lib/client-registry.js.map',
// Lazy chunks: the client fetches these from the host's /sidebar/bundle
+46 -12
View File
@@ -1,10 +1,11 @@
/**
* Follow the linked git worktree a session is ACTUALLY working in.
*
* The explorer is rooted at the session's stored header cwd, which never
* changes. A session can move into a linked git worktree (`git worktree add`)
* The explorer starts from the host's committed workingDirectory, which can
* change independently of the immutable header. It can also follow a linked
* git worktree (`git worktree add`)
* during its life including a worktree of a repository that is not the one
* the header cwd points at and the sidebar should follow it.
* the current directory points at and the sidebar should follow it.
*
* The active root is derived from the session's own `tool/call` arguments:
* absolute paths are collected newest-event-first (structured `cwd` / `workdir`
@@ -14,7 +15,8 @@
* and only top levels whose `--absolute-git-dir` differs from their
* `--git-common-dir` (i.e. real LINKED worktrees, not the main checkout and
* not submodules) are adopted. The highest-scoring linked worktree of the
* newest event that has one wins; when there is no evidence the session cwd is
* newest event that has one wins, but only evidence after the last committed
* working-directory/change is eligible. When there is no evidence the cwd is
* kept (lifted to the repository top level for subdirectory sessions).
*
* Resolutions are cached process-wide ({@link ACTIVE_ROOT_TTL_MS}), concurrent
@@ -72,7 +74,7 @@ const ACTIVE_ROOT_PATH_PATTERN = /[A-Za-z]:(?:\\|\/)[^\\/\s"'\x60,;|)<>*?]+(?:[\
* (`undefined` = "no git top level here"), which is what keeps a non-repo
* session cheap; those entries are evictable like any other.
*/
const activeWorktreeRootCache = new Map<string, { root: string; base: string; expires: number }>()
const activeWorktreeRootCache = new Map<string, { root: string; base: string; directoryEpoch: number | undefined; expires: number }>()
const pathTopCache = new Map<string, string | undefined>()
const linkedWorktreeCache = new Map<string, boolean>()
@@ -106,6 +108,34 @@ function cachePut<K, V>(map: Map<K, V>, key: K, value: V, max: number): void {
}
}
/** Latest committed directory change, observed incrementally per live Session. */
const directoryEpochs = new WeakMap<object, { through: number; epoch: number }>()
/**
* Cache identity must notice explicit cd even when its resulting base equals
* the old base (an old tool may have temporarily selected a linked worktree).
* Indexed reads inspect only newly appended events, with zero snapshot copies;
* unchanged live cursors cost O(1). A first read only needs the same bounded
* history window used by the worktree evidence scan.
*/
function directoryEpochOf(ctx: Context, sessionId: string): number | undefined {
const session = ctx.sessions.get(sessionId)
if (session?.seq === undefined || session.eventAt === undefined) return undefined
const end = session.seq
const previous = directoryEpochs.get(session)
if (previous?.through === end) return previous.epoch
const start = previous?.through ?? Math.max(0, end - ACTIVE_ROOT_MAX_EVENTS)
let epoch = previous?.epoch ?? -1
for (let index = end - 1; index >= start; index -= 1) {
const event = session.eventAt(index)
if (event?.type !== 'working-directory/change') continue
epoch = event.seq
break
}
directoryEpochs.set(session, { through: end, epoch })
return epoch
}
/**
* Normalized IDENTITY of a path (case- and separator-insensitive), for
* comparisons and cache keys only: it lowercases, so it must never be handed
@@ -280,6 +310,9 @@ async function activeRootFromEvents(events: readonly SidebarSessionEvent[], base
let probes = 0
for (let index = events.length - 1; index >= start; index -= 1) {
const event = events[index]
// An explicit directory transition is the authority boundary. Older tool
// paths belong to the previous execution context and must not override it.
if (event?.type === 'working-directory/change') break
if (event === undefined || event.type !== 'tool/call') continue
const weights = new Map<string, ActivePathEntry>()
collectActivePaths(event.data, weights, false)
@@ -342,17 +375,18 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base
const override = (process.env[ACTIVE_ROOT_OVERRIDE_ENV] ?? '').trim()
if (override !== '' && isAbsolute(override)) return requireAbsolute(override)
// The comparison is on the raw base, so a session whose caller switched base
// (the `/sidebar/*` routes pass the client's own) never reuses the other
// (a committed working_directory change) never reuses the other
// one's root.
const directoryEpoch = directoryEpochOf(ctx, sessionId)
const cached = activeWorktreeRootCache.get(sessionId)
if (cached !== undefined && cached.expires > Date.now() && cached.base === base) {
if (cached !== undefined && cached.expires > Date.now() && cached.base === base && cached.directoryEpoch === directoryEpoch) {
cachePut(activeWorktreeRootCache, sessionId, cached, ACTIVE_ROOT_CACHE_MAX)
return cached.root
}
const flightKey = `${sessionId}\0${base}`
const flightKey = `${sessionId}\0${base}\0${directoryEpoch ?? ''}`
const pending = activeRootInFlight.get(flightKey)
if (pending !== undefined) return pending
const promise = resolveActiveWorktreeRoot(ctx, sessionId, base).then(
const promise = resolveActiveWorktreeRoot(ctx, sessionId, base, directoryEpoch).then(
(root) => {
activeRootInFlight.delete(flightKey)
return root
@@ -367,18 +401,18 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base
}
/** One uncached resolution (see {@link activeWorktreeRootOf}). */
async function resolveActiveWorktreeRoot(ctx: Context, sessionId: string, base: string): Promise<string> {
async function resolveActiveWorktreeRoot(ctx: Context, sessionId: string, base: string, directoryEpoch: number | undefined): Promise<string> {
const top = await topLevelOf(base)
if (top === undefined) {
// "Not inside a repository" is an answer too (the base itself), and caching
// it is what keeps a non-repo session from re-probing on every ask.
cachePut(activeWorktreeRootCache, sessionId, { root: base, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
cachePut(activeWorktreeRootCache, sessionId, { root: base, base, directoryEpoch, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
return base
}
const canonicalTop = requireAbsolute(top)
const effectiveBase = pathUnderOf(base, canonicalTop) ? base : canonicalTop
const active = await activeRootFromEvents(await sessionEventsOf(ctx, sessionId), effectiveBase)
const root = active ?? effectiveBase
cachePut(activeWorktreeRootCache, sessionId, { root, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
cachePut(activeWorktreeRootCache, sessionId, { root, base, directoryEpoch, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
return root
}
+1
View File
@@ -585,6 +585,7 @@ export function SideChatView(props: {
injectionLabel: t('sideChatInjection'),
terminal: {
...shared,
commandLine: (line: number) => t('sideChatBlockCommandLine', { line }),
signal: (signal: string) => t('sideChatBlockSignal', { signal }),
exitCode: (exitCode: number) => t('sideChatBlockExitCode', { code: exitCode }),
// DSH 0.1.6-alpha.2 added this pill text: a settle the view cannot
+2
View File
@@ -37,6 +37,7 @@ export function blockLabels(): BlockLabels {
/** The `TerminalBlockLabels` shape (structural mirror; the host owns the type). */
export interface TerminalLabels {
commandLine: (line: number) => string
signal: (signal: string) => string
exitCode: (exitCode: number) => string
noExitCode: string
@@ -56,6 +57,7 @@ export interface TerminalLabels {
export function terminalBlockLabels(): TerminalLabels {
return {
...blockLabels(),
commandLine: (line: number) => t('sideChatBlockCommandLine', { line }),
signal: (signal: string) => t('sideChatBlockSignal', { signal }),
exitCode: (exitCode: number) => t('sideChatBlockExitCode', { code: exitCode }),
// DSH 0.1.6-alpha.2 added this pill text: a settle the view cannot
+1
View File
@@ -451,6 +451,7 @@ export const ar: Record<string, string> = {
sideChatBlockFailed: 'فشل',
sideChatBlockDone: 'اكتمل',
sideChatBlockNoOutput: '(لا يوجد إخراج)',
sideChatBlockCommandLine: 'سطر الأمر {line}',
codeBlockTitle: 'كتلة التعليمات البرمجية',
codeBlockWrap: 'التفاف الأسطر',
codeBlockUnwrap: 'بدون التفاف للأسطر',
+1
View File
@@ -436,6 +436,7 @@ export const de: Record<string, string> = {
sideChatBlockFailed: 'Fehlgeschlagen',
sideChatBlockDone: 'Fertig',
sideChatBlockNoOutput: '(keine Ausgabe)',
sideChatBlockCommandLine: 'Befehlszeile {line}',
codeBlockTitle: 'Codeblock',
codeBlockWrap: 'Zeilen umbrechen',
codeBlockUnwrap: 'Zeilen nicht umbrechen',
+1
View File
@@ -443,6 +443,7 @@ export const fr: Record<string, string> = {
sideChatBlockFailed: 'Échec',
sideChatBlockDone: 'Terminé',
sideChatBlockNoOutput: '(aucune sortie)',
sideChatBlockCommandLine: 'Ligne de commande {line}',
codeBlockTitle: 'Bloc de code',
codeBlockWrap: 'Retour à la ligne',
codeBlockUnwrap: 'Ne pas retourner à la ligne',
+1
View File
@@ -450,6 +450,7 @@ export const hi: Record<string, string> = {
sideChatBlockFailed: 'विफल',
sideChatBlockDone: 'पूर्ण',
sideChatBlockNoOutput: '(कोई आउटपुट नहीं)',
sideChatBlockCommandLine: 'कमांड की पंक्ति {line}',
codeBlockTitle: 'कोड ब्लॉक',
codeBlockWrap: 'पंक्तियाँ लपेटें',
codeBlockUnwrap: 'पंक्तियाँ न लपेटें',
+1
View File
@@ -448,6 +448,7 @@ export const id: Record<string, string> = {
sideChatBlockFailed: 'Gagal',
sideChatBlockDone: 'Selesai',
sideChatBlockNoOutput: '(tanpa output)',
sideChatBlockCommandLine: 'Baris perintah {line}',
codeBlockTitle: 'Blok kode',
codeBlockWrap: 'Bungkus baris',
codeBlockUnwrap: 'Jangan bungkus baris',
+1
View File
@@ -441,6 +441,7 @@ export const it: Record<string, string> = {
sideChatBlockFailed: 'Non riuscito',
sideChatBlockDone: 'Completato',
sideChatBlockNoOutput: '(nessun output)',
sideChatBlockCommandLine: 'Riga di comando {line}',
codeBlockTitle: 'Blocco di codice',
codeBlockWrap: 'A capo automatico',
codeBlockUnwrap: 'Nessun a capo',
+1
View File
@@ -450,6 +450,7 @@ export const ja: Record<string, string> = {
sideChatBlockFailed: '失敗',
sideChatBlockDone: '完了',
sideChatBlockNoOutput: '(出力なし)',
sideChatBlockCommandLine: 'コマンド行 {line}',
codeBlockTitle: 'コードブロック',
codeBlockWrap: '折り返しを有効にする',
codeBlockUnwrap: '折り返しを無効にする',
+1
View File
@@ -442,6 +442,7 @@ export const ko: Record<string, string> = {
sideChatBlockFailed: '실패',
sideChatBlockDone: '완료',
sideChatBlockNoOutput: '(출력 없음)',
sideChatBlockCommandLine: '명령어 {line}행',
codeBlockTitle: '코드 블록',
codeBlockWrap: '줄 바꿈',
codeBlockUnwrap: '줄 바꿈 해제',
+1
View File
@@ -448,6 +448,7 @@ export const nl: Record<string, string> = {
sideChatBlockFailed: 'Mislukt',
sideChatBlockDone: 'Voltooid',
sideChatBlockNoOutput: '(geen uitvoer)',
sideChatBlockCommandLine: 'Opdrachtregel {line}',
codeBlockTitle: 'Codeblok',
codeBlockWrap: 'Regels afbreken',
codeBlockUnwrap: 'Regels niet afbreken',
+1
View File
@@ -452,6 +452,7 @@ export const pl: Record<string, string> = {
sideChatBlockFailed: 'Niepowodzenie',
sideChatBlockDone: 'Zakończono',
sideChatBlockNoOutput: '(brak wyniku)',
sideChatBlockCommandLine: 'Wiersz polecenia {line}',
codeBlockTitle: 'Blok kodu',
codeBlockWrap: 'Zawijanie wierszy',
codeBlockUnwrap: 'Bez zawijania wierszy',
+1
View File
@@ -433,6 +433,7 @@ export const pt: Record<string, string> = {
sideChatBlockFailed: 'Falhou',
sideChatBlockDone: 'Concluído',
sideChatBlockNoOutput: '(sem saída)',
sideChatBlockCommandLine: 'Linha de comando {line}',
codeBlockTitle: 'Bloco de código',
codeBlockWrap: 'Quebrar linhas',
codeBlockUnwrap: 'Não quebrar linhas',
+1
View File
@@ -448,6 +448,7 @@ export const ru: Record<string, string> = {
sideChatBlockFailed: 'Ошибка',
sideChatBlockDone: 'Готово',
sideChatBlockNoOutput: '(нет вывода)',
sideChatBlockCommandLine: 'Строка команды {line}',
codeBlockTitle: 'Блок кода',
codeBlockWrap: 'Переносить строки',
codeBlockUnwrap: 'Не переносить строки',
+1
View File
@@ -433,6 +433,7 @@ export const sv: Record<string, string> = {
sideChatBlockFailed: 'Misslyckades',
sideChatBlockDone: 'Klar',
sideChatBlockNoOutput: '(ingen utdata)',
sideChatBlockCommandLine: 'Kommandorad {line}',
codeBlockTitle: 'Kodblock',
codeBlockWrap: 'Radbrytning',
codeBlockUnwrap: 'Ingen radbrytning',
+1
View File
@@ -450,6 +450,7 @@ export const th: Record<string, string> = {
sideChatBlockFailed: 'ล้มเหลว',
sideChatBlockDone: 'เสร็จสิ้น',
sideChatBlockNoOutput: '(ไม่มีเอาต์พุต)',
sideChatBlockCommandLine: 'บรรทัดคำสั่ง {line}',
codeBlockTitle: 'บล็อกโค้ด',
codeBlockWrap: 'ตัดบรรทัดอัตโนมัติ',
codeBlockUnwrap: 'ไม่ตัดบรรทัด',
+1
View File
@@ -450,6 +450,7 @@ export const tr: Record<string, string> = {
sideChatBlockFailed: 'Başarısız',
sideChatBlockDone: 'Tamamlandı',
sideChatBlockNoOutput: '(çıktı yok)',
sideChatBlockCommandLine: 'Komut satırı {line}',
codeBlockTitle: 'Kod bloğu',
codeBlockWrap: 'Satırları kaydır',
codeBlockUnwrap: 'Satırları kaydırma',
+1
View File
@@ -450,6 +450,7 @@ export const vi: Record<string, string> = {
sideChatBlockFailed: 'Thất bại',
sideChatBlockDone: 'Hoàn tất',
sideChatBlockNoOutput: '(không có đầu ra)',
sideChatBlockCommandLine: 'Dòng lệnh {line}',
codeBlockTitle: 'Khối mã',
codeBlockWrap: 'Ngắt dòng',
codeBlockUnwrap: 'Không ngắt dòng',
+1
View File
@@ -465,6 +465,7 @@ export const zhHK: Record<string, string> = {
sideChatBlockFailed: '失敗',
sideChatBlockDone: '完成',
sideChatBlockNoOutput: '(無輸出)',
sideChatBlockCommandLine: '指令第 {line} 行',
codeBlockTitle: '程式碼區塊',
codeBlockWrap: '自動換行',
codeBlockUnwrap: '取消自動換行',
+1
View File
@@ -465,6 +465,7 @@ export const zhMO: Record<string, string> = {
sideChatBlockFailed: '失敗',
sideChatBlockDone: '完成',
sideChatBlockNoOutput: '(無輸出)',
sideChatBlockCommandLine: '指令第 {line} 行',
codeBlockTitle: '程式碼區塊',
codeBlockWrap: '自動換行',
codeBlockUnwrap: '取消自動換行',
+1
View File
@@ -465,6 +465,7 @@ export const zhTW: Record<string, string> = {
sideChatBlockFailed: '失敗',
sideChatBlockDone: '完成',
sideChatBlockNoOutput: '(無輸出)',
sideChatBlockCommandLine: '指令第 {line} 行',
codeBlockTitle: '程式碼區塊',
codeBlockWrap: '自動換行',
codeBlockUnwrap: '取消自動換行',
+2
View File
@@ -462,6 +462,7 @@ export const zh = {
sideChatBlockFailed: '失败',
sideChatBlockDone: '完成',
sideChatBlockNoOutput: '(无输出)',
sideChatBlockCommandLine: '命令第 {line} 行',
codeBlockTitle: '代码块',
codeBlockWrap: '自动换行',
codeBlockUnwrap: '取消自动换行',
@@ -1084,6 +1085,7 @@ export const en: Record<keyof typeof zh, string> = {
sideChatBlockFailed: 'Failed',
sideChatBlockDone: 'Done',
sideChatBlockNoOutput: '(no output)',
sideChatBlockCommandLine: 'Command line {line}',
codeBlockTitle: 'Code block',
codeBlockWrap: 'Wrap lines',
codeBlockUnwrap: 'Do not wrap lines',
+1 -1
View File
@@ -819,7 +819,7 @@ export function matchUrlTarget(tabs: readonly TabDescriptor[], url: URL): TabDes
* The plugin version this service instance reports. Keep in lockstep with
* `package.json`'s version — `tests/service.spec.ts` asserts the pair.
*/
export const SIDEBAR_SERVICE_VERSION = '0.27.0'
export const SIDEBAR_SERVICE_VERSION = '0.28.0-alpha.0'
/**
* Monotonic capability list consumers use to gate new API usage (features
+30 -38
View File
@@ -1,3 +1,5 @@
/// <reference lib="esnext.disposable" preserve="true" />
/**
* Structural types for the cordis services this plugin consumes, plus the
* Context face both halves share.
@@ -90,7 +92,7 @@ export interface SidebarWebServer {
registerUpgrade(route: SidebarWebUpgradeRoute): () => void
}
/** A published session's header slice the sidebar reads (authoritative cwd). */
/** A published session's immutable original-project metadata. */
export interface SidebarSessionHeader {
cwd?: string
}
@@ -99,6 +101,9 @@ export interface SidebarSessionHeader {
export interface SidebarSessionStore {
get(id: string): {
header: SidebarSessionHeader
/** Live cursor and indexed reads avoid copying the whole log for cache identity. */
readonly seq?: number
eventAt?(seq: number): SidebarSessionEvent | undefined
/**
* The live session's append-only event log as an immutable snapshot.
* Read-only access — the jobs.output route replays `job_output`
@@ -110,13 +115,16 @@ export interface SidebarSessionStore {
}
/**
* The web runtime service face (mirror of @deepseek-ai/dsh-web-app's
* WebRuntimeValues): the bind-derived trust list the /api gateway's fence
* accepts — LAN IP literals sampled when the server binds all interfaces,
* plus explicit `--trusted-host` authorities.
* Host request admission plus the client transport recovery face.
*/
export interface SidebarWebRuntime {
trustedHosts: readonly string[]
export interface SidebarConnectionService {
/** Public Host/Origin and authentication policy (DSH 0.2.0-rc.2+). */
requestRejection(request: { headers: Record<string, string | string[] | undefined> }): 401 | 403 | undefined
state: {
getSnapshot(): 'connected' | 'disconnected' | 'connecting' | undefined
subscribe(listener: () => void): () => void
}
reconnect(): void
}
/** Registration options the sidebar passes to `ctx.slots.register` (subset of the real options). */
@@ -685,20 +693,6 @@ export interface SidebarWorkspacesService {
}
}
/**
* The invariant service face (mirror of @deepseek-ai/dsh-invariants'
* InvariantRegistry). The upstream augmentation does not reach this Context
* (dual-cordis-instance resolution), so the register signature is restated
* structurally, exactly like the other service faces above.
*/
export interface SidebarInvariantsService {
/** Reserve one package's checks and install them in the service's child fiber. */
register(
packageName: string,
installer: (ctx: Context, fail: (message: string) => never) => void | Promise<void>,
): () => void
}
/**
* The settings service face (mirror of `@deepseek-ai/dsh-settings`'
* `SettingsForms`).
@@ -799,14 +793,25 @@ export interface SidebarContextShape {
webServer: SidebarWebServer
/** The session store (host `.get`) and the client list feed (`.list`) faces. */
sessions: SidebarSessionStore & SidebarSessionsService
/** The web runtime trust list (bind-derived). */
webRuntime: SidebarWebRuntime
/** Committed current execution directory; the header keeps the original project. */
workingDirectory: {
readonly defaultDirectory?: string
get(session: { header: SidebarSessionHeader }): string
}
/** Host-owned live/prepared observation, including cold-session projections. */
sessionQuery: {
observeSession(id: string, options: { projectionMode: 'all' }): Promise<{
header: SidebarSessionHeader
projections?: { values: { workingDirectory?: string | null } }
[Symbol.dispose](): void
}>
}
/** Native host request admission and client transport recovery. */
connection: SidebarConnectionService
/** The client slot registry (register/inject). */
slots: SidebarSlotsService
/** The settings service face (prefs persistence + namespace reads). */
settings: SidebarSettingsService
/** The invariant registry face. */
invariants: SidebarInvariantsService
/** The tool registry face. */
tools: SidebarToolsService
/** The client locale service face. */
@@ -839,19 +844,6 @@ export interface SidebarContextShape {
sessionTitle: SidebarSessionTitleService
/** The host session-persistence service (optional; side chat cold resume). */
sessionPersistence: SidebarSessionPersistenceService
/**
* The client connection lifecycle (DSH 0.1.2-alpha.2+; optional so older
* hosts and test fakes simply hide the disconnect banner): the observable
* recovery state of the Remote transport (`undefined` before the first
* connection outcome) and an immediate-reconnect request.
*/
connection?: {
state: {
getSnapshot(): 'connected' | 'disconnected' | 'connecting' | undefined
subscribe(listener: () => void): () => void
}
reconnect(): void
}
/** The composer draft face (client ui-conversation, lazy `ctx.get` probe). */
conversation: SidebarConversation
/** Host-authoritative workspace membership; resolved lazily at reference insertion. */
+31 -30
View File
@@ -2,12 +2,9 @@
* dsh-better-sidebar host half: the /sidebar JSON API (explorer listing, file
* read/write, git), the /sidebar/file media route (images), the /sidebar/html
* preview route, the /sidebar/bundle lazy-chunk route (client code splits),
* and the two WebSocket upgrades (sidebar_open pushes). Every route passes the same
* browser-trust fence as the /api gateway — Host-header loopback or the
* web runtime's `trustedHosts` (LAN IP literals sampled at boot plus
* `--trusted-host` authorities), read per request from the live service
* value so the fence tracks the same trust source the /api gateway derives
* its list from.
* and the WebSocket upgrades. Every route delegates admission to the same
* public Connection service as the /api gateway (Host/Origin and browser
* authentication), read per request.
*
* All operations are conversation-scoped: requests carry a sessionId and the
* session's authoritative cwd comes from the session store.
@@ -36,7 +33,6 @@ import { ensureWorkspacePath } from './path-security.ts'
import { searchFiles } from './fs-search.ts'
import { compileExcludePatterns } from './exclude-patterns.ts'
import { decodeHtmlUrl } from './html-route.ts'
import { isTrustedApiRequest } from './trust-fence.ts'
import { registerBundleRoute } from './bundle-route.ts'
import { createDirectoryWatchers, type DirectoryWatchers } from './fs-watch.ts'
import { createSidechatPushHub } from './sidechat-push.ts'
@@ -112,8 +108,8 @@ export interface SidebarFsLevel {
error?: string
}
/** Services required before mounting: the webserver routes, the session store, the web runtime's trusted hosts, and the tool registry. */
export const inject = ['webServer', 'sessions', 'webRuntime', 'tools']
/** Services required before mounting: routes, sessions, native request admission, and tools. */
export const inject = ['webServer', 'sessions', 'connection', 'tools']
/** Content types for the media route, by extension. */
const MEDIA_TYPES: Record<string, string> = {
@@ -137,24 +133,31 @@ export function mediaTypeForPath(path: string): string {
}
/**
* Resolve a session's authoritative working directory. The attached session
* header wins; while the session is still hydrating from persistence (the
* web client attaches the current conversation a moment after page load, so
* the very first sidebar requests can arrive detached) the caller's own
* list-summary cwd is used; the session-persistence index is queried as a
* last resort for cold (not-yet-attached) sessions so a detached first
* request still resolves the correct project instead of the host process
* cwd (which on Windows is the DSH source root after `dsh.cmd`'s `pushd`,
* causing every user-project path to be misclassified as "outside
* workspace"). The host process cwd is the FINAL fallback for deployments
* without persistence (tests / stripped-down hosts); production always
* provides persistence, so the bug-fix path (header → client → persistence)
* always resolves the real session cwd before reaching it.
* Resolve the committed execution directory before client or original-header
* hints. Live reads are synchronous; detached reads use the host observation
* lease and its revision-keyed projection cache, never a plugin-owned log fold
* or TTL that could hide a working_directory change.
*/
async function sessionCwdOf(ctx: Context, sessionId: string, clientCwd?: string): Promise<string> {
const session = ctx.sessions.get(sessionId)
const headerCwd = session?.header.cwd
if (headerCwd !== undefined && headerCwd !== '') return headerCwd
// The immutable header is the original project, not the current execution
// directory. Read the host's committed value on every request (no TTL).
if (session !== undefined) {
const cwd = ctx.get('workingDirectory')?.get(session) ?? session.header.cwd
if (cwd !== undefined && cwd !== '') return cwd
}
const query = ctx.get('sessionQuery')
if (query !== undefined) {
const observation = await query.observeSession(sessionId, { projectionMode: 'all' })
try {
const cwd = observation.projections?.values.workingDirectory
?? observation.header.cwd
?? ctx.get('workingDirectory')?.defaultDirectory
if (cwd !== undefined && cwd !== '') return requireAbsolute(cwd)
} finally {
observation[Symbol.dispose]()
}
}
if (clientCwd !== undefined && clientCwd !== '') {
try {
return requireAbsolute(clientCwd)
@@ -1301,18 +1304,16 @@ async function importLegacyPrefs(
/**
* Plugin body: mount the fenced routes and the sidebar_open push socket.
* @param ctx - host plugin context (webServer, sessions, webRuntime).
* @param ctx - host plugin context (webServer, sessions, connection).
* @param config - deployment-provided limits; the Loader validates against
* {@link Config} and fills defaults, direct callers get them from
* {@link resolveSidebarConfig}.
*/
export function apply(ctx: Context, config?: SidebarConfig): void {
const resolved = resolveSidebarConfig(config)
// The web runtime's bind-derived trust list (boot-sampled LAN literals
// plus --trusted-host authorities) — the authoritative source the /api
// gateway fence derives its list from. Read per request from the live
// service value; a replaced list takes effect without a plugin restart.
const fence = (req: SidebarHttpRequest): boolean => isTrustedApiRequest(req, ctx.webRuntime.trustedHosts)
// Connection owns both deployment trust and authentication; never infer or
// bypass its policy from invocation flags or a copied trust list.
const fence = (req: SidebarHttpRequest): boolean => ctx.connection.requestRejection(req) === undefined
// The model-facing open-request registry: queues `sidebar_open` requests
// per session and pushes them to connected sidebar views over the
// `/sidebar/ws/agent-opens` socket.
-32
View File
@@ -1,32 +0,0 @@
/**
* Package-owned invariant companion for `dsh-better-sidebar`.
* @module dsh-better-sidebar/invariant
*/
/* jscpd:ignore-start */
import type { Context } from './context-types.ts'
const PACKAGE_NAME = 'dsh-better-sidebar'
/** Cordis companion plugin name. */
export const name = 'dsh-better-sidebar-invariant'
/** Service required before the companion can reserve package ownership. */
export const inject = ['invariants']
/**
* No runtime invariant: the sidebar owns no service state or event protocol
* of its own — every route is mounted under the host's webServer fence, the
* pty lifecycle is exercised by the smoke spec, and the panel's store is a
* plain snapshot registry asserted by the behavior specs. The route fence,
* pty quota, and store semantics are each observed through their seams.
*/
const install: () => void = () => {}
/**
* Register this package's invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
/* jscpd:ignore-end */
+16 -3
View File
@@ -616,6 +616,8 @@ export function buildSidechatApi(ctx: Context, live?: AssistantLiveBuffer): Side
throw new SidebarError('sidechat-error', `parent session "${sessionId}" is not running`, 409)
}
const parentSession = parent.session
const workingDirectory = ctx.get('workingDirectory')
const parentCwd = workingDirectory?.get(parentSession) ?? parentSession.header.cwd
// The parent's CURRENT model route. agent.options freezes the
// creation-time deployment default — a composer model switch rides
// `model/selection` events + the session-local selection and never
@@ -651,13 +653,24 @@ export function buildSidechatApi(ctx: Context, live?: AssistantLiveBuffer): Side
...(routeProvider === undefined ? {} : { agentProvider: routeProvider }),
...(routeModel === undefined ? {} : { agentModel: routeModel }),
})
// A truncated inheritance can end before the parent's last directory
// change. Header cwd alone cannot win: the host projection replays seed
// working-directory/change events over it. Stamp the committed directory
// at the seed boundary, using the host-owned event rather than refolding
// its history or asking set() to enqueue a synthetic user notice.
const directorySeed: SeedEvent[] = workingDirectory === undefined ? [] : [{
type: 'working-directory/change',
seq: inheritance.seed.length,
time: Date.now(),
data: { cwd: parentCwd },
}]
const descriptorEvent: SeedEvent = {
type: 'subagent/descriptor',
seq: inheritance.seed.length,
seq: inheritance.seed.length + directorySeed.length,
time: Date.now(),
data: descriptor as unknown as Record<string, unknown>,
}
const seed = [...inheritance.seed, descriptorEvent]
const seed = [...inheritance.seed, ...directorySeed, descriptorEvent]
// Fork-marker fields (the exact shape the host's own session.fork uses,
// api-session-controller): without `isSeeded` + `inheritedEventCount` the
// session treats the whole seed as the child's OWN events, so the child's
@@ -684,7 +697,7 @@ export function buildSidechatApi(ctx: Context, live?: AssistantLiveBuffer): Side
const options: CreateAgentOptions = {
sessionId: childId,
meta: {
...(parentSession.header.cwd === undefined ? {} : { cwd: parentSession.header.cwd }),
...(parentCwd === undefined ? {} : { cwd: parentCwd }),
parentSession: parentSession.id,
isSeeded: true,
origin: 'subagent',
-126
View File
@@ -1,126 +0,0 @@
/**
* Browser-trust fence for the sidebar routes, copied from the /api gateway's
* fence in @deepseek-ai/dsh-client-connection
* (src/api-request-trust.ts + src/loopback-hostname.ts, BSD-3-Clause,
* copied here because the package does not export these helpers and the
* plugin must not depend on its internals) with one addition: the desktop
* shell's application origin, which reaches only the routes the shell does not
* forward. Host-header loopback or a configured trusted authority passes;
* cross-site browser markers refuse.
* This is a DNS-rebinding / cross-site defense, not authentication.
*/
import type { IncomingHttpHeaders } from 'node:http'
/** The request facts the fence reads (structural subset of IncomingMessage). */
interface ApiTrustRequest {
headers: IncomingHttpHeaders
/** Present on a real node request; the bfcache exception is media-route only. */
method?: string
url?: string
}
function header(headers: IncomingHttpHeaders, name: string): string | undefined {
const value = headers[name]
return typeof value === 'string' ? value : undefined
}
/**
* Origin of the Electron desktop shell's application page. The shell serves the
* GUI from the `dsh-app:` scheme, so a page-initiated WebSocket handshake
* carries this origin while the socket itself targets the Host's loopback
* authority — an authority match is impossible by construction. The shell's own
* request forwarder admits exactly this non-null origin and refuses every other
* one; WebSocket upgrades bypass that forwarder (the scheme handler does not
* carry them), which is why this fence is the first place the shell origin is
* ever compared against a request.
*/
const SHELL_APP_ORIGIN = 'dsh-app://app'
/** Normalized URL of a Host-header authority, or undefined when unparsable. */
function parseAuthority(authority: string): URL | undefined {
try {
return new URL(`http://${authority}`)
} catch {
return undefined
}
}
/** Whether a normalized URL hostname names the local loopback authority. */
export function isLoopbackHostname(hostname: string): boolean {
if (hostname === 'localhost' || hostname === '[::1]') return true
const parts = hostname.split('.')
return parts.length === 4
&& parts[0] === '127'
&& parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
}
/** Canonical authority form: hostname, or hostname:port when a port was written. */
function canonicalAuthority(entry: string, entryUrl: URL): string {
const port = entryUrl.port !== '' ? entryUrl.port : new URL(`https://${entry}`).port
return port === '' ? entryUrl.hostname : `${entryUrl.hostname}:${port}`
}
/** Whether the request authority matches a trustedHosts entry (exact or port-less). */
function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): boolean {
return trustedHosts.some((entry) => {
const entryUrl = parseAuthority(entry)
if (entryUrl === undefined) return false
return canonicalAuthority(entry, entryUrl) === entryUrl.hostname
? entryUrl.hostname === hostUrl.hostname
: entryUrl.host === hostUrl.host
})
}
/**
* Decide whether one sidebar request may reach the plugin routes.
* @param request - node HTTP request facts (headers, and the method/url the
* media-route exception is scoped to).
* @param trustedHosts - non-loopback authorities this deployment serves.
* @returns true when the Host is ours (loopback or trusted) and browser markers are same-origin.
*/
export function isTrustedApiRequest(request: ApiTrustRequest, trustedHosts: readonly string[]): boolean {
const host = header(request.headers, 'host')
if (host === undefined) return false
const hostUrl = parseAuthority(host)
if (hostUrl === undefined) return false
if (!isLoopbackHostname(hostUrl.hostname) && !isTrustedAuthority(hostUrl, trustedHosts)) return false
const fetchSite = header(request.headers, 'sec-fetch-site')
if (fetchSite === 'cross-site') {
// Chromium can restore a same-origin image from bfcache with a stale
// cross-site marker. The exception is deliberately narrow: the media route
// only, browser image subresources only (`no-cors` + `image`), and the
// unforgeable Referer must name this exact authority. API requests, uploads,
// HTML previews, foreign embeds and Referer-less requests stay refused.
const referer = header(request.headers, 'referer')
const mediaRequest = request.method === 'GET' && (request.url ?? '').startsWith('/sidebar/file')
const restoredImage = mediaRequest
&& header(request.headers, 'sec-fetch-mode') === 'no-cors'
&& header(request.headers, 'sec-fetch-dest') === 'image'
&& referer !== undefined
&& (() => {
try {
return new URL(referer).host === hostUrl.host
} catch {
return false
}
})()
if (!restoredImage) return false
}
// Origin fence: when a browser attaches an Origin it must name this
// hostname (the Host fence above already bound the authority, so the port
// must not re-decide trust). Comparing hostname, not host: some Chromium
// builds (Edge 151) serialize the Origin of a non-default-port loopback page
// without the port, and refusing those bricks every /sidebar route. Absent
// Origin is fine — the Host fence above already bound the request. The
// literal "null" (sandboxed iframes, file: pages) is an opaque origin, refused.
const origin = header(request.headers, 'origin')
if (origin === undefined) return true
// Checked only after the Host fence above bound the authority: the shell
// page's fixed origin is admitted as itself, never as an authority.
if (origin === SHELL_APP_ORIGIN) return true
try {
return new URL(origin).hostname === hostUrl.hostname
} catch {
return false
}
}
+20 -20
View File
@@ -75,26 +75,27 @@ function sessionCtx(cwd: string, calls: Array<Record<string, unknown>>): Context
}
/**
* The same live-session face with the session LOOKUP counted. The root cache is
* consulted before the session is ever read, so `lookups()` is the observable
* difference between "answered from the TTL cache" and "scanned the event log
* again" — which is what makes the no-rescan assertion below discriminative.
* Count actual event-log snapshots, not cheap session scans. Alpha.5 reads the
* live cursor to invalidate explicit directory changes, even on a cache hit;
* that must not copy or rescan the log during the TTL window.
*/
function countingSessionCtx(cwd: string, calls: Array<Record<string, unknown>>): { ctx: Context; lookups: () => number } {
let lookups = 0
function countingSessionCtx(cwd: string, calls: Array<Record<string, unknown>>): { ctx: Context; scans: () => number } {
let scans = 0
const ctx = {
sessions: {
get: () => {
lookups += 1
return {
header: { cwd },
snapshotEvents: () => calls.map((data, index) => ({ type: 'tool/call', seq: index, time: index, data })),
snapshotEvents: () => {
scans += 1
return calls.map((data, index) => ({ type: 'tool/call', seq: index, time: index, data }))
},
}
},
},
get: () => undefined,
} as never
return { ctx: ctx as Context, lookups: () => lookups }
return { ctx: ctx as Context, scans: () => scans }
}
describe('active worktree root', () => {
@@ -165,7 +166,7 @@ describe('active worktree root', () => {
const repo = join(root, 'repo')
try {
initRepo(repo, 'a.txt')
const { ctx, lookups } = countingSessionCtx(repo, [])
const { ctx, scans } = countingSessionCtx(repo, [])
probed.length = 0
const answers = await Promise.all(
Array.from({ length: 8 }, () => activeWorktreeRootOf(ctx, 's-burst', repo)),
@@ -173,7 +174,7 @@ describe('active worktree root', () => {
expect(probed).toEqual([repo])
// The whole resolution is shared, not just the spawn: the event log is
// read (and scanned) once for the burst.
expect(lookups()).toBe(1)
expect(scans()).toBe(1)
// Every concurrent caller still gets the resolved answer.
expect(new Set(answers)).toEqual(new Set([realpathSync.native(repo)]))
} finally {
@@ -192,13 +193,13 @@ describe('active worktree root', () => {
const repo = join(root, 'repo')
try {
initRepo(repo, 'a.txt')
const { ctx, lookups } = countingSessionCtx(repo, [])
const { ctx, scans } = countingSessionCtx(repo, [])
probed.length = 0
await Promise.all(
Array.from({ length: 6 }, (_unused, index) => activeWorktreeRootOf(ctx, `s-shared-${index}`, repo)),
)
expect(probed).toEqual([repo])
expect(lookups()).toBe(6)
expect(scans()).toBe(6)
} finally {
removeTree(root)
}
@@ -213,18 +214,17 @@ describe('active worktree root', () => {
mkdirSync(join(repo, 'src'))
// A tool call INSIDE the repository: scanning it costs a probe, and the
// answer is the repository top level.
const { ctx, lookups } = countingSessionCtx(repo, [{ cwd: join(repo, 'src') }])
const { ctx, scans } = countingSessionCtx(repo, [{ cwd: join(repo, 'src') }])
const first = await activeWorktreeRootOf(ctx, 's-ttl', repo)
expect(first).toBe(realpathSync.native(repo))
expect(lookups()).toBe(1)
expect(scans()).toBe(1)
expect(probed.length).toBeGreaterThan(0)
probed.length = 0
await expect(activeWorktreeRootOf(ctx, 's-ttl', repo)).resolves.toBe(first)
// No spawn AND no event-log scan (the cache is consulted before the
// session is read, so the scan never starts).
// No spawn AND no event-log snapshot/scan, despite checking the live cursor.
expect(probed).toEqual([])
expect(lookups()).toBe(1)
expect(scans()).toBe(1)
} finally {
removeTree(root)
}
@@ -240,7 +240,7 @@ describe('active worktree root', () => {
const repo = join(root, 'repo')
try {
initRepo(repo, 'a.txt')
const { ctx, lookups } = countingSessionCtx(repo, [])
const { ctx, scans } = countingSessionCtx(repo, [])
const first = await activeWorktreeRootOf(ctx, 's-ttl-span', repo)
probed.length = 0
const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 10_000)
@@ -250,7 +250,7 @@ describe('active worktree root', () => {
clock.mockRestore()
}
expect(probed).toEqual([])
expect(lookups()).toBe(1)
expect(scans()).toBe(1)
} finally {
removeTree(root)
}
+1 -1
View File
@@ -177,7 +177,7 @@ function responseRecorder(): { res: SidebarHttpResponse; wire: Wire } {
function mountHost(): { api: SidebarWebRoute; download: SidebarWebRoute } {
const routes: SidebarWebRoute[] = []
const ctx = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
+16
View File
@@ -0,0 +1,16 @@
/** alpha.5 requires an accessible name for each authored terminal command line. */
import { afterEach, describe, expect, it } from 'vitest'
import { terminalBlockLabels } from '../src/client/block-labels.ts'
import { attachLocale } from '../src/client/locales.ts'
afterEach(() => { attachLocale(undefined) })
describe('terminal command line labels', () => {
it.each([
['en', 'Command line 2'],
['zh', '命令第 2 行'],
])('localizes the one-based line number in %s', (active, expected) => {
attachLocale({ getSnapshot: () => ({ active }) })
expect(terminalBlockLabels().commandLine(2)).toBe(expected)
})
})
+4 -1
View File
@@ -552,6 +552,7 @@ describe('ChangesTab', () => {
it('renders exactly one clean empty state, and the graph has its own', async () => {
mockGit([])
mockGraphEmpty()
vi.spyOn(api, 'changesOps').mockResolvedValue({ events: [], lastSeq: 0 })
const container = document.createElement('div')
document.body.append(container)
@@ -565,9 +566,11 @@ describe('ChangesTab', () => {
// A clean repository says it ONCE: both sections (unstaged/staged) used
// to print their own "no changes" line under the same message. The Graph
// area says its own (it is a separate section, with its own route).
const empties = [...container.querySelectorAll<HTMLElement>('[data-kind="empty"]')]
const gitLens = container.querySelector<HTMLElement>('[data-git-root]')!
const empties = [...gitLens.querySelectorAll<HTMLElement>('[data-kind="empty"]')]
.map(node => node.textContent)
expect(empties).toEqual([t('changesClean')])
expect(container.querySelector('[aria-labelledby$="-session"]')!.textContent).toContain(t('changesSessionEmpty'))
expect(container.querySelector('[data-scm-section="graph"]')!.textContent).toContain(t('graphEmpty'))
// No resource group or tree row is rendered when nothing changed.
expect(container.querySelectorAll('[data-group]')).toHaveLength(0)
+51
View File
@@ -0,0 +1,51 @@
/**
* Host baseline contract: package DSH peers/dev pins, standalone installers,
* e2e fallback/version check and CI must move together, without floating CLI tags.
*/
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
const baseline = '0.2.1-alpha.5'
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
const bash = readFileSync(new URL('../scripts/install.sh', import.meta.url), 'utf8')
const powershell = readFileSync(new URL('../scripts/install.ps1', import.meta.url), 'utf8')
const e2e = readFileSync(new URL('../scripts/e2e-common.sh', import.meta.url), 'utf8')
const ci = readFileSync(new URL('../.github/workflows/ci.yml', import.meta.url), 'utf8')
describe('DSH host baseline', () => {
it('keeps all DSH package peers and dev pins on the exact baseline', () => {
for (const [section, prefix] of [['peerDependencies', '^'], ['devDependencies', '']] as const) {
const entries = Object.entries(pkg[section]).filter(([name]) => name.startsWith('@deepseek-ai/dsh-'))
expect(entries.length, section).toBeGreaterThan(0)
for (const [name, version] of entries) {
expect(version, `${section}.${name}`).toBe(`${prefix}${baseline}`)
}
}
})
it('does not publish or depend on the retired invariant companion', () => {
expect(pkg.exports).not.toHaveProperty('./invariant')
expect(pkg.files).not.toContain('lib/invariant.js')
for (const section of ['peerDependencies', 'devDependencies', 'dependencies']) {
expect(pkg[section]).not.toHaveProperty('@deepseek-ai/dsh-invariants')
}
})
it('pins both standalone installer npx fallbacks', () => {
expect(bash).toContain(`printf 'npx -y --package @deepseek-ai/dsh@${baseline} dsh'`)
expect(powershell).toContain(`$cliArgs = @('-y', '--package', '@deepseek-ai/dsh@${baseline}', 'dsh', 'plugin'`)
for (const source of [bash, powershell]) {
expect(source).not.toMatch(/^\s*(?:source|\.)\s+[^\r\n]*e2e-common/m)
}
})
it('pins the e2e fallback and expected version to the same baseline', () => {
expect(e2e).toContain('DSH_NPX_SPEC="${DSH_NPX_SPEC:-@deepseek-ai/dsh@' + baseline + '}"')
expect(e2e).toContain('expected="${DSH_EXPECT_VERSION:-' + baseline + '}"')
})
it('pins CI with its heap budget and peer resolution intact', () => {
expect(ci).toContain(`NODE_OPTIONS: --max-old-space-size=4096\n run: npm install -g @deepseek-ai/dsh@${baseline}\n`)
expect(ci).not.toMatch(/^\s*run:.*--legacy-peer-deps/m)
})
})
+1 -26
View File
@@ -14,7 +14,7 @@ import { mkdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect, type APIRequestContext, type Page } from '@playwright/test'
import { PAGE_URL, createHostApi, hostRpc, sendFirstMessage } from './host'
import { PAGE_URL, createHostApi, dismissOnboarding, hostRpc, sendFirstMessage } from './host'
/** 本用例自己的 workspace(与其它 spec 互不干扰)。 */
const WORKSPACE_PATH = join(tmpdir(), 'dsh-e2e-blank-session-workspace')
@@ -36,31 +36,6 @@ test.afterAll(async () => {
await api?.dispose()
})
/** keyless 启动会叠一层 onboarding 浮层(吃掉指针事件):先等它出现,再反复点掉。 */
async function dismissOnboarding(page: Page): Promise<void> {
try {
await expect
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
.toBeGreaterThan(0)
} catch {
return
}
for (let round = 0; round < 10; round++) {
let dismissed = false
for (const name of ['Continue', 'Configure later']) {
const button = page.getByRole('button', { name, exact: true }).first()
if ((await button.count()) === 0) continue
try {
await button.click({ timeout: 4_000 })
dismissed = true
await page.waitForTimeout(1_000)
} catch {
// 被更上层浮层挡住:下一轮换另一个按钮再试。
}
}
if (!dismissed) break
}
}
/** 屏幕内可见的底部入口数量(与插件探针同一判据:rect 与视口相交)。 */
async function onScreenCount(page: Page): Promise<number> {
+2 -5
View File
@@ -3,7 +3,7 @@ import { mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect } from '@playwright/test'
import { createHostApi, gotoPage, hostRpc, sendFirstMessage, sidebarApi } from './host'
import { createHostApi, dismissOnboarding, gotoPage, hostRpc, sendFirstMessage, sidebarApi } from './host'
// A dedicated fixture: never initialize or write the caller's working repository.
test('read-only Git Graph renders merge history and filters without checkout', async ({ page }, testInfo) => {
@@ -35,10 +35,7 @@ test('read-only Git Graph renders merge history and filters without checkout', a
expect(response.ok()).toBe(true)
await gotoPage(page)
await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 90_000 })
for (const label of [/^Continue$/, /^Configure later$/]) {
const button = page.getByRole('button', { name: label }).first()
try { await button.click({ timeout: 8_000 }) } catch { /* onboarding may already be dismissed */ }
}
await dismissOnboarding(page)
await sendFirstMessage(page)
await page.locator('[data-sidebar-right-expand]').first().click()
await page.locator('[data-sidebar-right-guide-entry="git"]').click()
+2 -5
View File
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect, type Page } from '@playwright/test'
import { createHostApi, gotoPage, hostRpc, sendFirstMessage } from './host'
import { createHostApi, dismissOnboarding, gotoPage, hostRpc, sendFirstMessage } from './host'
/**
* A SELECTED change row must stay an in-flow 28px band inside its own
@@ -120,10 +120,7 @@ function rowGeometryProblems(page: Page, expected: SelectedRow | null): Promise<
* the expand control is gone once the sidebar is open). */
async function openGitPage(page: Page): Promise<void> {
await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 90_000 })
for (const label of [/^Continue$/, /^Configure later$/]) {
const button = page.getByRole('button', { name: label }).first()
try { await button.click({ timeout: 8_000 }) } catch { /* onboarding may already be dismissed */ }
}
await dismissOnboarding(page)
await sendFirstMessage(page)
await page.locator('[data-sidebar-right-expand]').first().click()
await page.locator('[data-sidebar-right-guide-entry="git"]').click()
+35
View File
@@ -117,6 +117,41 @@ export async function gotoPage(page: Page, extra: Record<string, string> = {}):
await page.goto(pageUrl(extra), { waitUntil: 'domcontentloaded' })
}
/** Dismiss keyless onboarding before interacting with the shell. */
export async function dismissOnboarding(page: Page): Promise<void> {
// alpha.5's Close belongs to Get started, not to another panel or dialog.
const getStarted = page.getByRole('dialog', { name: 'Get started', exact: true })
const buttons = [
getStarted.getByRole('button', { name: 'Close', exact: true }),
page.getByRole('button', { name: 'Continue', exact: true }),
page.getByRole('button', { name: 'Configure later', exact: true }),
]
try {
await expect.poll(async () => {
const counts = await Promise.all(buttons.map(button => button.count()))
return counts.reduce((total, count) => total + count, 0)
}, { timeout: 60_000 }).toBeGreaterThan(0)
} catch {
// A previously acknowledged onboarding may not appear again.
return
}
for (let round = 0; round < 8; round++) {
let dismissed = false
for (const button of buttons) {
if (await button.count() === 0) continue
try {
await button.click({ timeout: 4_000 })
dismissed = true
await page.waitForTimeout(1_000)
} catch {
// A stacked welcome notice can mask another onboarding step.
}
}
if (!dismissed) break
}
await expect(getStarted).not.toBeVisible()
}
/** Authenticated request context for host RPC seeding (cookie attached). */
export async function createHostApi(): Promise<APIRequestContext> {
return request.newContext({
+2 -40
View File
@@ -30,8 +30,8 @@
import { mkdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect, type APIRequestContext, type Page } from '@playwright/test'
import { PAGE_URL, createHostApi, gotoPage, hostRpc, sendFirstMessage, sidebarApi } from './host'
import { test, expect, type APIRequestContext } from '@playwright/test'
import { PAGE_URL, createHostApi, dismissOnboarding, gotoPage, hostRpc, sendFirstMessage, sidebarApi } from './host'
/** Workspace the sidebar renders against (created by the lane's seeding). */
const WORKSPACE_PATH = process.env.DSH_E2E_WORKSPACE ?? join(tmpdir(), 'dsh-e2e-workspace')
@@ -155,44 +155,6 @@ test.beforeAll(async () => {
await seedSession()
})
/**
* Dismiss the keyless boot's onboarding takeovers, which mask the whole shell:
* a versioned welcome notice ("Continue", persists its acknowledgement to
* settings) and, once that is acknowledged, a provider-config dialog
* ("Configure later", session-only — always present while no credential is
* configured). Both mount only after the settings join resolves. Wait
* (bounded) for one to appear; a DSH build without onboarding proceeds
* straight on.
*
* Dismissal loops until none remain, in any stacking order — a masked click is
* retried next round instead of failing.
* @param page - the lane's page.
*/
async function dismissOnboarding(page: Page): Promise<void> {
try {
await expect
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
.toBeGreaterThan(0)
} catch {
console.warn('[e2e] no onboarding takeover appeared; proceeding without dismissal')
}
for (let round = 0; round < 8; round++) {
let dismissed = false
for (const name of ['Continue', 'Configure later']) {
const button = page.getByRole('button', { name, exact: true }).first()
if ((await button.count()) === 0) continue
try {
await button.click({ timeout: 4_000 })
dismissed = true
await page.waitForTimeout(1_000)
} catch {
// Masked by the takeover stacked above it; the next round tries the
// other button first.
}
}
if (!dismissed) break
}
}
test.afterAll(async () => {
await api?.dispose()
+2 -27
View File
@@ -27,7 +27,7 @@ import { mkdirSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect, type APIRequestContext } from '@playwright/test'
import { PAGE_URL, createHostApi, hostRpc, sendFirstMessage } from './host'
import { PAGE_URL, createHostApi, dismissOnboarding, hostRpc, sendFirstMessage } from './host'
/** Workspace the sidebar renders against (created by this lane's seeding). */
const WORKSPACE_PATH = process.env.DSH_E2E_WORKSPACE ?? join(tmpdir(), 'dsh-e2e-workspace')
@@ -80,32 +80,7 @@ test('the native tab types survive an in-page client entry replacement', async (
const sidebar = page.locator('[data-dsh-better-sidebar]')
await expect(sidebar).toBeAttached({ timeout: 90_000 })
// A keyless boot stacks onboarding takeovers over the shell (versioned
// welcome notice, then the provider-config dialog). Same bounded dismissal
// loop as the mount lane: a masked click is retried, an absent takeover is
// fine.
try {
await expect
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
.toBeGreaterThan(0)
} catch {
console.warn('[e2e] no onboarding takeover appeared; proceeding without dismissal')
}
for (let round = 0; round < 8; round++) {
let dismissed = false
for (const name of ['Continue', 'Configure later']) {
const button = page.getByRole('button', { name, exact: true }).first()
if ((await button.count()) === 0) continue
try {
await button.click({ timeout: 4_000 })
dismissed = true
await page.waitForTimeout(1_000)
} catch {
// Masked by the takeover stacked above it; the next round tries again.
}
}
if (!dismissed) break
}
await dismissOnboarding(page)
// The session header (and with it the native right sidebar's controls) only
// exists once the session has a turn — the mount lane does the same.
+2 -28
View File
@@ -37,8 +37,8 @@
import { mkdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect, type APIRequestContext, type Page } from '@playwright/test'
import { PAGE_URL, createHostApi, hostRpc, sendFirstMessage } from './host'
import { test, expect, type APIRequestContext } from '@playwright/test'
import { PAGE_URL, createHostApi, dismissOnboarding, hostRpc, sendFirstMessage } from './host'
/** This lane's own workspace (lanes run serially against one server — never
* share seed paths with mount/drag). */
@@ -104,32 +104,6 @@ interface ResourceStat {
duration: number
}
/** Dismiss whatever onboarding takeover is present (same dance as the other
* lanes) so the pointer can reach the sidebar's controls. */
async function dismissOnboarding(page: Page): Promise<void> {
try {
await expect
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
.toBeGreaterThan(0)
} catch {
console.warn('[e2e-perf] no onboarding takeover appeared; proceeding')
}
for (let round = 0; round < 8; round++) {
let dismissed = false
for (const name of ['Continue', 'Configure later']) {
const button = page.getByRole('button', { name, exact: true }).first()
if ((await button.count()) === 0) continue
try {
await button.click({ timeout: 4_000 })
dismissed = true
await page.waitForTimeout(1_000)
} catch {
// Masked by a takeover stacked above; retry in the next round.
}
}
if (!dismissed) break
}
}
test('measure: mount latency, longtasks and bundle cost through a full tab sweep', async ({ page }) => {
await page.addInitScript(PERF_PROBE)
+1 -26
View File
@@ -19,7 +19,7 @@ import { execFileSync } from 'node:child_process'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { test, expect, type APIRequestContext, type Page } from '@playwright/test'
import { PAGE_URL, createHostApi, hostRpc, sendFirstMessage } from './host'
import { PAGE_URL, createHostApi, dismissOnboarding, hostRpc, sendFirstMessage } from './host'
/** Git must not pick up the developer's identity/config inside the lane. */
const GIT_ENV = {
@@ -110,31 +110,6 @@ test.afterAll(async () => {
await api?.dispose()
})
/** Dismiss whatever onboarding takeover is present (the other lanes' dance). */
async function dismissOnboarding(page: Page): Promise<void> {
try {
await expect
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
.toBeGreaterThan(0)
} catch {
console.warn('[e2e-scroll] no onboarding takeover appeared; proceeding')
}
for (let round = 0; round < 8; round++) {
let dismissed = false
for (const name of ['Continue', 'Configure later']) {
const button = page.getByRole('button', { name, exact: true }).first()
if ((await button.count()) === 0) continue
try {
await button.click({ timeout: 4_000 })
dismissed = true
await page.waitForTimeout(1_000)
} catch {
// Masked by the takeover stacked above; retry in the next round.
}
}
if (!dismissed) break
}
}
/** Open the native Sidebar, then the plugin's Files page inside it. */
async function openFiles(page: Page): Promise<void> {
+2 -18
View File
@@ -44,8 +44,8 @@
import { mkdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect, type APIRequestContext, type Page } from '@playwright/test'
import { PAGE_URL, createHostApi, hostRpc, sendFirstMessage } from './host'
import { test, expect, type APIRequestContext } from '@playwright/test'
import { PAGE_URL, createHostApi, dismissOnboarding, hostRpc, sendFirstMessage } from './host'
import { removeTree } from '../temp-tree.ts'
/** This lane's own workspace: a 40-child directory plus a small sibling. */
@@ -84,22 +84,6 @@ test.beforeAll(async () => {
test.afterAll(async () => { await api?.dispose() })
async function dismissOnboarding(page: Page): Promise<void> {
try {
await expect
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
.toBeGreaterThan(0)
} catch { /* a build without onboarding proceeds straight to the tree */ }
for (let round = 0; round < 8; round++) {
let dismissed = false
for (const name of ['Continue', 'Configure later']) {
const button = page.getByRole('button', { name, exact: true }).first()
if ((await button.count()) === 0) continue
try { await button.click({ timeout: 4_000 }); dismissed = true; await page.waitForTimeout(1_000) } catch { /* masked */ }
}
if (!dismissed) break
}
}
/**
* Install the census: follow the pane's tree body (through a replacement, so a
+2 -2
View File
@@ -26,7 +26,7 @@ import type { SidebarWebRoute } from '../src/context-types.ts'
import { removeTree } from './temp-tree.ts'
interface FakeContext {
webRuntime: { trustedHosts: readonly string[] }
connection: { requestRejection: () => undefined }
webServer: {
register: (route: SidebarWebRoute) => () => void
registerUpgrade: () => () => void
@@ -67,7 +67,7 @@ function workspace(name: string): string {
async function serve(workspace: string): Promise<{ origin: string; routes: SidebarWebRoute[] }> {
const routes: SidebarWebRoute[] = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: { register: (route) => { routes.push(route); return () => {} }, registerUpgrade: () => () => {} },
sessions: { get: () => ({ header: { cwd: workspace } }) },
tools: { register: () => () => {} },
+2 -2
View File
@@ -143,7 +143,7 @@ describe('createWorkspaceFile', () => {
* editor reads.
*/
interface FakeContext {
webRuntime: { trustedHosts: readonly string[] }
connection: { requestRejection: () => undefined }
webServer: {
register: (route: SidebarWebRoute) => () => void
registerUpgrade: () => () => void
@@ -160,7 +160,7 @@ interface FakeContext {
function mountApi(workspace: string): SidebarWebRoute {
const routes: SidebarWebRoute[] = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: { register: (route) => { routes.push(route); return () => {} }, registerUpgrade: () => () => {} },
sessions: { get: () => ({ header: { cwd: workspace } }) },
tools: { register: () => () => {} },
+2 -2
View File
@@ -26,7 +26,7 @@ import type { SidebarWebRoute } from '../src/context-types.ts'
import { removeTree } from './temp-tree.ts'
interface FakeContext {
webRuntime: { trustedHosts: readonly string[] }
connection: { requestRejection: () => undefined }
webServer: {
register: (route: SidebarWebRoute) => () => void
registerUpgrade: () => () => void
@@ -56,7 +56,7 @@ function workspaceWith(name: string, contents: Buffer | string): string {
function mountApi(workspace: string): SidebarWebRoute {
const routes: SidebarWebRoute[] = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: { register: (route) => { routes.push(route); return () => {} }, registerUpgrade: () => () => {} },
sessions: { get: () => ({ header: { cwd: workspace } }) },
tools: { register: () => () => {} },
+2 -2
View File
@@ -32,7 +32,7 @@ import type { SidebarWebRoute } from '../src/context-types.ts'
import { removeTree } from './temp-tree.ts'
interface FakeContext {
webRuntime: { trustedHosts: readonly string[] }
connection: { requestRejection: () => undefined }
webServer: {
register: (route: SidebarWebRoute) => () => void
registerUpgrade: () => () => void
@@ -56,7 +56,7 @@ interface Mounted {
function mountApi(workspace: string): Mounted {
const routes: SidebarWebRoute[] = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: { register: (route) => { routes.push(route); return () => {} }, registerUpgrade: () => () => {} },
sessions: { get: () => ({ header: { cwd: workspace } }) },
tools: { register: () => () => {} },
+1 -1
View File
@@ -92,7 +92,7 @@ function makeRemoteFixture(): RemoteFixture {
function mount(): { route: SidebarWebRoute } {
const routes: SidebarWebRoute[] = []
const ctx = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (_route: SidebarWebUpgradeRoute) => () => {},
+1 -1
View File
@@ -208,7 +208,7 @@ function mount(setup: {
},
logger: { info: () => {}, warn: () => {} },
profileContext: undefined,
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (_route: SidebarWebUpgradeRoute) => () => {},
+1 -1
View File
@@ -142,7 +142,7 @@ describe('DSH community-market manifest compatibility', () => {
const dshPeers = Object.keys(peers).filter(name => name === '@deepseek-ai/dsh' || name.startsWith('@deepseek-ai/dsh-'))
expect(dshPeers.length).toBeGreaterThan(10)
for (const name of dshPeers) {
expect(peers[name], name).toMatch(/^\^0\.2\.0-[a-z0-9.]+$/)
expect(peers[name], name).toMatch(/^\^0\.2\.1-alpha\.5$/)
}
})
})
+1 -1
View File
@@ -17,7 +17,7 @@ describe('dsh-better-sidebar plugin export shape', () => {
const unwrapped = loader.unwrapExports(sidebar) as Record<string, unknown>
expect(unwrapped).toBe(sidebar)
expect(unwrapped.name).toBe('dsh-better-sidebar')
expect(unwrapped.inject).toEqual(['webServer', 'sessions', 'webRuntime', 'tools'])
expect(unwrapped.inject).toEqual(['webServer', 'sessions', 'connection', 'tools'])
expect(unwrapped.Config).toBeDefined()
expect(typeof unwrapped.apply).toBe('function')
})
+26 -57
View File
@@ -9,14 +9,12 @@
* conversation, same provider context-cache prefix — while the shadowed
* bulk never lands in the durable copy. The construction is verified with
* the REAL fold (`foldSurface` from `@deepseek-ai/dsh-session/surface`) and
* pinned against the REAL session relational invariants
* (`@deepseek-ai/dsh-session/invariant`): when the tail cannot be proven
* checked by the real session seed validator: when the tail cannot be proven
* equivalent, the builder falls back to today's verbatim full copy.
*/
import { describe, expect, it } from 'vitest'
import { deriveEventMessage, foldSurface } from '@deepseek-ai/dsh-session/surface'
import { Session, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant'
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
import { buildSidechatInheritance } from '../src/sidechat-core.ts'
import type { SidebarSessionEvent } from '../src/context-types.ts'
@@ -264,23 +262,18 @@ function expectContiguous(seed: readonly { seq: number }[]): void {
seed.forEach((event, index) => expect(event.seq).toBe(index))
}
/** Run the REAL session relational invariants over one candidate log and
* return the failure messages (empty = the log satisfies them). */
function invariantFailures(log: readonly SidebarSessionEvent[]): string[] {
const failures: string[] = []
const session = { snapshotEvents: () => log }
const ctx = {
sessions: { list: () => [session] },
on: () => {},
invariants: {
register: (_pkg: string, installer: (c: unknown, f: (m: string) => void) => void) => {
installer(ctx, (message: string) => { failures.push(message) })
return () => {}
},
},
}
void SessionInvariant.apply(ctx as never)
return failures
/** Validate a complete inherited seed through the same real constructor as the routes. */
function expectAcceptedSeed(seed: readonly SidebarSessionEvent[]): void {
const id = 'session-compaction-seed-acceptance' as SessionId
const session = Session.create(
id,
seed as unknown as readonly SessionEvent[],
{ version: SESSION_FORMAT_VERSION, id, createdAt: Date.now(), isSeeded: true },
SessionLogOffset(seed.length),
)
expect(session.snapshotEvents()).toHaveLength(seed.length + 1)
expect(session.ownEvents()).toHaveLength(1)
expect(session.ownEvents()[0]?.type).toBe('session/end-seed')
}
describe('buildSidechatInheritance compaction tail', () => {
@@ -322,15 +315,6 @@ describe('buildSidechatInheritance compaction tail', () => {
expect(child).toEqual(parent)
})
it('satisfies the real session relational invariants', () => {
const events = compactedLog()
const { seed } = buildSidechatInheritance(events)
expect(seed.length).toBeLessThan(events.length)
expect(invariantFailures(events)).toEqual([])
expect(invariantFailures(seed)).toEqual([])
expect(invariantFailures(buildSidechatInheritance(turn(0, 1, { callId: 'c1' }).events).seed)).toEqual([])
})
it('is accepted by the real dsh-session seed validator', () => {
const events = compactedLog()
const { seed } = buildSidechatInheritance(events)
@@ -338,19 +322,8 @@ describe('buildSidechatInheritance compaction tail', () => {
// inherited cut) — this is the layer that once rejected a seed whose
// surfaceOp markers were stripped, so it gates every envelope decision
// the rebasing makes.
const id = 'session-compaction-seed-acceptance'
const session = Session.create(
id as SessionId,
seed as never,
{ version: SESSION_FORMAT_VERSION, id: id as SessionId, createdAt: Date.now(), isSeeded: true },
SessionLogOffset(seed.length),
)
// The constructor appends the inherited-cut marker right after the seed,
// and that marker is the child's first own event (log position = the
// inherited count) — same shape as today's full-copy threads.
expect(session.snapshotEvents()).toHaveLength(seed.length + 1)
expect(session.ownEvents()).toHaveLength(1)
expect(session.ownEvents()[0]?.type).toBe('session/end-seed')
// The constructor also appends the child's first own end-seed marker.
expectAcceptedSeed(seed)
})
it('falls back to the verbatim full copy when the log has no compaction', () => {
@@ -417,7 +390,7 @@ describe('buildSidechatInheritance compaction tail', () => {
expect(seed.at(-2)?.type).toBe('step/end')
expect(seed.at(-1)?.type).toBe('turn/end')
expect((seed.at(-1) as { data?: { reason?: { kind?: string } } }).data?.reason?.kind).toBe('interrupted')
expect(invariantFailures(seed)).toEqual([])
expectAcceptedSeed(seed)
})
it('delivers the dangling-tool snapshot on the trimmed tail (mid-turn compaction)', () => {
@@ -432,6 +405,7 @@ describe('buildSidechatInheritance compaction tail', () => {
expect(seed.at(-1)?.type).not.toBe('tool/call')
expect(snapshot).not.toBeNull()
expect(JSON.stringify(snapshot)).toContain('bash')
expectAcceptedSeed(seed)
})
it('skips shadowed nodes and orphaned calls when the region ends mid-turn', () => {
@@ -448,8 +422,8 @@ describe('buildSidechatInheritance compaction tail', () => {
expect(seed.some(event => JSON.stringify(event).includes('mid result'))).toBe(false)
expect(seed.some(event => JSON.stringify(event).includes('a2 kept'))).toBe(true)
expect(visibleSequence(seed)).toEqual(visibleSequence(events))
expectAcceptedSeed(seed)
expectContiguous(seed)
expect(invariantFailures(seed)).toEqual([])
})
it('remaps replace operations that stay inside the tail', () => {
@@ -484,6 +458,7 @@ describe('buildSidechatInheritance compaction tail', () => {
expect(rebased).toBeDefined()
expect(rebased?.surfaceOp?.startSeq).toBeLessThan(rebased?.seq ?? 0)
expect(rebased?.surfaceOp?.endSeq).toBeLessThan(rebased?.seq ?? 0)
expectAcceptedSeed(seed)
})
it('trims when the protected head was rewritten mid-session (turn 1, later step)', () => {
@@ -528,7 +503,7 @@ describe('buildSidechatInheritance compaction tail', () => {
expect(head?.data?.turn).toBe(1)
expect(head?.data?.step).toBe(1)
expect(visibleSequence(seed)).toEqual(visibleSequence(events))
expect(invariantFailures(seed)).toEqual([])
expectAcceptedSeed(seed)
})
it('trims when the pruner rewrote a keep-window tool result mid-turn', () => {
@@ -578,7 +553,7 @@ describe('buildSidechatInheritance compaction tail', () => {
const record = seed.find(event => event.type === 'compaction/prune') as { data?: { shadowedSeqs?: number[] } }
expect(record?.data?.shadowedSeqs?.[0]).toBe(replacement?.surfaceOp?.startSeq)
expect(visibleSequence(seed)).toEqual(visibleSequence(events))
expect(invariantFailures(seed)).toEqual([])
expectAcceptedSeed(seed)
})
it('trims when the keep window opens on a turn whose inbox insert precedes its turn/start', () => {
@@ -612,16 +587,9 @@ describe('buildSidechatInheritance compaction tail', () => {
const splices = seed.filter(event => event.type === 'agent/inbox/spliced')
expect(splices.length).toBeGreaterThanOrEqual(2)
expect(visibleSequence(seed)).toEqual(visibleSequence(events))
expect(invariantFailures(seed)).toEqual([])
// The real validator accepts (this is the layer that rejected the
// pre-fix seed on the real session).
const id = 'session-inbox-splice-acceptance'
Session.create(
id as SessionId,
seed as never,
{ version: SESSION_FORMAT_VERSION, id: id as SessionId, createdAt: Date.now(), isSeeded: true },
SessionLogOffset(seed.length),
)
expectAcceptedSeed(seed)
})
it('drops a mid-keep compaction group atomically when its citations fall in the dropped span', () => {
@@ -685,12 +653,13 @@ describe('buildSidechatInheritance compaction tail', () => {
const seedGroups = seed.filter(event => event.type === 'compaction/start' || event.type === 'compaction/summary' || event.type === 'compaction/end')
expect(seedGroups).toEqual([])
expect(visibleSequence(seed)).toEqual(visibleSequence(events))
expect(invariantFailures(seed)).toEqual([])
expectAcceptedSeed(seed)
// Control: the same log without the consumed group (its four trailing
// events) cuts at cp0 instead and also trims.
const control = events.slice(0, -4)
const controlSeed = buildSidechatInheritance(control).seed
expect(controlSeed.length).toBeLessThan(control.length)
expectAcceptedSeed(controlSeed)
})
it('drops a command/done atomically when its run falls in the dropped span', () => {
@@ -732,7 +701,7 @@ describe('buildSidechatInheritance compaction tail', () => {
expect(seed.some(event => event.type === 'command/done')).toBe(false)
expect(seed.some(event => event.type === 'command/run')).toBe(false)
expect(visibleSequence(seed)).toEqual(visibleSequence(events))
expect(invariantFailures(seed)).toEqual([])
expectAcceptedSeed(seed)
// Together: a command that runs INSIDE the keep window and settles
// there — both records ride, and the done's citation remaps onto the
@@ -759,7 +728,7 @@ describe('buildSidechatInheritance compaction tail', () => {
// The citation names a non-command event (the user message), not the run.
expect(trimmed.seed[citedIdx]?.type).toBe('user/message')
expect(visibleSequence(trimmed.seed)).toEqual(visibleSequence(together))
expect(invariantFailures(trimmed.seed)).toEqual([])
expectAcceptedSeed(trimmed.seed)
})
it('reuses the previous compaction when the newest summary is orphaned', () => {
+76 -1
View File
@@ -8,10 +8,14 @@
* afterSeq deltas, tail cap, live/persisted sources).
*/
import { describe, expect, it, vi } from 'vitest'
import { resolve } from 'node:path'
import WorkingDirectoryService from '@deepseek-ai/dsh-working-directory'
import { Session, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
import { SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent'
import { buildSidechatApi } from '../src/sidechat-routes.ts'
import { SidebarError } from '../src/wire.ts'
import { SIDE_BOUNDARY_PROMPT, SIDE_INJECTION_SOURCE_KIND, SIDE_NEW_THREAD_TITLE, sideLabel } from '../src/sidechat-core.ts'
import { buildSidechatInheritance, SIDE_BOUNDARY_PROMPT, SIDE_INJECTION_SOURCE_KIND, SIDE_NEW_THREAD_TITLE, sideLabel } from '../src/sidechat-core.ts'
import type { Context } from '../src/context-types.ts'
/** A fake live agent (inject/followup/cancel/inbox spied). */
@@ -107,8 +111,10 @@ function ctxWith(services: {
sessionPersistence?: unknown
llm?: unknown
sessionController?: unknown
workingDirectory?: unknown
}): Context {
const table: Record<string, unknown> = {
...(services.workingDirectory === undefined ? {} : { workingDirectory: services.workingDirectory }),
...(services.agents === undefined ? {} : { agents: services.agents }),
...(services.agentPresets === undefined ? {} : { agentPresets: services.agentPresets }),
...(services.sessionTitle === undefined ? {} : { sessionTitle: services.sessionTitle }),
@@ -130,6 +136,75 @@ function ev(type: string, seq: number, data: Record<string, unknown> = {}): { ty
}
describe('sidechat.start', () => {
it('creates a sidechat in the current execution directory, not the original header cwd', async () => {
const parent = agent('parent')
const services = happyServices(parent, agent('child'))
const get = vi.fn((session: unknown) => {
expect(session).toBe(parent.session)
return '/current-execution-directory'
})
const api = buildSidechatApi(ctxWith({ ...services, workingDirectory: { get } }))
await api['sidechat.start']({ sessionId: 'parent', question: 'current project' })
expect(services.create.mock.calls[0]![0]).toMatchObject({ meta: { cwd: '/current-execution-directory' } })
expect(get).toHaveBeenCalledOnce()
})
it('stamps current cwd after a truncated seed so the real working-directory projection cannot restore an older cwd', async () => {
const original = resolve('/original-project')
const previous = resolve('/previous-execution')
const current = resolve('/current-execution')
const parent = agent('parent', {
header: { cwd: original },
events: [
ev('working-directory/change', 0, { cwd: previous }),
ev('turn/start', 1, { turn: 1 }),
ev('step/start', 2, { turn: 1, step: 1 }),
ev('working-directory/change', 3, { cwd: current }),
ev('tool/call', 4, { turn: 1, step: 1, callId: 'pending', name: 'bash', arguments: '{}' }),
],
})
type DirectoryProjection = {
init(header: { cwd?: string }): string | null
apply(state: string | null, event: SessionEvent): string | null
}
let registered: DirectoryProjection | undefined
// Capture the REAL alpha.5 unit contributed by the host service. These
// context seams do not run system-prompt assembly, fs checks, or notices.
const workingDirectory = new WorkingDirectoryService({
reflect: { provide: () => {} },
sessionProjections: {
register: (definition: DirectoryProjection) => { registered = definition },
stateOf: (session: { header: { cwd?: string }; snapshotEvents(): SessionEvent[] }) => {
if (registered === undefined) throw new Error('working-directory unit not registered')
return session.snapshotEvents().reduce((cwd, event) => registered!.apply(cwd, event), registered.init(session.header))
},
},
systemPrompt: { context: () => {}, getContextOrder: () => 0 },
on: () => {},
effect: () => {},
} as never, {})
expect(workingDirectory.get(parent.session as never)).toBe(current)
const services = happyServices(parent, agent('child'))
await buildSidechatApi(ctxWith({ ...services, workingDirectory }))['sidechat.start']({ sessionId: 'parent' })
const options = services.create.mock.calls[0]![0] as {
sessionId: SessionId; meta: Partial<SessionHeader>; seed: readonly SessionEvent[]; inheritedEventCount: number
}
const projection = registered!
// Control proves that merely changing meta.cwd is insufficient: the
// dangling-call cut dropped current but retained previous in the seed.
const unstamped = buildSidechatInheritance(parent.session.snapshotEvents() as never).seed
expect(unstamped.map(event => event.type)).toEqual(['working-directory/change'])
expect(unstamped.reduce((cwd, event) => projection.apply(cwd, event as SessionEvent), projection.init({ cwd: current }))).toBe(previous)
const child = Session.create(options.sessionId, options.seed, {
...options.meta, id: options.sessionId, version: SESSION_FORMAT_VERSION, createdAt: Date.now(), isSeeded: true,
}, SessionLogOffset(options.inheritedEventCount))
expect(child.header.cwd).toBe(current)
expect(options.seed.every((event, index) => event.seq === index)).toBe(true)
expect(child.ownEvents()[0]?.type).toBe('session/end-seed')
expect(workingDirectory.get(child)).toBe(current)
expect(options.seed.at(-2)).toMatchObject({ type: 'working-directory/change', data: { cwd: current } })
})
it('creates a seeded subagent-origin child and admits the boundary + question', async () => {
const parent = agent('parent', {
events: [
+165 -8
View File
@@ -54,7 +54,7 @@ const canCreateSymlink = (() => {
})()
interface FakeContext {
webRuntime: { trustedHosts: readonly string[] }
connection: { requestRejection: () => undefined }
webServer: {
register: (route: SidebarWebRoute) => () => void
registerUpgrade: (route: SidebarWebUpgradeRoute) => () => void
@@ -95,7 +95,7 @@ describe('host plugin smoke', () => {
const upgrades: SidebarWebUpgradeRoute[] = []
const effects: Array<() => void | (() => void)> = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: {
register: (route) => { routes.push(route); return () => {} },
registerUpgrade: (route) => { upgrades.push(route); return () => {} },
@@ -147,7 +147,7 @@ describe('host plugin smoke', () => {
const upgrades: SidebarWebUpgradeRoute[] = []
const effects: Array<() => void | (() => void)> = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: {
register: () => () => {},
registerUpgrade: (route) => { upgrades.push(route); return () => {} },
@@ -197,7 +197,7 @@ describe('host plugin smoke', () => {
const routes: SidebarWebRoute[] = []
const effects: Array<() => void | (() => void)> = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: {
register: (route) => { routes.push(route); return () => {} },
registerUpgrade: () => () => {},
@@ -495,6 +495,8 @@ describe('git destructive operations (scratch repository)', () => {
describe('session cwd resolution over the API route', () => {
interface CtxOverrides {
workingDirectory?: { readonly defaultDirectory?: string; get: (session: { header: { cwd?: string } }) => string }
sessionQuery?: { observeSession: (id: string, options: { projectionMode: 'all' }) => Promise<{ header: { cwd?: string }; projections?: { values: { workingDirectory?: string | null } }; [Symbol.dispose](): void }> }
sessions?: { get: (id: string) => { header: { cwd?: string } } | undefined }
sessionPersistence?: { open: (id: string, access: 'read' | 'write') => Promise<{ header: { cwd?: string }; read: () => Promise<{ events: never[] }>; close: () => Promise<void> }> }
}
@@ -503,7 +505,7 @@ describe('session cwd resolution over the API route', () => {
const routes: SidebarWebRoute[] = []
lastMountedRoutes = routes
const ctx = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
@@ -517,7 +519,7 @@ describe('session cwd resolution over the API route', () => {
// The session/agent event feeds: nothing emits in these tests.
on: () => () => {},
// No jobs/agents services in the smoke context: the routes degrade.
get: (key: string) => key === 'sessionPersistence' ? overrides.sessionPersistence : undefined,
get: (key: string) => overrides[key as keyof CtxOverrides],
}
apply(ctx as never)
return routes
@@ -693,6 +695,161 @@ describe('session cwd resolution over the API route', () => {
}
})
it('follows committed working-directory changes immediately, without reusing the old active-root cache', async () => {
const first = resolvePath('/working-directory-first')
const second = resolvePath('/working-directory-second')
let current = first
const session = { header: { cwd: resolvePath('/original-project') } }
const route = mount({
sessions: { get: () => session },
workingDirectory: { get: (received) => { expect(received).toBe(session); return current } },
})
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-switch', cwd: '/stale-client' })).toMatchObject({ ok: true, value: { cwd: first } })
current = second
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-switch', cwd: '/stale-client' })).toMatchObject({ ok: true, value: { cwd: second } })
})
it('routes file and Git reads to the new execution directory immediately after a switch', async () => {
const scratch = realpathSync.native(mkdtempSync(join(tmpdir(), 'sidebar-wd-switch-')))
const first = join(scratch, 'first')
const second = join(scratch, 'second')
let current = first
try {
for (const [directory, branch] of [[first, 'first-project'], [second, 'second-project']]) {
mkdirSync(directory!)
writeFileSync(join(directory!, 'directory.txt'), branch!)
const result = spawnSync('git', ['init', '-q', '-b', branch!, directory!], { encoding: 'utf8' })
if (result.status !== 0) throw new Error(result.stderr)
}
const route = mount({
sessions: { get: () => ({ header: { cwd: first } }) },
workingDirectory: { get: () => current },
})
const payload = { sessionId: 'wd-files-git', cwd: first }
expect(await invoke(route, 'fs.read', { ...payload, path: 'directory.txt' })).toMatchObject({ ok: true, value: { content: 'first-project' } })
expect(await invoke(route, 'git.status', payload)).toMatchObject({ ok: true, value: { branch: 'first-project' } })
current = second
expect(await invoke(route, 'fs.read', { ...payload, path: 'directory.txt' })).toMatchObject({ ok: true, value: { content: 'second-project' } })
expect(await invoke(route, 'git.status', payload)).toMatchObject({ ok: true, value: { branch: 'second-project' } })
} finally {
removeTree(scratch)
}
})
it('does not let historical linked-worktree tool evidence override a committed directory change back to the main checkout', async () => {
const scratch = realpathSync.native(mkdtempSync(join(tmpdir(), 'sidebar-wd-linked-')))
const main = join(scratch, 'main')
const linked = join(scratch, 'linked')
const run = (cwd: string, args: string[]): void => {
const result = spawnSync('git', ['-C', cwd, '-c', 'user.name=Test', '-c', 'user.email=test@dsh.invalid', ...args], { encoding: 'utf8' })
if (result.status !== 0) throw new Error(result.stderr)
}
try {
run(scratch, ['init', '-q', '-b', 'main', main])
run(main, ['commit', '-q', '--allow-empty', '-m', 'initial'])
run(main, ['worktree', 'add', '-q', '-b', 'linked', linked])
let current = linked
const events = [{ type: 'tool/call', seq: 0, time: 0, data: { cwd: linked } }] as Array<{ type: string; seq: number; time: number; data: { cwd: string } }>
const route = mount({
sessions: { get: () => ({ header: { cwd: main }, snapshotEvents: () => events }) },
workingDirectory: { get: () => current },
})
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-linked' })).toMatchObject({ ok: true, value: { cwd: linked } })
events.push({ type: 'working-directory/change', seq: 1, time: 1, data: { cwd: main } })
current = main
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-linked' })).toMatchObject({ ok: true, value: { cwd: main } })
expect(await invoke(route, 'git.status', { sessionId: 'wd-linked', cwd: linked })).toMatchObject({ ok: true, value: { branch: 'main' } })
// Same base: old tool evidence selected linked while the host cwd was
// still main. Explicit cd to main must invalidate that cached override.
const sameBaseEvents = events.slice(0, 1)
const snapshotEvents = vi.fn(() => sameBaseEvents)
const eventAt = vi.fn((seq: number) => sameBaseEvents[seq])
const session = { header: { cwd: main }, get seq() { return sameBaseEvents.length }, eventAt, snapshotEvents }
const sameBaseRoute = mount({
sessions: { get: () => session }, workingDirectory: { get: () => main },
})
const payload = { sessionId: 'wd-same-base' }
expect(await invoke(sameBaseRoute, 'session.cwd', payload)).toMatchObject({ ok: true, value: { cwd: linked } })
expect(await invoke(sameBaseRoute, 'session.cwd', payload)).toMatchObject({ ok: true, value: { cwd: linked } })
sameBaseEvents.push({ type: 'turn/start', seq: 1, time: 1, data: { cwd: main } })
expect(await invoke(sameBaseRoute, 'session.cwd', payload)).toMatchObject({ ok: true, value: { cwd: linked } })
expect(snapshotEvents).toHaveBeenCalledTimes(1)
sameBaseEvents.push({ type: 'working-directory/change', seq: 2, time: 2, data: { cwd: main } })
expect(await invoke(sameBaseRoute, 'session.cwd', payload)).toMatchObject({ ok: true, value: { cwd: main } })
expect(await invoke(sameBaseRoute, 'session.cwd', payload)).toMatchObject({ ok: true, value: { cwd: main } })
expect(snapshotEvents).toHaveBeenCalledTimes(2)
expect(eventAt).toHaveBeenCalledTimes(3)
} finally {
removeTree(scratch)
}
})
it('uses cold observation working-directory projections before stale client/header hints and releases every lease', async () => {
let current = resolvePath('/cold-execution-first')
let releases = 0
const route = mount({ sessionQuery: {
observeSession: async (id, options) => {
expect(id).toBe('wd-cold')
expect(options).toEqual({ projectionMode: 'all' })
return {
header: { cwd: resolvePath('/original-project') },
projections: { values: { workingDirectory: current } },
[Symbol.dispose]: () => { releases += 1 },
}
},
} })
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-cold', cwd: '/stale-client' })).toMatchObject({ ok: true, value: { cwd: current } })
current = resolvePath('/cold-execution-second')
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-cold', cwd: '/stale-client' })).toMatchObject({ ok: true, value: { cwd: current } })
expect(releases).toBe(2)
})
it('uses the host custom default for a null cold working-directory projection before a stale client hint', async () => {
const defaultDirectory = resolvePath('/configured-execution-default')
let releases = 0
const route = mount({
workingDirectory: { defaultDirectory, get: () => { throw new Error('cold reads must not call get without a live session') } },
sessionQuery: { observeSession: async () => ({
header: {}, projections: { values: { workingDirectory: null } },
[Symbol.dispose]: () => { releases += 1 },
}) },
})
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-cold-default', cwd: '/stale-client' })).toMatchObject({ ok: true, value: { cwd: defaultDirectory } })
expect(releases).toBe(1)
})
it('releases the cold observation lease when the working-directory projection cannot be read', async () => {
let releases = 0
const route = mount({ sessionQuery: {
observeSession: async () => ({
header: { cwd: resolvePath('/original-project') },
get projections(): never { throw new Error('working-directory projection failed') },
[Symbol.dispose]: () => { releases += 1 },
}),
} })
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-projection-failure', cwd: '/stale-client' })).toMatchObject({
ok: false, error: { message: 'working-directory projection failed' },
})
expect(releases).toBe(1)
})
it('does not mask failed authoritative working-directory reads with stale header or client hints', async () => {
const live = mount({
sessions: { get: () => ({ header: { cwd: resolvePath('/original-project') } }) },
workingDirectory: { get: () => { throw new Error('working-directory service failed') } },
})
expect(await invoke(live, 'session.cwd', { sessionId: 'wd-live-error', cwd: '/stale-client' })).toMatchObject({
ok: false, error: { message: 'working-directory service failed' },
})
const cold = mount({ sessionQuery: {
observeSession: async () => { throw new Error('working-directory observation failed') },
} })
expect(await invoke(cold, 'session.cwd', { sessionId: 'wd-cold-error', cwd: '/stale-client' })).toMatchObject({
ok: false, error: { message: 'working-directory observation failed' },
})
})
it('uses the client summary cwd while the session is detached', async () => {
const route = mount()
const result = await invoke(route, 'session.cwd', { sessionId: 's-detached', cwd: '/tmp/summary-cwd' })
@@ -1515,7 +1672,7 @@ const mountWithSettings = (settings?: unknown, home?: string): SidebarWebRoute =
const routes: SidebarWebRoute[] = []
lastMountedRoutes = routes
const ctx = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
@@ -1755,7 +1912,7 @@ describe('agent sidebar-open tool gating', () => {
configure: () => () => {},
}
const ctx = {
webRuntime: { trustedHosts: [] },
connection: { requestRejection: () => undefined },
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
+135 -374
View File
@@ -1,108 +1,17 @@
/**
* Remote-access trust regression tests: the /sidebar fence must accept a
* reverse-proxy domain or LAN IP listed in the DSH web runtime's
* `webRuntime.trustedHosts` — the same trust list the /api gateway accepts
* (LAN IP literals sampled at bind plus `--trusted-host` authorities).
*
* Regression: the fence used to read the connection row's trustedHosts
* through the Loader (`entry.options.name === 'connection'`, which never
* matched the row's module-specifier name), so trustedHosts stayed empty and
* every remote /sidebar request was 403 "forbidden".
*
* A second group pins the one origin the fence admits without an authority
* match: the desktop shell's `dsh-app://app` page, whose WebSocket upgrades
* reach the Host directly and therefore carry an origin no Host authority can
* name.
*/
import { describe, expect, it } from 'vitest'
import { mkdtempSync, writeFileSync } from 'node:fs'
import { Writable } from 'node:stream'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
/** The sidebar must use native Connection admission, never a reconstructed trust list. */
import { describe, expect, it, vi } from 'vitest'
import { apply } from '../src/index.ts'
import type { SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
import { removeTree } from './temp-tree.ts'
import type { SidebarHttpRequest, SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
interface FakeRes {
status: number
headers: Record<string, string>
body: string
writeHead(status: number, headers?: Record<string, string>): void
end(body?: string | Buffer): void
}
/**
* The response face these fence assertions read, backed by a REAL Writable.
*
* `/sidebar/file` STREAMS now (`createReadStream` → `pipeline` into the
* response), and `pipeline` needs an actual writable destination rather than a
* plain object with an `end`. The status/header/body facade the assertions use
* is layered on the same object, so the media cases keep reading exactly what
* they read before.
*/
function fakeRes(): FakeRes {
const chunks: Buffer[] = []
const stream = new Writable({
write(chunk: Buffer, _encoding, callback) {
chunks.push(Buffer.from(chunk))
callback()
},
})
// Captured BEFORE the facade shadows the method: `facade === stream`, so
// calling `stream.end()` from the replacement would recurse into itself.
const finishStream = Writable.prototype.end.bind(stream)
const facade = stream as unknown as FakeRes
facade.status = 0
facade.headers = {}
facade.body = ''
const collect = (): void => { facade.body = Buffer.concat(chunks).toString('utf8') }
facade.writeHead = (status, headers = {}) => {
facade.status = status
facade.headers = headers
}
facade.end = (body) => {
if (body !== undefined) chunks.push(Buffer.from(body))
collect()
finishStream()
}
// `stream.end()` from the pipeline path never goes through `facade.end`, so
// the body is also harvested once the writable finishes.
stream.on('finish', collect)
return facade
}
function req(
method: string,
url: string,
headers: Record<string, string>,
body = '{}',
): IncomingMessage {
const chunks = [Buffer.from(body)]
return {
method,
url,
headers,
[Symbol.asyncIterator]: async function* () {
for (const chunk of chunks) yield chunk
},
} as unknown as IncomingMessage
}
/** Mount apply() against a fake context with a replaceable webRuntime trust list. */
function mount(initialTrustedHosts: readonly string[] = []): {
api: (r: IncomingMessage, s: ServerResponse) => Promise<void>
upgrade: (path: string) => SidebarWebUpgradeRoute['handler']
media: (r: IncomingMessage, s: ServerResponse) => Promise<void>
setTrustedHosts: (hosts: readonly string[]) => void
cleanup: () => void
} {
const runtime = { trustedHosts: [...initialTrustedHosts] }
/** No retired webRuntime service: rc.2 and newer both expose Connection admission. */
function mount(initialRejection: 401 | 403 | undefined = undefined) {
let rejection = initialRejection
const connection = { requestRejection: vi.fn((_request: SidebarHttpRequest) => rejection) }
const routes: SidebarWebRoute[] = []
const upgrades: SidebarWebUpgradeRoute[] = []
const effects: Array<() => void | (() => void)> = []
const ctx = {
webRuntime: runtime,
const effects: Array<() => void> = []
apply({
connection,
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (route: SidebarWebUpgradeRoute) => { upgrades.push(route); return () => {} },
@@ -114,317 +23,169 @@ function mount(initialTrustedHosts: readonly string[] = []): {
if (typeof cleanup === 'function') effects.push(cleanup)
},
inject: () => () => {},
// The session/agent event feeds: nothing emits in these tests.
on: () => () => {},
get: () => undefined,
}
apply(ctx as never)
const api = routes.find(route => route.path === '/sidebar/api')?.handler
if (api === undefined) throw new Error('test setup: /sidebar/api route not registered')
const media = routes.find(route => route.path === '/sidebar/file')?.handler
if (media === undefined) throw new Error('test setup: /sidebar/file route not registered')
} as never)
return {
api: api as (r: IncomingMessage, s: ServerResponse) => Promise<void>,
upgrade: (path) => {
const handler = upgrades.find(route => route.path === path)?.handler
if (handler === undefined) throw new Error(`test setup: ${path} upgrade route not registered`)
return handler
},
media: media as (r: IncomingMessage, s: ServerResponse) => Promise<void>,
setTrustedHosts: (hosts) => { runtime.trustedHosts = [...hosts] },
connection,
routes,
upgrades,
setRejection: (next: 401 | 403 | undefined) => { rejection = next },
cleanup: () => { for (const cleanup of effects) cleanup() },
}
}
/** A remote-domain request with the browser markers a same-origin fetch sends. */
function remoteDomainRequest(): IncomingMessage {
return req('POST', '/sidebar/api/session.cwd', {
host: 'example.com',
'sec-fetch-site': 'same-origin',
origin: 'https://example.com',
}, '{"sessionId":"test-session"}')
function request(url: string, headers: SidebarHttpRequest['headers'] = { host: '127.0.0.1:3080' }) {
let reads = 0
const req: SidebarHttpRequest = {
method: 'POST',
url,
headers,
[Symbol.asyncIterator]: async function* () {
reads += 1
yield JSON.stringify({ sessionId: 'test-session' })
},
}
return { req, reads: () => reads }
}
/** A LAN-IP request with the browser markers a same-origin fetch sends. */
function lanRequest(): IncomingMessage {
return req('POST', '/sidebar/api/session.cwd', {
host: '192.0.2.1:3080',
'sec-fetch-site': 'same-origin',
origin: 'http://192.0.2.1:3080',
}, '{"sessionId":"test-session"}')
function response() {
const out = { status: 0, body: '' }
return {
out,
res: {
writeHead: (status: number) => { out.status = status },
end: (body?: string | Uint8Array) => { out.body += String(body ?? '') },
} as never,
}
}
describe('remote-access trust (webRuntime.trustedHosts)', () => {
it('accepts a reverse-proxy domain configured in webRuntime.trustedHosts', async () => {
const { api, cleanup } = mount(['example.com'])
describe('native Connection admission', () => {
it('accepts the native verdict without webRuntime and preserves the request and method receiver', async () => {
const mounted = mount()
try {
const res = fakeRes()
await api(remoteDomainRequest(), res as unknown as ServerResponse)
expect(res.status).toBe(200)
const { req } = request('/sidebar/api/session.cwd', {
host: 'example.com',
origin: 'https://example.com',
cookie: 'native-authenticated-session',
})
const { res, out } = response()
await mounted.routes.find(route => route.path === '/sidebar/api')!.handler(req, res)
expect(out.status).toBe(200)
expect(mounted.connection.requestRejection).toHaveBeenCalledExactlyOnceWith(req)
expect(mounted.connection.requestRejection.mock.contexts[0]).toBe(mounted.connection)
} finally {
cleanup()
mounted.cleanup()
}
})
it('accepts LAN IP literals from webRuntime.trustedHosts', async () => {
const { api, cleanup } = mount(['192.0.2.1'])
it.each([401, 403] as const)('refuses native %s on every HTTP route and WebSocket before consuming data', async (rejection) => {
const mounted = mount(rejection)
try {
const res = fakeRes()
await api(lanRequest(), res as unknown as ServerResponse)
expect(res.status).toBe(200)
expect(mounted.routes.map(route => route.path)).toEqual([
'/sidebar/api', '/sidebar/upload', '/sidebar/write', '/sidebar/bundle',
'/sidebar/archive', '/sidebar/file', '/sidebar/html',
])
expect(mounted.upgrades.map(route => route.path)).toEqual([
'/sidebar/ws/agent-opens', '/sidebar/ws/fs-watch', '/sidebar/ws/sidechat',
])
for (const route of mounted.routes) {
const input = request(route.path)
const { res, out } = response()
await route.handler(input.req, res)
expect(out.status, route.path).toBe(403)
expect(input.reads(), route.path).toBe(0)
expect(mounted.connection.requestRejection).toHaveBeenLastCalledWith(input.req)
}
for (const route of mounted.upgrades) {
const input = request(route.path)
const socket = { destroy: vi.fn() }
await route.handler(input.req, socket, new Uint8Array())
expect(socket.destroy, route.path).toHaveBeenCalledOnce()
expect(input.reads(), route.path).toBe(0)
expect(mounted.connection.requestRejection).toHaveBeenLastCalledWith(input.req)
}
expect(mounted.connection.requestRejection).toHaveBeenCalledTimes(10)
} finally {
cleanup()
mounted.cleanup()
}
})
it('stays loopback-only when webRuntime.trustedHosts is empty', async () => {
const { api, cleanup } = mount([])
it.each([null, false, 0, ''])('does not treat an unexpected falsy verdict (%s) as admission', async (verdict) => {
const mounted = mount()
try {
const remote = fakeRes()
await api(remoteDomainRequest(), remote as unknown as ServerResponse)
expect(remote.status).toBe(403)
const loopback = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', {
host: '127.0.0.1:3080',
'sec-fetch-site': 'same-origin',
}, '{"sessionId":"test-session"}'), loopback as unknown as ServerResponse)
expect(loopback.status).toBe(200)
mounted.connection.requestRejection.mockReturnValue(verdict as never)
for (const route of mounted.routes) {
const input = request(route.path)
const { res, out } = response()
await route.handler(input.req, res)
expect(out.status, route.path).toBe(403)
expect(input.reads(), route.path).toBe(0)
}
for (const route of mounted.upgrades) {
const input = request(route.path)
const socket = { destroy: vi.fn() }
await route.handler(input.req, socket, new Uint8Array())
expect(socket.destroy, route.path).toHaveBeenCalledOnce()
expect(input.reads(), route.path).toBe(0)
}
} finally {
cleanup()
mounted.cleanup()
}
})
it('accepts an Origin that names the Host hostname without its port (Edge 151 serialization)', async () => {
// Some Chromium builds serialize the Origin of a non-default-port loopback
// page without the port; refusing those bricks every /sidebar route.
const { api, cleanup } = mount([])
it('has no old-host fallback when native admission is missing', async () => {
const mounted = mount()
try {
const res = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', {
host: '127.0.0.1:3080',
'sec-fetch-site': 'same-origin',
origin: 'http://127.0.0.1',
}, '{"sessionId":"test-session"}'), res as unknown as ServerResponse)
expect(res.status).toBe(200)
Reflect.deleteProperty(mounted.connection, 'requestRejection')
const input = request('/sidebar/api/session.cwd')
const { res, out } = response()
await expect(mounted.routes.find(route => route.path === '/sidebar/api')!.handler(input.req, res)).rejects.toThrow(TypeError)
expect(out.status).toBe(0)
expect(input.reads()).toBe(0)
} finally {
cleanup()
mounted.cleanup()
}
})
it('rejects an Origin whose hostname differs from the Host even on loopback', async () => {
// hostname, not port, re-decides trust: a same-127/8 address that is not
// the page's own hostname is still a different authority.
const { api, cleanup } = mount([])
it('does not bypass native refusals for former desktop, image, or port exceptions', async () => {
const mounted = mount(403)
try {
const res = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', {
host: '127.0.0.1:3080',
'sec-fetch-site': 'same-origin',
origin: 'http://127.0.0.2',
}, '{"sessionId":"test-session"}'), res as unknown as ServerResponse)
expect(res.status).toBe(403)
for (const headers of [
{ host: '127.0.0.1:3080', origin: 'dsh-app://app' },
{ host: '127.0.0.1:3080', origin: 'http://127.0.0.1' },
{
host: '127.0.0.1:3080', 'sec-fetch-site': 'cross-site',
'sec-fetch-mode': 'no-cors', 'sec-fetch-dest': 'image', referer: 'http://127.0.0.1:3080/',
},
]) {
const { req } = request('/sidebar/file', headers)
req.method = 'GET'
const { res, out } = response()
await mounted.routes.find(route => route.path === '/sidebar/file')!.handler(req, res)
expect(out.status).toBe(403)
expect(mounted.connection.requestRejection).toHaveBeenLastCalledWith(req)
expect(req.headers).toBe(headers)
}
} finally {
cleanup()
mounted.cleanup()
}
})
it('rejects the opaque "null" origin', async () => {
const { api, cleanup } = mount([])
it('reads native admission on every request, including authentication expiry', async () => {
const mounted = mount()
try {
const res = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', {
host: '127.0.0.1:3080',
'sec-fetch-site': 'same-origin',
origin: 'null',
}, '{"sessionId":"test-session"}'), res as unknown as ServerResponse)
expect(res.status).toBe(403)
const route = mounted.routes.find(route => route.path === '/sidebar/api')!
const { req } = request('/sidebar/api/session.cwd')
for (const [rejection, expected] of [[undefined, 200], [401, 403], [403, 403], [undefined, 200]] as const) {
mounted.setRejection(rejection)
const { res, out } = response()
await route.handler(req, res)
expect(out.status).toBe(expected)
}
expect(mounted.connection.requestRejection).toHaveBeenCalledTimes(4)
} finally {
cleanup()
}
})
/**
* The four headers a same-origin `<img>` carries after Chromium restores it
* from bfcache: the stale cross-site marker plus the real Referer. The
* `Sec-Fetch-*` and `Referer` headers are forbidden request headers, so a
* foreign page cannot forge them.
*/
function restoredImageHeaders(host: string, referer: string): Record<string, string> {
return {
host,
'sec-fetch-site': 'cross-site',
'sec-fetch-mode': 'no-cors',
'sec-fetch-dest': 'image',
referer,
}
}
/** One real GET /sidebar/file for a temp PNG with `headers` on the request. */
async function mediaRequestWith(
headers: Record<string, string>,
trustedHosts: readonly string[] = [],
): Promise<{ status: number; headers: Record<string, string> }> {
const directory = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fence-'))
const file = join(directory, 'shot.png')
writeFileSync(file, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
const { media, cleanup } = mount(trustedHosts)
try {
const query = new URLSearchParams({ sessionId: 'test-session', cwd: directory, path: file }).toString()
const res = fakeRes()
await media(req('GET', `/sidebar/file?${query}`, headers), res as unknown as ServerResponse)
return { status: res.status, headers: res.headers }
} finally {
cleanup()
removeTree(directory)
}
}
it('accepts a restored same-origin image on the media route (Chromium stale cross-site marker)', async () => {
const res = await mediaRequestWith(restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/'))
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('image/png')
})
it('accepts the same restored image on a trusted remote host', async () => {
const res = await mediaRequestWith(restoredImageHeaders('example.com', 'https://example.com/'), ['example.com'])
expect(res.status).toBe(200)
})
it('refuses a cross-site image without a Referer', async () => {
const headers = restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/')
delete headers.referer
expect((await mediaRequestWith(headers)).status).toBe(403)
})
it.each([
['a non-image no-cors subresource', { ...restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/'), 'sec-fetch-dest': 'script' }],
['a CORS image read', { ...restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/'), 'sec-fetch-mode': 'cors' }],
['a foreign Referer', restoredImageHeaders('127.0.0.1:3080', 'https://attacker.invalid/')],
['a look-alike Referer host', restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1.attacker.invalid/')],
['a userinfo-spoofed Referer', restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1@attacker.invalid/')],
['a malformed Referer', restoredImageHeaders('127.0.0.1:3080', 'null')],
['a Referer on a different port', restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:9999/')],
['a Referer naming localhost instead of the Host', restoredImageHeaders('127.0.0.1:3080', 'http://localhost:3080/')],
])('refuses a restored image carrying %s', async (_case, headers) => {
expect((await mediaRequestWith(headers)).status).toBe(403)
})
it('still refuses a matching-Referer image whose Origin is foreign or opaque', async () => {
const base = restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/')
expect((await mediaRequestWith({ ...base, origin: 'https://attacker.invalid' })).status).toBe(403)
expect((await mediaRequestWith({ ...base, origin: 'null' })).status).toBe(403)
})
it('keeps the exception off the API and non-GET media paths', async () => {
const headers = restoredImageHeaders('127.0.0.1:3080', 'http://127.0.0.1:3080/')
const { api, media, cleanup } = mount([])
try {
const onApi = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', headers, '{"sessionId":"test-session"}'), onApi as unknown as ServerResponse)
expect(onApi.status).toBe(403)
const onMediaPost = fakeRes()
await media(req('POST', '/sidebar/file', headers, ''), onMediaPost as unknown as ServerResponse)
expect(onMediaPost.status).toBe(403)
} finally {
cleanup()
}
})
it('reads webRuntime.trustedHosts per request, not once at apply', async () => {
const { api, setTrustedHosts, cleanup } = mount([])
try {
const before = fakeRes()
await api(remoteDomainRequest(), before as unknown as ServerResponse)
expect(before.status).toBe(403)
// The trust list gains an authority after mount (e.g. config reload):
// the already-mounted fence must pick it up without a plugin restart.
setTrustedHosts(['example.com'])
const after = fakeRes()
await api(remoteDomainRequest(), after as unknown as ServerResponse)
expect(after.status).toBe(200)
} finally {
cleanup()
}
})
})
/**
* The desktop shell serves the GUI from `dsh-app://app`, and its WebSocket
* upgrades reach the Host directly (the scheme handler does not carry
* upgrades), so a handshake carries an origin no Host authority can name.
* Refusing it destroys every /sidebar/ws socket — agent-opens pushes, fs-watch
* refreshes — while the forwarded HTTP routes keep working, because the shell
* strips the origin header before forwarding those.
*/
describe('desktop shell application origin', () => {
/** The shell page's own origin, as its handshakes and fetches present it. */
const SHELL_ORIGIN = 'dsh-app://app'
it('accepts the shell page origin on a loopback Host', async () => {
const { api, cleanup } = mount([])
try {
const res = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', {
host: '127.0.0.1:19488',
origin: SHELL_ORIGIN,
}, '{"sessionId":"test-session"}'), res as unknown as ServerResponse)
expect(res.status).toBe(200)
} finally {
cleanup()
}
})
it('never carries the shell origin past the Host fence', async () => {
// The addition is an origin exception, not an authority: an untrusted Host
// must still refuse even when the request wears the shell's own origin.
const { api, cleanup } = mount([])
try {
const res = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', {
host: 'evil.example',
origin: SHELL_ORIGIN,
}, '{"sessionId":"test-session"}'), res as unknown as ServerResponse)
expect(res.status).toBe(403)
} finally {
cleanup()
}
})
it('matches the shell origin exactly, not by scheme and not by suffix', async () => {
const { api, cleanup } = mount([])
try {
for (const origin of ['dsh-app://evil', 'dsh-app://app.evil.example', 'http://evil.example']) {
const res = fakeRes()
await api(req('POST', '/sidebar/api/session.cwd', {
host: '127.0.0.1:19488',
origin,
}, '{"sessionId":"test-session"}'), res as unknown as ServerResponse)
expect(res.status, origin).toBe(403)
}
} finally {
cleanup()
}
})
it('destroys a cross-site handshake before the upgrade completes', async () => {
// The fence runs ahead of ws's own handshake handling, so its verdict on
// the upgrade path is observable as whether the socket gets destroyed.
const { upgrade, cleanup } = mount([])
try {
const socket = {
destroyed: false,
destroy(): void { this.destroyed = true },
}
await upgrade('/sidebar/ws/agent-opens')(req('GET', '/sidebar/ws/agent-opens?sessionId=test-session', {
host: '127.0.0.1:19488',
origin: 'http://evil.example',
connection: 'Upgrade',
upgrade: 'websocket',
}), socket, new Uint8Array())
expect(socket.destroyed).toBe(true)
} finally {
cleanup()
mounted.cleanup()
}
})
})
+2 -3
View File
@@ -1,6 +1,5 @@
/**
* tsdown build for dsh-better-sidebar: the host-half lib (lib/index.js and
* the lib/invariant.js companion, ESM node) plus the two browser client
* tsdown build for dsh-better-sidebar: the host-half lib (lib/index.js, ESM node) plus the two browser client
* bundles (lib/client.js and lib/client-registry.js, CJS closure factory) —
* one per install channel:
*
@@ -328,7 +327,7 @@ const CHUNKS = ['editor', 'mermaid', 'locale', 'terminal']
export default [
{
entry: { index: 'src/index.ts', invariant: 'src/invariant.ts' },
entry: { index: 'src/index.ts' },
outDir: 'lib',
format: ['esm'],
platform: 'node',