diff --git a/.agents/skills/issue-triage/references/fixed-pending-release.json b/.agents/skills/issue-triage/references/fixed-pending-release.json index 7eda18f99..309bba737 100644 --- a/.agents/skills/issue-triage/references/fixed-pending-release.json +++ b/.agents/skills/issue-triage/references/fixed-pending-release.json @@ -1,4 +1,21 @@ { "_comment": "已在 `dev` 修好、但还没随版本发布的 issue:看板 Status 固定 Done(脚本按它覆盖 等待开发/等待审核),因为队列里已经没有剩余开发工作,只剩发版。发版后把这里清空(或删掉已随该版本进 main 的号)。不要用这个文件表达排期——排期看 priority 标签与 promoted.json。", - "done": [915, 983, 992, 1059] + "done": [ + 877, + 915, + 949, + 951, + 955, + 959, + 983, + 988, + 992, + 995, + 1009, + 1014, + 1015, + 1024, + 1059, + 1080 + ] } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 59e3a19a1..1af4c48e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -171,14 +171,14 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - # Pin the exact 0.2.1-rc.1 host CLI; never use a dist-tag. + # Pin the exact 0.2.2-rc.1 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.1-rc.1 + run: npm install -g @deepseek-ai/dsh@0.2.2-rc.1 # lib/ is gitignored; the tarball is produced from this build. - name: Build and pack the npm tarball diff --git a/.gitignore b/.gitignore index 4cbe7d3a7..cb9fe3c95 100644 --- a/.gitignore +++ b/.gitignore @@ -154,3 +154,6 @@ registry/ playwright-report/ test-results/ + +# generated by scripts/build-mermaid-frame-asset.mjs +src/client/mermaid-frame-asset.generated.ts diff --git a/AGENTS.md b/AGENTS.md index 14b352265..e269d57cb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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.1-rc.1`。 +- **钉版写精确版本号,绝不写 dist-tag**(`alpha` / `latest` / `next` 的指向与候选版经常不一致);默认与 CI 同为 `@deepseek-ai/dsh@0.2.2-rc.1`。 - 该步骤需要 `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,14 +40,14 @@ ## 3. DSH 版本适配 -- **当前基线 DSH 0.2.1-rc.1(v0.28.0 正式版起)**。13 条 `@deepseek-ai/dsh-*` peer 下限均为 `^0.2.1-rc.1` 浮动 caret 范围、**绝不钉精确版本**(只有 devDependencies 精确钉);本包不声明 `package.json#engines.dsh`,因此走 peer 兼容性检查;宿主对声明了该字段的包优先且仅按它判定,不读 peer。`dsh.plugin.json#engines.dsh` 不参与这一规则。`tests/market-manifest.spec.ts` 钉住这条形状。 +- **当前基线 DSH 0.2.2-rc.1(v0.30.0 起)**。**v0.30.0 起 14 条** `@deepseek-ai/dsh-*` peer(新增 `dsh-client-ui-input-trigger`,划选引用 chip 用它的 `ctx.inputTriggers`)下限均为 `^0.2.2-rc.1` 浮动 caret 范围、**绝不钉精确版本**(只有 devDependencies 精确钉);本包不声明 `package.json#engines.dsh`,因此走 peer 兼容性检查;宿主对声明了该字段的包优先且仅按它判定,不读 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 下限。** -- 支持线(用户侧):DSH **0.2.1-rc.1+** 使用插件 **v0.28.2**;0.2.1-alpha.5 用户固定 **v0.28.0-alpha.0**;0.2.0-rc.2 用户固定 **v0.26.1**(v0.27.0 尚未发布);0.2.0-rc.1 用户固定 v0.24.1;0.1.7 线的最后支持版是 **v0.22.1**(v0.23.0 从未发布到 npm)。按本仓库先例**不写运行时兼容层**。 +- 支持线(用户侧):DSH **0.2.2-rc.1+** 使用插件 **v0.30.0**;DSH **0.2.1-rc.1+(含 npm `latest` 0.2.1-rc.5)** 固定 **v0.28.2**——v0.29.0 从未发布到 npm,0.2.1 线不要再抬;0.2.1-alpha.5 用户固定 **v0.28.0-alpha.0**;0.2.0-rc.2 用户固定 **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` / 自建信任例外。 - **v0.28.0 正式版接管 npm `latest`**:宿主 npm `latest` 此时仍指向 `0.2.0-rc.2`,不满足本插件 RC 基线;用户已明确接受这一分离,所有安装文档必须显著提醒旧宿主固定 `v0.26.1`,不要用浮动 `latest`。发布 workflow 沿用现有版本号规则,无需改动。 -- **本次 RC 适配不改功能实现**:alpha.5 → rc.1 上游完整树差异共 355 项,全部为 `package.json`,源码零变化;同步版本、peer、伴随依赖与文档,重新获取 RC 验证证据,不沿用 alpha 测试数字。 +- **本次 0.2.1 → 0.2.2 适配有真实代码改动**(不是纯版本同步):`dsh-agent` 用 agent 自有的 `AgentModel`(`agent.model`,`select()` 同时落盘并作用于下一步)替换了可安装的 `ModelSelectionRef` + `installModelSelection(ctx, ref)`,sidechat 的模型选择随之改写;`dsh-tools` 移除了 PTC(`tool/ptc-dispatch*`)的事件**类型声明**(运行期仍记录,`known-event-types` 仍在),只有测试要按擦除形状追加;图标从内联 `` 变成 sprite ``,按图元的断言要跟着改。逐项证据见 [0.2.2 适配记录](docs/plans/2026-11-04-dsh-0.2.2-rc.1-adaptation.md)。 - 动设置面 / sidechat / 原生 tab 之前,先读 [docs/host-contracts.md](docs/host-contracts.md)(原 §3.4 的 1–13 条按原编号都在那里)。 --- diff --git a/CHANGELOG.md b/CHANGELOG.md index 6279ab824..b0bdfc654 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,57 @@ > 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。 +### v0.30.0 + +- 🧭 **适配 DSH 0.2.2-rc.1(本版 peer 下限抬到 `^0.2.2-rc.1`)**:宿主把模型选择从可安装的 `ModelSelectionRef` 换成 agent 自有的 `AgentModel`——`agent.model.select()` 同时落盘并作用于下一步,侧边对话的线程模型选择随之改写(不再自己 install 一份 ref);`dsh-tools` 移除了 PTC(`tool/ptc-dispatch*`)的事件**类型声明**(运行期仍记录),宿主图标由内联 `` 改为 sprite ``。**支持线随之移动**:0.x 的 caret 不跨 minor,因此 DSH 0.2.1 线(`0.2.1-rc.1 ~ rc.5`,即当前的宿主 npm `latest`)请继续固定插件 **v0.28.2**(`v0.29.0` 从未发布到 npm),0.2.2-rc.1+ 请用 **v0.30.0**。 + - 🧪 验证:`typecheck` + 全量 `vitest` + `plugin-mount`(真实 0.2.2-rc.1 宿主 + Chromium);逐项证据见 [0.2.2 适配记录](docs/plans/2026-11-04-dsh-0.2.2-rc.1-adaptation.md)。 +- 🧭 **安装脚本会先查 profile 自带的 `@deepseek-ai/dsh-*` 副本是否混版**([#1107](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1107)):profile 里自己装的宿主包会抢在 DSH 安装之前被解析,本插件静态 import 的 `dsh-subagent` 因此绑到混搭版本;混版缺导出时整只宿主只报 `DesktopHostFatalError: required plugins did not activate`,看不到是哪个包缺了什么。`scripts/install.sh` / `scripts/install.ps1` 现在装完会运行随包发布的 `scripts/check-profile-host-tree.mjs`(按 DSH 自己的 profile 解析规则:只看 profile 内的副本、只判定 `dsh-subagent` 精确声明的 `dsh-attachment` peer)——混版就打印两份版本号与修复命令并退出,不再提示重启。README 常见问题补了同一条修复路径(从 profile 的 `package.json` / overrides 移除 `@deepseek-ai/dsh-*` 后 `pnpm install`,或把两份副本对齐到同一版本)。 + - 🧪 测试:新增 `tests/install-host-tree.spec.ts`(6 例,真跑发布脚本:混版退出码 1 并给出两份版本;配对一致 / 只有 subagent 副本 / profile 之外的旧副本被忽略 / 未装插件均放行;并钉住两个安装脚本都调用它、脚本随包发布)。 +- 🧵 **父会话进行中开的侧边对话不再写出一份永久不可读的子会话日志**([#1109](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1109)):父会话压缩过之后,种子是围绕最后一个压缩检查点按**重编号**复制的,而继承来的 `session-log-deepseek/delivery-accepted` 的 `throughSeq` 是绝对 seq——重编号后它仍指向父会话的位置,于是子会话里出现「水位线不早于它自己的标记」,宿主 v4 读取器直接判日志损坏(`SessionFormatError: delivery throughSeq must precede its marker`):该子会话从此再也读不出来,连带父会话 `includeDescendants` 导出失败。现在重编号会把这条水位线一起重映射;水位线落在被丢弃的区间(子会话侧没有对应事件)时,该记录整条丢弃而不是伪造一个水位线。**已损坏的历史日志不会被修复**,只是不再产生新的。 + - 🧪 测试:`tests/sidechat-compaction-seed.spec.ts` 新增 1 例(带真实投递标记的压缩父日志:每条存活标记的水位线都必须早于自己、且仍指向父会话标记的同一事件;水位线被丢弃的标记不得存活)。 +- 🛟 **原生页签关闭与桌面 Cmd+Q 不再无声丢掉编辑器草稿**([#1072](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1072) / [#1071](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1071)):宿主原生右侧栏的页签条(× / 中键 / 上下文菜单 / `page.close`)与桌面壳的退出都没有「可确认」的关闭钩子(`registerCloseHandler` 是同步清理,唯一的阻止方式是 `throw`;桌面 Cmd+Q 走壳自己的 `before-quit` → `app.exitRequested`,页面收不到可取消事件,详见[宿主契约 §C](docs/host-contracts.md))。插件无法在这两条路径上弹确认,因此改为降低损失:草稿变脏时按 1 s 节流把**实时文档**写入 `localStorage`(key = `sessionId::path`;单条 200k 字符、总计 600k、最多 8 条、FIFO 淘汰),在原生关闭回调与 `beforeunload` 时立即落盘,重开同一文件时提示「检测到未保存的草稿,恢复吗?」。保存成功、确认丢弃、确认刷新 / 就地换文件都会删掉对应备份。 + - 🧪 测试:新增 `tests/editor-draft-backup.spec.tsx`(8 例:节流后读到实时文本、FIFO 上限、超大草稿跳过、与磁盘相同即丢弃、恢复后保存的是草稿、拒绝恢复时打开磁盘内容、无草稿不提示、原生关闭钩子立即落盘);`tests/editor-unsaved-guard.spec.tsx` 追加 2 例(确认丢弃同时删备份、`beforeunload` 先落盘再拦截)。 + - ⚠️ 宿主侧仍缺:Electron 桌面壳没有 `will-prevent-unload` 对话框,也没有退出前可取消钩子;真正的「保存 / 丢弃 / 取消」需要宿主补能力,届时再接 `confirmDiscardDraft` 并删除这条降级路径。 + +- 📐 **页面 CSS zoom 不再被误判成页面级 transform**([#1102](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1102);贡献者 PR [#1110](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1110) @HootRock):`body { zoom: 1.15 }` 下 panel host 的 `100vh` 按 zoom 放大(811px 视口 → 约 932.6px),几何自检因此判定「页面被 transform」→ 降级成 absolute、把文档撑高,聚焦 / 滚动会把整个外壳一起推走。现在预期高度按祖先链累积的 `zoom` 归一,宽度与位移仍按原阈值判定,真实 transform 不会被掩盖。 + - 🧪 测试:`tests/e2e/panel-host-zoom.e2e.ts`(Chromium 实测 `body { zoom: 1.15 }` 下不再降级)。 +- 🎛 **Changes 的「Git / 本轮文件」切换改用公开组件**([#1098](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1098);贡献者 PR [#1101](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1101) @wang-kaopu):此前自己画一套按钮、还依赖宿主私有 CSS Modules 的哈希类名,宿主一改样式就退化成浏览器原生按钮(方框 + 1px 黑边)。现在改用 `dsh-client-ui-primitives` 公开导出的 `SegmentedControl`,私有类名依赖一并删除。 + - 🧪 测试:`tests/changes-tab.spec.tsx` 覆盖 ARIA 面板关系、键盘导航、lens 持久化与刷新。 +- 🎨 **底部工作台的终端不再自带黑底**:终端区域一直是一块纯黑矩形,而周围的 tab 条与面板都不是。原因是 xterm 自带样式表里的 `.xterm .xterm-viewport { background-color: #000 }`,而本插件的规则 `.screen .xterm-viewport` 被 CSS Modules 把 xterm 的类名也哈希了(编译成 `.o8IiwG_xterm-viewport`),真实 DOM 里根本不匹配;即便包上 `:global()`,同权重的规则也会因为 xterm 在 `open()` 时才注入样式表而输在源顺序。现在选择器写成 `.screen :global(.xterm .xterm-viewport)`(`:global` 保命、多一级 `.xterm` 把特异性抬到 0,3,0),`.screen` 自身也不再画 `bg-base`。Chromium 实测:0,2,0 → `rgb(0, 0, 0)`,0,3,0 → `rgba(0, 0, 0, 0)`。 +- 🗂 **容器工作区里能直接看到并切换每个子仓库**:`git.status` 早就把发现到的全部根放在 `repositories` 里,但 Git 面板只在「⋯(更多操作)→ 仓库」二级菜单中列出它们——面板顶部既没有仓库名也没有数量,正文默认渲染 `repositories[0]`,于是有三个项目的工作区看起来只有一个。现在发现多个根时,「更改」区块上方渲染一行仓库胶囊(`data-scm-repos`,每个根一个 `[data-scm-repo]`),当前检出以 `[data-active="true"]` 高亮;点击走既有的 `chooseRepo`,读数、写操作与提交图继续被钉在选中的根上。单一仓库工作区不渲染这一行,原菜单入口保留。 + - 🧪 `tests/git-repo-switcher.spec.tsx` 新增 3 例:多仓库逐个列出并可切换、同一检出的反斜杠/尾斜杠/大小写写法只算一个、单仓库不渲染切换行。 +- **侧边对话支持图片输入**:可以粘贴截图或选择 PNG / JPEG / WebP / GIF,预览并移除后发送,也支持只发图片。文本与图片整批交给宿主附件服务,历史和待发送队列保留图片预览;刷新或冷恢复后仍可读取。默认上限为 8 张、单张 10 MiB、合计 20 MiB,宿主限制更小时跟随宿主。发送失败保留草稿,网络响应丢失时提示先检查对话;已明确声明只支持文本的模型会拒绝图片。 +- 🔖 **编辑器里划选一段文字,主会话输入框里落一枚可点击的引用 chip(发送时展开成路径 + 围栏正文)**([#888](https://github.com/omdsh-dev/DSH-better-sidebar/issues/888)):`code` / `markdown` / `jsonl` 编辑面与 Markdown 预览里划选后,弹窗「添加到对话」不再只是把文本塞进输入框,而是插入一枚 chip。这枚 chip 归属本插件自己的 input-trigger source(`betterSidebarQuote`,经 `ctx.inputTriggers.registerSource` 注册):**点击它会把源文件在侧边栏打开并定位到被引行**,`line`–`lineEnd` 整段闪 2.4 s(皮肤令牌 `--dsw-alias-interactive-bg-hover-accent`,`prefers-reduced-motion` 下减弱);发送时由该 source 的 `codec.serialize` 还原成与升级前字节一致的 `<相对路径>[:起[-止]]` 表头 + ≤500 字符的围栏正文,超限只留表头。行段末行走模块内的一次性旁路 `src/client/line-target.ts`(key = path + line,最多 32 条),**不写进宿主导航参数**——宿主 `SidebarRightResourceParamsMap.file` 只声明了 `line`。 + - 降级链:宿主没有 `ctx.inputTriggers`、注册被拒、composer 不在可插入相位、`draftRev` 不匹配 → 退回 #1052 内置的不可点击 chip;再退纯文本,最终行为与升级前一致。插不进去的那一次会删掉刚写入的引用记录,不留孤儿 id。 + - 记录存 `localStorage`(`dsh-better-sidebar:quote-refs`,FIFO 200 条):该模块同时进 core bundle 与 lazy editor chunk,两个模块实例只能靠它互见记录。点击时校验 chip 所属会话,换了会话不跳转(cwd 可能不同,会打开错文件)。 + - chip 只打开右侧栏,**底部工作台没有该入口**(底部 `TabContent → EditorHost` 是同一组件、同样消费 `line`,但本功能未在底部真机验证)。行号取划选时的快照:文件之后被编辑,点击会落到同一行号(可能已偏移),不做锚点搜索。 + - 新增 peer `@deepseek-ai/dsh-client-ui-input-trigger`(`^0.2.1-rc.1`,DSH peer 增至 14 条);接入面与三级降级写进[指南 §7.2](docs/external-plugin-guide.md)。 + - 🧪 测试:新增 `tests/selection-quote.spec.ts`(27 例)、`tests/quote-flash.spec.ts`(13 例)、`tests/line-target.spec.ts`(8 例);`tests/conversation-draft.spec.ts` 追加 2 例(chip 的 `source`/`ref` 覆盖不改动 #1052 的默认载荷),`tests/editor-line-nav-mode.spec.tsx` 追加 1 例(同一 chip 连点两次仍跳转、仍闪光)。 +- ⚡ **大 Markdown 的 Mermaid 预览不再卡死渲染器(chunk 内测量隔离到沙箱 iframe)**:Mermaid 用 `SVGElement.getBBox()` 量文字,测量节点挂在 `document.body` 上 → 每次测量都刷新整个 DSH 文档布局。真机实测一次 `getBBox` **59–75 ms**(15,418 节点),空 iframe 里只要 **1 ms**;31 张图因此阻塞主线程 >20 s,触发桌面壳看门狗杀渲染器,恢复标签页后循环卡死。现在图表改在隐藏的 `sandbox="allow-scripts"` iframe(blob: 自包含 mermaid UMD + 协议)里渲染,父侧只做 postMessage 收发与 SVG 清洗:**单图 1,500–7,300 ms → 30–104 ms,31 图约 5 s 内完成**,客户端 mermaid chunk 同时从 **7.04 MB → 3.69 MB**。另加共享渲染队列(可见/近视口优先,其余 `requestIdleCallback` 逐张补齐,两次之间让出 16 ms 主线程;**所有图最终都会渲染成图,不再退化为代码块**)与按围栏行数预留高度的占位骨架。设计与实测见 [docs/plans/2026-10-23-mermaid-iframe-isolation.md](docs/plans/2026-10-23-mermaid-iframe-isolation.md)。 +- ⚡ **大文档滚动流畅性:渲染让位于滚动、隐藏页签不空转、摘掉全量 DOM 扫描**:图表渲染队列在滚动期间暂停(停止滚动 350 ms 后恢复),并且只服务当前可见的预览——隐藏页签里的图表保持占位、切回时才渲染;`Markdown` 变更触发的两次全量扫描(内联 HTML pass、标题锚点 pass)由「每次 mutation 跑一遍」(实测 8–15 ms/次)改为 80 ms 合并一次;打开文档时的近视口判断改为先批量读 rect、再统一写入,去掉每张图一次强制布局;`.mermaidWrap` 增加 `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`,视口外的图表不再参与布局与绘制。滚动时不再有后台渲染、全量扫描与视口外 SVG 重绘抢主线程;图表仍会在滚动停止后或进入视口时补齐,不退化为代码块。 +- 🐞 **图表渲染失败时直接显示 mermaid 的解析错误**:之前只显示通用「Mermaid 渲染失败」+ 源码块(完整错误只在 hover title 里)。现在错误条下方直接给出 mermaid 报错的首两行(如 `Parse error on line 10 ... Expecting 'SEMI', ... got 'UNICODE_TEXT'`),配合下方源码可快速定位坏围栏;错误信息仍完整保留在 title 中。 +- 🪟 **Windows + WSL 工作区:UNC 路径不再被折叠成盘符相对路径**:`resolveAddressPath` 在 Windows 基址下重排分隔符时把每段连续 `\` 折成一个,`\\wsl.localhost\\...` 的 UNC 前缀也因此被折成 `\wsl.localhost\...`;宿主随后用 `path.resolve()` 把它锚定到自己的当前盘(`C:\wsl.localhost\...`),侧边栏打开 WSL 工作区里任何文件都报 `ENOENT`。现在 UNC 前缀原样保留、只折叠其后的部分(盘符路径行为不变)。 + - 🧪 测试:`tests/worktree-address.spec.ts` 新增 1 例(UNC 绝对路径、工作区相对路径、正斜杠写法都保持双前导分隔符)。 +- 🗂 **会话 cwd 是 Git 仓库子目录时不再被上抬到仓库顶层**([#1024](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1024) / [#1080](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1080);贡献者 PR [#1070](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1070) @hy5424):侧边栏根此前被替换成 `git rev-parse --show-toplevel`,聊天里的相对路径文件链接因此解析成 `/` 而不是 `//`(ENOENT),文件搜索也搜错根。现在会话 cwd 本身即根,只有会话自己的工具调用证据指向 linked worktree 时才替换;基址先按真实路径规范化,`/var` 与 `/private/var` 这类符号链接拼写不会让嵌套 worktree 被误判到工作区之外(#952)。 + - 🧪 测试:`tests/active-worktree.spec.ts` 新增英文 / 中文子目录两例(修复前均为红)。 +- 🧩 **右侧栏的二级菜单不再溢出视口**([#955](https://github.com/omdsh-dev/DSH-better-sidebar/issues/955) / [#988](https://github.com/omdsh-dev/DSH-better-sidebar/issues/988);贡献者 PR [#974](https://github.com/omdsh-dev/DSH-better-sidebar/pull/974)):`layout.css` 的 `@media (prefers-reduced-motion: reduce)` 少了一个 `}`,把它后面六条子菜单翻转规则全吞进媒体查询,默认主题下永不生效;Git 面板「更多操作 → 仓库 / 工作树」还有第二层原因——该入口从不写 `data-dsh-sidebar-submenu`。现在补回括号,并让 Git 面板也发布同一 token(复用 `menu-flip` 同一套机制,没有第二套定位逻辑)。`tests/css-block-scope.spec.ts` 与 `tests/git-view-worktree.spec.tsx` 守护。 +- 🖼 **HTML 预览能加载相对 CSS / JS**([#959](https://github.com/omdsh-dev/DSH-better-sidebar/issues/959);贡献者 PR [#972](https://github.com/omdsh-dev/DSH-better-sidebar/pull/972)):`/sidebar/file` 与 `/sidebar/html` 共用的 MIME 表只声明了图片 / PDF / HTML,`.css` / `.js` 落到 `application/octet-stream`,浏览器严格 MIME 检查直接拒收,页面无样式、脚本不执行。补上 css / js / mjs / json / 字体 / wasm 等 web 资源类型;未知扩展名仍回落 octet-stream。 +- 📝 **合并模式下换文件前确认未保存草稿**(贡献者 PR [#1083](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1083)):`EditorHost.openFile` 的 in-place 分支此前直接改写 `path`,viewer 重挂载、草稿静默消失;现在与关闭 / 删除共用同一份脏草稿登记表(`isEditorDirty`),取消则停在原文件,被其它 tab 类型认领或打开同一路径时不弹。新增 `switchUnsavedConfirm` 文案(21 份词典)。 +- 🐞 **三笔小修**:分栏窗格唯一标签拖回后不再丢失([#877](https://github.com/omdsh-dev/DSH-better-sidebar/issues/877),PR [#922](https://github.com/omdsh-dev/DSH-better-sidebar/pull/922));搜索探针同步 spawn 失败时不再抛 `Cannot access 'timer' before initialization` 而失去 plain-walk 兜底([#995](https://github.com/omdsh-dev/DSH-better-sidebar/issues/995),PR [#1032](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1032));并发同名上传的 rename 争用改为有界重试(PR [#966](https://github.com/omdsh-dev/DSH-better-sidebar/pull/966))。 +- **尖括号包裹的本地链接不再被追加问号**([#1015](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1015);贡献者 PR [#1067](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1067)):行内链接 `[t](<../../../docs/notes/a.md>)` 的尖括号此前被当成 destination 的一部分,改写后变成 `[t](<./a.md>?)`,预览里不再是链接。现在先剥掉尖括号、按内部路径判定,再原样重新包裹;带空格 / 括号的 destination 一并纳入(Windows 反斜杠与标题片段一起归一)。`tests/markdown-navigation.spec.ts` 守护。 +- **侧边对话里的本地源码链接可点开**(贡献者 PR [#1074](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1074)):Side Chat 转录里的 `[source]()` 此前按字面量显示、或只能打开 Markdown;现在渲染成文件按钮并在编辑器里打开到第 37 行(`:line`、`:line:column`、`#L24` 行号都认)。新增的 `allLocalFiles` 只对 prose surface 生效,文档预览仍只认 Markdown。 +- 🐞 **「侧边卡片」不再给程序化类型发假开关**([#1009](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1009)):`hidden: true` 的 tab 类型(内置的 diff 页、dsh-remote 的 `dsh-remote:file`)本就没有 `+` 菜单行和原生 guide 条目,设置页却照注册表给它发了一张卡片——点掉后侧边栏毫无变化,唯一实际效果是 `openTab` 静默拒绝它的打开(差异预览的「展开为独立页签」、远程文件打开随之失效),同一现象也被 dsh-remote 侧报告为「开关无效」。现在清单只列真正出现在侧边栏的类型,`isTabEnabled()` 对 hidden 类型恒为 true(旧版本写下的 `tabsEnabled[id] = false` 不再拦截它们的打开)。`tests/side-card-section.spec.tsx` + `tests/service.spec.ts` 各新增一例守护。 +- 🛡 **侧边对话不再可以被归档进死角**([#949](https://github.com/omdsh-dev/DSH-better-sidebar/issues/949)):宿主对 `origin: subagent` 的会话行在任何筛选下都不渲染(连「已归档」也看不到),侧聊一经归档就再也捞不回来。现在侧聊的归档按钮对侧线程禁用,并用 tooltip 说明原因(指向「保存为新会话」);关闭页签仍按 #942 的既定行为归档其会话。 +- 🔌 **`agentOpenTools` 的开关读取改成三态**([#951](https://github.com/omdsh-dev/DSH-better-sidebar/issues/951)):设置行在重挂载窗口里会缺席,旧实现把「读不到」当成「关闭」并注销 `sidebar_open`,于是工具反复注册/注销、重启后第一轮也不在。现在只有明确 `false` 才注销,并在设置写入成功与 loader 就绪后各重估一次;重复 sync 幂等。 +- 📱 **手机端整页不再可上下拖动**([#1014](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1014)):`[data-dsh-panel-host]` 的 `height: 100vh` 按大视口解析(地址栏展开时比 `innerHeight` 高),挂载自检误判为「页面被 transform」→ 降级成 absolute 把文档撑高。现在 `100vh` 兜底 + `100dvh` 跟随动态视口,差值归零;不支持 `dvh` 的引擎保持旧行为(#616 的「不依赖包含块」不回归)。 + +### v0.29.0 + +- **侧边对话接入 GenUI**:通过现有 `ctx.betterSidebar` 服务新增可选的 `registerSidechatSurfaceAdapter`,支持 GenUI 0.15.0 渲染已结算的助手回复;未注册消费方时保持原 Markdown。 +- **子线程归属与生命周期**:保留线程、消息及原始文本块身份;隐藏、切换线程、替换行或卸载后撤销旧回调,交互不会转发到主会话。保留原链接改写缓存、媒体处理与流式状态。 +- **冷恢复边界**:仅移除明确标为继承的历史前缀,普通恢复标记不再清掉子线程历史。 +- **贡献**:感谢 [@sunxiuguo](https://github.com/sunxiuguo) 的配套实现([#1033](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1033));保留原始贡献提交,并整合最新 dev 与 0.28.2 的冷会话读取修复。 + ### v0.28.2 - 🛡 **冷会话(detached)的 cwd 改读工作区地址,不再整份解码会话日志**:`sessionQuery.observeSession(..., { projectionMode: 'all' })` 为拿一个 `workingDirectory` 要解码整份 zstd 日志并水合全部投影;而启动期真正并发的是 **fs-watch 每监视目录一帧**、`/sidebar/file|html` 每资源一次、`/sidebar/upload|write` 每次一次——它们都绕过 0.28.1 只覆盖 `/sidebar/api` 的 `cwdOf()` 单飞,所以 39 MB 级会话在 130–180 ms 里被并发整读数十次(0.28.0 的 44 次 OOM、0.28.1 的 36 次是同一路径,不是「去重失效」)。现在 detached 会话的 cwd 走 `sessionPersistence.stat` 的 **header-only** 读(只读第一个 zstd 帧)+ 进程内 memo/在飞去重,`activeWorktreeRootOf` 对 detached 会话直接返回该地址;宿主 attach 后仍跟随 `working_directory` 与 linked worktree。 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index fbebd5e33..e3a17be13 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -4,6 +4,43 @@ > > 📝 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.30.0 + +- 🧭 **Adapted to DSH 0.2.2-rc.1 (peer floors move to `^0.2.2-rc.1`)**: the host replaced the installable `ModelSelectionRef` with an agent-owned `AgentModel` — `agent.model.select()` records the choice durably and applies it to the next step, so the side-chat thread model selection rides the agent's own handle instead of an installed ref. `dsh-tools` dropped the PTC (`tool/ptc-dispatch*`) event **type declarations** (the runtime still records them), and host icons switched from inline `` to sprite ``. **The support line moves with it**: a 0.x caret never spans a minor, so DSH 0.2.1 hosts (`0.2.1-rc.1 ~ rc.5`, today's npm `latest`) keep pinning plugin **v0.28.2** (`v0.29.0` was never published), while 0.2.2-rc.1+ takes **v0.30.0**. + - 🧪 Verified by `typecheck`, the full `vitest` suite, and `plugin-mount` against a real 0.2.2-rc.1 host in Chromium; see the [0.2.2 adaptation record](docs/plans/2026-11-04-dsh-0.2.2-rc.1-adaptation.md). +- 🧭 **The installers now verify that a profile's own `@deepseek-ai/dsh-*` copies belong to one host version** ([#1107](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1107)): profile-installed host packages resolve ahead of the DSH installation, so the `dsh-subagent` this plugin imports statically binds to a mixed set; a missing export then takes the whole host down with `DesktopHostFatalError: required plugins did not activate`, never naming the package. `scripts/install.sh` / `scripts/install.ps1` now run the shipped `scripts/check-profile-host-tree.mjs` after installing (mirroring DSH's own profile resolution: profile-local copies only, and only the exact `dsh-attachment` peer `dsh-subagent` declares) — a torn pair prints both versions plus the repair and stops instead of telling you to restart. The README FAQ documents the same repair (remove `@deepseek-ai/dsh-*` from the profile's `package.json` / overrides and `pnpm install`, or align both copies). + - 🧪 New `tests/install-host-tree.spec.ts` (6 cases, running the shipped script: a torn pair exits 1 with both versions; a matching pair, a subagent-only copy, a stale copy above the profile, and an absent plugin all pass; both installers are pinned to call it and the script is pinned into `files`). +- 🧵 **A side chat opened while the parent is mid-turn no longer persists an unreadable child session log** ([#1109](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1109)): once the parent has compacted, the seed is copied around its last compaction checkpoint with **renumbered** seqs, but the inherited `session-log-deepseek/delivery-accepted` `throughSeq` is an absolute seq — it still named the parent's position, so the child carried a watermark that did not precede its own marker. The host's v4 reader treats such a log as corrupt (`SessionFormatError: delivery throughSeq must precede its marker`): the child can never be read again, which also breaks the parent's `includeDescendants` export. The rebase now remaps the watermark, and drops the record entirely when the watermark fell inside the dropped span (there is no child-side equivalent, and inventing one would claim a delivery that never happened). **Already-corrupt logs are not repaired**; only new ones are prevented. + - 🧪 `tests/sidechat-compaction-seed.spec.ts` adds one case: a compacted parent carrying real delivery markers must yield a seed where every surviving marker's watermark precedes it and still names the same event the parent marked, while markers whose watermark was trimmed away must not survive. +- 🛟 **The native tab close and Desktop Cmd+Q no longer discard editor drafts silently** ([#1072](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1072), [#1071](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1071)): the host's right-column tab strip (× / middle click / context menu / `page.close`) and the Desktop shell's quit expose no confirmable close hook — `registerCloseHandler` is a synchronous cleanup whose only veto is a throw, and Desktop Cmd+Q runs through the shell's own `before-quit` → `app.exitRequested` where the page sees no cancellable event (see [host contracts §C](docs/host-contracts.md)). The editor now throttles the **live document** into `localStorage` (key = `sessionId::path`; 200k characters per draft, 600k total, 8 drafts, FIFO), flushes it in the native close handler and in `beforeunload`, and offers "An unsaved draft was found. Restore it?" when the same file is reopened. Saving, confirming a discard, and confirming a reload / in-place switch drop the backup. + - 🧪 Tests: new `tests/editor-draft-backup.spec.tsx` (8 cases) and two new cases in `tests/editor-unsaved-guard.spec.tsx`. + - ⚠️ Host gap: the Electron desktop shell has no `will-prevent-unload` dialog and no cancellable quit hook, so a real save / discard / cancel flow needs a host capability; the guard would then call `confirmDiscardDraft` and this fallback path could go away. + +- 📐 **Page CSS zoom is no longer mistaken for a page-level transform** ([#1102](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1102), PR [#1110](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1110)): with `body { zoom: 1.15 }` the panel host's `100vh` resolved to ~932.6px in an 811px viewport, so the geometry self-check switched the host to absolute positioning and grew the document. The expected height now folds the ancestor `zoom` chain while width and offsets keep their thresholds, so a real page transform is still caught. +- 🎛 **The Changes lens switcher uses the public `SegmentedControl`** ([#1098](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1098), PR [#1101](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1101)): it previously painted its own buttons on top of host-private CSS-module hash names and degraded to native browser buttons whenever the host restyled. The private-class dependency is gone. +- 🗂 **A container workspace now shows and switches every child repository**: `git.status` has always reported every discovered root in `repositories`, but the Git panel only listed them in the "More actions → Repository" submenu — no name and no count at the top of the panel, and the body rendered `repositories[0]`, so a workspace holding three projects looked like it had one. When more than one root is discovered, a chip row (`data-scm-repos`, one `[data-scm-repo]` per root) now renders above the Changes section with the current checkout marked `[data-active="true"]`; clicking a chip goes through the existing `chooseRepo`, so reads, mutations and the commit graph stay pinned to the chosen root. A single-repository workspace renders no row, and the existing menu entry stays. + - 🧪 `tests/git-repo-switcher.spec.tsx` adds three cases: every root listed and switchable, backslash/trailing-slash/case spellings folded to one checkout, and no row for a single-repository workspace. +- 🔖 **Selecting text in the editor now drops a clickable quote chip into the main composer (expanded to a path plus fenced body on send)** ([#888](https://github.com/omdsh-dev/DSH-better-sidebar/issues/888)): in the `code` / `markdown` / `jsonl` editing surfaces and in Markdown preview, "Add to conversation" used to paste the text into the composer; it now inserts a chip owned by a plugin-registered input-trigger source (`betterSidebarQuote` via `ctx.inputTriggers.registerSource`). **Clicking the chip reopens the source file in the sidebar at the quoted lines** and flashes the whole `line`–`lineEnd` span for 2.4 s (skin token `--dsw-alias-interactive-bg-hover-accent`, softened under `prefers-reduced-motion`); on send the source's `codec.serialize` restores the byte-identical `[:start[-end]]` header plus a fenced body of up to 500 characters (header only beyond that). The end line reaches the viewer through a module-local one-shot side channel (`src/client/line-target.ts`, keyed by path + line, capped at 32), **never through host navigation params** — the host's `SidebarRightResourceParamsMap.file` only declares `line`. + - Degradation: no `ctx.inputTriggers` service, a rejected registration, a composer outside an insertable phase, or a stale `draftRev` falls back to the built-in non-clickable chip from #1052, then to plain text, so behaviour never regresses past the previous release. A failed insert deletes the record it just wrote, so no orphan ids accumulate. + - Records live in `localStorage` (`dsh-better-sidebar:quote-refs`, FIFO of 200) because the module ships in both the core bundle and the lazy editor chunk; the two instances can only see each other's records that way. Clicking validates the chip's session first — a different session may carry a different cwd and would open the wrong file. + - The chip only opens the right sidebar; **the bottom workbench has no entry for it** (the bottom `TabContent → EditorHost` is the same component and does consume `line`, but this feature has not been verified by hand there). Line numbers are the selection-time snapshot: after the file is edited, a click lands on the same line number (possibly drifted) — no anchor search is performed. + - New peer `@deepseek-ai/dsh-client-ui-input-trigger` (`^0.2.1-rc.1`, bringing the DSH peers to 14); the integration surface and its three-tier fallback are documented in [guide §7.2](docs/external-plugin-guide.md). + - 🧪 Tests: new `tests/selection-quote.spec.ts` (27 cases), `tests/quote-flash.spec.ts` (13), `tests/line-target.spec.ts` (8); `tests/conversation-draft.spec.ts` gains 2 cases (the chip's `source`/`ref` override leaves #1052's default payload untouched), and `tests/editor-line-nav-mode.spec.tsx` gains 1 (a second click on the same chip still jumps and still flashes). +- 🪟 **Windows + WSL workspaces: a UNC path is no longer folded into a drive-relative one.** Re-spelling paths on a Windows base folded every run of separators into one `\`, which also folded the UNC prefix of `\\wsl.localhost\\...` into `\wsl.localhost\...`; the host's `path.resolve()` then anchored that on its own process drive (`C:\wsl.localhost\...`), so every file opened from a WSL workspace failed with ENOENT. The UNC prefix now survives and only the rest is folded (drive paths are unchanged). + - 🧪 `tests/worktree-address.spec.ts` adds one case: UNC absolute, workspace-relative, and forward-slash spellings all keep the two leading separators. +- 🗂 **A session cwd that is a Git repository subdirectory is no longer lifted to the repository top** ([#1024](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1024), [#1080](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1080); contributor PR [#1070](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1070) @hy5424): the sidebar root was replaced with `git rev-parse --show-toplevel`, so a relative file link in chat resolved to `/` instead of `//` (ENOENT) and file search used the wrong root. The session cwd is now the root as it stands; only linked-worktree evidence from the session's own tool calls replaces it. The cwd is canonicalized first, so symlinked spellings (`/var` vs `/private/var`) cannot make a nested worktree look outside the workspace (#952). + - 🧪 `tests/active-worktree.spec.ts` adds one ASCII and one Chinese subdirectory case (both red before the fix). +- ⚡ **Mermaid previews of large Markdown documents no longer stall the renderer (layout measurement isolated in a sandboxed iframe)**: mermaid measures label text with `SVGElement.getBBox()` against a node appended to `document.body`, so every measurement flushes the whole DSH document layout — measured on a real desktop host at **59–75 ms per measurement** (15,418 nodes) versus **1 ms** in an empty iframe. A 31-diagram document therefore blocked the main thread for >20 s, tripping the desktop shell's surface watchdog and turning tab restoration into a crash loop. Diagrams now render inside a hidden `sandbox="allow-scripts"` iframe (a self-contained blob: document with the mermaid UMD bundle inlined plus a small postMessage protocol); the parent only sends/receives and sanitizes SVG: **per diagram 1,500–7,300 ms → 30–104 ms, 31 diagrams in ~5 s**, while the client mermaid chunk shrinks from **7.04 MB to 3.69 MB**. A shared render queue (visible/near-viewport diagrams first, the rest filled in on `requestIdleCallback`, 16 ms main-thread yields between renders — **every diagram is still rendered, none degrades to a code block**) and fence-line-sized placeholder skeletons complete the change. Design and measurements: [docs/plans/2026-10-23-mermaid-iframe-isolation.md](docs/plans/2026-10-23-mermaid-iframe-isolation.md). +- ⚡ **Smooth scrolling for large documents**: the render queue pauses while the reader scrolls (resuming 350 ms after the last scroll event) and only serves the preview that is actually on screen — hidden tabs keep placeholders and warm their diagrams when shown again. The two mutation-driven full-document scans (inline HTML pass, heading-anchor pass) coalesce bursts into one pass every 80 ms (previously a scan per mutation, measured at 8–15 ms each); initial near-viewport detection reads every rect in one batch before the swap writes, removing one forced layout per diagram; `.mermaidWrap` gains `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`, so off-screen diagrams leave layout and paint entirely. Scrolling no longer competes with background renders, document-wide scans or off-screen SVG repaint; diagrams still fill in when the reader stops or scrolls them into view — never as code blocks. +- 🐞 **A failed diagram shows the mermaid parse error inline**: instead of only a generic "Mermaid render failed" label plus the source block (the full error was hidden in the hover title), the error strip now prints the first two lines of mermaid's message (e.g. `Parse error on line 10 ... Expecting 'SEMI', ...`), so a broken fence is found without hunting; the full text stays on the title. + +### v0.29.0 + +- **GenUI in side chats**: the existing `ctx.betterSidebar` service exposes the opt-in `registerSidechatSurfaceAdapter` for GenUI 0.15.0 to render settled assistant replies. Without a consumer, Markdown rendering stays unchanged. +- **Child-thread ownership and lifecycle**: preserve thread, event and original text-block identity. Hiding, switching threads, replacing a row or disposing the plugin revokes old callbacks; actions never fall back to the main conversation. Existing rewrite caches, media handling and streaming state remain intact. +- **Cold-resume boundary**: remove only an explicitly inherited history prefix; ordinary restore markers no longer discard child history. +- **Contribution**: thanks to [@sunxiuguo](https://github.com/sunxiuguo) for the provider implementation ([#1033](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1033)). Original commits are preserved, alongside current dev and the 0.28.2 cold-session read fix. + ### v0.28.2 - 🛡 **A detached session's cwd now comes from its stored workspace address instead of decoding the whole session log.** `sessionQuery.observeSession(..., { projectionMode: 'all' })` decodes the entire zstd artifact and hydrates every projection to answer with one `workingDirectory` string. The real startup fan-out never went through the 0.28.1 `cwdOf()` single-flight (which only covers `/sidebar/api`): the fs-watch socket sends **one frame per watched directory**, and `/sidebar/file|html` resolve cwd per resource, `/sidebar/upload|write` per call — so a 39 MB session was fully decoded dozens of times inside 130–180 ms (the 44-read OOM on 0.28.0 and the 36 reads reported against 0.28.1 are the same path, not a broken dedupe). The cold cwd now uses `sessionPersistence.stat` — a **header-only** read (first zstd frame) with a process-level memo and same-session in-flight sharing — and `activeWorktreeRootOf` returns that address for detached sessions. Once the host attaches the session, the committed `working_directory` and linked-worktree following resume as before. diff --git a/README.md b/README.md index 8301ed1a9..1a2cc223c 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ CI GitHub stars License: MIT - Supported DSH versions: 0.2.1-rc.1+ + Supported DSH versions: 0.2.2-rc.1+
@@ -42,16 +42,17 @@ With the `dsh-context` plugin installed, three places offer a one-click jump int dsh plugin --profile web add dsh-better-sidebar@latest ``` -Then **hard-refresh the browser** (Cmd/Ctrl+Shift+R). Requires DSH **0.2.1-rc.1+**. +Then **hard-refresh the browser** (Cmd/Ctrl+Shift+R). Requires DSH **0.2.2-rc.1+**. -> **Compatibility warning — match the plugin to the host line.** As of 2026-10-26, DSH's npm `latest` is **0.2.1-rc.2**, so the command above installs the compatible v0.28.2. Hosts still on **0.2.0-rc.2** must pin `dsh-better-sidebar@0.26.1` (and should upgrade the host to `0.2.1-rc.2` first); DSH 0.2.1-alpha.5 users must pin `dsh-better-sidebar@0.28.0-alpha.0`. The marketplace installer picks the plugin's `latest` regardless of host version, so an old host gets a version-rejection error — upgrade the host or pin the version explicitly. The two packages' `latest` tags are independent. +> **Compatibility warning — match the plugin to the host line.** As of 2026-11-04, DSH's npm `latest` is **0.2.1-rc.5** and `next` is **0.2.2-rc.1**. **v0.30.0 requires DSH 0.2.2-rc.1+**; hosts on the 0.2.1 line (**0.2.1-rc.1 ~ rc.5**, i.e. today's `latest`) must pin `dsh-better-sidebar@0.28.2` — v0.29.0 was never published to npm. DSH 0.2.1-alpha.5 users must pin `dsh-better-sidebar@0.28.0-alpha.0`, and hosts still on **0.2.0-rc.2** must pin `dsh-better-sidebar@0.26.1`. A 0.x caret never spans a minor version, so one plugin build cannot serve two host lines. The marketplace installer picks the plugin's `latest` regardless of host version, so an old host gets a version-rejection error — upgrade the host or pin the version explicitly. The two packages' `latest` tags are independent.
Pick the plugin version for your DSH version | Your DSH version | Install command | | --- | --- | -| **0.2.1-rc.1+** | `dsh plugin --profile web add dsh-better-sidebar@0.28.2` | +| **0.2.2-rc.1+** | `dsh plugin --profile web add dsh-better-sidebar@0.30.0` | +| **0.2.1-rc.1 ~ 0.2.1-rc.5** | `dsh plugin --profile web add dsh-better-sidebar@0.28.2` | | **0.2.1-alpha.5** | `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` | @@ -70,12 +71,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. Confirm DSH is 0.2.1-rc.1 or newer, then run dsh plugin --profile web add dsh-better-sidebar@0.28.2 +1. Confirm DSH is 0.2.2-rc.1 or newer, then run dsh plugin --profile web add dsh-better-sidebar@0.30.0 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 0.28.2` (macOS / Linux / Windows Git Bash; `./scripts/install.ps1 -Version 0.28.2` for native Windows). It handles installation + bundle registration. +**One-line script** — clone this repo and run `bash scripts/install.sh 0.30.0` (macOS / Linux / Windows Git Bash; `./scripts/install.ps1 -Version 0.30.0` for native Windows). It handles installation + bundle registration. **Updating**: just re-run the install command, then hard-refresh the browser. @@ -89,15 +90,30 @@ If something fails, check the FAQ table in https://github.com/omdsh-dev/DSH-bett | `Ignored build scripts` error | pnpm 11 blocked a transitive dependency's build script. Run `pnpm approve-builds` in the profile directory (`~/.dsh/profiles/web`) — this plugin itself has no build-script dependencies. | | `minimum release age` / version younger than 24h | The release is less than 24 hours old. Wait 24h or re-run (pnpm auto-adds `minimumReleaseAgeExclude`). | | "Profile directory not found" | Run `dsh web` once to initialize `~/.dsh/profiles/web`. | +| Host dies on start: `DesktopHostFatalError: … required plugins did not activate / better-sidebar` | The profile carries its own `@deepseek-ai/dsh-*` copies (left by an older DSH, or listed in the profile's `package.json` / overrides) and they resolve ahead of the installation, so the `dsh-subagent` this plugin imports statically binds to a mixed set; when an export is missing the host only reports this fatal and never names the package. Confirm with the check shipped in the current plugin: `node ~/.dsh/profiles/web/node_modules/dsh-better-sidebar/scripts/check-profile-host-tree.mjs ~/.dsh/profiles/web`. Fix: remove `@deepseek-ai/dsh-*` from the profile's `package.json` / overrides and `pnpm install` there (the installation then supplies them), or align both copies to one version; then restart. The install scripts run this check for you. | | **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@0.2.1-rc.1 dsh plugin --profile web add dsh-better-sidebar@0.28.2`. | +| `dsh: command not found` | Install DSH first; or use `npx -y --package @deepseek-ai/dsh@0.2.2-rc.1 dsh plugin --profile web add dsh-better-sidebar@0.30.0`. |
## 🆕 Recent Updates +**v0.30.0 — DSH 0.2.2 support, side-chat images, clickable quote chips** + +- **DSH 0.2.2-rc.1 is the new baseline** (all 14 peer floors move to `^0.2.2-rc.1`). The host replaced the installable model-selection ref with an agent-owned `AgentModel`, so a side-chat thread's model switch now goes through `agent.model.select()` — recorded once in the log and applied to the next step. A 0.x caret never spans a minor: DSH 0.2.1 hosts (today's npm `latest`) keep pinning plugin v0.28.2. +- **Side Chat takes images**: paste a screenshot or pick PNG / JPEG / WebP / GIF, preview or remove before sending, or send images alone; the preview survives a reload and a cold restore. +- **Quote chips are clickable**: a passage selected with "Add to conversation" lands as a chip that jumps back to the source file and flashes the quoted lines, with a nonce so a second click jumps again; if the reference record cannot be persisted the plugin falls back to the previous built-in chip instead of landing a dead one. +- **Drafts survive the host-owned close paths**: closing a native sidebar tab or quitting the desktop app keeps the unsaved draft and offers it back when the same file is reopened — the host exposes no cancellable close hook, so this is backup-and-restore rather than a prompt. +- **Reliability**: a side-chat seed built from a compacted parent no longer persists an unreadable session log; page CSS zoom is no longer misread as a page transform; the bottom workbench terminal no longer paints black; container workspaces show every child repository in the Git panel; the installers refuse a profile whose `@deepseek-ai/dsh-*` copies are a mixed version pair and print the repair command. + +**v0.29.0 — GenUI in side chats** + +- Adds the opt-in `registerSidechatSurfaceAdapter` service for GenUI 0.15.0. Settled assistant replies can render interactive components, with actions and state kept in the owning child thread. +- Uninstalled consumers, streaming replies and unsupported fences retain the existing Markdown view. The 0.28.2 cold-session read fix remains included. +- Provider contribution: [@sunxiuguo](https://github.com/sunxiuguo), [#1033](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1033). + **v0.28.2 — large-session cold-read fix** - **Root cause fixed**: a detached session's cwd no longer decodes the whole session log — it reads the workspace address stored in the header (first zstd frame only, header-only), memoized per session with in-flight sharing; `activeWorktreeRootOf` no longer folds the stored log for a detached session @@ -111,17 +127,10 @@ If something fails, check the FAQ table in https://github.com/omdsh-dev/DSH-bett - **Silent wrong-file writes are gone**: tab reconciliation now covers tabs in background sessions, and worktree sessions use one address base — a renamed/deleted file is no longer re-created on the next save, and a chat link never opens a same-named file from another checkout - **Host crash guard**: pathological `git status` output is capped with a latch and a process-tree kill, turning "host dies with `RangeError`" into one failed SCM refresh - **Git page**: histories with more than 1,000 branches load again; tags now decorate commits, rows and details, and tag changes invalidate pagination -- **Editor**: saving after an mtime-only change no longer deadlocks on `fs-conflict`; the reading position survives tab re-seating; “Add to conversation” lands as a compact reference chip and never flattens earlier chips +- **Editor**: saving after an mtime-only change no longer deadlocks on `fs-conflict`; the reading position survives tab re-seating; “Add to conversation” lands as a compact reference chip and never flattens earlier chips — and a selected passage now becomes a *clickable* quote chip that jumps back to the source file and flashes the quoted lines ([#888](https://github.com/omdsh-dev/DSH-better-sidebar/issues/888)) - **Markdown links**: local destinations normalize Windows backslashes, so `C:\ws\_analysis\report.md` opens instead of a bare ENOENT - **Sidebar**: the bottom-workbench toggle stays visible while the right panel is open; the macOS dock fallback avoids the traffic lights; a content-stable tab scope ends needless full-file re-reads; closing a side-chat tab archives its session -**v0.28.0 — stable plugin release for DSH 0.2.1-rc.1+** - -- Move all 13 DSH peer floors to `^0.2.1-rc.1`; retain the alpha.0 functionality without runtime changes -- The upstream alpha.5 → rc.1 full-tree diff contains 355 files, all `package.json`; no source changes -- DSH 0.2.0-rc.2 hosts stay on plugin v0.26.1; DSH 0.2.1-alpha.5 hosts stay on v0.28.0-alpha.0 -- Validation: [RC adaptation record](./docs/plans/2026-10-17-dsh-0.2.1-rc.1-adaptation.md) - ## 🔌 Plugin Ecosystem `ctx.betterSidebar` offers two extension points to every plugin — `registerTab` / `registerFileViewer`; the built-in 6 tabs + 4 viewers use the very same API. The GitHub topic [`dsh-better-sidebar`](https://github.com/topics/dsh-better-sidebar) already lists **30+ ecosystem plugins**; the full integration guide is at **[docs/external-plugin-guide.md](./docs/external-plugin-guide.md)**. @@ -215,7 +224,7 @@ export function apply(ctx: Context) { - Routes sit behind a Host-header trust fence (same as `/api`); `fs.write` is atomic; git is only invoked via CLI and never sets identity - ⚠️ **Since v0.23.0 the fs routes do no workspace-containment check**: they can read/write any path the host user can reach (OS permissions only) — callers must not treat these routes as fenced -- HTML previews render in an **opaque-origin sandboxed iframe**; the sandbox can be disabled per feature in settings (off by default, with warnings) +- HTML previews render in an **opaque-origin sandboxed iframe** and serve relative CSS, JavaScript, JSON, fonts and WebAssembly with their content types; the sandbox can be disabled per feature in settings (off by default, with warnings) - No git push/pull/fetch; the file tree only watches **expanded** directories; Markdown preview renders the saved file - Read-only formats (spreadsheets / PDF / images / Office) are rendered by DSH's own document preview and follow the host version; the browser view only exists in the desktop profile - Unsaved drafts are confirmed before closing a tab / deleting a file / refreshing; saving after external modification is rejected, never silently overwritten diff --git a/README_ZH.md b/README_ZH.md index ec1c9849b..f42525c61 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -7,7 +7,7 @@ CI GitHub stars License: MIT - 支持的 DSH 版本:0.2.1-rc.1+ + 支持的 DSH 版本:0.2.2-rc.1+
@@ -42,16 +42,17 @@ dsh plugin --profile web add dsh-better-sidebar@latest ``` -装完**硬刷新浏览器**(Cmd/Ctrl+Shift+R)即可。要求 DSH **0.2.1-rc.1+**。 +装完**硬刷新浏览器**(Cmd/Ctrl+Shift+R)即可。要求 DSH **0.2.2-rc.1+**。 -> **兼容性警告:插件版本必须与宿主线匹配。** 截至 2026-10-26,DSH 的 npm `latest` 是 **0.2.1-rc.2**,上方命令安装的 v0.28.2 与之兼容。仍停留在 **0.2.0-rc.2** 的宿主必须固定 `dsh-better-sidebar@0.26.1`(并建议先升级宿主到 `0.2.1-rc.2`);DSH 0.2.1-alpha.5 用户固定 `dsh-better-sidebar@0.28.0-alpha.0`。市场安装器按插件的 `latest` 安装、不按宿主版本选版本,旧宿主会收到版本拒绝错误——请升级宿主或显式固定版本。两个包的 `latest` 标签不是同一支持线。 +> **兼容性警告:插件版本必须与宿主线匹配。** 截至 2026-11-04,DSH 的 npm `latest` 是 **0.2.1-rc.5**、`next` 是 **0.2.2-rc.1**。**v0.30.0 要求 DSH 0.2.2-rc.1+**;仍停在 0.2.1 线(**0.2.1-rc.1 ~ rc.5**,也就是今天的 `latest`)的宿主必须固定 `dsh-better-sidebar@0.28.2`——v0.29.0 从未发布到 npm。DSH 0.2.1-alpha.5 用户固定 `dsh-better-sidebar@0.28.0-alpha.0`,**0.2.0-rc.2** 宿主固定 `dsh-better-sidebar@0.26.1`。0.x 的 caret 不跨 minor,因此一个构建无法同时服务两条宿主线。市场安装器按插件的 `latest` 安装、不按宿主版本选版本,旧宿主会收到版本拒绝错误——请升级宿主或显式固定版本。两个包的 `latest` 标签不是同一支持线。
按 DSH 版本选插件版本 | 你的 DSH 版本 | 安装命令 | | --- | --- | -| **0.2.1-rc.1+** | `dsh plugin --profile web add dsh-better-sidebar@0.28.2` | +| **0.2.2-rc.1+** | `dsh plugin --profile web add dsh-better-sidebar@0.30.0` | +| **0.2.1-rc.1 ~ 0.2.1-rc.5** | `dsh plugin --profile web add dsh-better-sidebar@0.28.2` | | **0.2.1-alpha.5** | `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` | @@ -70,12 +71,12 @@ dsh plugin --profile web add dsh-better-sidebar@latest ```text 帮我安装 dsh-better-sidebar 插件(DSH 侧边栏工作台),步骤: -1. 先确认 DSH 为 0.2.1-rc.1 或更新版本,再执行 dsh plugin --profile web add dsh-better-sidebar@0.28.2 +1. 先确认 DSH 为 0.2.2-rc.1 或更新版本,再执行 dsh plugin --profile web add dsh-better-sidebar@0.30.0 2. 完成后提醒我硬刷新浏览器(Cmd/Ctrl+Shift+R) 遇到报错先查 https://github.com/omdsh-dev/DSH-better-sidebar README 的常见问题表。 ``` -**一键脚本**——克隆本仓库后执行 `bash scripts/install.sh 0.28.2`(macOS / Linux / Windows Git Bash;Windows 原生用 `./scripts/install.ps1 -Version 0.28.2`),自动完成安装 + bundle 注册。 +**一键脚本**——克隆本仓库后执行 `bash scripts/install.sh 0.30.0`(macOS / Linux / Windows Git Bash;Windows 原生用 `./scripts/install.ps1 -Version 0.30.0`),自动完成安装 + bundle 注册。 **更新**:重跑一次安装命令即可,然后硬刷新浏览器。 @@ -89,15 +90,30 @@ dsh plugin --profile web add dsh-better-sidebar@latest | 报 `Ignored build scripts` | pnpm 11 拦截了某个传递依赖的构建脚本。在 profile 目录(`~/.dsh/profiles/web`)跑 `pnpm approve-builds` 按提示放行——本插件自身已无构建脚本依赖。 | | 报 `minimum release age` / 版本不足 24h | 装的版本发布不足 24 小时。等 24h 或重跑一次(pnpm 会自动补 `minimumReleaseAgeExclude`)。 | | 报「找不到 profile 目录」 | 先跑一次 `dsh web`,让它初始化 `~/.dsh/profiles/web`。 | +| 宿主启动即崩:`DesktopHostFatalError: … required plugins did not activate / better-sidebar` | profile 里自带了 `@deepseek-ai/dsh-*` 副本(旧 DSH 版本留下的,或被写进 profile 的 `package.json` / overrides),它们会抢在宿主安装之前被解析,本插件静态 import 的 `dsh-subagent` 因此绑到混搭版本;混版缺导出时宿主只报这条 fatal,看不到是哪个包缺了什么。先确认(新版插件随包提供):`node ~/.dsh/profiles/web/node_modules/dsh-better-sidebar/scripts/check-profile-host-tree.mjs ~/.dsh/profiles/web`。修复:从 profile 的 `package.json` / overrides 移除 `@deepseek-ai/dsh-*` 后在该目录 `pnpm install`(让宿主安装提供),或把两份副本对齐到同一版本;然后重启。安装脚本会自动跑这条检查。 | | 页面出现**两个侧边栏** | 双挂载。删掉 `~/.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@0.2.1-rc.1 dsh plugin --profile web add dsh-better-sidebar@0.28.2`。 | +| 提示 `dsh: command not found` | 先安装 DSH;或用 `npx -y --package @deepseek-ai/dsh@0.2.2-rc.1 dsh plugin --profile web add dsh-better-sidebar@0.30.0`。 |
## 🆕 最近更新 +**v0.30.0 — 支持 DSH 0.2.2、侧边对话可发图、引用 chip 可点击** + +- **基线抬到 DSH 0.2.2-rc.1**(14 条 peer 下限全部前移到 `^0.2.2-rc.1`)。宿主把可安装的模型选择 ref 换成了 agent 自有的 `AgentModel`,侧边对话的模型切换改走 `agent.model.select()`——只落盘一次,并作用于下一步。0.x 的 caret 不跨 minor:DSH 0.2.1 线(也就是今天的 npm `latest`)继续固定插件 v0.28.2。 +- **侧边对话可以发图**:粘贴截图或选择 PNG / JPEG / WebP / GIF,发送前可预览、可移除,也可以只发图片;刷新页面或冷恢复后预览仍在。 +- **引用 chip 可点击**:用「添加到对话」划选的一段文字会落成一枚 chip,点击跳回源文件并闪烁被引行段;带 nonce,所以连点两次仍会再次跳转。引用记录写不进存储时回退到原来的内置 chip,而不是落一枚点不动的死 chip。 +- **草稿不再被宿主侧的关闭路径吞掉**:关闭原生侧边页签、或退出桌面端时,未保存草稿会被备份,重开同一文件时提示恢复——宿主没有可取消的关闭钩子,所以这是备份 + 恢复,不是弹窗拦截。 +- **可靠性**:父会话压缩过之后开的侧聊不再写出不可读的会话日志;页面 CSS zoom 不再被误判为页面变换;底部工作台终端不再自带黑底;容器工作区在 Git 面板里能看到每个子仓库;安装脚本发现 profile 里 `@deepseek-ai/dsh-*` 版本混搭会直接拒绝并打印修复命令。 + +**v0.29.0 — 侧边对话接入 GenUI** + +- 新增可选的 `registerSidechatSurfaceAdapter` 服务,配合 GenUI 0.15.0 在已结算的侧边回复里渲染交互组件;状态和动作归属对应子线程。 +- 未安装消费插件、流式回复及不支持的围栏继续显示原 Markdown;保留 0.28.2 的冷会话读取修复。 +- 配套实现由 [@sunxiuguo](https://github.com/sunxiuguo) 贡献,见 [#1033](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1033)。 + **v0.28.2 — 大会话冷读修复** - **根因修复**:detached 会话的 cwd 不再解码整份会话日志——改读存储在 header 里的工作区地址(只读第一个 zstd 帧,header-only),按会话做进程内缓存与在飞去重;`activeWorktreeRootOf` 对 detached 会话不再折持久化日志 @@ -111,17 +127,10 @@ dsh plugin --profile web add dsh-better-sidebar@latest - **不再静默写错文件**:页签调解覆盖后台会话,worktree 会话统一地址基准——改名/删除的已打开文件不会被下一次保存重建,聊天链接也不会静默打开另一检出的同名文件 - **宿主崩溃防护**:病态 `git status` 输出加了闩锁与进程树终止,「宿主 `RangeError` 崩溃」降为一次 SCM 刷新失败 - **Git 页**:>1000 分支的历史恢复加载;tag 现在装饰提交行与详情,tag 变化会使旧分页失效 -- **编辑器**:仅 mtime 变化后保存不再死锁 `fs-conflict`;刷新后保留阅读位置;「添加到对话」落地为紧凑引用 chip,不再展平已有 chip +- **编辑器**:仅 mtime 变化后保存不再死锁 `fs-conflict`;刷新后保留阅读位置;「添加到对话」落地为紧凑引用 chip,不再展平已有 chip —— 现在划选的一段文字还会变成**可点击**的引用 chip,点击跳回源文件并闪烁被引行段([#888](https://github.com/omdsh-dev/DSH-better-sidebar/issues/888)) - **Markdown 链接**:本地 destination 的 Windows 反斜杠归一,`C:\ws\_analysis\report.md` 不再报裸 ENOENT - **侧栏**:右栏展开时底部工作台入口常显;macOS 兜底入口避开红绿灯;页签 scope 按内容稳定,消除无谓的整文件重读;关闭侧聊页签时归档其会话 -**v0.28.0 — 面向 DSH 0.2.1-rc.1+ 的插件正式版** - -- 13 条 DSH peer 下限前移到 `^0.2.1-rc.1`,沿用 alpha.0 的功能实现,不增加运行时改动 -- 上游 alpha.5 → rc.1 完整树差异共 355 个文件,全部为 `package.json`,源码零变化 -- DSH 0.2.0-rc.2 宿主固定插件 v0.26.1;DSH 0.2.1-alpha.5 宿主固定 v0.28.0-alpha.0 -- 验证:[RC 适配记录](./docs/plans/2026-10-17-dsh-0.2.1-rc.1-adaptation.md) - ## 🔌 插件生态 `ctx.betterSidebar` 向所有插件开放 `registerTab` / `registerFileViewer` 两个扩展点,内置 6 tab + 4 viewer 与第三方插件走同一套 API。GitHub topic [`dsh-better-sidebar`](https://github.com/topics/dsh-better-sidebar) 下已有 **30+ 生态插件**;完整接入文档见 **[docs/external-plugin-guide.md](./docs/external-plugin-guide.md)**。 @@ -215,7 +224,7 @@ export function apply(ctx: Context) { - 路由受 Host 头信任围栏保护(与 `/api` 一致);`fs.write` 原子写入;git 只调 CLI、绝不设置身份 - ⚠️ **v0.23.0 起文件系统路由不做工作区包含检查**:能读写宿主用户可访问的任意路径(只受 OS 权限约束)——调用方不能再把这些路由当作被围栏保护的接口 -- HTML 预览在**不透明源沙箱 iframe** 中渲染;设置页可按功能关闭沙箱(默认关闭,带警告文案) +- HTML 预览在**不透明源沙箱 iframe** 中渲染,相对引用的 CSS、JavaScript、JSON、字体与 WebAssembly 均按内容类型返回;设置页可按功能关闭沙箱(默认关闭,带警告文案) - Git 无 push/pull/fetch;文件树只对**已展开**的目录做 watch;Markdown 预览渲染的是已保存文件 - 只读预览的格式(表格 / PDF / 图片 / Office)由 DSH 内置文档预览渲染,实现随宿主版本走;浏览器视图只在 desktop profile 存在 - 未保存草稿在关闭标签页 / 删除文件 / 刷新页面前都会先确认;磁盘被外部改动后再保存会被拒绝,不会静默覆盖 diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index 50813ae0c..99c0c27d7 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -2,13 +2,13 @@ > 面向 **消费插件开发者**:如何让你的插件向 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.28.2 正式版**(13 条 DSH peer 下限 `^0.2.1-rc.1`,仅支持 DSH **0.2.1-rc.1+**;0.2.1-alpha.5 请固定 v0.28.0-alpha.0,0.2.0-rc.2 请固定 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,替换语义不复存在)。 -> **版本对照提醒**:当前正式版为 **v0.28.2**(DSH 0.2.1-rc.1+;宿主 npm `latest` 已为 0.2.1-rc.2)。仍停留在 DSH 0.2.0-rc.2 的宿主必须固定插件 v0.26.1;DSH 0.2.1-alpha.5 固定 v0.28.0-alpha.0。市场安装器按插件 `latest` 安装、不按宿主版本选版本。 -> 本次 alpha.5 → rc.1 上游完整树差异 355 项全部为 `package.json`、源码零变化,因此不改功能实现;伴随依赖为 Cordis peer `^4.0.5` / dev `4.0.5`、group `1.0.5`、schemastery `~3.18.5`、include `1.0.10`。RC 验证单独记录于 [适配记录](plans/2026-10-17-dsh-0.2.1-rc.1-adaptation.md),不以已发布 alpha 的测试数字替代。 +> 适用版本:**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.30.0**(14 条 DSH peer 下限 `^0.2.2-rc.1`,仅支持 DSH **0.2.2-rc.1+**;0.2.1 线(0.2.1-rc.1 ~ rc.5)请固定 v0.28.2;0.2.1-alpha.5 请固定 v0.28.0-alpha.0,0.2.0-rc.2 请固定 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,替换语义不复存在)。 +> **版本对照提醒**:当前版本 **v0.30.0**(DSH 0.2.2-rc.1+)。0.x 的 caret 不跨 minor,因此 0.2.1 线(0.2.1-rc.1 ~ 0.2.1-rc.5,即今天的宿主 npm `latest`)必须固定插件 **v0.28.2**——v0.29.0 从未发布;DSH 0.2.1-alpha.5 固定 v0.28.0-alpha.0,0.2.0-rc.2 固定 v0.26.1。市场安装器按插件 `latest` 安装、不按宿主版本选版本。 +> 上一次 alpha.5 → rc.1 适配只动了 `package.json`(完整树差异 355 项,源码零变化);**本次 0.2.1 → 0.2.2 有真实代码改动**(`AgentModel` 取代可安装的 `ModelSelectionRef`、PTC 事件类型声明被移除、宿主图标改为 sprite),逐项记录见 [0.2.2 适配记录](plans/2026-11-04-dsh-0.2.2-rc.1-adaptation.md);伴随依赖仍为 Cordis peer `^4.0.5` / dev `4.0.5`、group `1.0.5`、schemastery `~3.18.5`、include `1.0.10`。 > 权威代码:`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)。 +> alpha.5 已删除 `@deepseek-ai/dsh-invariants` 与上游 `/invariant` 子路径;本插件同步移除 invariant companion,不提供替代注册服务。HTTP/WS 准入遵循宿主 Connection(见 §6)。 > 当前目录语义:**已 attach** 的会话里,文件 / Git / 终端与新建 sidechat 跟随会话 `working_directory`(live 读 `ctx.workingDirectory.get(session)`);**cold / detached** 会话读存储 header(`ctx.sessionPersistence.stat(id)`,只读第一个 zstd 帧,不解码日志;进程内 memo + 在飞去重),`activeWorktreeRootOf` 对 detached 直接返回该工作区地址。不要为取一个 cwd 调 `ctx.sessionQuery.observeSession`:它会解码整份会话日志并水合全部投影,启动期 fs-watch 每目录一帧的扇出会把它放大成数十次整读(详见 [2026-10-27 记录](plans/2026-10-27-workspace-cwd-over-cold-reads.md))。linked worktree 仍按 base 目录记账;新 sidechat seed 尾部盖章当前 cwd,防止继承历史目录覆盖它。 -> alpha.5 的 `TerminalBlockLabels` 要求 `commandLine(line)`;两个渲染消费者与全部 21 份词典同步。宿主兼容性优先读 `package.json#engines.dsh`,缺席才读 DSH peers;本插件没有该字段,仍用 13 条 peers(第三方 `dsh.plugin.json` 不参与)。 +> alpha.5 的 `TerminalBlockLabels` 要求 `commandLine(line)`;两个渲染消费者与全部 21 份词典同步。宿主兼容性优先读 `package.json#engines.dsh`,缺席才读 DSH peers;本插件没有该字段,仍用 14 条 peers(第三方 `dsh.plugin.json` 不参与)。 > 仓库开发规则(硬约束 / CI / 发版)见 [AGENTS.md](../AGENTS.md)。 --- @@ -97,6 +97,8 @@ import type {} from 'dsh-better-sidebar' // 触发 declare module '@deepseek-ai > ⚠️ **计划上架 DSH 插件市场**的插件还须遵守市场 manifest 约束(`dependencies`/`peerDependencies`/`optionalDependencies` 一律不得出现 `cordis`、`scripts` 不得含 install 类钩子),详见 [AGENTS.md](../AGENTS.md) 硬约束一节。 +> 📌 本插件自己的 DSH peer 下限自 v0.30.0 起统一为 `^0.2.2-rc.1`(**v0.30.0 起 14 条**——新增 `@deepseek-ai/dsh-client-ui-input-trigger`,划选引用 chip 的点击与发送展开走它的 `ctx.inputTriggers` 服务,见 §7.2)。宿主预检按名字为 `@deepseek-ai/dsh` 或 `@deepseek-ai/dsh-` 开头的 peer 判定兼容性,所以**只加在 devDependencies 里是不够的**。 + ### 2.3 类型导入路径 ```ts @@ -210,7 +212,13 @@ interface TabDescriptor { icon?: ReactNode | ((size: number) => ReactNode) /** + 菜单排序(升序);默认 100。内置:editor=10, git=20, subagent=30, sidechat=35, terminal-bottom=40 */ order?: number - /** 从 + 菜单隐藏(editor/diff 用:由其他流程触发打开,不在菜单里) */ + /** + * 从 + 菜单隐藏(diff 用:由其他流程触发打开,不在菜单里)。同时不占原生 + * guide 条目、也不出现在「侧边卡片」设置清单里——它没有任何可见承载面, + * 开关无处可关(旧版本给它发过开关,点掉后唯一效果是 `openTab` 静默拒绝, + * 见 #1009)。因此 hidden 类型**恒为启用**:`isTabEnabled()` 忽略 + * `tabsEnabled[id]`。 + */ hidden?: boolean /** * 只投放到插件自己的底部工作台,**永不注册原生右侧栏承载面**(#774)。 @@ -460,7 +468,7 @@ ctx.effect(() => { | id | order | single | hidden | 用途 | |---|---|---|---|---| | `editor` | 10 | 否(按 path 去重) | 否 | 唯一「文件窗口」(编辑/预览 + 资源管理)。chrome 恒合并形态:路径输入框 + 编辑器控件 + 可开关内嵌文件树(全局搜索 `fs.search`;状态存 `tab.meta.treeOpen/treeWidth`)。`editorExplorer`:关(默认)= 按 path 新开,无路径窗口 = 纯资源管理器;开 = 树点击/Enter 经 `updateTab` 原地切换(id/meta 不变),无路径窗口 = 带 chrome 空窗口。树右键「在新 Tab 中打开」「在侧边打开」(pane 右侧 split)。新会话 seed 空文件窗口(`title:'Files'`);旧 `explorer` tab 经 `sanitizeState` 迁移。树 listing 与文件名搜索应用 `explorerExclude` 排除模式(editor 卡片齿轮弹窗可编辑;host 侧过滤,匹配条目彻底移除且永不阻塞折叠);单目录链折叠为 `a/b/c` 面包屑行(POSIX 隐藏与排除条目不计入唯一子项判定) | -| `git` | 20 | 是 | 是(本轮文件操作数) | 「Git」统一 tab(id 保留 `git` 以兼容持久化布局):**Git 视角**(Source Control:独立折叠的 Changes / Graph;Changes 内为多行 Message + 仅填草稿的 Generate、Merge Changes → Staged Changes → Changes(资源组也独立折叠,计数常驻标题最右,文件行整行 hover);Git 刷新仅留在 Changes 标题,外层本轮文件刷新保留;真实 parent hashes 泳道图;常驻底栏为可点击分支 + `*`/`+`/`!` 标记、upstream 的 behind↓ / ahead↑ 及安全 Pull-then-Push 同步;Push/Pull 与 worktree·子仓库选择移入 More Actions;提交只消费已暂存项,冲突/空消息/无暂存时禁止,草稿按会话·仓库·worktree 隔离)+ **本轮文件视角**(原 file-trace:模型读/写/编辑实时折叠,按操作时间倒序平铺、不按文件分组,每行「操作 → 文件路径 → 大小/时间」,支持类型筛选);会话事件经插件自有宿主路由 `changes.ops` 供给(live 日志优先、冷会话回放持久化记录,`afterSeq` 增量),primed 后用 `wait` 挂在宿主侧等下一个工具事件而不是重放整窗),badge 读 tab 轮询写入的同步缓存。页头复用宿主会话页的下划线 Tabs 样式(`wSkVaW_tabs/tab/tabActive`,宿主尚未公开组件;支持左右方向键与 Home/End 切换)。两视角共用底部可拖拽预览面板(`tab.meta.lens/previewH` 持久化),diff 渲染统一走 `src/client/diff/`(`DiffRows`/`DiffFiles`:mod 配对 + 行内高亮 + 语法着色 + 上下文折叠);Git 目标可展开为独立 diff tab(落进工作台的 diff 分栏) | +| `git` | 20 | 是 | 是(本轮文件操作数) | 「Git」统一 tab(id 保留 `git` 以兼容持久化布局):**Git 视角**(Source Control:独立折叠的 Changes / Graph;Changes 内为多行 Message + 仅填草稿的 Generate、Merge Changes → Staged Changes → Changes(资源组也独立折叠,计数常驻标题最右,文件行整行 hover);Git 刷新仅留在 Changes 标题,外层本轮文件刷新保留;真实 parent hashes 泳道图;常驻底栏为可点击分支 + `*`/`+`/`!` 标记、upstream 的 behind↓ / ahead↑ 及安全 Pull-then-Push 同步;Push/Pull 与 worktree·子仓库选择移入 More Actions;提交只消费已暂存项,冲突/空消息/无暂存时禁止,草稿按会话·仓库·worktree 隔离)+ **本轮文件视角**(原 file-trace:模型读/写/编辑实时折叠,按操作时间倒序平铺、不按文件分组,每行「操作 → 文件路径 → 大小/时间」,支持类型筛选);会话事件经插件自有宿主路由 `changes.ops` 供给(live 日志优先、冷会话回放持久化记录,`afterSeq` 增量),primed 后用 `wait` 挂在宿主侧等下一个工具事件而不是重放整窗),badge 读 tab 轮询写入的同步缓存。页头使用宿主公开的 `@deepseek-ai/dsh-client-ui-primitives` 中的 `SegmentedControl`(36px 高度、主题 Token 样式;自动处理选中状态、ARIA 关系及左右方向键、Home/End 键盘导航)。两视角共用底部可拖拽预览面板(`tab.meta.lens/previewH` 持久化),diff 渲染统一走 `src/client/diff/`(`DiffRows`/`DiffFiles`:mod 配对 + 行内高亮 + 语法着色 + 上下文折叠);Git 目标可展开为独立 diff tab(落进工作台的 diff 分栏) | | `subagent` | 30 | 是 | 否 | 任务管理(工作流图/树、团队任务板、后台任务抽屉) | | `sidechat` | 35 | 否(`sidechat:`,按 `meta.threadId` 去重) | 否 | 侧边对话(每对话一 Tab):打开即建空线程(首条消息赢得标签并同步标题);线程 = 插件自建子会话(种子继承父会话上下文,进行中回合以 `interrupted` 闭合;种子带合法 `subagent/descriptor`,SubagentView 按 `Side: ` 前缀过滤),`origin:'subagent'` 隐藏于主列表;走 `/sidebar/api/sidechat.*` 路由;头部菜单切换/重开(`parkSidechatReopen` + 确定性 id),关 Tab 释放 live agent;重开经 `collectOwnEvents` 回源到种子边界;「保存为新会话」= `session.fork`(`this` 敏感)。[设计文档](plans/2026-08-20-sidechat-tab-design.md) | | `diff` | -1 | 否(按 id 去重) | 是 | 差异查看(changes tab 的预览面板「展开为独立页签」触发,同一渲染栈) | @@ -528,6 +536,9 @@ interface FileViewerProps { customData?: unknown // fetchStrategy='custom' 时(load() 的返回值) // 引用带行号时才有(#826,见 §0「地址里的行号」):一次性导航,不是文件的属性 line?: number // 1 基行号(如 `a.c#L131` / `a.c:131`);定位用得上的 viewer 消费它 + // 行段引用(v0.30.0+):与 line 同时到达,给出被引区间的末行。内置编辑器据此 + // 闪一下整段;不消费它的 viewer 行为与只收到 line 相同。 + lineEnd?: number onLineConsumed?: () => void // 已消费该 line 的回报;不调用则每次加载都会重新下发(默认不消费) // 以下为内置文本编辑器与 EditorHost 内部协作字段,外部 viewer 忽略: toolbar?: 'self' | 'host' @@ -712,6 +723,14 @@ const url = ctx.betterSidebar.hostRouteUrl( > 注:内置的 `api.ts` 是 better-sidebar 内部模块,外部插件 **不要** value-import 它(构建纯度门会挡);按上表模式自己 fetch 即可,路由一律经 `hostRouteUrl()`(或等价的「相对路径 + 页面前缀」解析)。所有 HTTP/WS 路由复用宿主 `ctx.connection.requestRejection(req)`:Host/Origin 与浏览器认证均由宿主裁决,只有返回 `undefined` 才准入;同源页面也必须先完成宿主登录。 +### 6.2 侧聊图片输入 + +`POST /sidebar/api/sidechat.prompt` 接受 `{childId,text,images?}`,图片条目为 `{mediaType,data,name?}`,`data` 是原始图片字节的 base64,允许空文本加图片。成功返回 `{accepted:true,messageId}`,消息身份由宿主创建。`sidechat.info` 的 `images` 字段报告附件服务可用性和实际数量、单张及合计字节限制;图片是否适用于所选模型在发送时校验。像素预算与边长上限由宿主在准入时校验,超限回 **413**(wire 错误码 `too-large`,保留宿主 message);存储失败回 **500** `sidechat-error`,不再冒充调用方的 400。 + +请求体只在可能携带图片(超过 1 MiB 元数据上限)时计入并发图片准入;纯文本 prompt 不受该限制影响,超限回 413 而不是可重试的 503。 + +转录与 pending 行携带图片出现位置和显示元数据,读取走经宿主鉴权的 `GET /sidebar/sidechat-image?childId=...&messageId=...&blockIndex=...`。路由核验侧聊归属与用户消息身份,禁止用附件 ID 或本地路径直接读取。图片请求只在页签可见时发出;冷历史读取不恢复 Agent。输入与读取边界详见[设计记录](plans/2026-11-02-sidechat-image-input.md)。 + --- ## 7. 服务方法完整清单 @@ -749,7 +768,8 @@ interface BetterSidebarService { folderIcon(path: string, open: boolean, size: number): ReactNode /** 按 id 查 tab 描述符 */ getTab(id: string): TabDescriptor | undefined - /** 某个 tab 类型是否在 Side card 设置中启用(v0.4.1+;缺省 = 启用) */ + /** 某个 tab 类型是否在 Side card 设置中启用(v0.4.1+;缺省 = 启用; + * hidden: true 的类型恒为 true——设置清单不提供它的开关,见 §4) */ isTabEnabled(id: string): boolean /** 某个 file viewer 是否在 Side card 设置中启用(v0.4.1+;缺省 = 启用) */ isViewerEnabled(id: string): boolean @@ -836,8 +856,15 @@ interface BetterSidebarService { /** 在 scope.sessionId 的侧边栏编辑器打开一个文件(title 缺省为文件名; * id 按路径派生(`editor:` + path),与内置 open-path 拦截一致,不同文件可并排打开)。 * 注意:path 派生 id 只对 openFile/openSidebarFile 成立;editorExplorer 合并模式的 - * 原地切换经 updateTab 重写 path/title,tab id 保持稳定、不再对应 path。 */ - openFile(scope: SessionScope, path: string, title?: string): void + * 原地切换经 updateTab 重写 path/title,tab id 保持稳定、不再对应 path。 + * `options`(v0.30.0+):`{ line?, lineEnd? }` —— 打开后定位到该行;给了 + * `lineEnd` 时内置编辑器会把**整段**闪一下(划选引用 chip 的回跳用它标出 + * 「引的是哪几行」)。行号语义与聊天链接一致:只取起始行、列号丢弃, + * markdown / html 先切到编辑态,`line` 是瞬态(不进持久化白名单)。 + * `lineEnd` 走 `src/client/line-target.ts` 的一次性旁路(key = path + line, + * 被 viewer 取走即删),**不进**宿主的 `navigation.params`——那张表只声明了 + * `line`,塞额外键属于未声明契约。 */ + openFile(scope: SessionScope, path: string, title?: string, options?: { line?: number; lineEnd?: number }): void /** 把插件自有 host 路由(如 `'sidebar/api/fs.read'`)解析成绝对 URL, * 保留反代子路径前缀(v0.25.0+,features 含 'hostRouteUrl')。前导斜杠会被 * 去掉——带着它就会甩掉前缀、钉到源站根;桌面壳的真实基底也由它给出。 @@ -995,12 +1022,69 @@ ctx.effect(() => --- +### 7.1 侧边对话渲染适配器(新增提案,尚未发布) + +这是 v0.29.0 新增、配合 GenUI 0.15.0 的窄范围接入能力,关联 [dsh-genui #354](https://github.com/omdsh-dev/dsh-genui/issues/354)。消费方必须先探测方法存在;未安装、旧版本或未注册适配器时,侧边对话继续使用原有 `MarkdownText` 和 `markdownTextProps()`,不改变普通 Markdown 与代码围栏。 + +```ts +interface SidechatSurface { + readonly root: HTMLElement + readonly source: 'dsh-better-sidebar/sidechat' + readonly threadId: string + readonly eventSeq: number + readonly contentBlockIndex: number + readonly text: string + readonly sendPrompt: (text: string) => Promise +} +interface SidechatSurfaceAdapter { + readonly id: string + readonly mount: (surface: SidechatSurface) => (() => void) +} +// BetterSidebarService 的新增消费入口: +registerSidechatSurfaceAdapter(adapter: SidechatSurfaceAdapter): () => void +``` + +两个类型可从 `dsh-better-sidebar` 或 `dsh-better-sidebar/client/service` 做 type-only 导入。注册必须包在消费插件的 `ctx.effect()` 中;同一个 id 重复注册会抛错,返回的 disposer 可重复调用。 + +- 只提供当前可见、已结算、身份有效的 assistant 文本块。用户消息、推理、工具、流式增量、隐藏页签及身份缺失的行不接入。`eventSeq` 与 `contentBlockIndex` 必须是非负安全整数;块序号保留原始 `message.content` 数组位置,包括非文本和空块留下的空位,不按过滤后的行号重新编号。 +- `root` 是该行真实的 Markdown 容器;`text` 是链接改写前的原始文本。侧边对话容器始终带 `data-genui-surface="dsh-better-sidebar/sidechat"`,包括流式与没有消费插件时,供主对话扫描器明确排除;**不伪造宿主的 `data-chat-*` 标记**。 +- 消费插件自行决定是否增强 `dsh-ui` 围栏,复用它自己的解析器、渲染器和状态,不把渲染实现放到 BetterSidebar,也不扫描该 root 之外的内容。挂载返回的 cleanup 必须释放监听器、观察者、计时器和渲染实例,并还原原始 Markdown;挂载中途失败须先回滚自身改动再抛错。单个适配器的挂载或释放异常会记录,但不会中断其余适配器和侧边对话。 +- 晚注册会接到当时仍可见的行。隐藏、行变更、线程切换或卸载会释放;再次可见时重新挂载。适配器卸载会释放它自己的所有行;BetterSidebar 卸载会释放所有行和注册。内部只保留当前活跃的 root,不积累隐藏页签的引用,也不新增轮询。 +- `sendPrompt(text)` 只调用当前行捕获的子线程 `sidechat.prompt` 路由。它不读取主会话、`scope.sessionId` 或任何兜底目标。行、适配器、线程绑定或插件失效之后,旧回调拒绝执行;请求失败同时通过现有侧边对话错误区显示并 reject 给消费方。调用方应处理 rejection,销毁时取消延迟动作。 + +该提案仍需以真实 DSH `0.2.1-rc.2` profile 同时安装两个候选插件验收,不能把单元测试或模拟 DOM 结果写成已完成双插件验收。 + +### 7.2 划选「添加到对话」的引用 chip(v0.30.0+) + +在内置编辑器(`code` / `markdown` / `jsonl` 的 CodeMirror 面,以及 markdown 预览)里划选一段文字,弹窗「添加到对话」会往主会话 composer 落一枚 chip。此处记录它用到的契约与降级,第三方插件若想复刻同一套交互可以照抄。 + +**宿主服务与 chip 身份** + +- 落 chip 走宿主 `conversation` 服务的 `input.for(session).insertReference(ref, span)`(#1052 之后内置的通道;`ref: ReferenceInsert = { source, ref, label, appearance?, clipboardText }`,`span = { draftRev, start, end }`)。`insertDraftReference()` 负责把「插件投影坐标」折成编辑器检测投影坐标、补前导空格、并在 `snapshot.occurrences` 存在时走 span 通道而不是整框重写(#1002:整框重写会把已有 chip 拍平成纯文本)。 +- **要可点击、要在发送时展开,chip 必须属于一个自有的 input-trigger source**:`ctx.inputTriggers.registerSource({ trigger: '@', name, candidates, onPick, openReference?, codec? })`。`name` 就是 chip 的 `ref.source`,宿主按它路由点击(`openReference(session, { ref, appearance })` 返回 `true` 表示已处理)与发送时的 `codec.serialize(ref, signal)`。没有 codec 的 source,宿主会**拒绝发送**而不是静默降级成剪贴板文本——所以「注册 source」必须先于「插 chip」。 +- 本插件的 source 名是 `betterSidebarQuote`,`candidates` 恒为空(它不进 `@` 菜单,只做 chip 归属);chip 的 `ref` 是短 id,记录(路径 / 行段 / 正文 / 所属会话)存在 `localStorage`(`dsh-better-sidebar:quote-refs`,FIFO 200 条)——因为该模块同时进 core bundle 与 lazy editor chunk,两个模块实例只能靠 `localStorage` 互见记录。 +- 发送时的展开结果与「没有 chip 的时代」字节一致:`<相对路径>[:起[-止]]` 表头 + ≤500 字符时附围栏正文,超限只留表头。 + +**降级链(每一级都是宿主真支持的,不是静默 no-op)** + +1. 自有 source 已注册且 chip 插得进去 → 可点击 chip; +2. 否(宿主无 `ctx.inputTriggers`、注册被拒、composer 不在 plain/claimed 相位、`draftRev` 不匹配……)→ 退回 #1052 的内置 `source: 'reference'` chip(不可点击,但内容正确); +3. 再否(没有 chip 通道)→ 纯文本 `appendToDraft`。 + +失败的那次尝试会把刚写入的 quote 记录回滚(`localStorage` 里不留孤儿 id)。 + +**点击回跳** + +`openReference` 校验 chip 的 `sessionId` 与当前会话一致(否则拒绝:换了会话 cwd 可能不同,会打开错文件),然后 `ctx.betterSidebar.openFile(scope, path, undefined, { line, lineEnd })`;内置编辑器定位到 `line` 并把 `line`–`lineEnd` 整段闪 2.4 s(皮肤令牌 `--dsw-alias-interactive-bg-hover-accent`,`prefers-reduced-motion` 下减弱)。`lineEnd` 与「本次导航的 nonce」都走**插件的模块级一次性旁路**(`src/client/line-target.ts`,key = path + line;arm 时自增 nonce,编辑器按 nonce 判重、读后即消费),不写进宿主导航参数。nonce 是「同一个 chip 连点两次」仍能再次跳转/闪光的关键:宿主对没移动的 `line` 不重发导航,只比较 path + line 会把二次点击误判成已消费,残留的 arm 还可能让之后同 path + line 的普通打开误闪。**底部工作台没有该入口**:chip 只打开右侧栏,底部 `TabContent → EditorHost` 虽是同一组件、同样消费 `line`,但本功能未在底部真机验证。**行号漂移**:记录的是划选时的行号,文件之后被编辑,点击会落到同一行号(可能已偏移);不做锚点搜索或内容定位。 + +--- + ## 8. 声明式设置(v0.4.1+) -每个注册的 tab / viewer **自动**出现在 DSH 设置页「侧边卡片」分区(`SideCardSection` 按注册表驱动渲染,无硬编码): +每个注册的 tab / viewer **自动**出现在 DSH 设置页「侧边卡片」分区(`SideCardSection` 按注册表驱动渲染,无硬编码),**`hidden: true` 的 tab 类型除外**: -- 展示:小卡片网格(图标 + 标题 + 类型 id),**高亮 = 启用**,勾选徽标钉在卡片最右端;viewer 卡片额外显示扩展名。 -- 持久化:开关写入 `SidebarPrefs.tabsEnabled / viewersEnabled`(开放 map,**缺省 = 启用**,显式 `false` 才禁用)。 +- 展示:小卡片网格(图标 + 标题 + 类型 id),**高亮 = 启用**,勾选徽标钉在卡片最右端;viewer 卡片额外显示扩展名。`hidden` 类型没有 `+` 菜单行、没有原生 guide 条目,也就没有可切换的承载面,因此不进清单,且 `isTabEnabled()` 对它恒为 true(#1009)。 +- 持久化:开关写入 `SidebarPrefs.tabsEnabled / viewersEnabled`(开放 map,**缺省 = 启用**,显式 `false` 才禁用;`hidden` 类型的键被忽略)。 - 关闭语义:tab 从 `+` 菜单消失、`openTab` 拒绝新开(`console.warn`)、派生流程(子代理自动展开、agent 终端自动补 tab)停止,**已打开的 tab 保留**;viewer 被 `matchFileViewer` 跳过,文件落到下一个匹配。 - `settings.toggles`(可选):在卡片行下追加**嵌套设置行**(仅父级启用时显示),绑定 `SidebarPrefs` 字段;通过卡片底部「功能设置」条在原生弹窗中编辑。行控件形状见 §4.1 的 `SettingRow`:`type: 'switch' | 'text' | 'number'`(v0.11.0+;text/number 行 blur/Enter 提交,number 行按 min/max 钳制,unit 渲染单位后缀)与 `type: 'select'`(v0.13.0+;`options` 支持 value/title/desc/icon,`multi` 多选存数组并按 options 顺序提交;任一项带 icon 时渲染大图标选项卡)与 `type: 'patterns'`(可编辑字符串数组——chips + 删除钮 + 常驻添加输入框,add/remove 均原子提交整表,占位符走 `patternsPlaceholder`,值必须存 `string[]`;能力 gate `settingPatterns`)。内置示例:subagent tab 的 `autoOpenSubagent`、editor tab 的 `editorExplorer` 图标化下拉(工作区路径围栏与它的开关已移除,见 §8.1)与 `explorerExclude` 排除模式行。 - `settings.pluginToggles`(可选,v0.12.0+):**插件自有设置行**,行控件与 toggles 相同,但 key 是插件局部的——持久化在 prefs 文档的 `pluginSettings[]`(开放 map,无需宿主 schema 字段)。tab 与 viewer 都可用(v0.12.0 起 viewer 卡片也有设置条)。 @@ -1096,7 +1180,7 @@ interface SettingsDescriptor { > > 这是一次**权限放开**:插件侧边栏的 fs 路由现在能读写**宿主用户能访问的任意路径**,只受 OS 权限约束。也就是说,一个能访问到本插件 `/sidebar/*` 路由的同源页面/脚本(**包括你写的第三方消费插件**)可以借这些路由读取、改写、删除该用户权限内的任何文件——例如 `~/.ssh/`、`~/.dsh/`、其他项目的源码。 > -> 缓解手段只有两块,别指望有第三块:① 每条 HTTP/WS 路由都过宿主的**浏览器信任与认证栅栏**(`ctx.connection.requestRejection(req)`,见 §6.2),所以前提是攻击面已有宿主认可的来源与认证;② 宿主用户的 OS 权限本身的边界。**不要**再把「工作区围栏」当成安全边界来设计你的插件——它已经不在了。 +> 缓解手段只有两块,别指望有第三块:① 每条 HTTP/WS 路由都过宿主的**浏览器信任与认证栅栏**(`ctx.connection.requestRejection(req)`,见 §6),所以前提是攻击面已有宿主认可的来源与认证;② 宿主用户的 OS 权限本身的边界。**不要**再把「工作区围栏」当成安全边界来设计你的插件——它已经不在了。 历史背景(`< v0.23.0`):旧的实现用 realpath 解析后比对工作区前缀,越界回 403,并有一个 `workspaceFence` 开关(默认开)可临时关闭;开启时编辑器/文件树错误面会显示原因 + 一键关闭按钮(`FenceErrorNotice`)。用户要求删除该检查,上述代码路径随之删除(`src/path-security.ts` 现在是纯词法解析)。旧 profile 里遗留的 `workspaceFence` 键只是**未知键**——schemastery 的 object schema 对未知键是容忍的,既不报错也不再有任何效果。 @@ -1159,7 +1243,7 @@ interface SettingsDescriptor { - **面板表面**:右/底面板背景 = `var(--dsw-alias-bg-layer-1)`。**绝不消费 `--dsw-specific-sidebar-fill`**(宿主左导航专属,皮肤按左导航语义覆盖它,面板消费会失去填充)。换面板表面 = 覆写 `--dsw-alias-bg-layer-1`。 - **终端/编辑器表面**:`effectiveTokenValue` 读 `--dsw-alias-bg-base`——`transparent` 与 alpha < 0.9 的半透明值回退不透明底色(文字不叠背景画,issue #90);≥ 0.9 放行。 -- **根锚点**:宿主 div 带 `data-dsh-better-sidebar`(append 到 body);其内**面板宿主层** `[data-dsh-panel-host]`(`fixed; inset:0; z-25; pointer-events:none; overflow:hidden+clip`,v0.13.1+),面板/开关簇 absolute 定位,免疫中间层 transform 劫持;页面级 transform 触发 `data-dsh-panel-host-degraded` 降级。`overflow` 级联是**契约**(`hidden` 兜底 + `clip` 收尾,`tests/panel-host-css.spec.ts` 守护):`hidden` 盒子仍是滚动容器,脚本滚动或浏览器 scroll-into-view 修正(焦点移入视口外区域、嵌套 iframe/工作台加载时抢焦点、面板滑出动画中 focus() 落点)会沿最近可滚祖先滚走整层——面板与开关簇集体偏离视口角(computed left/right 仍"正确",偏移藏在盒子自身 scroll offset 里);`clip` 裁剪语义相同但不产生滚动盒,任何路径都滚不动这层。皮肤作用域覆盖限定在 `[data-dsh-better-sidebar]` 内。 +- **根锚点**:宿主 div 带 `data-dsh-better-sidebar`(append 到 body);其内**面板宿主层** `[data-dsh-panel-host]`(`fixed; inset:0; height:100vh 兜底 + 100dvh; z-25; pointer-events:none; overflow:hidden+clip`,v0.13.1+),面板/开关簇 absolute 定位,免疫中间层 transform 劫持;页面级 transform 触发 `data-dsh-panel-host-degraded` 降级。显式高度同样**契约**(`tests/panel-host-css.spec.ts` 守护):不得依赖包含块(`100%` / `auto`,issue #616);`dvh` 必须排在 `vh` 之后——`vh` 取的是大视口,手机地址栏展开时该层高于布局视口,会误触发挂载自检、把宿主降级成 `absolute` 并撑高文档(issue #1014)。`overflow` 级联是**契约**(`hidden` 兜底 + `clip` 收尾,`tests/panel-host-css.spec.ts` 守护):`hidden` 盒子仍是滚动容器,脚本滚动或浏览器 scroll-into-view 修正(焦点移入视口外区域、嵌套 iframe/工作台加载时抢焦点、面板滑出动画中 focus() 落点)会沿最近可滚祖先滚走整层——面板与开关簇集体偏离视口角(computed left/right 仍"正确",偏移藏在盒子自身 scroll offset 里);`clip` 裁剪语义相同但不产生滚动盒,任何路径都滚不动这层。皮肤作用域覆盖限定在 `[data-dsh-better-sidebar]` 内。 - **布局变量**(`` 上,面板打开时有效):`--dsh-sidebar-width` / `--dsh-sidebar-height`。右面板宽度 = AppFrame 的 `padding-right` 预留(新版 `#root [data-dsh-frame]` / rc.8 `#root > [data-slot="root"] > div` 双锚点),AppFrame border box 保持完整桌面视口宽度(Harness 以此判定桌面/窄屏布局,避免插件面板展开误入窄屏);AppFrame 的 details 拖拽手柄按同一变量向左平移贴合列边缘。底部面板仍走 centerCol `margin-bottom`;centerCol 锚点 = **JS 标注**(禁止 `nth-child`):侧栏 shell 的定位器给测得的 centerCol 节点打 `[data-dsh-center-col]` 标签(`Sidebar.tsx` locate,节点更换/HMR 时随 ref 迁移),`layout.css` 用 `#root [data-dsh-center-col]` 选中(`drag-layout.e2e.ts` 断言恰一节点且为对话槽宿主的父级——alpha.2 起 shell 把 `#root [data-slot="main.conversation"]` 解析进列并跳过 `display: contents` 祖先(`center-column.ts` 的 `CENTER_COLUMN_SELECTOR` 同时认 `main.conversation` 与 alpha.1 的 `conversation`),定位器从槽宿主向上取第一个非 `contents` 的祖先;frame 宽度与桌面 Session Log 由 `desktop-layout.e2e.ts` 断言)。 - **用户空间 CSS(v0.14.1+;titleBar 让位机制移除后只剩它)**:`SidebarPrefs.customCss`(设置页「自定义 CSS」分组)注入 ` + + + + + + +` + +/** The generated module. */ +const generated = `/** + * GENERATED by scripts/build-mermaid-frame-asset.mjs — do not edit. + * + * Self-contained mermaid iframe document (inline mermaid UMD + frame + * protocol). See src/client/mermaid-frame.ts for why the preview renders + * diagrams inside an iframe at all. + */ +// The explicit \`: string\` annotation keeps the ~3.5 MB literal out of the +// emitted .d.ts (otherwise tsc expands it into the declaration). +export const MERMAID_FRAME_HTML: string = ${JSON.stringify(frameHtml)} +` + +const target = new URL('../src/client/mermaid-frame-asset.generated.ts', import.meta.url) +writeFileSync(target, generated) +console.log( + 'mermaid frame asset written:', + `${(generated.length / 1024 / 1024).toFixed(2)} MB`, + '(mermaid UMD', + `${(mermaidSource.length / 1024 / 1024).toFixed(2)} MB)`, +) diff --git a/scripts/check-profile-host-tree.mjs b/scripts/check-profile-host-tree.mjs new file mode 100644 index 000000000..76179ef41 --- /dev/null +++ b/scripts/check-profile-host-tree.mjs @@ -0,0 +1,112 @@ +/** + * Detect the torn host-package shadow pair that keeps this plugin from + * activating at all (issue #1107: `DesktopHostFatalError: required plugins did + * not activate / better-sidebar`). + * + * DSH resolves a profile plugin's bare imports through its own runtime + * interception (`dsh-app-boot`'s `routeScoped`): a copy the profile installs + * under `/node_modules` wins over the installation's own tuple, and + * that winning copy is itself the anchor for that copy's siblings' imports. + * So a profile carrying its own `@deepseek-ai/dsh-subagent` also binds + * `@deepseek-ai/dsh-attachment` from the profile tree. The plugin statically + * imports `dsh-subagent` (src/sidechat-routes.ts), whose module graph pulls + * the rest of the host packages — a mixed set can strip a symbol that graph + * imports, and the failure surfaces as a host fatal error ("required plugins + * did not activate") instead of one readable plugin error. + * + * The reliable signal for that mix is the sibling pin: `dsh-subagent` declares + * the exact host version of `dsh-attachment`, so a profile copy that disagrees + * with it came from a different host release. When the profile shadows only the + * subagent, the installation supplies the sibling and that pairing is out of + * reach here. + * + * The lookup below mirrors that resolution exactly: Node's node_modules order + * from the installed plugin, restricted to the profile directory — the prefix + * the interception stops at (`layer.localPrefix`), which is why copies above + * the profile (the shared `profiles/node_modules` tree) never win there and + * are ignored here. + * + * Only an exact pinned peer is judged (`dsh-subagent` pins the sibling host + * package by exact version, so the pairing is decidable); ranged peers are + * treated as clear rather than guessed at. + * + * Usage: node scripts/check-profile-host-tree.mjs + * Exit 0 — nothing torn (plugin not installed, no shadow copy, or a matching + * pair); exit 1 — torn pair, with the repair printed to stderr. + */ +import { existsSync, readFileSync, realpathSync } from 'node:fs' +import { createRequire } from 'node:module' +import { join, resolve, sep } from 'node:path' + +const PLUGIN = 'dsh-better-sidebar' +const SUBAGENT = '@deepseek-ai/dsh-subagent' +const ATTACHMENT = '@deepseek-ai/dsh-attachment' +const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/ + +function realOrUndefined(path) { + try { + return realpathSync(path) + } catch { + return undefined + } +} + +function manifestOf(dir) { + return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) +} + +/** + * The copy Node would pick for `name` from `anchor`, limited to the profile + * tree. Returns undefined when the profile installs no such copy (the host + * installation then supplies it, consistently for every importer). + */ +function shadowOf(anchor, name, profileDir) { + const prefix = profileDir + sep + for (const searchPath of createRequire(anchor).resolve.paths(name) ?? []) { + if (!searchPath.startsWith(prefix)) continue + const dir = join(searchPath, name) + if (existsSync(join(dir, 'package.json'))) return dir + } + return undefined +} + +/** The broken pairing, or undefined when the profile cannot break this import. */ +function tornPair(profileDir) { + const profile = realOrUndefined(profileDir) + if (profile === undefined) return undefined + const pluginDir = realOrUndefined(join(profile, 'node_modules', PLUGIN)) + // A `link:` install resolves outside the profile tree and is not intercepted + // as a profile-layer importer, so the shadow rule does not apply to it. + if (pluginDir === undefined || !pluginDir.startsWith(profile + sep)) return undefined + const subagentDir = shadowOf(join(pluginDir, 'package.json'), SUBAGENT, profile) + if (subagentDir === undefined) return undefined + const expected = manifestOf(subagentDir).peerDependencies?.[ATTACHMENT] + if (typeof expected !== 'string' || !EXACT_VERSION.test(expected)) return undefined + const attachmentDir = shadowOf(join(subagentDir, 'package.json'), ATTACHMENT, profile) + if (attachmentDir === undefined) return undefined + const subagent = manifestOf(subagentDir).version + const attachment = manifestOf(attachmentDir).version + return attachment === expected ? undefined : { profile, subagent, expected, attachment } +} + +const profileArg = process.argv[2] +if (profileArg === undefined || profileArg === '') { + console.error('用法:node scripts/check-profile-host-tree.mjs ') + process.exit(2) +} + +const torn = tornPair(resolve(profileArg)) +if (torn === undefined) { + console.log('[host-tree] profile 未自带宿主包影子副本,或 @deepseek-ai/dsh-subagent ↔ dsh-attachment 配对一致') + process.exit(0) +} + +console.error(`[host-tree] profile 自带的宿主包配对不一致:${SUBAGENT} ${torn.subagent} 要求 ${ATTACHMENT} ${torn.expected},实际解析到 ${torn.attachment}`) +console.error(`[host-tree] profile:${torn.profile}`) +console.error('[host-tree] 它们会抢在 DSH 安装之前被解析,本插件静态 import 的 dsh-subagent 因此绑到混搭版本;混版缺导出时宿主启动只报') +console.error('[host-tree] DesktopHostFatalError / required plugins did not activate,看不到是哪个包缺了什么。') +console.error('[host-tree] 修复(任选其一,然后重启 DSH):') +console.error(`[host-tree] A. 让 DSH 安装提供宿主包:从 profile 的 package.json 与 overrides 移除 @deepseek-ai/dsh-*,再 cd ${torn.profile} && pnpm install`) +console.error(`[host-tree] (若副本由别的依赖带进来:cd ${torn.profile} && pnpm update @deepseek-ai/dsh-*` + ')') +console.error(`[host-tree] B. 把副本对齐到同一版本:cd ${torn.profile} && pnpm add ${SUBAGENT}@${torn.expected} ${ATTACHMENT}@${torn.expected}`) +process.exit(1) diff --git a/scripts/e2e-common.sh b/scripts/e2e-common.sh index 978896c13..60b257ec2 100644 --- a/scripts/e2e-common.sh +++ b/scripts/e2e-common.sh @@ -44,7 +44,7 @@ e2e_require_cmd() { # 回退的 npx 版本是显式钉死的:不钉就会解析 npm 的 dist-tag,可能静默挂到 # 插件不支持的宿主上。**必须写精确版本,不能写 `@next`/`@alpha` 等 dist-tag**。 # 该版本必须与 package.json 的 DSH peer 基线同步。 -DSH_NPX_SPEC="${DSH_NPX_SPEC:-@deepseek-ai/dsh@0.2.1-rc.1}" +DSH_NPX_SPEC="${DSH_NPX_SPEC:-@deepseek-ai/dsh@0.2.2-rc.1}" e2e_resolve_dsh_cmd() { local explicit="${DSH_CMD}" if ! command -v "$DSH_CMD" >/dev/null 2>&1; then @@ -66,7 +66,7 @@ e2e_resolve_dsh_cmd() { # 己在挂什么),只告警。 e2e_check_dsh_version() { local explicit="$1" actual expected - expected="${DSH_EXPECT_VERSION:-0.2.1-rc.1}" + expected="${DSH_EXPECT_VERSION:-0.2.2-rc.1}" # `dsh --version` 冷启动要走 npx,给足预算;拿不到版本就只告警。 actual="$($DSH_CMD --version 2>/dev/null | tr -d '[:space:]' | head -c 64 || true)" case "$actual" in @@ -163,13 +163,16 @@ EOF # ── dsh web 启动 + 就绪轮询 ────────────────────────────────────────────────── # 后台启动 dsh web(--port 0 = OS 分配,避免端口冲突;keyless 可起)。 +# `--no-open` 是必须的:宿主默认会在启动后打开系统浏览器,本地反复跑这条 +# lane 会不断弹窗(CI 是无头环境不受影响,本地开发机不是)。基线宿主 +# 0.2.2-rc.1 的 web app 已提供该 flag(@deepseek-ai/dsh-web-app/lib/startup.js)。 # $1 = stdout 日志;$2 = stderr 日志(缺省合并进 $1:mount lane 单文件, # aggregate lane 分 out/err 两个文件)。写入全局 SERVER_PID。 e2e_start_dsh_web() { if [ $# -ge 2 ]; then - $DSH_CMD web --port "$PORT" >"$1" 2>"$2" & + $DSH_CMD web --port "$PORT" --no-open >"$1" 2>"$2" & else - $DSH_CMD web --port "$PORT" >"$1" 2>&1 & + $DSH_CMD web --port "$PORT" --no-open >"$1" 2>&1 & fi SERVER_PID=$! } diff --git a/scripts/e2e-sidechat-images.mjs b/scripts/e2e-sidechat-images.mjs new file mode 100644 index 000000000..22e919431 --- /dev/null +++ b/scripts/e2e-sidechat-images.mjs @@ -0,0 +1,375 @@ +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { spawn } from 'node:child_process' +import { createRequire } from 'node:module' +import { fileURLToPath } from 'node:url' +import { dirname, join, resolve } from 'node:path' +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, openSync, closeSync, symlinkSync, utimesSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { createHash } from 'node:crypto' +import { setTimeout as delay } from 'node:timers/promises' + +// Intended location: /scripts/e2e-sidechat-images.mjs. +// Dependencies must be preinstalled; this script never installs packages. +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const args = process.argv.slice(2) +const option = (name, fallback) => { + if (!args.includes(name)) return fallback + const value = args[args.indexOf(name) + 1] + assert(value && !value.startsWith('--'), `${name} requires a value`) + return value +} +const baseline = args.includes('--baseline') +const largeImage = args.includes('--large-image') +const fixtureWidth = largeImage ? 1024 : 64 +const fixtureHeight = largeImage ? 768 : 48 +const plugin = resolve(option('--plugin', root)) +const hostRootOption = option('--host-root') +assert(hostRootOption, '--host-root is required (directory containing node_modules/@deepseek-ai/dsh/lib/bin.js)') +const hostRoot = resolve(hostRootOption) +const tools = join(hostRoot, 'node_modules') +const hostPackage = JSON.parse(readFileSync(join(tools, '@deepseek-ai/dsh/package.json'), 'utf8')) +assert.equal(hostPackage.version, '0.2.2-rc.1', 'preinstalled host must be 0.2.2-rc.1') +const channel = option('--channel') +const require = createRequire(join(root, 'package.json')) +const { chromium, request, expect } = require('@playwright/test') +const sharp = createRequire(join(hostRoot, 'package.json'))('sharp') +const cli = join(tools, '@deepseek-ai/dsh/lib/bin.js') +const artifactsParent = resolve(option('--artifacts-dir', tmpdir())) +mkdirSync(artifactsParent, { recursive: true }) +// Preserve evidence after success or failure. +const run = mkdtempSync(join(artifactsParent, baseline ? 'sidechat-baseline-' : 'sidechat-images-')) +const home = join(run, 'home') +const workspace = join(run, 'workspace') +const profile = join(home, 'profiles/web') +const result = { mode: baseline ? 'baseline' : 'images', status: 'running', run, plugin, startedAt: new Date().toISOString(), steps: [], screenshots: [], providerRequests: [], pluginRequests: [], imageReads: [], pageErrors: [], registrationErrors: [] } +let host, browser, api, page, mock +let hostSerial = 0 +let hostPort = 0 +let interrupted +let finalization +const hash = bytes => createHash('sha256').update(bytes).digest('hex') +const json = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n') +const redact = text => String(text).replace(/([?&]token=)[^\s&"<>]+/g, '$1[redacted]') +async function until(label, read, timeout = 45000) { + const end = Date.now() + timeout + while (Date.now() < end) { + const value = await read() + if (value) return value + await delay(200) + } + throw new Error(`Timed out waiting for ${label}`) +} +async function stopHost() { + if (!host) return + const child = host + host = undefined + if (child.exitCode !== null || !child.pid) return + if (process.platform === 'win32') { + await new Promise((done, reject) => { + const killer = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }) + killer.once('error', reject) + killer.once('exit', code => { if (code !== 0) child.kill(); done() }) + }) + } else { + const killGroup = signal => { + try { process.kill(-child.pid, signal) } catch (error) { if (error.code !== 'ESRCH') throw error } + } + killGroup('SIGTERM') + const deadline = Date.now() + 5000 + while (child.exitCode === null && child.signalCode === null && Date.now() < deadline) await delay(100) + killGroup('SIGKILL') + } + await until('host exit', () => child.exitCode !== null || child.signalCode !== null, 15000) +} +async function boot() { + if (interrupted !== undefined) throw new Error(`Interrupted by ${interrupted}`) + const logfile = join(run, `host-${++hostSerial}.log`) + const fd = openSync(logfile, 'a') + const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^DSH_|(?:API_KEY|AUTH_TOKEN|ACCESS_TOKEN|SECRET)/i.test(key))) + Object.assign(env, { DSH_HOME: home, SIDECHAT_IMAGE_TEST_KEY: 'local-deterministic-test-key' }) + host = spawn(process.execPath, [cli, 'web', '--port', String(hostPort), '--no-open'], { cwd: workspace, env, stdio: ['ignore', fd, fd], windowsHide: true, detached: process.platform !== 'win32' }) + closeSync(fd) + let spawnError + host.once('error', error => { spawnError = error }) + const launch = await until('authenticated host launch', () => { + if (spawnError) throw spawnError + const text = readFileSync(logfile, 'utf8') + const match = text.match(/http:\/\/127\.0\.0\.1:\d+\/\?token=[\w-]+/) + if (match) return match[0] + if (host.exitCode !== null) throw new Error(`Host exited ${host.exitCode}; inspect ${logfile}`) + }, 120000) + api = await request.newContext() + const exchange = await api.get(launch, { maxRedirects: 0 }) + assert(exchange.status() >= 300 && exchange.status() < 400, 'launch token exchange redirects') + const state = await api.storageState() + assert(state.cookies.length > 0, 'launch token exchanged through Playwright request') + const origin = new URL(launch).origin + hostPort = Number(new URL(launch).port) + result.steps.push({ step: 'host-authenticated', origin, hostPid: host.pid }) + return { origin, state } +} +async function rpc(origin, method, value) { + const response = await api.post(`${origin}/api/${method}`, { data: { type: 'client-request', rpcId: `audit-${Date.now()}`, method, payload: { args: { request: value } } } }) + assert(response.ok(), `${method} HTTP ${response.status()}`) + const body = await response.json() + assert.equal(body.result?.ok, true, JSON.stringify(body)) + return body.result.value +} +async function screenshot(name) { + const path = join(run, `${name}.png`) + await page.screenshot({ path, fullPage: true }) + result.screenshots.push(path) +} +async function observePage(context) { + page = await context.newPage() + page.on('pageerror', error => result.pageErrors.push(redact(error.message))) + page.on('console', message => { if (message.type() === 'error' && /native register .* error|\[dsh-better-sidebar\]/.test(message.text())) result.registrationErrors.push(redact(message.text())) }) + page.on('request', req => { + if (req.url().includes('/sidebar/') && req.method() === 'POST') { + try { + const body = req.postDataJSON() + if (Array.isArray(body.images)) body.images = body.images.map(({ data, ...image }) => ({ ...image, encodedBytes: data.length, sourceBytes: Buffer.from(data, 'base64').length })) + result.pluginRequests.push({ path: new URL(req.url()).pathname, bodyBytes: Buffer.byteLength(req.postData() ?? ''), body }) + } catch (error) { result.registrationErrors.push(`Request capture failed: ${redact(error.message)}`) } + } + }) + page.on('response', response => { + if (response.url().includes('/sidebar/sidechat-image')) result.imageReads.push({ path: new URL(response.url()).pathname + new URL(response.url()).search, status: response.status(), contentType: response.headers()['content-type'] }) + }) +} +async function dismiss() { + for (let i = 0; i < 5; i++) { + for (const name of [/^(Continue|继续)$/, /^(Configure later|稍后配置)$/, /^(Close|关闭)$/]) { + const button = page.getByRole('dialog').getByRole('button', { name }).first() + if (await button.isVisible().catch(() => false) && await button.isEnabled().catch(() => false)) await button.click({ timeout: 2000 }).catch(() => {}) + } + await delay(250) + } +} +const composer = () => page.locator('[class*="sidechatComposer"] textarea:visible').first() +const transcriptImages = () => page.locator('[class*="sidechatScroll"] img:visible') +async function openSidechat() { + if (await composer().isVisible().catch(() => false)) return + const expand = page.locator('[data-sidebar-right-expand]:visible').first() + if (await expand.isVisible()) await expand.click() + if (await composer().isVisible().catch(() => false)) return + const entry = page.locator('[data-sidebar-right-guide-entry="sidechat"]').first() + if (!await entry.isVisible()) await page.locator('[data-dockkit-add-tab]:visible').first().click() + await expect(page.locator('[data-sidebar-right-guide-entry="terminal"]')).toHaveCount(1) + await expect(page.locator('[data-sidebar-right-guide-entry="browser"]')).toHaveCount(0) + await entry.click() + await expect(composer()).toBeVisible({ timeout: 45000 }) +} +async function mountSmoke() { + async function openFiles() { + const files = page.locator('[data-sidebar-right-guide-entry="files"]') + if (!await files.isVisible().catch(() => false)) await page.locator('[data-dockkit-add-tab]:visible').first().click() + await files.click() + await expect(page.locator('[data-sidebar-right-panel] [role="button"][title$="hello.txt"]:visible')).toHaveCount(1) + } + await openFiles() + await page.locator('[data-sidebar-right-panel] [role="button"][title$="hello.txt"]:visible').click() + await expect(page.locator('[data-sidebar-right-panel]')).toContainText('image mount fixture') + await openFiles() + await page.evaluate(() => globalThis.document.querySelector('[data-dsh-better-sidebar]')?.setAttribute('data-e2e-generation', 'before-reload')) + const stamp = new Date() + utimesSync(join(plugin, 'lib/client.js'), stamp, new Date(stamp.getTime() + 2000)) + await expect(page.locator('[data-dsh-better-sidebar][data-e2e-generation="before-reload"]')).toHaveCount(0, { timeout: 60000 }) + await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 60000 }) + await openFiles() + await expect(page.locator('[data-sidebar-right-unavailable]')).toHaveCount(0) + assert.deepEqual(result.registrationErrors, []) + result.steps.push({ step: 'packed-mount-and-native-entry-replacement', filesReadable: true, registrationErrors: 0 }) + await screenshot('native-entry-replacement') +} +async function assertImages(count, step) { + await expect(transcriptImages()).toHaveCount(count, { timeout: 45000 }) + await expect.poll(() => transcriptImages().evaluateAll(images => images.every(image => image.complete && image.naturalWidth > 0))).toBe(true) + result.steps.push({ step, count, images: await transcriptImages().evaluateAll(images => images.map(image => ({ alt: image.alt, width: image.naturalWidth, height: image.naturalHeight }))) }) + await screenshot(step) +} +async function sendImage(kind, fixture) { + const marker = `audit-${kind}-image` + const before = result.providerRequests.length + if (kind === 'selected') { + await page.locator('[class*="sidechatComposer"] input[type="file"]').setInputFiles(fixture) + } else { + await page.evaluate(async base64 => { + const bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0)) + await navigator.clipboard.write([new globalThis.ClipboardItem({ 'image/png': new Blob([bytes], { type: 'image/png' }) })]) + }, readFileSync(fixture).toString('base64')) + await composer().focus() + await page.keyboard.press(process.platform === 'darwin' ? 'Meta+V' : 'Control+V') + } + await expect(page.locator('[class*="sidechatComposer"] img:visible')).toHaveCount(1) + await composer().fill(marker) + await screenshot(`${kind}-draft`) + await composer().press('Enter') + const capture = await until(`${kind} provider image request`, () => result.providerRequests.slice(before).find(item => item.images.length > 0 && JSON.stringify(item.body.messages).includes(marker))) + assert.equal(capture.body.model, 'image-test') + const latestUser = capture.body.messages.findLast(message => message.role === 'user' && Array.isArray(message.content) && message.content.some(block => block.type === 'text' && block.text === marker)) + assert(latestUser, 'provider request contains the submitted user marker') + assert(latestUser.content.some(block => block.type === 'image_url'), 'submitted user message carries provider image') + await expect(page.locator('[class*="sidechatScroll"]')).toContainText('IMAGE_AUDIT_OK', { timeout: 45000 }) + result.steps.push({ step: `${kind}-provider-image`, capture: capture.path, images: capture.images }) +} + +function finalize() { + finalization ??= (async () => { + await browser?.close().catch(() => {}) + await api?.dispose().catch(() => {}) + await stopHost().catch(error => { result.status = 'failed'; result.cleanupError = String(error); process.exitCode = 1 }) + if (mock) { mock.closeAllConnections(); await new Promise(done => mock.close(done)) } + result.finishedAt = new Date().toISOString() + result.providerRequests = result.providerRequests.map(({ body: _body, ...capture }) => capture) + json(join(run, 'result.json'), result) + for (let n = 1; n <= hostSerial; n++) { + const path = join(run, `host-${n}.log`) + writeFileSync(path, redact(readFileSync(path, 'utf8'))) + } + console.log(redact(JSON.stringify({ status: result.status, result: join(run, 'result.json'), error: result.error }, null, 2))) + })() + return finalization +} +function onInterrupt(signal) { + if (interrupted !== undefined) return + interrupted = signal + result.status = 'failed' + result.interrupted = signal + const code = signal === 'SIGINT' ? 130 : 143 + void finalize().then(() => process.exit(code), error => { + console.error(redact(error.stack ?? error)) + process.exit(code) + }) +} +process.on('SIGINT', () => onInterrupt('SIGINT')) +process.on('SIGTERM', () => onInterrupt('SIGTERM')) + +try { + mkdirSync(profile, { recursive: true }) + mkdirSync(workspace, { recursive: true }) + mkdirSync(join(profile, 'node_modules'), { recursive: true }) + symlinkSync(join(tools, '@deepseek-ai'), join(profile, 'node_modules/@deepseek-ai'), process.platform === 'win32' ? 'junction' : 'dir') + symlinkSync(plugin, join(profile, 'node_modules/dsh-better-sidebar'), process.platform === 'win32' ? 'junction' : 'dir') + json(join(profile, 'package.json'), { name: 'sidechat-image-audit-profile', private: true, dependencies: { 'dsh-better-sidebar': `link:${plugin.replaceAll('\\', '/')}` }, dsh: { profile: { bundles: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', 'dsh-better-sidebar'] } } }) + const fixture = join(run, 'fixture.png') + if (largeImage) { + const pixels = Buffer.alloc(fixtureWidth * fixtureHeight * 3) + let seed = 42 + for (let i = 0; i < pixels.length; i++) { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; pixels[i] = seed >>> 24 } + for (let y = 0; y < 64; y++) for (let x = 0; x < 64; x++) { const i = (y * fixtureWidth + x) * 3; pixels[i] = 240; pixels[i + 1] = 74; pixels[i + 2] = 34 } + await sharp(pixels, { raw: { width: fixtureWidth, height: fixtureHeight, channels: 3 } }).png().toFile(fixture) + assert(readFileSync(fixture).length > 1024 * 1024, 'fixture exercises the image-specific body budget') + } else await sharp({ create: { width: fixtureWidth, height: fixtureHeight, channels: 3, background: '#f04a22' } }).png().toFile(fixture) + result.fixture = { path: fixture, sha256: hash(readFileSync(fixture)), bytes: readFileSync(fixture).length, width: fixtureWidth, height: fixtureHeight } + writeFileSync(join(workspace, 'hello.txt'), 'image mount fixture\n') + mock = createServer(async (req, res) => { + try { + if (req.url === '/v1/models') { + res.writeHead(200, { 'content-type': 'application/json' }) + return res.end(JSON.stringify({ object: 'list', data: [{ id: 'image-test', object: 'model', owned_by: 'audit' }] })) + } + assert.equal(req.url, '/v1/chat/completions') + assert.equal(req.headers.authorization, 'Bearer local-deterministic-test-key') + let raw = '' + for await (const chunk of req) raw += chunk + const body = JSON.parse(raw) + const images = [] + for (const message of body.messages ?? []) for (const block of Array.isArray(message.content) ? message.content : []) { + if (block.type !== 'image_url') continue + const match = /^data:(image\/[^;]+);base64,(.+)$/.exec(block.image_url.url) + assert(match, 'provider image is inline base64') + const bytes = Buffer.from(match[2], 'base64') + const metadata = await sharp(bytes).metadata() + assert.equal(metadata.width, fixtureWidth) + assert.equal(metadata.height, fixtureHeight) + const pixel = await sharp(bytes).removeAlpha().raw().toBuffer() + assert(Math.abs(pixel[0] - 240) < 10 && Math.abs(pixel[1] - 74) < 10 && Math.abs(pixel[2] - 34) < 10, 'provider pixels match fixture') + images.push({ mime: match[1], bytes: bytes.length, sha256: hash(bytes), width: metadata.width, height: metadata.height }) + } + const path = join(run, `provider-${result.providerRequests.length + 1}.json`) + json(path, body) + result.providerRequests.push({ path, body, images }) + const text = images.length ? 'IMAGE_AUDIT_OK' : 'AUDIT_READY' + const common = { id: 'chatcmpl-audit', object: 'chat.completion.chunk', created: 1, model: 'image-test' } + if (body.stream) { + res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' }) + res.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: { role: 'assistant', content: text }, finish_reason: null }] })}\n\n`) + res.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 8, completion_tokens: 3, total_tokens: 11 } })}\n\n`) + res.end('data: [DONE]\n\n') + } else { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ ...common, object: 'chat.completion', choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }], usage: { prompt_tokens: 8, completion_tokens: 3, total_tokens: 11 } })) + } + } catch (error) { + result.mockError = redact(error) + res.writeHead(500) + res.end('mock assertion failed') + } + }) + await new Promise((done, reject) => { mock.once('error', reject); mock.listen(0, '127.0.0.1', done) }) + const mockPort = mock.address().port + json(join(profile, 'cordis.patch.yml'), [ + { id: 'llm-pi-ai', config: { providers: { 'image-mock': { api: 'openai-completions', baseURL: `http://127.0.0.1:${mockPort}/v1`, apiKeyEnv: 'SIDECHAT_IMAGE_TEST_KEY', models: [{ id: 'image-test', input: ['text', 'image'], contextWindow: 262144, maxTokens: 4096 }], retryPolicy: { mode: 'normal', maxRetries: 0 } } } } }, + { id: 'agent-default-model', config: { provider: 'image-mock', model: 'image-test' } } + ]) + let connection = await boot() + const created = await rpc(connection.origin, 'workspace/create', { path: workspace }) + const session = await rpc(connection.origin, 'session/create', { workspaceId: created.workspace.workspaceId }) + result.sessionId = session.sessionId + browser = await chromium.launch({ ...(channel ? { channel } : {}), headless: true }) + let context = await browser.newContext({ storageState: connection.state, viewport: { width: 1440, height: 1000 }, locale: 'en-US', permissions: ['clipboard-read', 'clipboard-write'] }) + await observePage(context) + await page.goto(connection.origin, { waitUntil: 'domcontentloaded' }) + await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 60000 }) + await dismiss() + const hostComposer = page.getByRole('textbox', { name: /^(Describe what you want to build|描述你想要构建)/ }) + await hostComposer.click({ timeout: 45000 }) + await page.keyboard.type('image audit parent seed') + await page.getByRole('button', { name: /^(Send message|发送消息)$/ }).click() + await until('parent model response', () => result.providerRequests.length > 0) + await page.locator('[data-sidebar-right-expand]:visible').first().waitFor({ timeout: 45000 }) + await openSidechat() + await screenshot('baseline-sidechat') + result.steps.push({ step: 'baseline-rendered', imageInputs: await page.locator('[class*="sidechatComposer"] input[type="file"]').count() }) + if (!baseline) { + await sendImage('selected', fixture) + await assertImages(1, 'selected-saved') + await sendImage('pasted', fixture) + await assertImages(2, 'pasted-saved') + const threadCall = result.pluginRequests.findLast(item => item.body?.childId) + assert(threadCall, 'observed child thread through real plugin requests') + result.childId = threadCall.body.childId + await page.reload({ waitUntil: 'domcontentloaded' }) + await openSidechat() + await assertImages(2, 'page-reload') + const coldUrl = page.url() + const coldState = await context.storageState() + await context.close() + await api.dispose() + api = undefined + await stopHost() + connection = await boot() + context = await browser.newContext({ storageState: { ...coldState, cookies: connection.state.cookies }, viewport: { width: 1440, height: 1000 }, locale: 'en-US' }) + await observePage(context) + await page.goto(coldUrl, { waitUntil: 'domcontentloaded' }) + await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 60000 }) + await dismiss() + await openSidechat() + await assertImages(2, 'cold-host-restart') + assert(result.imageReads.filter(item => item.status === 200).length >= 6, 'saved image reads succeed across reload and cold host') + assert(!result.mockError, result.mockError) + if (largeImage) assert(result.pluginRequests.filter(item => item.path.endsWith('/sidechat.prompt')).every(item => item.bodyBytes > 1024 * 1024), 'selected and pasted image prompts exceed the ordinary JSON body cap') + if (args.includes('--mount-check')) await mountSmoke() + } + assert.deepEqual(result.pageErrors, []) + result.status = baseline ? 'baseline-recorded' : 'passed' +} catch (error) { + result.status = 'failed' + result.error = redact(error.stack ?? error) + if (page) await screenshot('failure').catch(() => {}) + process.exitCode = 1 +} finally { + await finalize() +} diff --git a/scripts/install.ps1 b/scripts/install.ps1 index 3e22e9216..63fed4622 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -28,7 +28,7 @@ # 环境变量(均可省略): # DSH_HOME 默认 %USERPROFILE%\.dsh # REGISTRY 默认 https://registry.npmjs.org -# DSH_CMD 默认优先 PATH 上的 dsh,缺省回退 npx -y --package @deepseek-ai/dsh@0.2.1-rc.1 +# DSH_CMD 默认优先 PATH 上的 dsh,缺省回退 npx -y --package @deepseek-ai/dsh@0.2.2-rc.1 # # 说明: # - pnpm 11 的 minimumReleaseAge 会拒绝发布 <24h 的新版本。脚本会预写 @@ -161,8 +161,9 @@ if ($DryRun) { Say "[dry-run] 步骤 1:确保 $WS_YML 含 minimumReleaseAgeExclude($PKG)" Say "[dry-run] 步骤 2:执行 $CLI plugin --profile $Profile add $PKG@$SPEC(安装 + bundle 自动注册)" Say "[dry-run] 步骤 3:校验 dsh.profile.bundles 含 $PKG" - Say "[dry-run] 步骤 4:幂等移除 $PATCH_YML 里旧的 better-sidebar 手动挂载行(避免双挂载)" - if ($Restart) { Say '[dry-run] 步骤 5:pm2 restart dsh-web' } else { Say '[dry-run] 步骤 5:提示用户手动重启 DSH' } + Say "[dry-run] 步骤 4:校验 profile 自带的 @deepseek-ai 宿主包配对(混版会让宿主启动即崩)" + Say "[dry-run] 步骤 5:幂等移除 $PATCH_YML 里旧的 better-sidebar 手动挂载行(避免双挂载)" + if ($Restart) { Say '[dry-run] 步骤 6:pm2 restart dsh-web' } else { Say '[dry-run] 步骤 6:提示用户手动重启 DSH' } exit 0 } @@ -173,7 +174,7 @@ Ensure-WorkspaceSettings if ($CLI -eq 'dsh') { $cliArgs = @('plugin', '--profile', $Profile, 'add', "$PKG@$SPEC") } else { - $cliArgs = @('-y', '--package', '@deepseek-ai/dsh@0.2.1-rc.1', 'dsh', 'plugin', '--profile', $Profile, 'add', "$PKG@$SPEC") + $cliArgs = @('-y', '--package', '@deepseek-ai/dsh@0.2.2-rc.1', 'dsh', 'plugin', '--profile', $Profile, 'add', "$PKG@$SPEC") } Say "执行 $CLI plugin --profile $Profile add $PKG@$SPEC ..." $addOut = & $CLI @cliArgs 2>&1 @@ -196,7 +197,24 @@ if ($bundles -notcontains $PKG) { } Say "bundle 已注册:dsh.profile.bundles 包含 $PKG(下次启动自动挂载)" -# 步骤 4:幂等移除旧的 manual 挂载行(避免与 bundle 双挂载) +# 步骤 4:校验 profile 自带的宿主包配对(#1107)。profile 里的 @deepseek-ai +# 副本会抢在宿主安装之前被加载(DSH 的 profile 解析把 profile 内副本排在 +# 安装副本之前),本插件静态 import 的 dsh-subagent 因此绑到混搭版本;混版 +# 缺导出时宿主只报 DesktopHostFatalError / required plugins did not activate, +# 看不到是哪个包缺了什么。判据用 dsh-subagent 精确声明的 dsh-attachment peer。 +# 检查脚本随包发布,用刚装好的那份运行。 +$hostTreeCheck = Join-Path $PROFILE_DIR "node_modules\$PKG\scripts\check-profile-host-tree.mjs" +if (Test-Path $hostTreeCheck) { + & node $hostTreeCheck $PROFILE_DIR + if ($LASTEXITCODE -ne 0) { + Warn 'profile 自带的 @deepseek-ai 宿主包混版:重启后本插件无法激活(宿主启动失败)。按上面的提示修好后重跑本脚本。' + exit 1 + } +} else { + Warn "未找到 $hostTreeCheck(该插件版本未携带宿主包配对检查),跳过。" +} + +# 步骤 5:幂等移除旧的 manual 挂载行(避免与 bundle 双挂载) $mountScript = @' const fs = require("fs"); const p = process.argv[2]; @@ -246,7 +264,7 @@ if ($mountResult -eq 'removed') { Say "安装完成:$PKG@$SPEC" -# 步骤 5:重启提示 +# 步骤 6:重启提示 if ($Restart) { if (Get-Command pm2 -ErrorAction SilentlyContinue) { Say '重启 dsh-web(pm2)...' diff --git a/scripts/install.sh b/scripts/install.sh index 7a9cb01ab..9aa4e45b1 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -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@0.2.1-rc.1 +# DSH_CMD 默认优先用 PATH 上的 `dsh`,缺省回退 npx -y --package @deepseek-ai/dsh@0.2.2-rc.1 # # 说明: # - 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.2.1-rc.1 dsh' + printf 'npx -y --package @deepseek-ai/dsh@0.2.2-rc.1 dsh' else die "未找到 dsh 或 npx。请先安装 DSH(并确保 Node/npm 可用),或用 DSH_CMD 指定 dsh 路径。" fi @@ -160,8 +160,9 @@ if [ "$DRY_RUN" = true ]; then say "[dry-run] 步骤 1:确保 $WS_YML 含 minimumReleaseAgeExclude(${PKG})" say "[dry-run] 步骤 2:执行 $CLI plugin --profile $PROFILE_NAME add $PKG@${SPEC}(安装 + bundle 自动注册)" say "[dry-run] 步骤 3:校验 dsh.profile.bundles 含 $PKG" - say "[dry-run] 步骤 4:幂等移除 $PATCH_YML 里旧的 better-sidebar 手动挂载行(避免双挂载)" - if [ "$RESTART" = true ]; then say "[dry-run] 步骤 5:pm2 restart dsh-web"; else say "[dry-run] 步骤 5:提示用户手动重启 DSH"; fi + say "[dry-run] 步骤 4:校验 profile 自带的 @deepseek-ai 宿主包配对(混版会让宿主启动即崩)" + say "[dry-run] 步骤 5:幂等移除 $PATCH_YML 里旧的 better-sidebar 手动挂载行(避免双挂载)" + if [ "$RESTART" = true ]; then say "[dry-run] 步骤 6:pm2 restart dsh-web"; else say "[dry-run] 步骤 6:提示用户手动重启 DSH"; fi exit 0 fi @@ -190,7 +191,23 @@ if ! node -e ' fi say "bundle 已注册:dsh.profile.bundles 包含 ${PKG}(下次启动自动挂载)" -# 步骤 3:幂等移除旧的 manual 挂载行(避免与 bundle 双挂载) +# 步骤 4:校验 profile 自带的宿主包配对(#1107)。profile 里的 @deepseek-ai +# 副本会抢在宿主安装之前被加载(DSH 的 profile 解析把 profile 内副本排在 +# 安装副本之前),本插件静态 import 的 dsh-subagent 因此绑到混搭版本;混版 +# 缺导出时宿主只报 DesktopHostFatalError / required plugins did not activate, +# 看不到是哪个包缺了什么。判据用 dsh-subagent 精确声明的 dsh-attachment peer。 +# 检查脚本随包发布,用刚装好的那份运行。 +HOST_TREE_CHECK="$PROFILE_DIR/node_modules/$PKG/scripts/check-profile-host-tree.mjs" +if [ -f "$HOST_TREE_CHECK" ]; then + if ! node "$HOST_TREE_CHECK" "$PROFILE_DIR"; then + warn "profile 自带的 @deepseek-ai 宿主包混版:重启后本插件无法激活(宿主启动失败)。按上面的提示修好后重跑本脚本。" + exit 1 + fi +else + warn "未找到 ${HOST_TREE_CHECK}(该插件版本未携带宿主包配对检查),跳过。" +fi + +# 步骤 5:幂等移除旧的 manual 挂载行(避免与 bundle 双挂载) MOUNT_RESULT="$(node -e ' const fs = require("fs"); const p = process.argv[1]; @@ -231,7 +248,7 @@ if (!removed) { say "安装完成:$PKG@$SPEC" -# 步骤 4:重启提示 +# 步骤 6:重启提示 if [ "$RESTART" = true ]; then if command -v pm2 >/dev/null 2>&1; then say "重启 dsh-web(pm2)..." diff --git a/src/active-worktree.ts b/src/active-worktree.ts index 676b88102..0a42b4d50 100644 --- a/src/active-worktree.ts +++ b/src/active-worktree.ts @@ -22,8 +22,9 @@ * (#952). Outside the workspace any linked worktree is adopted, which is PR * #802's cross-repository case. The highest-scoring adoptable worktree of the * 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). + * working-directory/change is eligible. With no such evidence the session cwd + * itself is kept, a session living in a subdirectory of its repository + * included: the repository top level is never a root on its own. * * Resolutions are cached process-wide ({@link ACTIVE_ROOT_TTL_MS}), concurrent * callers share one in-flight resolution AND one in-flight base probe, and @@ -33,7 +34,7 @@ * answered with its base (the workspace address) and never folds the stored * log — see {@link activeWorktreeRootOf}. */ -import { stat } from 'node:fs/promises' +import { realpath, stat } from 'node:fs/promises' import { dirname, isAbsolute, join, sep } from 'node:path' import type { Context, SidebarSessionEvent } from './context-types.ts' import { requireAbsolute } from './fs-tree.ts' @@ -459,7 +460,8 @@ async function sessionEventsOf(ctx: Context, sessionId: string): Promise { if (base === '') return base @@ -512,6 +514,29 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base return promise } +/** + * The session cwd as the filesystem spells it, without ever substituting the + * repository top level. + * + * This value is the base a relative link path resolves against, so lifting a + * subdirectory session to `` would resolve `/tools/a.md` as + * `/tools/a.md` (#1024 / #1080). Canonicalizing instead of returning the + * caller's spelling keeps the value comparable with the canonical paths + * `git rev-parse` reports: the workspace-containment decision in + * {@link isAdoptableTop} must still see a nested worktree as INSIDE the + * workspace when the cwd was reached through a symlink (macOS's `/var` vs + * `/private/var` is the #952 layout). + */ +async function sessionRootOf(base: string): Promise { + try { + return await realpath(base) + } catch { + // A cwd deleted between the git probe and this syscall keeps its spelling; + // that answer is no worse than the pre-existing one. + return base + } +} + /** One uncached resolution (see {@link activeWorktreeRootOf}). */ async function resolveActiveWorktreeRoot(ctx: Context, sessionId: string, base: string, directoryEpoch: number | undefined): Promise { // Read the cursor BEFORE the scan: if an event lands mid-resolution the @@ -525,10 +550,9 @@ async function resolveActiveWorktreeRoot(ctx: Context, sessionId: string, base: cachePut(activeWorktreeRootCache, sessionId, { root: base, base, directoryEpoch, eventSeq, gitResolved: false, 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 + const canonicalBase = await sessionRootOf(base) + const active = await activeRootFromEvents(await sessionEventsOf(ctx, sessionId), canonicalBase) + const root = active ?? canonicalBase cachePut(activeWorktreeRootCache, sessionId, { root, base, directoryEpoch, eventSeq, gitResolved: true, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX) return root } diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index 4ba63058a..5c5d44d8e 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -22,7 +22,7 @@ * The strategy dispatch is pure (planFirstMatch / planFsReadOutcome in * editor-load.ts); this component only wires it to the host APIs. */ -import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' import { createElement } from 'react' import clsx from 'clsx' import { IconCheckOutlineRegular, IconFolderOpenRegular, IconRefreshOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' @@ -30,7 +30,8 @@ import type { Context } from '../context-types.ts' import { api, mediaUrl, type SessionScope } from './api.ts' import { BinaryDownload } from './binary-download.tsx' import { planFirstMatch, planFsReadOutcome, type EditorLoadAction } from './editor-load.ts' -import { clearEditorDirty, setEditorDirty } from './editor-dirty.ts' +import { clearDraftBackup } from './editor-draft-backup.ts' +import { clearEditorDirty, isEditorDirty, setEditorDirty } from './editor-dirty.ts' import { baseName } from './FileTree.tsx' import { createFrameBatcher } from './frame-batcher.ts' import { openClaimedNativeFile, openSidebarFile } from './sidebar-file.ts' @@ -40,6 +41,7 @@ import { updatePluginSettings } from './plugin-settings.ts' import { createOpenInApp } from './open-in-app.ts' import { TreePanel } from './TreePanel.tsx' import { t } from './locales.ts' +import { consumeLineTarget, peekLineTarget } from './line-target.ts' import { relativeTo } from './paths.ts' import { resolveSidebarPath } from './paths.ts' import { clearRetargetedPath, closePathTabs, consumeRetargetedPath, pathTabKey, retargetPathTabs } from './tree-mutations.ts' @@ -47,6 +49,9 @@ import type { EditorToolbarControls, EditorToolbarState, FileViewerDescriptor } import { firstLeaf, insertLeafAt, leafWithTab, mintTabId, type SidebarStore, type SidebarTab } from './state.ts' import css from './sidebar.module.css' +/** One landing navigation the editor host has read from the side channel. */ +interface LineNav { key: string; nonce: number | null; end?: number } + type EditorLoad = | { status: 'loading' } | { status: 'error'; message: string } @@ -113,6 +118,14 @@ function accepted(pending: Promise): Promise { ) } +/** Ask before a reload/switch drops a draft. A host without confirm blocks + * the action: refusing is recoverable, while silently discarding is not. + * (The tab-close guard intentionally proceeds instead — an unclosable tab + * is worse than one skipped prompt.) */ +function confirmDiscard(message: string): boolean { + return typeof window.confirm === 'function' ? window.confirm(message) : false +} + export function EditorHost(props: { ctx: Context store: SidebarStore @@ -152,22 +165,68 @@ export function EditorHost(props: { // preview. This host survives every reload, so the spent line is remembered // here; the key carries the line, so a NEW reference re-arms it, and a file // switch drops it (coming back to a file is a fresh open). - const [spentLine, setSpentLine] = useState(null) + // + // The identity is (key, nonce), not just the key: a SECOND click on the same + // chip names the same `path#line`, and the host's navigation drops it (its + // adapter only patches a `line` that moved), so the key alone would read as + // "already spent" and the second click would neither jump nor flash. The + // nonce rides the side channel (line-target.ts) and is bumped on every arm + // of that key, so a re-click is a fresh navigation and no arm outlives it. + const [spentLine, setSpentLine] = useState(null) const lineKey = tab.line === undefined ? null : `${path}#${tab.line}` + // The pending range/identity for this landing. The peek is a PURE read on + // purpose: React may render twice, and a discarded render must not eat the + // arm the committed one still needs (the arm is consumed by the layout + // effect below, after commit). + const peeked = tab.line === undefined ? undefined : peekLineTarget(path, tab.line) + // The navigation this host took for `lineKey`, kept across the renders in + // between: the first commit shows the loading row (no viewer yet), so the + // viewer's render must reuse the arm this host already read — otherwise the + // flash range would be gone by the time the viewer exists. + const lineNavRef = useRef(null) + const previous = lineNavRef.current + const nav = useMemo(() => { + if (lineKey === null) return null + if (peeked !== undefined) { + return { key: lineKey, nonce: peeked.nonce, ...(peeked.end === undefined ? {} : { end: peeked.end }) } + } + return previous !== null && previous.key === lineKey ? previous : null + }, [lineKey, peeked, previous]) + const isFreshLine = lineKey !== null && ( + spentLine === null + || spentLine.key !== lineKey + || (nav !== null && nav.nonce !== spentLine.nonce) + ) + const lineEnd = isFreshLine ? nav?.end : undefined + // The navigation this commit actually hands to the viewer, so the viewer's + // consumption marks exactly that one spent (and not a newer arm). + const handedLineRef = useRef<{ key: string; nonce: number | null } | null>(null) + useLayoutEffect(() => { + if (isFreshLine && lineKey !== null) { + // A plain line open (no arm) still hands a navigation; its identity has + // a null nonce, so the viewer can spend it like any other. + lineNavRef.current = nav ?? { key: lineKey, nonce: null } + handedLineRef.current = { key: lineKey, nonce: lineNavRef.current.nonce } + // One shot per handed navigation: an ordinary open of the same line + // later must not inherit this flash. + if (tab.line !== undefined) consumeLineTarget(path, tab.line) + return + } + handedLineRef.current = null + if (nav === null) lineNavRef.current = null + }, [nav, isFreshLine, lineKey, path, tab.line]) const onLineConsumed = useCallback(() => { - if (lineKey !== null) setSpentLine(lineKey) - }, [lineKey]) + if (handedLineRef.current !== null) setSpentLine(handedLineRef.current) + }, []) useEffect(() => { setSpentLine(null) }, [path]) // Manual refresh (issue #167 + PR #228): a dirty draft is dropped by the // reload (the editor instance remounts), so confirm before discarding it. const refreshFile = (): void => { - if (toolbar?.dirty === true) { - const confirmed = typeof window.confirm === 'function' - ? window.confirm(t('refreshUnsavedConfirm')) - : false - if (!confirmed) return - } + if (toolbar?.dirty === true && !confirmDiscard(t('refreshUnsavedConfirm'))) return + // The confirmed reload discards the live draft: its durable backup must + // not offer the discarded bytes back on the next open. + if (toolbar?.dirty === true) clearDraftBackup(scope.sessionId, path) setReloadSeq(sequence => sequence + 1) } @@ -231,9 +290,20 @@ export function EditorHost(props: { */ const openFile = (absolute: string): void => { if (inPlace) { - if (!openClaimedNativeFile(ctx, scope.sessionId, scope.cwd, absolute)) { - ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) }, scope.sessionId) + // A native tab type claims the file: it opens elsewhere and THIS editor + // keeps its draft, so there is nothing to confirm. + if (openClaimedNativeFile(ctx, scope.sessionId, scope.cwd, absolute)) return + // An in-place switch remounts the viewer, and the draft lives only in + // that instance — ask before dropping it, reading the same dirty + // registry the tab close uses. Re-opening the current path is not a + // switch. + if (absolute !== path && isEditorDirty(tab.id, scope.sessionId)) { + if (!confirmDiscard(t('switchUnsavedConfirm'))) return + // The confirmed switch discards the live draft: drop its durable + // backup too, or the next open would offer the discarded bytes back. + clearDraftBackup(scope.sessionId, path) } + ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) }, scope.sessionId) } else { openSidebarFile(ctx, scope.sessionId, absolute, { cwd: scope.cwd }) } @@ -659,7 +729,10 @@ export function EditorHost(props: { // The reference's landing line, if the address carried one (#826) // AND this open has not spent it yet. Only the text viewer acts on // it; a markdown/html/image viewer gets the field and ignores it. - line: lineKey !== null && lineKey !== spentLine ? tab.line : undefined, + line: isFreshLine ? tab.line : undefined, + // The quoted span's end, when the open armed one (the landing + // flash). Viewers without a flash ignore it. + lineEnd, onLineConsumed, content: load.content, size: load.size, diff --git a/src/client/MarkdownHtml.tsx b/src/client/MarkdownHtml.tsx index b9914b01b..f6fd2753b 100644 --- a/src/client/MarkdownHtml.tsx +++ b/src/client/MarkdownHtml.tsx @@ -236,17 +236,45 @@ function MarkdownSegment({ text, hasMermaid, media, codeLabels }: MarkdownSegmen const container = containerRef.current if (container === null) return runInlineHtmlPass(container, media) - let scheduled = false + let timer: number | undefined + /** A pass was skipped because the page was hidden; flush it on return. */ + let dirty = false + const runPass = (): void => { + // Only `hidden` pauses the pass; jsdom reports a non-visible state too, + // and the initial pass already ran there. + if (document.visibilityState === 'hidden') { + dirty = true + return + } + dirty = false + runInlineHtmlPass(container, media) + } const observer = new MutationObserver(() => { - if (scheduled) return - scheduled = true - queueMicrotask(() => { - scheduled = false - runInlineHtmlPass(container, media) - }) + if (timer !== undefined) return + // Coalesce a burst of mutations (shiki settling, diagram swaps, inline + // HTML injection) into one pass: the scan walks every text node in the + // document, so a pass per mutation turns a diagram-heavy render into a + // stream of full-document scans. + timer = window.setTimeout(() => { + timer = undefined + runPass() + }, 80) }) + const onVisibilityChange = (): void => { + if (document.visibilityState === 'hidden' || !dirty) return + if (timer !== undefined) { + window.clearTimeout(timer) + timer = undefined + } + runPass() + } + document.addEventListener('visibilitychange', onVisibilityChange) observer.observe(container, { childList: true, subtree: true }) - return () => { observer.disconnect() } + return () => { + observer.disconnect() + document.removeEventListener('visibilitychange', onVisibilityChange) + if (timer !== undefined) window.clearTimeout(timer) + } }, [text, media]) return (
diff --git a/src/client/SideCardSection.tsx b/src/client/SideCardSection.tsx index 94ff86afb..e1d1365ba 100644 --- a/src/client/SideCardSection.tsx +++ b/src/client/SideCardSection.tsx @@ -11,7 +11,11 @@ * - 侧边栏内容: one SMALL CARD per REGISTERED tab type (built-ins and * external plugins alike), laid out in a responsive grid that wraps * several cards per row — icon chip + title + type id, clicked to toggle - * the switch persisted in `prefs.tabsEnabled[id]`. + * the switch persisted in `prefs.tabsEnabled[id]`. Programmatic-only + * types (`hidden: true`, e.g. the built-in diff page or dsh-remote's + * `dsh-remote:file`) are NOT listed: they have no + menu row and no + * native guide entry, so a switch could only break their opens without + * hiding anything (#1009). * - 文件预览: one SMALL CARD per REGISTERED file viewer — icon chip + title * + the extensions it covers, clicked to toggle `prefs.viewersEnabled[id]`. * @@ -97,10 +101,17 @@ function iconOf(icon: ReactNode | ((size: number) => ReactNode) | undefined, siz return typeof icon === 'function' ? icon(size) : icon } -/** Tab inventory order: hidden types (editor/diff) last, then + menu order. */ -function tabOrder(a: TabDescriptor, b: TabDescriptor): number { - if (a.hidden !== b.hidden) return a.hidden === true ? 1 : -1 - return (a.order ?? 100) - (b.order ?? 100) +/** + * The tab inventory: the types that actually reach the side card, in + menu + * order. `hidden` types are programmatic-only (no + menu row, no native + * guide entry), so they have no side-card presence to switch — listing them + * produced switches whose only observable effect was to refuse their own + * opens (#1009). + * @param tabs - the service's whole registry. + * @returns a sorted copy without the hidden types. + */ +function tabInventory(tabs: readonly TabDescriptor[]): TabDescriptor[] { + return tabs.filter(tab => tab.hidden !== true).sort((a, b) => (a.order ?? 100) - (b.order ?? 100)) } /** Viewer inventory order: priority desc (the catch-all `code` comes last). */ @@ -658,10 +669,10 @@ export function SideCardSection({ store, service }: SideCardSectionProps) { // The declarative inventory: the registered tab types and file viewers. // Local state + service.subscribe (registry changes are rare — plugin // load/unload — so a plain effect is enough; no external-store ceremony). - const [tabs, setTabs] = useState(() => [...service.getTabs()].sort(tabOrder)) + const [tabs, setTabs] = useState(() => tabInventory(service.getTabs())) const [viewers, setViewers] = useState(() => [...service.getFileViewers()].sort(viewerOrder)) useEffect(() => service.subscribe(() => { - setTabs([...service.getTabs()].sort(tabOrder)) + setTabs(tabInventory(service.getTabs())) setViewers([...service.getFileViewers()].sort(viewerOrder)) }), [service]) diff --git a/src/client/SideChatView.module.css b/src/client/SideChatView.module.css index e0e11dfd9..8c4d1dda8 100644 --- a/src/client/SideChatView.module.css +++ b/src/client/SideChatView.module.css @@ -645,3 +645,23 @@ transition: none; } } + +.sidechatImages { + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 8px; +} +.sidechatImagePreview { + display: flex; + align-items: flex-start; + border: 1px solid var(--dsw-alias-hairline); + border-radius: 8px; +} +.sidechatImage { + display: block; + max-width: 180px; + max-height: 140px; + object-fit: contain; + border-radius: 6px; +} diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index feb219ded..f6ad6732a 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -31,7 +31,9 @@ * session, archive) lives in the COMPOSER BAR, not a top header — the reader's * attention is on the input, and a header's actions went unnoticed. */ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { SidechatImages } from './SidechatImages.tsx' +import { useSidechatDraft, encodeSidechatImages } from './sidechat-draft.ts' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useSyncExternalStore } from 'react' import clsx from 'clsx' import { @@ -45,6 +47,7 @@ import { IconCloseFillRegular, IconEditOutlineRegular, IconNewChatOutlineRegular, + IconPaperclipOutlineRegular, IconPlusOutlineRegular, IconSearchOutlineRegular, IconSendOutlineRegular, @@ -63,7 +66,9 @@ import { type ReadBlockLabels, type TerminalBlockLabels, } from '@deepseek-ai/dsh-client-ui-primitives' +import { SIDECHAT_IMAGE_MEDIA_TYPES } from '../sidechat-images.ts' import { markdownTextProps } from './markdown-labels.tsx' +import { SidechatAssistantRow, type SidechatRowSurfaceBinding } from './SidechatAssistantRow.tsx' import { rewriteProseLocalImageUrls } from './markdown-images.ts' import { hostTransportBase } from './desktop-env.ts' import { baseName, resolveSidebarPath } from './paths.ts' @@ -89,10 +94,11 @@ import { formatTokens, toolArgsSummary, transcriptRows, + sidechatRowKey, type SidechatToolCard, type SidechatTranscriptRow, } from './sidechat-transcript.ts' -import { api, mediaUrl } from './api.ts' +import { api, mediaUrl, SidebarApiError } from './api.ts' import { usePolling } from './use-polling.ts' import { useSidechatPush } from './use-sidechat-push.ts' import { t } from './locales.ts' @@ -232,6 +238,8 @@ function rememberSidechatThread(sessionId: string, threadId: string): void { /** Per-thread transcript cache: thread-own events merged by seq (polls ride * the afterSeq delta and never re-download what they already hold). */ interface ThreadCache { + /** Rows must never be rebound to a different child while a reset is pending. */ + threadId?: string entries: SidebarHistoryEntry[] /** The CURRENT attempt's live deltas (replaced every pull, never merged). */ live: SidechatLiveEvent[] @@ -496,29 +504,28 @@ interface RowSurface { /** One row renderer (React keys ride the source event seq). `surface` is the * markdown prose pass the rows run before rendering — the rows are model * prose, so a relative destination resolves against the session cwd (see - * use-markdown-surface) — plus the delivered-file open and media helpers. */ -function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSurface): React.ReactNode { + * use-markdown-surface) — plus the delivered-file open and media helpers. + * `genui` binds the rows to the owning child thread: the key remounts every + * row when the tab switches threads, and a registered GenUI consumer may + * claim a visible, settled assistant row (see SidechatAssistantRow). */ +function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSurface, genui: SidechatRowSurfaceBinding): React.ReactNode { + const key = `${genui.threadId ?? 'unbound'}:${sidechatRowKey(row)}` switch (row.kind) { case 'user': return ( -
- +
+ {row.text !== '' && } +
) case 'assistant': return ( -
- {/* `streaming` keeps the host's incremental parse across chunks - instead of restarting it; only the durable (settled) message is - the final parse. It rides the row's own flag so a superseded - live row never claims to be settled. */} - -
+ ) case 'reasoning': return ( @@ -527,7 +534,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu ) case 'injection': return ( - +
{row.text}
) @@ -535,7 +542,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu // A provider/agent failure: rendered plainly (never markdown) so a raw // provider message with odd punctuation survives verbatim. return ( -
+
{t('sideChatRunError', { message: row.text })}
) @@ -549,7 +556,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu if (row.durationMs !== undefined) parts.push(formatDurationMs(row.durationMs)) if (parts.length === 0) return null return ( -
+
{parts.join(' · ')}
) @@ -607,7 +614,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu ) return ( (null) const [busy, setBusy] = useState<'starting' | 'sending' | 'saving' | 'archiving' | null>(null) const [error, setError] = useState(null) const [saved, setSaved] = useState(false) @@ -713,11 +723,7 @@ export function SideChatView(props: { const [menuOpen, setMenuOpen] = useState(false) const [modelMenuOpen, setModelMenuOpen] = useState(false) const [catalog, setCatalog] = useState(null) - /** Local echo of the message just sent: shown until the host reports it - * pending or logs it durably (see the drop effect below). `seq` is the - * transcript tail at send time, so an OLDER identical message cannot - * retire the echo. */ - const [echo, setEcho] = useState<{ text: string; seq: number } | null>(null) + const [echo, setEcho] = useState<{ text: string; messageId: string; hasImages: boolean } | null>(null) const cacheRef = useRef({ entries: [], live: [], pending: [] }) // The previous poll's rows (see the mapping's reuse pass below). @@ -726,13 +732,14 @@ export function SideChatView(props: { /** The pending push-driven pull (one per burst of host frames). */ const invalidateRef = useRef(undefined) const scrollRef = useRef(null) - /** Heading slugs, anchor jumps and `.md` link claiming for the transcript (a + /** Heading slugs, anchor jumps and local file links for the transcript (a * prose surface: it renders no file of its own, so a relative link target * resolves against the session cwd). */ const { surfaceRef: chatSurfaceRef, openFile: openChatFile, rewrite: rewriteChatLinks } = useMarkdownSurface({ ctx, sessionId: scope.sessionId, cwd: scope.cwd, + allLocalFiles: true, }) /** * The prose pass every row runs before rendering: LOCAL image destinations @@ -811,6 +818,24 @@ export function SideChatView(props: { const summary = threadId === undefined ? undefined : list.byId[threadId] const running = summary?.running === true + /** + * Whether the host's own session list can ever show the bound session again + * after archiving it. It cannot for a subagent-origin row: the host's + * `sessionVisible()` returns false for `origin === 'subagent'` BEFORE the + * archived filter runs, and the only "unarchive" control lives on that list, + * so archiving a side thread is a one-way door (issue #949). Every thread + * this view binds is such a row; an absent summary is treated the same way — + * this view must not archive a session it cannot classify. The composer tip + * says why the action is disabled. + */ + const archiveBlocked = summary === undefined || summary.origin === 'subagent' + /** The archive control's hover text: the blocked reason wins over the + * running hint — stopping the thread would not make archiving recoverable. */ + const archiveTip = archiveBlocked + ? t('sideChatArchiveBlocked') + : running + ? t('sideChatArchiveRunning') + : t('sideChatArchive') // Connection recovery state (DSH 0.1.2-alpha.2+): drives the disconnect // banner and an immediate catch-up pull when the wire comes back. The poll @@ -865,14 +890,14 @@ export function SideChatView(props: { // loadLastThreads) reattaches to the thread the session was last in instead // of leaving yet another orphan "Side: New thread" session behind. useEffect(() => { - if (threadId !== undefined || !autoCreate || !visible) return + if (threadId !== undefined || !visible) return const reattach = reattachTarget() if (reattach !== undefined) { // Name the seat session: the same native id names a tab in every session. ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { threadId: reattach } }, scope.sessionId) return } - void startThread() + if (autoCreate) void startThread() }, [threadId, autoCreate, visible, startThread, reattachTarget, ctx, tab.id, scope.sessionId]) // Remember the thread this tab holds, so reopening the panel (or a restart) @@ -900,13 +925,15 @@ export function SideChatView(props: { * (first attach = the whole seed-cut slice; polls = afterSeq deltas), * merged by seq. */ const fetchThread = useCallback(async (childId: string): Promise => { + const cache = cacheRef.current + if (cache.threadId !== childId) return controllerRef.current?.abort() const controller = new AbortController() controllerRef.current = controller try { - const cache = cacheRef.current const afterSeq = cache.entries.at(-1)?.event.seq const { events, live, pending } = await api.sidechatEvents(childId, afterSeq, controller.signal) + if (controller.signal.aborted || cacheRef.current !== cache) return // The live set is the CURRENT attempt, so it replaces whatever the // previous pull held; a settled step drops out of the host buffer and // its durable assistant/message takes over in the mapping. The pending @@ -928,7 +955,9 @@ export function SideChatView(props: { /** The composer-bar badge pull (live state + preset/model identity). */ const fetchInfo = useCallback(async (childId: string): Promise => { try { - setInfo(await api.sidechatInfo(childId)) + const cache = cacheRef.current + const result = await api.sidechatInfo(childId) + if (cache === cacheRef.current && cache.threadId === childId) setInfo(result) } catch { // The badge is decorative; a wire failure keeps the last value. } @@ -937,7 +966,7 @@ export function SideChatView(props: { // Reset the transcript cache whenever the binding changes, then focus // the composer — it owns the first message of a fresh thread. useEffect(() => { - cacheRef.current = { entries: [], live: [], pending: [] } + cacheRef.current = { threadId, entries: [], live: [], pending: [] } prevRowsRef.current = [] controllerRef.current?.abort() if (invalidateRef.current !== undefined) { @@ -948,6 +977,7 @@ export function SideChatView(props: { setSaved(false) setInfo(null) setEcho(null) + setBusy(null) if (threadId !== undefined) { void fetchInfo(threadId) window.setTimeout(() => composerRef.current?.focus(), 0) @@ -1040,7 +1070,8 @@ export function SideChatView(props: { const live = cache.live .filter(event => !settled.has(`${String(event.data.turn)}:${String(event.data.step)}`)) .map(event => ({ event: event as SidebarSessionEvent })) - const next = threadId === undefined ? [] : transcriptRows([...cache.entries, ...live], prevRowsRef.current) + const next = threadId === undefined || cache.threadId !== threadId + ? [] : transcriptRows([...cache.entries, ...live], prevRowsRef.current) prevRowsRef.current = next return next }, @@ -1064,25 +1095,18 @@ export function SideChatView(props: { [threadId, revision, rows], ) - // Retire the local echo once the host accounts for the message it carries: - // either the unclaimed inbox lists it (the claim has not happened yet) or a - // durable user row NEWER than the send logged it (the claim already ran). - // An identical older message cannot retire the echo — the seq gate. const echoText = echo?.text ?? '' useEffect(() => { if (echo === null || busy === 'sending') return - if (pendingRows.some(item => item.text === echo.text)) { + if (pendingRows.some(item => item.id === echo.messageId)) { setEcho(null) return } - if (rows.some(row => row.kind === 'user' && row.seq > echo.seq && row.text === echo.text)) { + if (rows.some(row => row.kind === 'user' && row.messageId === echo.messageId)) { setEcho(null) } }, [echo, busy, pendingRows, rows]) - /** The echo is hidden the moment the inbox already carries the same text - * (the retire effect above then drops the state) so the message never shows - * twice for a frame. */ - const showEcho = echo !== null && !pendingRows.some(item => item.text === echo.text) + const showEcho = echo !== null && !pendingRows.some(item => item.id === echo.messageId) && !rows.some(row => row.kind === 'user' && row.messageId === echo.messageId) const canSave = threadId !== undefined && threadHasCompletedTurn(cacheRef.current.entries) const trailingPending = threadId !== undefined && threadTrailingPending(cacheRef.current.entries) @@ -1092,7 +1116,7 @@ export function SideChatView(props: { * reports it running. A RUNNING thread keeps the row regardless (the * long-tool-call window has no streaming text to show progress). */ const hasOutputRow = rows.some(row => row.kind === 'assistant' || row.kind === 'reasoning') - const showThinking = threadId !== undefined && (running || (echo !== null && !hasOutputRow)) + const showThinking = threadId !== undefined && (running || ((echo !== null || busy === 'sending') && !hasOutputRow)) // Follow the stream: stick to the bottom while the log — or the pending // tail — grows. @@ -1236,29 +1260,60 @@ export function SideChatView(props: { field.style.height = `${Math.min(field.scrollHeight, COMPOSER_MAX_HEIGHT)}px` } + // Capture a binding generation, not a mutable "current session" fallback. + // A deferred slider action from an old row must fail even after A → B → A. + const surfaceBinding = useMemo(() => ({ childId: threadId, active: visible }), [threadId, visible]) + useLayoutEffect(() => { + surfaceBinding.active = visible + return () => { surfaceBinding.active = false } + }, [surfaceBinding, visible]) + const sendSurfacePrompt = useCallback(async (text: string): Promise => { + try { + const childId = surfaceBinding.childId + if (!surfaceBinding.active || childId === undefined || childId.trim() === '' || text.trim() === '') { + throw new Error('Sidechat surface is no longer active or the prompt is empty') + } + setError(null) + await api.sidechatPrompt(childId, text) + if (surfaceBinding.active) { + void fetchThread(childId) + void fetchInfo(childId) + } + } catch (cause) { + if (surfaceBinding.active) setError(cause instanceof Error ? cause.message : String(cause)) + throw cause + } + }, [surfaceBinding, fetchThread, fetchInfo]) + const genuiRowSurface: SidechatRowSurfaceBinding = { + service: ctx.get('betterSidebar'), threadId, visible, sendPrompt: sendSurfacePrompt, + } + + const addImages = (files: readonly File[]): void => { + try { draft.add(files, info?.images?.available === true ? info.images.limits : undefined); setError(null) } + catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)) } + } + const handleSend = async (): Promise => { - const text = composer.trim() - if (text === '' || threadId === undefined || busy !== null) return + const attempt = draft.capture() + const childId = attempt.owner.childId + if ((attempt.text === '' && attempt.images.length === 0) || childId === undefined || busy !== null) return setBusy('sending') setError(null) - // Local echo: the host accepts a message into the child's inbox and only - // LOGS it when a step claims it, so between those moments the message used - // to be invisible ("sent, nothing happened"). The bubble shows at once and - // is retired once the inbox or the log carries the message. - setEcho({ text, seq: cacheRef.current.entries.at(-1)?.event.seq ?? 0 }) try { - await api.sidechatPrompt(threadId, text) - setComposer('') - const field = composerRef.current - if (field !== null) field.style.height = '' - void fetchThread(threadId) - void fetchInfo(threadId) + const images = await encodeSidechatImages(attempt) + if (!attempt.owner.active) return + const result = await api.sidechatPrompt(childId, attempt.text, images) + if (!attempt.owner.active) return + setEcho({ text: attempt.text, messageId: result.messageId, hasImages: images.length > 0 }) + draft.accept(attempt) + void fetchThread(childId) + void fetchInfo(childId) } catch (cause) { - // Nothing reached the host: drop the echo and say why. - setEcho(null) - setError(cause instanceof Error ? cause.message : String(cause)) + if (attempt.owner.active) setError(cause instanceof SidebarApiError && cause.code === 'network' + ? t('sideChatSendUncertain') + : cause instanceof Error ? cause.message : String(cause)) } finally { - setBusy(null) + if (attempt.owner.active) setBusy(null) } } @@ -1322,11 +1377,14 @@ export function SideChatView(props: { /** Archive the bound thread on the host (the same capability the session * list's own archive action uses; `stopActivity` settles a running agent - * first). The tab then moves to another live thread: leaving it bound to an - * archived session would dead-end the panel, because the host refuses to - * open archived sessions. */ + * first). Disabled for a side thread: the host session list never lists a + * subagent-origin row, so no "unarchive" entry could ever recover it (issue + * #949) — the guard below makes that a hard rule, not just a disabled + * styling. For a recoverable binding the tab then moves to another live + * thread: leaving it bound to an archived session would dead-end the panel, + * because the host refuses to open archived sessions. */ const handleArchive = async (): Promise => { - if (threadId === undefined || busy !== null) return + if (threadId === undefined || busy !== null || archiveBlocked) return setBusy('archiving') setError(null) setSaved(false) @@ -1387,19 +1445,20 @@ export function SideChatView(props: { onReconnect={() => { ctx.connection?.reconnect() }} /> )} -
+
{/* The host delegate is what makes a local markdown link in a row clickable at all (see use-markdown-surface), scoped to this transcript so nothing outside it is claimed. */} - {rows.map(row => renderRow(row, rowLabels, rowSurface))} + {rows.map(row => renderRow(row, rowLabels, rowSurface, genuiRowSurface))} {/* The unclaimed inbox: accepted messages whose claim has not logged them yet. The same bubble surface (and markdown pass) as a durable user row, plus the state word and the dequeue button. */} {pendingRows.map(item => (
- + {item.text !== '' && } +
@@ -1408,6 +1467,7 @@ export function SideChatView(props: { type="button" className={css.sidechatDequeueBtn} onClick={() => void handleDequeue(item.id)} + disabled={item.removable === false} title={t('sideChatDequeue')} aria-label={t('sideChatDequeue')} > @@ -1420,7 +1480,8 @@ export function SideChatView(props: { {showEcho && echo !== null && (
- + {echo.text !== '' && } + {echo.hasImages && {t('sideChatImageLoading')}}
@@ -1446,6 +1507,16 @@ export function SideChatView(props: { {saved &&
{t('sideChatSaved')}
} {error !== null &&
{t('sideChatError', { message: error })}
}
+ { addImages(Array.from(event.target.files ?? [])); event.target.value = '' }} /> + {draft.owner.images.length > 0 &&
+ {draft.owner.images.map(image =>
+ {image.file.name} + +
)} +
} + {busy === 'sending' && {t('sideChatSending')}}