feat: add optional Context diagnostics navigation

Use an activation-scoped Cordis controller for session, agent, and job-owner entries. Reuse native Context tabs, cancel stale navigation, and close source overlays without canceling pending requests.

Verify optional capability lifecycle, truthful job ownership, three real dsh-context configurations, and the existing mount regression suite.
This commit is contained in:
Menghuan1918 committed 2026-10-17 02:20:53 +08:00
1 parent 693b4850e3
commit 93c43b0ac9
44 files changed
+3194 -32

No files matched your search

+4
View File
@@ -2,6 +2,10 @@
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
### Unreleased
- **dsh-context 可选联动**:Context 侧栏入口可用时,在 Agent 详情、后台任务输出窗和会话标题栏提供诊断入口;后台任务仅查看明确的真实属主,不改变任务输出观察或停止命令的会话语义。跨会话先定位目标再打开 Context,复用其他分栏已有的标签;用户继续导航时取消,等待最多 10 秒。未安装、禁用或仅显示会话标签页时隐藏入口,不修改上下文、不恢复 Agent 执行,也不修改 dsh-context 偏好。全部入口共用 Cordis 作用域内的可选适配器,空闲时不新增轮询。
### v0.27.0
- 🌿 **Git 页面重做:VS Code Source Control 结构 + 只读提交图(同一页签)**([#941](https://github.com/omdsh-dev/DSH-better-sidebar/issues/941),贡献者 PR [#944](https://github.com/omdsh-dev/DSH-better-sidebar/pull/944) @hairyf + [#969](https://github.com/omdsh-dev/DSH-better-sidebar/pull/969) @vlln):「文件变动 > Git」的内容区改为 Source Control 结构——可折叠的 Changes(多行 Message + 仅填草稿的 Generate、Merge / Staged / Changes 三组各自独立折叠与计数、整行 hover)与 Graph 区、常驻底栏(可点击分支 + `*`/`+`/`!` 标记、upstream 的 `↓`/`↑` 与安全 Pull-then-Push);Push/Pull 与 worktree·子仓库选择移入 More Actions;提交只消费已暂存项,冲突 / 空消息 / 无暂存时禁止,草稿按会话·仓库·worktree 隔离。Graph 区由 **#969 的有界只读引擎**渲染(专用 `git.graph` 路由:子先于父的拓扑序、分支筛选、游标失效显式返回 `graph-stale`、每页 200 / 偏移 10000 / 分支 1000 / 进程 10 s / 输出 8 MiB 上限,超限报错不静默截断;泳道连线与引用徽章用主题状态色,hover 卡片与提交详情卡;**纯读取**——不 checkout / fetch / 改任何 ref)。底部预览面板改为固定三签 `提交详情 / 内容 / 差异`(有内容才有差异,读操作落在内容签)。**设计取舍与实施偏差见 [docs/plans/2026-10-16-git-page-vscode-scm-merge.md](docs/plans/2026-10-16-git-page-vscode-scm-merge.md)**(贡献者 PR [#939](https://github.com/omdsh-dev/DSH-better-sidebar/pull/939) @hairyf 的官方下划线 Tabs 镜片切换保留;第三个「提交图」镜头刻意未上线)。
+4
View File
@@ -32,6 +32,10 @@
Switch to **Git Graph** at the top of the Git panel for commit nodes, forks and merge edges across local branches, remote-tracking branches and HEAD. The branch selector only filters history — it **never checks out or fetches**; each commit is one line (lane edges + ref pills + subject), hover shows the author and short hash, and selecting one opens its full message and diff in the bottom pane. History loads in pages; reference changes during pagination prompt a refresh; reads are bounded (200 commits per page, offset 10,000, 1,000 branches) and report an explicit error past a limit. This first version shows no tags and offers no history-changing actions.
### 🧭 dsh-context diagnostics (optional)
With the `dsh-context` plugin installed, three places offer a one-click jump into that conversation's **Context** view: an agent node's detail card on the Tasks page, a background job's output window (the job's real owner session — never merely the session its row was watched under), and the session header. The entries **appear only** while dsh-context's `Context` page is actually registered: a deployment without it (or with that page hidden) shows no control at all, and while one jump is in flight every entry point is disabled. A failed jump is reported once, in a dismissible alert at the frame's bottom edge; nothing is polled while idle.
## 🚀 Installation
```sh
+4
View File
@@ -32,6 +32,10 @@
在 Git 面板顶部切到 **Git Graph**:本地分支、远程跟踪分支与 HEAD 的提交节点、分叉与合并连线。分支下拉框只筛选历史,**不会 checkout 或 fetch**;提交行是单行(泳道连线 + 引用徽章 + 标题),hover 看作者与短 hash,选中后在底部面板看完整提交信息与 diff。历史按页加载,分页期间 refs 变化会提示刷新;读取有上限(每页 200 条、偏移 10,000、分支 1,000),超限明确报错。首版不显示 tag,也不提供任何改写历史的操作。
### 🧭 dsh-context 诊断入口(可选)
装上 `dsh-context` 插件后,三处各有一个直达该会话 **Context(上下文)** 视图的入口:任务管理页的代理节点详情卡、后台任务输出窗(按任务的**真实属主会话**寻址,而不是它被挂在哪个会话名下)、以及会话标题栏。入口**只在** dsh-context 的 `Context` 页面确实注册时才出现——没装、没启用或该页面被隐藏的部署不会显示任何控件;一次跳转进行中时,三个入口一并禁用。跳转失败只报一条可关闭的提示(浮在窗口底部),空闲时不新增任何轮询。
## 🚀 安装
```sh
+3
View File
@@ -40,6 +40,7 @@
| 新建标签页列表 | 每个 tab 类型在原生 guide 里占一行:标题取 `title` + 图标取 `icon`(缺图标时宿主补一个方块占位),说明取可选的 `description`——**宿主只在 guide 列出的条目 ≤ 4 条时渲染说明**(上游 `MAX_DESCRIBED_ENTRIES = 4`),更长的列表整列丢掉所有说明;未声明 `description` 的条目渲染成单行「图标 + 标题」(rc.1 起 `description` 回到宿主契约,但**宿主与插件都没有兜底句**,所以插件恢复字段而不恢复旧的通用句);`hidden: true` 的类型不占行,**`bottomOnly: true` 的类型同样不占行**(#774:它只活在插件自己的底部 `+` 菜单里)。插件的 `editor` 类型不再单独占行(它认领的文件资源由 `files` 接管页承载同一视图)。**本插件默认贡献 4 个 guide 条目**(文件 / Git / 任务管理 / 侧边对话,恰好在上限内),**但宿主的终端条目也占一行**——装了宿主终端即是 5 条,说明整列不渲染;要让说明回来,需在插件设置页关掉足够多的 tab 类型把总数压到 ≤ 4 条 |
| 新建面板的种子(alpha.2) | 在新会话打开原生新面板时,宿主从已注册的 guide 条目里播种:恰好 1 个条目 → 直接打开那一页;0 或 ≥2 个条目 → 打开指南。`revealIfOpened` 打开的「页面」在**同一 pane 内**强制去重(已在该 pane 就不再新建);由已有 tab 地址驱动的打开不受该去重影响 |
| alpha.2 全局面板(不接入) | 插件**不采用** alpha.2 引入的全局主面板模型——根级 keyed `main` 槽(预留 key `conversation`,由 ui-conversation 注册为 `main.conversation`)、根级 `sidebar.panellist` 列表槽(`SidebarPanelMetadata` / `SidebarPanelIconOwnerProps`)、`ctx.layout.selectPanel(MainPanelId|null)` / `beginNavigation()` / `dispose()`、全局标准 prop `usePanelInfo`,以及改根级并新增会话级 `rightbar.session` 子槽的 `rightbar`——这些只作兼容保留,不向其迁移 |
| dsh-context 可选联动(开发线) | 通过 Cordis 子作用域等待宿主服务,并订阅原生类型及内容槽注册;仅当 Context 侧栏可用时显示 Agent 详情、后台任务真实属主与当前会话标题栏的诊断入口。跨会话先导航到目标再打开 Context,复用该会话其他分栏已有标签;发起导航即关闭来源详情/输出浮层,插件级请求不随浮层卸载取消;导航最多等待 10 秒,用户继续导航或依赖消失即结束。后台任务没有真实 `job.owner` 或可靠子代理地址时不提供诊断,不回退到观察会话。只借用 `ctx.layout.beginNavigation()` 的取消语义,不贡献全局主面板;不扩展 `ctx.betterSidebar` 公共 API,也不要求消费插件改代码或安装 dsh-context。 |
| 已移除 | 插件自绘右侧面板(含宽度拖拽 / 新会话默认宽度)与**自由窗口**(`features` 里的 `'floatWindows'` 已删除,v0.18.x 及更早版本的消费者请勿再 gate 该能力);`openByDefault` / `defaultWidthPercent` / `changesDiffFloat` 三个设置项同步删除(旧文档里的键会被忽略);**插件自带的终端与浏览器 tab 类型**(宿主 0.1.6/0.1.7 自带两者)与**只读文件预览**(image / pdf / Office / 表格,宿主 0.1.7 的 `ui-sidebar-documentpreview` 接手)同样不再内置,详见 §4.4 与 §5.4 |
---
@@ -1151,6 +1152,8 @@ interface SettingsDescriptor {
- **z-index**:面板宿主层 25、按钮簇 45——低于 DSH ui-cordis 插件面板(30)与浮层栈(100/1000+),浮层天然盖住侧边栏。
- **更改行选中态**:Git 文件行和本轮操作行保持原有布局;选中只绘制 `--dsw-alias-interactive-bg-active` 背景,以及行内 inset 4px、宽 2px 的 `--dsw-alias-state-business-primary` 标记。选中规则与缩进参考线的绝对定位规则必须分开;`tests/theme.spec.ts` 解析实际 CSS 规则守护,挂载测试验证点击后文件行仍在原分组内。
- **Context 诊断入口与提示**:图标沿用宿主 `Button` 与 `IconContextInjectionOutlineRegular`,标题栏为固定宽度按钮。跨会话错误通过 `shell.overlay` 展示一条可关闭提示,背景取 `--dsw-alias-bg-layer-3`、边框与图标取 `--dsw-alias-state-warn-primary`、正文取 label 令牌;宽度受视口约束,目标名与错误文案允许任意位置换行。能力中途消失时仍保留本次错误,不依赖来源弹层继续挂载。
### 12.2 注意事项
- 类名是 CSS Modules 哈希,**不是契约**;精确命中用 `[data-dsh-better-sidebar]` + 子串类名(`[class*='panel']`)或 DOM 结构。
+302
View File
@@ -0,0 +1,302 @@
#!/usr/bin/env bash
# =============================================================================
# dsh-better-sidebar 双插件 Context 诊断 e2e(真实 dsh-context + 本插件):
#
# 1. 全新 scratch profile(骨架复用 scripts/e2e-common.sh,不改该文件);
# 2. 真实安装:本仓库 tarball;dual / tab-only 变体再加 dsh-context@<钉版>;
# - dual 双插件齐全(三个入口都可用:当前会话 / 子代理详情 / 后台任务);
# - tab-only dsh-context 在,但用**它自己的公开设置** defaultPlacement=tab
# 只注册会话内视图、不注册右侧栏 tab 类型与 body —— 入口必须隐藏
# (controller 的判据是 kind+body 都可用);
# - no-context 只装 tarball —— 入口必须隐藏;
# 3. 启动真实 `dsh web`(keyless,--port 0 取 OS 分配端口,绝不动 :3384);
# 4. 运行 tests/e2e/context-diagnostics.e2e.ts(Playwright Chromium,无头)。
#
# 用法:
# bash scripts/e2e-context.sh [--variant dual|tab-only|no-context|all] [--grep <filter>]
#
# 环境变量(均可省略):
# DSH_CMD 必须保留 DSH_HOME 的真实 CLI;缺省 npx 钉版(避开桌面 shim)
# TARBALL 插件 tarball;缺省仓库根 dsh-better-sidebar-*.tgz(须已 pack)
# PORT 固定端口(默认 0 = OS 分配,从日志解析 URL)
# DSH_HOME_BASE scratch 根目录(默认系统临时目录)。脚本只在其下新建本调用拥有的
# 独立子目录,只写入/删除该子目录
# KEEP_HOME 非空时保留 scratch(调试用)
# CONTEXT_PKG context 插件规格;缺省 dsh-context@0.72.0。**必须写精确版本号,
# 绝不写 dist-tag**(AGENTS.md §2:dist-tag 指向与候选版经常不一致)
# 每个变体都安装仅测试用 fixture,播种父子会话和后台 job;绝不发送模型请求。
#
# 退出码 = 0 全部通过;非 0 失败。服务与 scratch 由 trap 兜底清理。
#
# 清理安全性(本脚本的硬约束,见用户/父代理要求):
# - 只定向 kill 本脚本自己启动的 $SERVER_PID(e2e_cleanup),**没有 pkill/killall**;
# - 只删 e2e_make_scratch(mktemp -d)产出的 $SCRATCH 与本脚本 mktemp -d 的 $TMP_DIR,
# 两者都在挂 trap 之前由 assert_mktemp_product 校验过形状,未通过即 die(不清理)。
# =============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
E2E_TAG=e2e-context
source "$SCRIPT_DIR/e2e-common.sh"
# Desktop command shims may overwrite DSH_HOME. Default to the pinned real CLI.
DSH_CMD="${DSH_CMD:-npx -y --package ${DSH_NPX_SPEC} dsh}"
PORT="${PORT:-0}"
TARBALL="${TARBALL:-}"
CONTEXT_PKG="${CONTEXT_PKG:-dsh-context@0.72.0}"
VARIANT="all"
GREP_FILTER=""
while [ $# -gt 0 ]; do
case "$1" in
--variant) VARIANT="${2:?--variant 需要参数}"; shift 2 ;;
--grep) GREP_FILTER="${2:?--grep 需要参数}"; shift 2 ;;
-h|--help) sed -n '2,46p' "${BASH_SOURCE[0]}"; exit 0 ;;
*) die "未知参数:$1(支持 --variant/--grep)" ;;
esac
done
case "$VARIANT" in
dual|tab-only|no-context) VARIANTS="$VARIANT" ;;
all) VARIANTS="dual tab-only no-context" ;;
*) die "--variant 只支持 dual / tab-only / no-context / all(收到 $VARIANT)" ;;
esac
e2e_require_cmd node "DSH 运行需要 Node.js >= 20"
e2e_require_cmd pnpm "dsh plugin 转发给 pnpm"
e2e_require_cmd npm "打包 fixture 插件需要"
e2e_resolve_dsh_cmd
e2e_resolve_tarball || die "找不到 tarball(TARBALL 或 \$ROOT/dsh-better-sidebar-*.tgz)——先运行 pnpm build && pnpm pack"
TARBALL="$(cd "$(dirname "$TARBALL")" && pwd)/$(basename "$TARBALL")"
say "tarball: $TARBALL"
# ── 清理目标形状校验 ─────────────────────────────────────────────────────────
# e2e_cleanup 会 rm -rf $SCRATCH / $TMP_DIR,两者都必须是本次调用 mktemp -d 的产物。
# 形状不符(例如被外部环境变量顶掉)时直接 die,绝不无审查清理。
assert_mktemp_product() {
local dir="$1" base="$2" name="$3"
[ -n "$dir" ] || die "$name 为空,拒绝挂清理 trap"
[ -d "$dir" ] || die "$name 不是目录:$dir(拒绝清理)"
base="$(cd "$base" && pwd -P)" || die "$name 根目录无法解析"
dir="$(cd "$dir" && pwd -P)" || die "$name 目录无法解析"
case "$dir" in
"$base"/"$name".*) ;;
*) die "$name 不是本次 mktemp -d 产物:$dir(期望 $base/$name.XXXXXX,拒绝清理)" ;;
esac
}
# ── 一个变体的完整流程(在子 shell 里跑:EXIT trap 只清这一个变体)──────────
run_variant() {
local variant="$1"
local fixture_dir=""
e2e_make_scratch dsh-e2e-context
assert_mktemp_product "$SCRATCH" "${DSH_HOME_BASE:-/tmp}" "dsh-e2e-context"
export DSH_HOME="$SCRATCH/home"
local workspace="$SCRATCH/workspace"
local web_log="$SCRATCH/web.log"
local profile="$DSH_HOME/profiles/web"
mkdir -p "$profile" "$workspace"
SERVER_PID=""
TMP_DIR=""
trap e2e_cleanup EXIT
say "[$variant] scratch:$SCRATCH"
# 步骤 1:引导 scratch profile(三件套 heredoc 及 minimumReleaseAgeExclude 的
# 理由见 e2e-common.sh 的 e2e_write_profile)
e2e_write_profile "$profile"
# 步骤 2:官方 CLI 安装(真实挂载路径)
say "[$variant] 安装插件 tarball…"
$DSH_CMD plugin --profile web add "file:$TARBALL"
if [ "$variant" = "dual" ] || [ "$variant" = "tab-only" ]; then
say "[$variant] 安装 ${CONTEXT_PKG}…"
install_plugin_spec "$CONTEXT_PKG" "$profile"
fi
local fixture_tmp
fixture_tmp="$(mktemp -d "${TMPDIR:-/tmp}/dsh-e2e-context-fixture.XXXXXX")"
assert_mktemp_product "$fixture_tmp" "${TMPDIR:-/tmp}" "dsh-e2e-context-fixture"
TMP_DIR="$fixture_tmp"
fixture_dir="$(build_fixture_package "$TMP_DIR")"
say "[$variant] 安装仅测试用 fixture 宿主插件($fixture_dir)…"
$DSH_CMD plugin --profile web add "file:$fixture_dir"
if [ "$variant" = "tab-only" ]; then
# The plugin's OWN public setting, applied as an id-targeted config override
# in the profile patch layer (the documented `PatchOptions` shape: bundles
# first, then cordis.patch.yml). `defaultPlacement: tab` keeps dsh-context's
# in-conversation Context view and does NOT register the right-sidebar tab
# type or its pane body — the "kind present, body absent / tab-only" state
# the entries must hide in. Written AFTER the installs so `dsh plugin add`
# cannot clobber it.
say "[$variant] 写入 dsh-context defaultPlacement=tab(profile patch 覆盖)…"
cat > "$profile/cordis.patch.yml" <<'EOF'
# e2e lane (scripts/e2e-context.sh, variant tab-only): an id-targeted config
# override of dsh-context's own public setting. It keeps the plugin's
# conversation-level Context view while leaving the native right column without
# a `dsh-context` tab type — the state the diagnostics entries must hide in.
- id: dsh-context
config:
defaultPlacement: tab
EOF
fi
# 步骤 3:校验挂载生效(dsh.profile.bundles 含 dsh-better-sidebar;dual 另证
# context 依赖真的进了 profile)
assert_profile_installed "$profile" "$variant"
# 步骤 4:启动真实 dsh web(--port 0 = OS 分配;keyless 可起)
say "[$variant] 启动 dsh web(port=${PORT})…"
export DSH_E2E_CONTEXT_WORKSPACE="$workspace"
$DSH_CMD web --port "$PORT" --no-open >"$web_log" 2>&1 &
SERVER_PID=$!
# 就绪行解析:带一次性 token 的鉴权 URL(理由见 e2e-mount.sh 的同名注释)
E2E_READY_RE='dsh web: http://127\.0\.0\.1:[0-9]+[^ ]*'
E2E_READY_PICK=head
local wait_rc=0
e2e_wait_dsh_web_ready "$web_log" || wait_rc=$?
if [ "$wait_rc" -eq 2 ]; then
echo "=== [$variant] dsh web 提前退出,日志尾部 ===" >&2
tail -30 "$web_log" >&2 || true
exit 1
fi
if [ "$wait_rc" -ne 0 ]; then
echo "=== [$variant] 120s 内未等到 dsh web 就绪,日志尾部 ===" >&2
tail -40 "$web_log" >&2 || true
exit 1
fi
say "[$variant] dsh web 就绪:${URL}(pid ${SERVER_PID})"
# 启动期前置校验(都读宿主日志,失败即停在测试之前,避免把「插件没加载」误读
# 成 controller 失效):
# 1) 宿主兼容性预检会把 peer 范围不满足的整行静默 disabled(AGENTS.md §12);
if grep -q "disabling profile plugin .*dsh-context" "$web_log"; then
warn "宿主预检禁用了 dsh-context 行——真机前提不成立"
grep -n "disabling profile plugin" "$web_log" >&2 || true
exit 1
fi
# 2) tab-only 变体的 id 定向 config 覆盖必须真的命中那行;未命中时 include 只
# 告警并跳过(cordis-plugin-include 的 applyEntryPatches),右侧栏类型就会
# 照旧注册——spec 会红,但这里更早给出原因。
if [ "$variant" = "tab-only" ] && grep -qE "patch: entry .*dsh-context.* not found" "$web_log"; then
warn "defaultPlacement 覆盖未命中 dsh-context 行(profile patch 的 id 对不上)"
grep -nE "patch: entry .*dsh-context.* not found" "$web_log" >&2 || true
exit 1
fi
# 步骤 5:运行本 lane 的 spec(只这一个文件;--grep 可选)
say "[$variant] 运行 Playwright(tests/e2e/context-diagnostics.e2e.ts)…"
export DSH_E2E_URL="$URL"
export DSH_E2E_WORKSPACE="$workspace"
export DSH_E2E_CONTEXT_VARIANT="$variant"
if [ -n "$GREP_FILTER" ]; then
pnpm exec playwright test tests/e2e/context-diagnostics.e2e.ts --output "test-results/context-$variant" --grep "$GREP_FILTER"
else
pnpm exec playwright test tests/e2e/context-diagnostics.e2e.ts --output "test-results/context-$variant"
fi
if ! grep -q '\[e2e-context-fixture\] seeding complete' "$web_log"; then
warn "fixture 未完成播种"
tail -20 "$web_log" >&2 || true
exit 1
fi
say "[$variant] 通过"
}
# 官方 CLI 安装一条插件规格;失败时给 profile 写 .npmrc 走官方 registry 重试一次
# (本机默认 registry 是 npmmirror,对新预发布/新版本可能滞后;AGENTS.md §2)。
install_plugin_spec() {
local spec="$1" profile="$2"
if $DSH_CMD plugin --profile web add "$spec"; then return 0; fi
warn "安装 $spec 失败——改用官方 registry(写 $profile/.npmrc)重试一次"
printf 'registry=https://registry.npmjs.org/\n' > "$profile/.npmrc"
$DSH_CMD plugin --profile web add "$spec"
}
# 把 tests/e2e/context-fixture-plugin.mjs 打成仅测试用的 npm 包(manifest 随本脚本
# 生成,镜像 tests/fixtures/aggregate-better-sidebar 的形态),返回 tarball 绝对路径。
build_fixture_package() {
local tmp="$1"
local dir="$tmp/fixture-context-seed"
mkdir -p "$dir/lib"
cp "$ROOT/tests/e2e/context-fixture-plugin.mjs" "$dir/lib/index.mjs"
cat > "$dir/package.json" <<'EOF'
{
"name": "fixture-context-seed",
"version": "0.0.0",
"private": true,
"type": "module",
"main": "lib/index.mjs",
"files": [
"lib",
"cordis.patch.yml"
],
"dsh": {
"bundle": {
"patch": "./cordis.patch.yml"
}
}
}
EOF
cat > "$dir/cordis.patch.yml" <<'EOF'
# e2e-only bundle patch: mount the context-diagnostics seeding fixture as its own
# row. It never ships (the package is built into the lane's scratch dir from
# tests/e2e/context-fixture-plugin.mjs).
- insert:
- id: e2e-context-fixture
name: 'fixture-context-seed'
EOF
( cd "$dir" && npm pack --pack-destination "$tmp" >&2 ) || return $?
local tgz
tgz="$(ls "$tmp"/fixture-context-seed-*.tgz 2>/dev/null | head -1 || true)"
[ -n "$tgz" ] || die "fixture 插件打包失败($dir)"
printf '%s\n' "$tgz"
}
# 校验挂载点:bundles 含 dsh-better-sidebar;dual 变体另证 context 插件确实进了
# profile 的 dependencies(否则「入口消失」会被误读成 controller 失效)。
assert_profile_installed() {
local profile="$1" variant="$2"
if ! node -e '
const fs = require("fs");
const p = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
const bundles = p.dsh?.profile?.bundles ?? [];
process.exit(bundles.includes("dsh-better-sidebar") ? 0 : 1);
' "$profile/package.json"; then
warn "dsh-better-sidebar 未出现在 dsh.profile.bundles 中——挂载未注册"
cat "$profile/package.json"
exit 1
fi
if [ "$variant" = "dual" ] || [ "$variant" = "tab-only" ]; then
if ! node -e '
const fs = require("fs");
const p = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
const dep = p.dependencies?.["dsh-context"] ?? "";
process.exit(dep === "" ? 1 : 0);
' "$profile/package.json"; then
warn "$variant 变体下 dsh-context 不在 profile dependencies 中——真机前提不成立"
cat "$profile/package.json"
exit 1
fi
fi
say "[$variant] 挂载已注册:dsh.profile.bundles 含 dsh-better-sidebar"
}
cd "$ROOT"
for one in $VARIANTS; do
say "==== 变体 $one ===="
# Keep this outside a conditional: Bash otherwise disables errexit inside
# run_variant and a failing Playwright run could be reported as successful.
( run_variant "$one" )
done
say "通过:双插件 Context 诊断 lane(变体:$VARIANTS)"
+17 -1
View File
@@ -24,6 +24,8 @@ import {
TerminalBlock, type TagTone,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { SidebarClientJobsService, SidebarJobView, SidebarObservedJob } from '../context-types.ts'
import type { ContextDiagnosticTarget } from './context-diagnostics.ts'
import { ContextDiagnosticsButton } from './context-diagnostics-ui.tsx'
import { terminalBlockLabels } from './block-labels.ts'
import {
formatJobDuration,
@@ -291,12 +293,20 @@ export function JobOutputWindow(props: {
ownerSessionId: string
/** The host's streamed observation of THIS job (undefined until it arrives). */
observed: SidebarObservedJob | undefined
/**
* The diagnostics target of the conversation that OWNS this job, resolved by
* the caller from the tree model (`undefined` = the owner is not in this
* tree, or the page has no such capability): the window never derives it
* from `ownerSessionId`, which names the session the roster was WATCHED
* under, not the session that owns the job.
*/
diagnostics?: ContextDiagnosticTarget | undefined
/** The row's main button — where the window first appears. */
anchor?: HTMLElement | null
/** Close the window (the close button, or Escape). */
onClose(): void
}): ReactNode {
const { jobs, job, ownerSessionId, observed, anchor, onClose } = props
const { jobs, job, ownerSessionId, observed, diagnostics: diagnosticTarget, anchor, onClose } = props
const [follow, setFollow] = useState(true)
const [copied, setCopied] = useState(false)
const [armed, setArmed] = useState(false)
@@ -346,6 +356,12 @@ export function JobOutputWindow(props: {
bodyRef={bodyRef}
actions={(
<>
{/*
The owning conversation's Context view, beside the copy action: it is
offered only when the caller resolved the job's OWNER into the tree
(see the `diagnostics` prop) and the deployment has the page at all.
*/}
<ContextDiagnosticsButton kind="job" target={diagnosticTarget} iconSize={12} onNavigate={onClose} />
<Button
variant="ghost"
size="sm"
+34
View File
@@ -60,6 +60,8 @@ import {
clientJobs, collectRows, useJobObservation, useJobWatchers, useJobsSnapshot,
} from './jobs-client.ts'
import { t } from './locales.ts'
import { diagnosticAddressOf } from './context-diagnostics-ui.tsx'
import type { ContextDiagnosticTarget } from './context-diagnostics.ts'
import { buildTasksModel, type TasksAgentNode, type TasksFoldNode, type TasksWorkflowNode } from './tasks-model.ts'
import { TasksGraph } from './TasksGraph.tsx'
import { TasksTree } from './TasksTree.tsx'
@@ -387,6 +389,36 @@ export function SubagentView(props: {
[byId, catalogs, rootId, sessionId, live, metrics, runs, teamMembers, team, folded, foldedIds, expandedGroups],
)
/**
* The tree's agent nodes by their session id — the ONLY sanctioned source of
* a job's diagnostics target. A jobs row is a roster entry under a WATCHED
* session (`row.ownerSessionId`) whose real owner is `job.owner`; a roster
* payload without an owner is announced under the watching session, which is
* not necessarily the session that owns the job. Resolving through the model
* therefore answers both halves at once: whether the owning session is in
* this tree at all, and what that node's address is (the root node has none
* — it IS the tree's main session — and must be addressed by its own id).
*/
const agentNodeBySession = useMemo((): ReadonlyMap<string, TasksAgentNode> => {
const nodes = new Map<string, TasksAgentNode>()
for (const node of model) if (node.kind === 'agent') nodes.set(node.id, node)
return nodes
}, [model])
/**
* The diagnostics target of one conversation, when this tree holds its node.
* The label is the NODE's own — the card's durable label, resolved by the
* model — never a caller's title: a jobs row only knows the watched
* session's display title, which is not the owning agent's name.
*/
const diagnosticsTargetOf = useCallback((ownerId: string): ContextDiagnosticTarget | undefined => {
const node = agentNodeBySession.get(ownerId)
if (node === undefined) return undefined
const address = diagnosticAddressOf(node.id, node.childAddress)
if (node.parentId !== undefined && address === undefined) return undefined
return { sessionId: node.id, label: node.label, ...(address === undefined ? {} : { address }) }
}, [agentNodeBySession])
/**
* Show one conversation in the main view. DSH moved child and session
* navigation OFF `ISessions` (0.1.6's `open` / `openSubagent` are gone from
@@ -636,6 +668,7 @@ export function SubagentView(props: {
observed={treeJobs.observed[row.job.id]}
anchor={popover.anchor}
onClose={closePopover}
diagnostics={row.job.owner === undefined ? undefined : diagnosticsTargetOf(row.job.owner)}
/>
)
}
@@ -656,6 +689,7 @@ export function SubagentView(props: {
asideAvailable={asideAvailable}
onJump={jumpToNode}
onOpenTask={openTaskById}
onClose={closePopover}
/>
)
}
+27 -1
View File
@@ -32,6 +32,8 @@ import {
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { SidebarSubagentAddress, SidebarTokenUsage } from '../context-types.ts'
import type { TasksAgentNode, TasksWorkflowNode } from './tasks-model.ts'
import type { ContextDiagnosticTarget } from './context-diagnostics.ts'
import { ContextDiagnosticsButton, diagnosticAddressOf } from './context-diagnostics-ui.tsx'
import {
activityLine, AgentGlyph, WorkflowGlyph, flatten, modeLabel, nodeDotState, taskDotState,
taskStatusLabel, taskTone, workflowStatusKey,
@@ -104,11 +106,16 @@ function PopTitleRow(props: { glyph: ReactNode; title: string }): ReactNode {
* The ROOT node has no child to embed — it IS the main session — and a host
* without the `subagentchat` type has no sidebar to open into, so both keep the
* single button.
*
* The optional `children` slot carries the card's OTHER footer control (the
* diagnostics jump): the two live in one row so the card still has exactly one
* action band, and the split's own box stays fixed-width beside it.
*/
function JumpActions(props: {
node: TasksAgentNode
asideAvailable: boolean
onJump(node: TasksAgentNode, place: 'side' | 'main'): void
children?: ReactNode
}): ReactNode {
const { node, asideAvailable, onJump } = props
const [open, setOpen] = useState(false)
@@ -163,6 +170,7 @@ function JumpActions(props: {
)}
</span>
)}
{props.children}
</>
)
}
@@ -188,6 +196,7 @@ export function AgentNodePopover(props: {
onJump(node: TasksAgentNode, place: 'side' | 'main'): void
/** Open the shared task window for one of the node's tasks. */
onOpenTask(taskId: string, anchor: HTMLElement): void
onClose(): void
}): ReactNode {
const { node, onJump, onOpenTask } = props
/** The row's mode word; `unknown` claims no mode and this row is omitted. */
@@ -206,6 +215,21 @@ export function AgentNodePopover(props: {
// newest range — the host's own wording, in its running or settled form
// (see activityLine).
const activity = activityLine(node)
/**
* The diagnostics jump's address: a child node carries the durable
* parent/child address its catalog row built, and the ROOT node has none —
* it IS the tree's main session — so it is addressed by its own session id.
* A node whose address is incomplete (a stale parent, a synthesized member)
* yields no diagnostics control; the transcript's original footer gate is
* independent of this optional integration.
*/
const diagnosticsAddress = node.parentId === undefined
? undefined
: diagnosticAddressOf(node.id, node.childAddress)
const diagnosticsUsable = node.parentId === undefined ? true : diagnosticsAddress !== undefined
const diagnosticsTarget: ContextDiagnosticTarget | undefined = diagnosticsUsable
? { sessionId: node.id, label: node.label, ...(diagnosticsAddress === undefined ? {} : { address: diagnosticsAddress }) }
: undefined
return (
<div className={css.popCard}>
<div className={css.popHead}>
@@ -280,7 +304,9 @@ export function AgentNodePopover(props: {
node={node}
asideAvailable={props.asideAvailable}
onJump={onJump}
/>
>
<ContextDiagnosticsButton kind="agent" target={diagnosticsTarget} iconSize={14} className={css.popActionIcon} onNavigate={props.onClose} />
</JumpActions>
</div>
)}
</div>
+254
View File
@@ -0,0 +1,254 @@
/**
* The UI half of the optional dsh-context diagnostics: three entry points into
* ONE conversation's "Context" view (an agent node's detail card, a background
* job's output window, the session header's utilities row) and the frame-wide
* error alert they share.
*
* Availability comes from the controller (./context-diagnostics.ts), never from
* a guess here: it re-proves the optional runtime faces and answers `available`
* (the tab type AND its keyed body), and its single `busy` flag disables all
* three entry points for the duration of an open.
*
* The controller is threaded PER ACTIVATION — created in ./index.tsx, handed to
* the host's two slots by closure, to the plugin's tree through the provider,
* and to the native bodies through the native surface's deps bag. No
* module-level store on purpose: two activations must never share one, and a
* body unmounting must never clear another entry point's controller.
*/
import { createContext, useContext, useSyncExternalStore, type ReactNode } from 'react'
import {
Button, IconCloseOutlineRegular, IconContextInjectionOutlineRegular, IconWarningTriangleOutlineRegular,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { Context, SidebarSubagentAddress } from '../context-types.ts'
import {
createContextDiagnostics,
type ContextDiagnosticError,
type ContextDiagnosticTarget,
type ContextDiagnostics,
type ContextDiagnosticsSnapshot,
} from './context-diagnostics.ts'
import { mountedSessionId } from './native/surface.ts'
import { t, type CopyKey } from './locales.ts'
import css from './context-diagnostics.module.css'
/** The entry id both slot registrations use. */
export const HEADER_ENTRY_ID = 'dsh-better-sidebar:context-diagnostics'
/** The three entry points, as the e2e lane tells them apart. */
export type DiagnosticsEntryKind = 'session' | 'agent' | 'job'
/** Testid of an entry point's control; ABSENT while the control is not offered. */
export const DIAGNOSTICS_ENTRY_ATTR = 'data-dsh-ctx-entry'
/** Testid of the frame-wide alert. */
export const DIAGNOSTICS_ALERT_ATTR = 'data-dsh-ctx-alert'
/** The controller's carrier; `undefined` = this tree has no diagnostics. */
const DiagnosticsStoreContext = createContext<ContextDiagnostics | undefined>(undefined)
/** Thread one activation's controller into a subtree (shell, native tab body). */
export function ContextDiagnosticsHost(props: {
controller?: ContextDiagnostics
children?: ReactNode
}): ReactNode {
return (
<DiagnosticsStoreContext.Provider value={props.controller}>
{props.children}
</DiagnosticsStoreContext.Provider>
)
}
/** The controller in scope for this tree (undefined = no entry point renders). */
function useDiagnosticsStore(): ContextDiagnostics | undefined {
return useContext(DiagnosticsStoreContext)
}
function useDiagnosticsSnapshot(store: ContextDiagnostics | undefined): ContextDiagnosticsSnapshot | undefined {
return useSyncExternalStore(store?.subscribe ?? NO_SUBSCRIBE, store?.getSnapshot ?? NO_SNAPSHOT)
}
const NO_SUBSCRIBE = (): (() => void) => () => {}
const NO_SNAPSHOT = (): undefined => undefined
/**
* One entry point's control, shared so the three surfaces cannot drift apart:
* the gate (capability available AND a resolved target), the single-open
* disable, and the e2e handle.
*/
export function ContextDiagnosticsButton(props: {
kind: DiagnosticsEntryKind
/** `undefined` = this surface has nothing addressable to offer. */
target: ContextDiagnosticTarget | undefined
/** The host glyph's size (the header uses 14, the floating window 12). */
iconSize: number
/** The caller's box class, when the glyph must not take row width. */
className?: string
/** Dismiss source UI after dispatch; the controller owns the pending request. */
onNavigate?(): void
}): ReactNode {
const { kind, target, iconSize, className } = props
const store = useDiagnosticsStore()
const snapshot = useDiagnosticsSnapshot(store)
if (store === undefined || target === undefined || snapshot?.available !== true) return null
const busy = snapshot.busy === true
return (
<Button
variant="ghost"
size="sm"
{...(className === undefined ? {} : { className })}
{...{ [DIAGNOSTICS_ENTRY_ATTR]: kind }}
// Busy is announced as well as enforced: one open at a time disables
// every entry point while it runs.
aria-busy={busy ? 'true' : undefined}
icon={<IconContextInjectionOutlineRegular size={iconSize} />}
aria-label={t('contextDiagnostics')}
title={t('contextDiagnostics')}
disabled={busy}
onClick={() => {
store.open(target)
props.onNavigate?.()
}}
/>
)
}
/**
* The header's control: an entry is drawn for the session the SLOT was mounted
* with and can outlive it by a moment while the host rebuilds the row, so the
* click re-checks `sidebarRight.mounted` and refuses to act once that session
* left the screen — a stale header must never navigate into the previous
* conversation.
*/
function ContextDiagnosticsHeader(props: {
controller: ContextDiagnostics
sessionId: string
isCurrent(): boolean
}): ReactNode {
const { controller, sessionId, isCurrent } = props
const snapshot = useDiagnosticsSnapshot(controller)
if (snapshot?.available !== true) return null
const busy = snapshot.busy === true
return (
<Button
variant="ghost"
size="sm"
className={css.headerButton}
{...{ [DIAGNOSTICS_ENTRY_ATTR]: 'session' satisfies DiagnosticsEntryKind }}
aria-busy={busy ? 'true' : undefined}
icon={<IconContextInjectionOutlineRegular size={14} />}
aria-label={t('contextDiagnostics')}
title={t('contextDiagnostics')}
disabled={busy}
onClick={() => {
if (!isCurrent()) return
controller.open({ sessionId, label: t('contextDiagnosticsTarget') })
}}
/>
)
}
/** The copy key of one failure reason. */
function reasonKey(reason: ContextDiagnosticError['reason']): CopyKey {
switch (reason) {
case 'navigation': return 'contextDiagnosticsNavigation'
case 'timeout': return 'contextDiagnosticsTimeout'
case 'open': return 'contextDiagnosticsOpenFailed'
case 'unavailable': return 'contextDiagnosticsUnavailable'
}
}
/**
* The ONE error alert (`shell.overlay`), dismissed by the controller's own
* `dismissError()` — never a timer. Gated on the ERROR only, not on
* `available`: an open already in flight when the capability went away must
* still report why it failed.
*/
export function ContextDiagnosticsAlert(props: { controller: ContextDiagnostics }): ReactNode {
const { controller } = props
const snapshot = useDiagnosticsSnapshot(controller)
const error = snapshot?.error
if (error === undefined) return null
return (
<div className={css.alertLayer} {...{ [DIAGNOSTICS_ALERT_ATTR]: '' }}>
<div className={css.alert} role="alert">
<span className={css.alertIcon} aria-hidden="true">
<IconWarningTriangleOutlineRegular size={14} />
</span>
<span className={css.alertText}>
<span className={css.alertTitle}>
{t('contextDiagnosticsFailed', { label: error.targetLabel })}
</span>
<span className={css.alertReason}>{t(reasonKey(error.reason))}</span>
</span>
<Button
variant="ghost"
size="sm"
className={css.alertClose}
icon={<IconCloseOutlineRegular size={12} />}
aria-label={t('contextDiagnosticsDismiss')}
title={t('contextDiagnosticsDismiss')}
onClick={() => { controller.dismissError() }}
/>
</div>
</div>
)
}
/**
* Contribute the header control and the frame-wide alert. Both ride
* `slots.inject`: neither declaration is guaranteed to be on the ledger at
* activation (the header and the frame come from other entries), and the
* callback re-runs if one collapses and is re-declared.
* @param ctx - the client context (slots + the native right column probe).
* @param controller - the controller of this activation.
* @returns a disposer unregistering both entries.
*/
export function registerContextDiagnosticsUI(ctx: Context, controller: ContextDiagnostics): () => void {
const disposers: Array<() => void> = []
try {
disposers.push(ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({
name: 'conversation.session.header.utilities',
id: HEADER_ENTRY_ID,
// After the host's own utilities and after the bottom-workbench toggle
// (order 10), so the two plugin controls sit together at the row's edge.
order: 20,
registrant: 'dsh-better-sidebar',
inject: (sessionId: string) => ({
controller,
sessionId,
isCurrent: () => mountedSessionId(ctx) === sessionId,
}),
}, ContextDiagnosticsHeader)))
disposers.push(ctx.slots.inject('shell.overlay', () => ctx.slots.register({
name: 'shell.overlay',
id: HEADER_ENTRY_ID,
order: 20,
registrant: 'dsh-better-sidebar',
inject: () => ({ controller }),
}, ContextDiagnosticsAlert)))
} catch (error) {
for (const dispose of disposers.reverse()) dispose()
throw error
}
return () => {
for (const dispose of disposers.reverse()) dispose()
disposers.length = 0
}
}
/** The activation's diagnostics controller (one per client activation). */
export function createContextDiagnosticsHost(ctx: Context): ContextDiagnostics {
return createContextDiagnostics(ctx)
}
/** A tree node's navigable address, when the tree really has one: the ROOT node
* carries none (it IS the main session) and is addressed by its own id, and an
* incomplete pair (a stale parent, a synthesized member) yields no control. */
export function diagnosticAddressOf(
nodeId: string,
address: SidebarSubagentAddress | undefined,
): SidebarSubagentAddress | undefined {
return address !== undefined && address.parentSessionId !== '' && address.childSessionId === nodeId
? address
: undefined
}
+83
View File
@@ -0,0 +1,83 @@
/**
* The diagnostics chrome: ONE header control, and the frame-wide error alert.
*
* Both surfaces ride existing scale and tokens only (skin contract, guide §12):
* the control is a host `Button sm` (28px) whose box is fixed so it can never
* squeeze the header's own row at the sidebar's narrow width, and the alert is
* a small card on the floating layer (`shell.overlay`), painted like the
* plugin's other floating surfaces, with a warning-token edge.
*
* The alert is also its own layer contract: the overlay seat is click-through,
* so this root opts back into pointer events for itself only.
*/
/* ── The header control ────────────────────────────────────────────────── */
/* `flex: none` + a fixed box: the header row gives up width before this
control does, and it never wraps onto a second line. */
.headerButton {
flex: none;
width: 28px;
padding: 0;
}
/* ── The frame-wide error alert ────────────────────────────────────────── */
/* Bottom-center, clear of the composer and of the sidebar columns. The seat
is click-through; the card itself is not. */
.alertLayer {
position: fixed;
left: 50%;
bottom: 16px;
transform: translateX(-50%);
z-index: 40;
display: flex;
justify-content: center;
/* Never wider than the viewport it floats over. */
max-width: min(420px, calc(100vw - 24px));
pointer-events: auto;
}
.alert {
display: flex;
align-items: flex-start;
gap: 8px;
width: 100%;
padding: 8px 8px 8px 10px;
background: var(--dsw-alias-bg-layer-3);
border: 1px solid var(--dsw-alias-state-warn-primary);
border-radius: 8px;
font: var(--dsw-font-xxs-12);
}
.alertIcon {
display: inline-flex;
flex: none;
margin-top: 2px;
color: var(--dsw-alias-state-warn-primary);
}
.alertText {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
min-width: 0;
}
.alertTitle {
color: var(--dsw-alias-label-primary);
overflow-wrap: anywhere;
}
/* The reason line, in the plugin's micro voice. */
.alertReason {
color: var(--dsw-alias-label-tertiary);
overflow-wrap: anywhere;
}
.alertClose {
flex: none;
width: 24px;
padding: 0;
}
+279
View File
@@ -0,0 +1,279 @@
/** Optional dsh-context navigation, owned by one better-sidebar activation. */
import type { Context, SidebarSubagentAddress } from '../context-types.ts'
// dsh-context 0.72.0 registers this type and keyed body; it exposes no service.
const CONTEXT_KIND = 'dsh-context'
const BODY_SLOT = 'sidebar.right.pane.tab'
const TIMEOUT_MS = 10_000
const RETRY_MS = 50
export interface ContextDiagnosticTarget {
sessionId: string
label?: string
address?: SidebarSubagentAddress
}
export interface ContextDiagnosticError {
reason: 'unavailable' | 'navigation' | 'timeout' | 'open'
targetLabel: string
}
export interface ContextDiagnosticsSnapshot {
available: boolean
busy: boolean
error?: ContextDiagnosticError
}
export interface ContextDiagnostics {
getSnapshot(): ContextDiagnosticsSnapshot
subscribe(listener: () => void): () => void
open(target: ContextDiagnosticTarget): void
dismissError(): void
dispose(): void
}
interface Observable<T> {
getSnapshot(): T
subscribe(listener: () => void): () => void
}
interface OpenTab {
sessionId: string
tabId: string
kind: string
}
interface RightFace {
mounted: Observable<string | undefined>
openTabs: Observable<readonly OpenTab[]>
openTab(kind: string): void
focus(tabId: string): void
active(): { id: string } | undefined
isExpanded(): boolean
toggleExpanded(): void
}
interface RegistryFace {
get(kind: string): { id: string; kind: string } | undefined
subscribe(listener: () => void): () => void
}
interface SlotsFace {
entriesOfSlot(key: string): readonly { options: { key?: string } }[]
subscribe(key: string, listener: () => void): () => void
}
interface Faces {
right: RightFace
registry: RegistryFace
slots: SlotsFace
workspace: { openSession(target: string | SidebarSubagentAddress): void }
layout: { beginNavigation(): AbortSignal }
}
interface Request {
target: ContextDiagnosticTarget
cleanups: Array<() => void>
ready: boolean
working: boolean
opened: boolean
signal?: AbortSignal
retry?: ReturnType<typeof setTimeout>
}
function record(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === 'object' ? value as Record<string, unknown> : undefined
}
function methods(value: unknown, names: readonly string[]): boolean {
const face = record(value)
return face !== undefined && names.every(name => typeof face[name] === 'function')
}
/** Re-prove the optional runtime faces; never treat package installation as readiness. */
function facesOf(ctx: Context): Faces | undefined {
try {
const right = ctx.get('sidebarRight') as unknown
const registry = ctx.get('sidebarRightTabs') as unknown
const workspace = ctx.get('uiWorkspace') as unknown
const layout = ctx.get('layout') as unknown
const slots = ctx.get('slots') as unknown
if (!methods(right, ['openTab', 'focus', 'active', 'isExpanded', 'toggleExpanded'])
|| !methods(record(right)?.mounted, ['getSnapshot', 'subscribe'])
|| !methods(record(right)?.openTabs, ['getSnapshot', 'subscribe'])
|| !methods(registry, ['get', 'subscribe'])
|| !methods(workspace, ['openSession'])
|| !methods(layout, ['beginNavigation'])
|| !methods(slots, ['entriesOfSlot', 'subscribe'])) return undefined
return { right, registry, workspace, layout, slots } as Faces
} catch {
return undefined
}
}
function available(faces: Faces | undefined): boolean {
if (faces === undefined) return false
try {
const type = faces.registry.get(CONTEXT_KIND)
return type?.kind === CONTEXT_KIND && typeof type.id === 'string' && type.id !== ''
&& faces.slots.entriesOfSlot(BODY_SLOT).some(entry => entry.options.key === type.id)
} catch {
return false
}
}
/** Create once in apply(), not once per keepMounted view. No idle timers or requests. */
export function createContextDiagnostics(ctx: Context): ContextDiagnostics {
let snapshot: ContextDiagnosticsSnapshot = { available: false, busy: false }
const listeners = new Set<() => void>()
let faces: Faces | undefined
let pending: Request | undefined
let disposed = false
const publish = (next: ContextDiagnosticsSnapshot): void => {
if (disposed || (snapshot.available === next.available && snapshot.busy === next.busy && snapshot.error === next.error)) return
snapshot = next
for (const listener of listeners) listener()
}
const finish = (request: Request, reason?: ContextDiagnosticError['reason']): void => {
if (pending !== request) return
pending = undefined
if (request.retry !== undefined) clearTimeout(request.retry)
for (const cleanup of request.cleanups.splice(0).reverse()) cleanup()
publish({
available: available(faces), busy: false,
...(reason === undefined ? {} : { error: { reason, targetLabel: request.target.label ?? request.target.sessionId } }),
})
}
const own = (request: Request, cleanup: () => void): void => {
if (pending === request) request.cleanups.push(cleanup)
else cleanup()
}
const refresh = (): void => {
const ready = available(faces)
if (!ready && pending !== undefined) finish(pending, 'unavailable')
else publish({ ...snapshot, available: ready })
}
const retry = (request: Request): void => {
if (pending !== request || request.retry !== undefined) return
request.retry = setTimeout(() => {
request.retry = undefined
attempt(request)
}, RETRY_MS)
}
const attempt = (request: Request): void => {
if (pending !== request || !request.ready || request.working) return
if (request.signal?.aborted === true) { finish(request); return }
const current = faces
if (current === undefined || !available(current)) { finish(request, 'unavailable'); return }
request.working = true
try {
// mounted changes before React adopts the arriving session's sidebar store.
if (current.right.mounted.getSnapshot() !== request.target.sessionId) return
let tab = current.right.openTabs.getSnapshot().find(row => row.sessionId === request.target.sessionId && row.kind === CONTEXT_KIND)
if (tab === undefined && !request.opened) {
current.right.openTab(CONTEXT_KIND)
request.opened = true
tab = current.right.openTabs.getSnapshot().find(row => row.sessionId === request.target.sessionId && row.kind === CONTEXT_KIND)
}
if (pending !== request || request.signal?.aborted) return
if (tab !== undefined) {
// Native page deduplication is pane-local; focus the session's existing page.
current.right.focus(tab.tabId)
if (!current.right.isExpanded()) current.right.toggleExpanded()
if (current.right.mounted.getSnapshot() === request.target.sessionId
&& current.right.active()?.id === tab.tabId && current.right.isExpanded()) {
finish(request)
return
}
}
retry(request)
} catch (error) {
if (record(error)?.message === 'sidebarRight: no session surface is mounted') retry(request)
else finish(request, 'open')
} finally {
request.working = false
}
}
// These dependencies suspend only this child fiber, never the main plugin.
const integration = ctx.inject(['sidebarRightTabs', 'sidebarRight', 'uiWorkspace', 'layout', 'slots'], (injected) => {
const connected = facesOf(injected as Context)
if (disposed || connected === undefined) return
faces = connected
const cleanups: Array<() => void> = []
try {
cleanups.push(connected.registry.subscribe(refresh))
cleanups.push(connected.slots.subscribe(BODY_SLOT, refresh))
refresh()
} catch {
faces = undefined
for (const cleanup of cleanups.reverse()) cleanup()
refresh()
return
}
return () => {
faces = undefined
for (const cleanup of cleanups.reverse()) cleanup()
refresh()
}
})
return {
getSnapshot: () => snapshot,
subscribe: (listener) => {
if (disposed) return () => {}
listeners.add(listener)
return () => { listeners.delete(listener) }
},
open: (target) => {
if (disposed || pending !== undefined) return
const current = faces
if (current === undefined || !available(current)) {
publish({ available: false, busy: false, error: { reason: 'unavailable', targetLabel: target.label ?? target.sessionId } })
return
}
if (target.sessionId === '' || (target.address !== undefined
&& (target.address.childSessionId !== target.sessionId || target.address.parentSessionId === ''))) {
publish({ available: true, busy: false, error: { reason: 'navigation', targetLabel: target.label ?? target.sessionId } })
return
}
const request: Request = { target: { ...target }, ready: false, working: false, opened: false, cleanups: [] }
pending = request
publish({ available: true, busy: true })
if (pending !== request) return
const deadline = setTimeout(() => { finish(request, 'timeout') }, TIMEOUT_MS)
own(request, () => { clearTimeout(deadline) })
try {
own(request, current.right.mounted.subscribe(() => { attempt(request) }))
own(request, current.right.openTabs.subscribe(() => { attempt(request) }))
if (current.right.mounted.getSnapshot() !== target.sessionId) current.workspace.openSession(target.address ?? target.sessionId)
if (pending !== request) return
// openSession itself selects the conversation panel, aborting older signals.
const signal = current.layout.beginNavigation()
request.signal = signal
const cancel = (): void => { finish(request) }
signal.addEventListener('abort', cancel, { once: true })
own(request, () => { signal.removeEventListener('abort', cancel) })
request.ready = true
attempt(request)
} catch {
finish(request, 'navigation')
}
},
dismissError: () => { publish({ available: snapshot.available, busy: snapshot.busy }) },
dispose: () => {
if (disposed) return
disposed = true
if (pending !== undefined) finish(pending)
snapshot = { available: false, busy: false }
void integration?.dispose()
listeners.clear()
},
}
}
+27 -2
View File
@@ -20,6 +20,7 @@ import { RenderBoundary } from './RenderBoundary.tsx'
import { createNativeTabRecords } from './native/tab-adapter.tsx'
import { registerNativeSurface } from './native/index.ts'
import { registerBottomToggle } from './sidebar/bottom-toggle.tsx'
import { ContextDiagnosticsHost, createContextDiagnosticsHost, registerContextDiagnosticsUI } from './context-diagnostics-ui.tsx'
import { createNativeSurface } from './native/surface.ts'
import { isTargetAvailable, openInterceptedLink, registerLinkInterception, shouldTakeOverLink } from './link-intercept.ts'
import { registerImeGuard } from './ime-guard.ts'
@@ -176,9 +177,17 @@ export function apply(ctx: Context): void {
const nativeRecords = createNativeTabRecords()
const nativeSurface = createNativeSurface(ctx, nativeRecords)
service.setSurface(nativeSurface)
// The optional dsh-context diagnostics: ONE controller per activation. It
// re-proves the optional runtime faces itself, so the plugin needs no new
// inject entry; it is threaded explicitly into the three consumers (the two
// host slots by closure, the plugin's own React tree through the provider,
// and the native tab bodies through the native surface's deps). On a
// deployment without dsh-context it reports `available: false` and every
// entry point stays absent.
const diagnostics = createContextDiagnosticsHost(ctx)
ctx.effect(
() => registerNativeSurface({
ctx, store: sidebarStore, service, records: nativeRecords,
ctx, store: sidebarStore, service, records: nativeRecords, diagnostics,
reportFailure: (phase, error) => { fail(`native ${phase}`, error) },
}),
'dsh-better-sidebar: native right-Sidebar registrations',
@@ -193,6 +202,14 @@ export function apply(ctx: Context): void {
() => () => { nativeSurface.dispose(); service.setSurface(undefined) },
'dsh-better-sidebar: native right-Sidebar surface',
)
ctx.effect(
() => registerContextDiagnosticsUI(ctx, diagnostics),
'dsh-better-sidebar: context diagnostics surfaces',
)
// The controller holds a child fiber (its runtime-face integration) and a
// pending-open timer; releasing both is what keeps a disabled plugin — and a
// hot reload that activates a fresh one — from leaving the old one behind.
ctx.effect(() => () => { diagnostics.dispose() }, 'dsh-better-sidebar: context diagnostics controller')
// Register the plugin's own built-in tabs and viewers through the same
// service (eating our own dogfood). The disposer unregisters them on
// fiber disposal (HMR-safe).
@@ -297,7 +314,15 @@ export function apply(ctx: Context): void {
host.setAttribute('data-dsh-better-sidebar', '')
document.body.appendChild(host)
root = createRoot(host)
root.render(createElement(RenderBoundary, { className: css.boundaryError }, createElement(Sidebar, { ctx, store: sidebarStore })))
root.render(createElement(
RenderBoundary,
{ className: css.boundaryError },
createElement(
ContextDiagnosticsHost,
{ controller: diagnostics },
createElement(Sidebar, { ctx, store: sidebarStore }),
),
))
mounted = true
guardAnchor()
scheduleHostCheck()
+8
View File
@@ -565,6 +565,14 @@ export const ar: Record<string, string> = {
workflowPhaseUnnamed: 'مرحلة بدون اسم',
workflowMembers: '{done}/{total} أعضاء',
jobsAutoCollapsed: 'تم الطي تلقائيًا (وكلاء كثيرون)',
contextDiagnostics: 'تشخيص السياق',
contextDiagnosticsTarget: 'الجلسة الحالية',
contextDiagnosticsFailed: 'تعذّر فتح تشخيص السياق لـ «{label}»',
contextDiagnosticsUnavailable: 'صفحة «السياق» في dsh-context غير متاحة (غير مثبّتة أو غير مسجّلة)',
contextDiagnosticsNavigation: 'تعذّر تحديد موقع هذه المحادثة',
contextDiagnosticsTimeout: 'انتهت مهلة الفتح — أعد المحاولة',
contextDiagnosticsOpenFailed: 'تعذّر فتح الصفحة',
contextDiagnosticsDismiss: 'إغلاق',
catalogLoadFailed: 'فشل تحميل {count} من الفروع',
addPluginsTabCard: 'إضافة إضافات تبويب',
addPluginsTabCardDesc: 'تسجيل صفحة شريط جانبي جديدة',
+8
View File
@@ -550,6 +550,14 @@ export const de: Record<string, string> = {
workflowPhaseUnnamed: 'Unbenannte Phase',
workflowMembers: '{done}/{total} Mitglieder',
jobsAutoCollapsed: 'Automatisch eingeklappt (viele Agenten)',
contextDiagnostics: 'Kontext-Diagnose',
contextDiagnosticsTarget: 'Aktuelle Sitzung',
contextDiagnosticsFailed: 'Kontext-Diagnose für „{label}“ konnte nicht geöffnet werden',
contextDiagnosticsUnavailable: 'Die Seite „Kontext“ von dsh-context ist nicht verfügbar (nicht installiert oder nicht registriert)',
contextDiagnosticsNavigation: 'Diese Unterhaltung konnte nicht gefunden werden',
contextDiagnosticsTimeout: 'Zeitüberschreitung beim Öffnen – bitte erneut versuchen',
contextDiagnosticsOpenFailed: 'Die Seite konnte nicht geöffnet werden',
contextDiagnosticsDismiss: 'Schließen',
catalogLoadFailed: '{count} Branches konnten nicht geladen werden',
addPluginsTabCard: 'Tab-Plugins hinzufügen',
addPluginsTabCardDesc: 'Eine neue Seitenleisten-Seite registrieren',
+8
View File
@@ -557,6 +557,14 @@ export const fr: Record<string, string> = {
workflowPhaseUnnamed: 'Phase sans nom',
workflowMembers: '{done}/{total} membres',
jobsAutoCollapsed: 'Replié automatiquement (nombreux agents)',
contextDiagnostics: 'Diagnostic du contexte',
contextDiagnosticsTarget: 'Session actuelle',
contextDiagnosticsFailed: 'Impossible d’ouvrir le diagnostic du contexte pour « {label} »',
contextDiagnosticsUnavailable: 'La page « Contexte » de dsh-context est indisponible (non installée ou non enregistrée)',
contextDiagnosticsNavigation: 'Impossible de localiser cette conversation',
contextDiagnosticsTimeout: 'Délai d’ouverture dépassé — réessayez',
contextDiagnosticsOpenFailed: 'La page n’a pas pu être ouverte',
contextDiagnosticsDismiss: 'Fermer',
catalogLoadFailed: '{count} branches n’ont pas pu être chargées',
addPluginsTabCard: 'Ajouter un plugin d’onglet',
addPluginsTabCardDesc: 'Enregistrer une nouvelle page de la barre latérale',
+8
View File
@@ -564,6 +564,14 @@ export const hi: Record<string, string> = {
workflowPhaseUnnamed: 'अनामित चरण',
workflowMembers: '{done}/{total} सदस्य',
jobsAutoCollapsed: 'एजेंट बहुत सारे, स्वतः संकुचित किया गया',
contextDiagnostics: 'कॉन्टेक्स्ट निदान',
contextDiagnosticsTarget: 'वर्तमान सत्र',
contextDiagnosticsFailed: '“{label}” का कॉन्टेक्स्ट निदान नहीं खोला जा सका',
contextDiagnosticsUnavailable: 'dsh-context का “कॉन्टेक्स्ट” पेज उपलब्ध नहीं है (इंस्टॉल या पंजीकृत नहीं)',
contextDiagnosticsNavigation: 'वह वार्तालाप ढूँढा नहीं जा सका',
contextDiagnosticsTimeout: 'खोलने में समय समाप्त — फिर प्रयास करें',
contextDiagnosticsOpenFailed: 'पेज नहीं खोला जा सका',
contextDiagnosticsDismiss: 'बंद करें',
catalogLoadFailed: '{count} ब्रांच लोड होने में विफल',
addPluginsTabCard: 'टैब प्लगइन जोड़ें',
addPluginsTabCardDesc: 'नया साइडबार पृष्ठ पंजीकृत करें',
+8
View File
@@ -562,6 +562,14 @@ export const id: Record<string, string> = {
workflowPhaseUnnamed: 'Fase tanpa nama',
workflowMembers: '{done}/{total} anggota',
jobsAutoCollapsed: 'Dilipat otomatis (agen banyak)',
contextDiagnostics: 'Diagnostik konteks',
contextDiagnosticsTarget: 'Sesi saat ini',
contextDiagnosticsFailed: 'Tidak dapat membuka diagnostik konteks untuk “{label}”',
contextDiagnosticsUnavailable: 'Halaman “Konteks” dsh-context tidak tersedia (tidak terpasang atau tidak terdaftar)',
contextDiagnosticsNavigation: 'Tidak dapat menemukan percakapan itu',
contextDiagnosticsTimeout: 'Waktu buka habis — coba lagi',
contextDiagnosticsOpenFailed: 'Halaman tidak dapat dibuka',
contextDiagnosticsDismiss: 'Tutup',
catalogLoadFailed: '{count} cabang gagal dimuat',
addPluginsTabCard: 'Tambah plugin tab',
addPluginsTabCardDesc: 'Daftarkan halaman sidebar baru',
+8
View File
@@ -555,6 +555,14 @@ export const it: Record<string, string> = {
workflowPhaseUnnamed: 'Fase senza nome',
workflowMembers: '{done}/{total} membri',
jobsAutoCollapsed: 'Compresso automaticamente (molti agenti)',
contextDiagnostics: 'Diagnostica del contesto',
contextDiagnosticsTarget: 'Sessione corrente',
contextDiagnosticsFailed: 'Impossibile aprire la diagnostica del contesto per «{label}»',
contextDiagnosticsUnavailable: 'La pagina «Contesto» di dsh-context non è disponibile (non installata o non registrata)',
contextDiagnosticsNavigation: 'Impossibile individuare quella conversazione',
contextDiagnosticsTimeout: 'Apertura scaduta — riprova',
contextDiagnosticsOpenFailed: 'Impossibile aprire la pagina',
contextDiagnosticsDismiss: 'Chiudi',
catalogLoadFailed: 'Impossibile caricare {count} branch',
addPluginsTabCard: 'Aggiungi plugin scheda',
addPluginsTabCardDesc: 'Registri una nuova pagina della barra laterale',
+8
View File
@@ -564,6 +564,14 @@ export const ja: Record<string, string> = {
workflowPhaseUnnamed: '無名フェーズ',
workflowMembers: '{done}/{total} メンバー',
jobsAutoCollapsed: 'エージェント多数のため自動折りたたみ',
contextDiagnostics: 'コンテキスト診断',
contextDiagnosticsTarget: '現在のセッション',
contextDiagnosticsFailed: '「{label}」のコンテキスト診断を開けませんでした',
contextDiagnosticsUnavailable: 'dsh-context の「コンテキスト」ページを利用できません(未インストールまたは未登録)',
contextDiagnosticsNavigation: 'そのセッションを特定できませんでした',
contextDiagnosticsTimeout: '開く処理がタイムアウトしました。再試行してください',
contextDiagnosticsOpenFailed: 'ページを開けませんでした',
contextDiagnosticsDismiss: '閉じる',
catalogLoadFailed: '{count} 個のブランチの読み込みに失敗',
addPluginsTabCard: 'Tab プラグインを追加',
addPluginsTabCardDesc: '新しいサイドバーページを登録',
+8
View File
@@ -556,6 +556,14 @@ export const ko: Record<string, string> = {
workflowPhaseUnnamed: '이름 없는 단계',
workflowMembers: '{done}/{total} 멤버',
jobsAutoCollapsed: '에이전트가 많아 자동으로 접었습니다',
contextDiagnostics: '컨텍스트 진단',
contextDiagnosticsTarget: '현재 세션',
contextDiagnosticsFailed: '‘{label}’의 컨텍스트 진단을 열 수 없습니다',
contextDiagnosticsUnavailable: 'dsh-context의 ‘컨텍스트’ 페이지를 사용할 수 없습니다(미설치 또는 미등록)',
contextDiagnosticsNavigation: '해당 대화를 찾을 수 없습니다',
contextDiagnosticsTimeout: '여는 시간이 초과되었습니다. 다시 시도하세요',
contextDiagnosticsOpenFailed: '페이지를 열지 못했습니다',
contextDiagnosticsDismiss: '닫기',
catalogLoadFailed: '{count}개 브랜치 로드 실패',
addPluginsTabCard: 'Tab 플러그인 추가',
addPluginsTabCardDesc: '새 사이드바 페이지 등록',
+8
View File
@@ -562,6 +562,14 @@ export const nl: Record<string, string> = {
workflowPhaseUnnamed: 'Naamloze fase',
workflowMembers: '{done}/{total} leden',
jobsAutoCollapsed: 'Automatisch ingeklapt (veel agents)',
contextDiagnostics: 'Contextdiagnose',
contextDiagnosticsTarget: 'Huidige sessie',
contextDiagnosticsFailed: 'Kon contextdiagnose voor ‘{label}’ niet openen',
contextDiagnosticsUnavailable: 'De pagina ‘Context’ van dsh-context is niet beschikbaar (niet geïnstalleerd of niet geregistreerd)',
contextDiagnosticsNavigation: 'Dat gesprek kon niet worden gevonden',
contextDiagnosticsTimeout: 'Openen duurde te lang — probeer opnieuw',
contextDiagnosticsOpenFailed: 'De pagina kon niet worden geopend',
contextDiagnosticsDismiss: 'Sluiten',
catalogLoadFailed: '{count} branches konden niet worden geladen',
addPluginsTabCard: 'Tabblad-plugins toevoegen',
addPluginsTabCardDesc: 'Een nieuwe zijbalkpagina registreren',
+8
View File
@@ -566,6 +566,14 @@ export const pl: Record<string, string> = {
workflowPhaseUnnamed: 'Faza bez nazwy',
workflowMembers: '{done}/{total} członków',
jobsAutoCollapsed: 'Automatycznie zwinięto (wiele agentów)',
contextDiagnostics: 'Diagnostyka kontekstu',
contextDiagnosticsTarget: 'Bieżąca sesja',
contextDiagnosticsFailed: 'Nie udało się otworzyć diagnostyki kontekstu dla „{label}”',
contextDiagnosticsUnavailable: 'Strona „Kontekst” w dsh-context jest niedostępna (niezainstalowana lub niezarejestrowana)',
contextDiagnosticsNavigation: 'Nie udało się znaleźć tej rozmowy',
contextDiagnosticsTimeout: 'Przekroczono czas otwierania — spróbuj ponownie',
contextDiagnosticsOpenFailed: 'Nie udało się otworzyć strony',
contextDiagnosticsDismiss: 'Zamknij',
catalogLoadFailed: 'Nie udało się załadować {count} gałęzi',
addPluginsTabCard: 'Dodaj wtyczki kart',
addPluginsTabCardDesc: 'Zarejestruj nową stronę panelu bocznego',
+8
View File
@@ -547,6 +547,14 @@ export const pt: Record<string, string> = {
workflowPhaseUnnamed: 'Fase sem nome',
workflowMembers: '{done}/{total} membros',
jobsAutoCollapsed: 'Recolhido automaticamente (muitos agentes)',
contextDiagnostics: 'Diagnóstico de contexto',
contextDiagnosticsTarget: 'Sessão atual',
contextDiagnosticsFailed: 'Não foi possível abrir o diagnóstico de contexto de “{label}”',
contextDiagnosticsUnavailable: 'A página “Contexto” do dsh-context está indisponível (não instalada ou não registrada)',
contextDiagnosticsNavigation: 'Não foi possível localizar essa conversa',
contextDiagnosticsTimeout: 'Tempo esgotado ao abrir — tente novamente',
contextDiagnosticsOpenFailed: 'Não foi possível abrir a página',
contextDiagnosticsDismiss: 'Fechar',
catalogLoadFailed: 'Falha ao carregar {count} branches',
addPluginsTabCard: 'Adicionar plugins de aba',
addPluginsTabCardDesc: 'Registrar uma nova página da barra lateral',
+8
View File
@@ -562,6 +562,14 @@ export const ru: Record<string, string> = {
workflowPhaseUnnamed: 'Безымянная фаза',
workflowMembers: '{done}/{total} участников',
jobsAutoCollapsed: 'Свернуто автоматически (много агентов)',
contextDiagnostics: 'Диагностика контекста',
contextDiagnosticsTarget: 'Текущая сессия',
contextDiagnosticsFailed: 'Не удалось открыть диагностику контекста для «{label}»',
contextDiagnosticsUnavailable: 'Страница «Контекст» dsh-context недоступна (не установлена или не зарегистрирована)',
contextDiagnosticsNavigation: 'Не удалось найти этот диалог',
contextDiagnosticsTimeout: 'Время открытия истекло — повторите попытку',
contextDiagnosticsOpenFailed: 'Не удалось открыть страницу',
contextDiagnosticsDismiss: 'Закрыть',
catalogLoadFailed: 'Не удалось загрузить ветки: {count}',
addPluginsTabCard: 'Добавить плагины вкладок',
addPluginsTabCardDesc: 'Зарегистрировать новую страницу боковой панели',
+8
View File
@@ -547,6 +547,14 @@ export const sv: Record<string, string> = {
workflowPhaseUnnamed: 'Namnlös fas',
workflowMembers: '{done}/{total} medlemmar',
jobsAutoCollapsed: 'Auto-dold (många agenter)',
contextDiagnostics: 'Kontextdiagnostik',
contextDiagnosticsTarget: 'Aktuell session',
contextDiagnosticsFailed: 'Kunde inte öppna kontextdiagnostik för ”{label}”',
contextDiagnosticsUnavailable: 'Sidan ”Kontext” i dsh-context är inte tillgänglig (inte installerad eller registrerad)',
contextDiagnosticsNavigation: 'Kunde inte hitta den konversationen',
contextDiagnosticsTimeout: 'Öppningen tog för lång tid — försök igen',
contextDiagnosticsOpenFailed: 'Sidan kunde inte öppnas',
contextDiagnosticsDismiss: 'Stäng',
catalogLoadFailed: '{count} grenar kunde inte läsas in',
addPluginsTabCard: 'Lägg till flik-plugins',
addPluginsTabCardDesc: 'Registrera en ny sidopanelssida',
+8
View File
@@ -564,6 +564,14 @@ export const th: Record<string, string> = {
workflowPhaseUnnamed: 'เฟสไม่มีชื่อ',
workflowMembers: '{done}/{total} สมาชิก',
jobsAutoCollapsed: 'ย่ออัตโนมัติ (เอเจนต์จำนวนมาก)',
contextDiagnostics: 'การวินิจฉัยบริบท',
contextDiagnosticsTarget: 'เซสชันปัจจุบัน',
contextDiagnosticsFailed: 'เปิดการวินิจฉัยบริบทของ “{label}” ไม่ได้',
contextDiagnosticsUnavailable: 'หน้า “บริบท” ของ dsh-context ใช้ไม่ได้ (ยังไม่ได้ติดตั้งหรือลงทะเบียน)',
contextDiagnosticsNavigation: 'หาบทสนทนานั้นไม่พบ',
contextDiagnosticsTimeout: 'เปิดเกินเวลา — ลองอีกครั้ง',
contextDiagnosticsOpenFailed: 'เปิดหน้าไม่สำเร็จ',
contextDiagnosticsDismiss: 'ปิด',
catalogLoadFailed: 'โหลดสาขาไม่สำเร็จ {count} รายการ',
addPluginsTabCard: 'เพิ่มปลั๊กอิน tab',
addPluginsTabCardDesc: 'ลงทะเบียนหน้าแถบด้านข้างใหม่',
+8
View File
@@ -564,6 +564,14 @@ export const tr: Record<string, string> = {
workflowPhaseUnnamed: 'Adsız aşama',
workflowMembers: '{done}/{total} üye',
jobsAutoCollapsed: 'Otomatik daraltıldı (çok sayıda ajan)',
contextDiagnostics: 'Bağlam tanılama',
contextDiagnosticsTarget: 'Geçerli oturum',
contextDiagnosticsFailed: '“{label}” için bağlam tanılaması açılamadı',
contextDiagnosticsUnavailable: 'dsh-context’in “Bağlam” sayfası kullanılamıyor (kurulu değil veya kayıtlı değil)',
contextDiagnosticsNavigation: 'O görüşme bulunamadı',
contextDiagnosticsTimeout: 'Açma zaman aşımına uğradı — yeniden deneyin',
contextDiagnosticsOpenFailed: 'Sayfa açılamadı',
contextDiagnosticsDismiss: 'Kapat',
catalogLoadFailed: '{count} dal yüklenemedi',
addPluginsTabCard: 'Sekme eklentileri ekle',
addPluginsTabCardDesc: 'Yeni bir kenar çubuğu sayfası kaydet',
+8
View File
@@ -564,6 +564,14 @@ export const vi: Record<string, string> = {
workflowPhaseUnnamed: 'Giai đoạn chưa đặt tên',
workflowMembers: '{done}/{total} thành viên',
jobsAutoCollapsed: 'Tự động thu gọn (nhiều agent)',
contextDiagnostics: 'Chẩn đoán ngữ cảnh',
contextDiagnosticsTarget: 'Phiên hiện tại',
contextDiagnosticsFailed: 'Không mở được chẩn đoán ngữ cảnh cho “{label}”',
contextDiagnosticsUnavailable: 'Trang “Ngữ cảnh” của dsh-context không khả dụng (chưa cài hoặc chưa đăng ký)',
contextDiagnosticsNavigation: 'Không xác định được cuộc trò chuyện đó',
contextDiagnosticsTimeout: 'Mở quá thời gian — hãy thử lại',
contextDiagnosticsOpenFailed: 'Không mở được trang',
contextDiagnosticsDismiss: 'Đóng',
catalogLoadFailed: '{count} nhánh không tải được',
addPluginsTabCard: 'Thêm plugin tab',
addPluginsTabCardDesc: 'Đăng ký trang thanh bên mới',
+8
View File
@@ -579,6 +579,14 @@ export const zhHK: Record<string, string> = {
workflowPhaseUnnamed: '未命名階段',
workflowMembers: '{done}/{total} 成員',
jobsAutoCollapsed: '代理較多,已自動收起',
contextDiagnostics: '上下文診斷',
contextDiagnosticsTarget: '目前工作階段',
contextDiagnosticsFailed: '無法開啟「{label}」的上下文診斷',
contextDiagnosticsUnavailable: 'dsh-context 的「上下文」頁面無法使用(未安裝或未註冊)',
contextDiagnosticsNavigation: '無法定位該工作階段',
contextDiagnosticsTimeout: '開啟逾時,請重試',
contextDiagnosticsOpenFailed: '頁面開啟失敗',
contextDiagnosticsDismiss: '關閉',
catalogLoadFailed: '{count} 個分支載入失敗',
addPluginsTabCard: '新增 Tab 插件',
addPluginsTabCardDesc: '註冊新的側邊欄頁面',
+8
View File
@@ -579,6 +579,14 @@ export const zhMO: Record<string, string> = {
workflowPhaseUnnamed: '未命名階段',
workflowMembers: '{done}/{total} 成員',
jobsAutoCollapsed: '代理較多,已自動收起',
contextDiagnostics: '上下文診斷',
contextDiagnosticsTarget: '目前工作階段',
contextDiagnosticsFailed: '無法開啟「{label}」的上下文診斷',
contextDiagnosticsUnavailable: 'dsh-context 的「上下文」頁面無法使用(未安裝或未註冊)',
contextDiagnosticsNavigation: '無法定位該工作階段',
contextDiagnosticsTimeout: '開啟逾時,請重試',
contextDiagnosticsOpenFailed: '頁面開啟失敗',
contextDiagnosticsDismiss: '關閉',
catalogLoadFailed: '{count} 個分支載入失敗',
addPluginsTabCard: '新增 Tab 插件',
addPluginsTabCardDesc: '註冊新的側邊欄頁面',
+8
View File
@@ -579,6 +579,14 @@ export const zhTW: Record<string, string> = {
workflowPhaseUnnamed: '未命名階段',
workflowMembers: '{done}/{total} 成員',
jobsAutoCollapsed: '代理較多,已自動收起',
contextDiagnostics: '上下文診斷',
contextDiagnosticsTarget: '目前工作階段',
contextDiagnosticsFailed: '無法開啟「{label}」的上下文診斷',
contextDiagnosticsUnavailable: 'dsh-context 的「上下文」頁面無法使用(未安裝或未註冊)',
contextDiagnosticsNavigation: '無法定位該工作階段',
contextDiagnosticsTimeout: '開啟逾時,請重試',
contextDiagnosticsOpenFailed: '頁面開啟失敗',
contextDiagnosticsDismiss: '關閉',
catalogLoadFailed: '{count} 個分支載入失敗',
addPluginsTabCard: '新增 Tab 插件',
addPluginsTabCardDesc: '註冊新的側邊欄頁面',
+18
View File
@@ -576,6 +576,16 @@ export const zh = {
workflowPhaseUnnamed: '未命名阶段',
workflowMembers: '{done}/{total} 成员',
jobsAutoCollapsed: '代理较多,已自动折叠',
// The optional dsh-context diagnostics (context-diagnostics-ui.tsx): the
// three entry points' control, and the ONE dismissible failure alert.
contextDiagnostics: '上下文诊断',
contextDiagnosticsTarget: '当前会话',
contextDiagnosticsFailed: '无法打开「{label}」的上下文诊断',
contextDiagnosticsUnavailable: 'dsh-context 的「上下文」页面不可用(未安装或未注册)',
contextDiagnosticsNavigation: '无法定位到该会话',
contextDiagnosticsTimeout: '打开超时,请重试',
contextDiagnosticsOpenFailed: '页面打开失败',
contextDiagnosticsDismiss: '关闭提示',
catalogLoadFailed: '{count} 个分支加载失败',
addPluginsTabCard: '添加 Tab 插件',
addPluginsTabCardDesc: '注册新的侧边栏页面',
@@ -1198,6 +1208,14 @@ export const en: Record<keyof typeof zh, string> = {
workflowPhaseUnnamed: 'Unnamed phase',
workflowMembers: '{done}/{total} members',
jobsAutoCollapsed: 'Auto-collapsed (many agents)',
contextDiagnostics: 'Context diagnostics',
contextDiagnosticsTarget: 'Current session',
contextDiagnosticsFailed: 'Could not open Context diagnostics for "{label}"',
contextDiagnosticsUnavailable: 'The dsh-context "Context" page is unavailable (not installed or not registered)',
contextDiagnosticsNavigation: 'Could not locate that conversation',
contextDiagnosticsTimeout: 'Opening timed out — try again',
contextDiagnosticsOpenFailed: 'The page could not be opened',
contextDiagnosticsDismiss: 'Dismiss',
catalogLoadFailed: '{count} branches failed to load',
addPluginsTabCard: 'Add tab plugins',
addPluginsTabCardDesc: 'Register a new sidebar page',
+15 -2
View File
@@ -27,6 +27,7 @@ import { t } from '../locales.ts'
import { splitTrailingLineSpec } from '../path-line.ts'
import { baseName } from '../paths.ts'
import { parseFileAddress } from '../resource-address.ts'
import type { ContextDiagnostics } from '../context-diagnostics.ts'
import type { BetterSidebarService, TabDescriptor } from '../service.ts'
import type { SidebarStore } from '../state.ts'
import {
@@ -218,6 +219,14 @@ export interface NativeSurfaceDeps {
readonly service: BetterSidebarService
/** The shared native tab record registry (the surface writes it too). */
readonly records: NativeTabRecords
/**
* The activation's optional dsh-context diagnostics controller (see
* ../context-diagnostics.ts). Forwarded into the tab bodies' injected bag,
* because a native body renders in the HOST's React tree and cannot read the
* plugin shell's provider. Omitted = the bodies render without the
* diagnostics entry points.
*/
readonly diagnostics?: ContextDiagnostics
/**
* Report a tab-type registration failure (phase label + cause).
*
@@ -239,7 +248,7 @@ export interface NativeSurfaceDeps {
* @returns a disposer unregistering everything.
*/
export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
const { ctx, store, service, records, reportFailure } = deps
const { ctx, store, service, records, reportFailure, diagnostics } = deps
// Bind the store BEFORE any body can render: the per-session state is the
// authority for the explorer's expansion set, so the native surface and the
// workbench share one set per session and a closed tab cannot drop it.
@@ -293,7 +302,11 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
disposers.push(ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
name: 'sidebar.right.pane.tab',
key: id,
inject: (sessionId: string) => ({ ...injected, ...params, sessionId }),
// The diagnostics controller rides the SAME injected bag every body
// already receives (a native body renders in the host's tree, so the
// plugin shell's provider is out of reach); the adapter turns it into
// the provider around the body it draws.
inject: (sessionId: string) => ({ ...injected, ...params, sessionId, ...(diagnostics === undefined ? {} : { diagnostics }) }),
}, NativeTabBody)))
disposers.push(ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
name: 'sidebar.right.pane.tab.title',
+41 -24
View File
@@ -29,6 +29,8 @@ import type { Context } from '../../context-types.ts'
import type { SessionScope } from '../api.ts'
import { RenderBoundary } from '../RenderBoundary.tsx'
import { OrphanedTab } from '../OrphanedTab.tsx'
import { ContextDiagnosticsHost } from '../context-diagnostics-ui.tsx'
import type { ContextDiagnostics } from '../context-diagnostics.ts'
import { referenceInChat } from '../reference-in-chat.ts'
import { useSessionRoot } from '../use-session-root.ts'
import type { BetterSidebarService, NativePathTab } from '../service.ts'
@@ -445,6 +447,13 @@ export interface NativeBodyInjected {
* the session the slot is scoped to.
*/
readonly sessionIdOf?: (info: NativeTabInfo) => string | undefined
/**
* The activation's optional diagnostics controller (thin wrapper over
* ./index.ts's deps): the body below turns it into the provider, because a
* native body renders in the HOST's tree and the plugin shell's provider
* cannot reach it. Absent = the body renders without diagnostics.
*/
readonly diagnostics?: ContextDiagnostics
}
/** The props the slot framework adds to every tab body and title. */
@@ -528,31 +537,39 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro
// The full-height host wrapper (see the `.nativeTabHost` rule in
// sidebar.module.css for the native `.paneBody` contract); its
// `data-dsh-native-tab-host` attribute lets the e2e lane assert the fill.
// The diagnostics provider sits INSIDE the boundary (a body that crashes
// must not take the provider's tree with it) and consumes the controller
// from this body's own injected bag — the host renders the body, so the
// plugin shell's provider is out of reach.
createElement(
'div',
{ className: css.nativeTabHost, 'data-dsh-native-tab-host': '' },
createElement(descriptor.component, {
ctx,
store,
scope,
tab: view.tab,
visible: nativeTab.visible,
expanded: view.expanded,
revealed: view.revealed,
onToggleDir: (path: string) => { records.toggleExpanded(seatSessionId, nativeTab.id, path) },
onReferenceFile: (path: string, isDir: boolean) => { referenceInChat(ctx, scopeSessionId, path, isDir) },
onOpenDiff: (tab: SidebarTab) => {
service.openTab({
type: 'diff',
title: tab.title,
id: tab.id,
...(tab.diff === undefined ? {} : { diff: tab.diff }),
}, scope)
},
onSubagentJump: (childSessionId: string) => {
service.openTab({ type: 'subagent', meta: { childSessionId } }, scope)
},
}),
ContextDiagnosticsHost,
{ controller: props.diagnostics },
createElement(
'div',
{ className: css.nativeTabHost, 'data-dsh-native-tab-host': '' },
createElement(descriptor.component, {
ctx,
store,
scope,
tab: view.tab,
visible: nativeTab.visible,
expanded: view.expanded,
revealed: view.revealed,
onToggleDir: (path: string) => { records.toggleExpanded(seatSessionId, nativeTab.id, path) },
onReferenceFile: (path: string, isDir: boolean) => { referenceInChat(ctx, scopeSessionId, path, isDir) },
onOpenDiff: (tab: SidebarTab) => {
service.openTab({
type: 'diff',
title: tab.title,
id: tab.id,
...(tab.diff === undefined ? {} : { diff: tab.diff }),
}, scope)
},
onSubagentJump: (childSessionId: string) => {
service.openTab({ type: 'subagent', meta: { childSessionId } }, scope)
},
}),
),
),
)
}
+10
View File
@@ -1220,6 +1220,16 @@
padding: 0;
}
/* A footer control that is a GLYPH, not a word: it keeps the host Button's own
28px box instead of taking a share of the row, so a long jump label and the
diagnostics control still fit the 280px card (the footer's `> *` rule hands
every other child the row). */
.popFoot > .popActionIcon {
flex: none;
width: 28px;
padding: 0;
}
.jumpMenu {
position: absolute;
right: 0;
+366
View File
@@ -0,0 +1,366 @@
/**
* The optional dsh-context diagnostics UI (context-diagnostics-ui.tsx): the
* two surfaces the plugin contributes to the HOST — the session header's
* utilities control and the frame-wide `shell.overlay` alert — and the rules
* that make them safe.
*
* Contract pinned here:
* - every entry point is gated on the controller's `available` (dsh-context
* absent, or present WITHOUT its keyed tab body, hides all three instead of
* offering a dead control), and `busy` disables them all (one open at a
* time);
* - the header control re-checks the session it was drawn for against the
* session really on screen (`ctx.sidebarRight.mounted`) at CLICK time: a
* header left over from the previous conversation must not navigate;
* - the alert is gated on the ERROR only — an open already in flight when the
* capability went away must still report why it failed — and dismissing it
* is the controller's own `dismissError()`, never a timer;
* - the controller is threaded PER ACTIVATION (provider prop, injected bag):
* one provider unmounting must never clear another's store.
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createElement, type ReactNode } from 'react'
import { act } from 'react-dom/test-utils'
import { renderRoot, setupReactAct } from './test-utils.ts'
import {
ContextDiagnosticsAlert,
ContextDiagnosticsButton,
ContextDiagnosticsHost,
registerContextDiagnosticsUI,
} from '../src/client/context-diagnostics-ui.tsx'
import { attachLocale } from '../src/client/locales.ts'
import type { Context } from '../src/context-types.ts'
import type {
ContextDiagnosticTarget,
ContextDiagnostics,
ContextDiagnosticsSnapshot,
} from '../src/client/context-diagnostics.ts'
setupReactAct()
/** The host locale service face `attachLocale` needs: pin the zh chain. */
function attachZhLocale(): void {
attachLocale({ getSnapshot: () => ({ active: 'zh' }) })
}
/** A controller double: the snapshot is driven by the test, not by a host. */
function makeController(initial: ContextDiagnosticsSnapshot) {
let snapshot = initial
const listeners = new Set<() => void>()
const opens: ContextDiagnosticTarget[] = []
const dismissals: number[] = []
const controller: ContextDiagnostics = {
getSnapshot: () => snapshot,
subscribe: (listener: () => void) => {
listeners.add(listener)
return () => { listeners.delete(listener) }
},
open: (target: ContextDiagnosticTarget) => { opens.push(target) },
dismissError: () => {
dismissals.push(1)
publish({ available: snapshot.available, busy: snapshot.busy })
},
dispose: () => {},
}
const publish = (next: ContextDiagnosticsSnapshot): void => {
snapshot = next
for (const listener of [...listeners]) listener()
}
return { controller, publish, opens, dismissals }
}
/** One captured slot registration (the options the plugin registered with). */
interface Registration {
name: string
id?: string
order?: number
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mirrors the host's own untyped inject
inject?: (...args: any[]) => Record<string, unknown>
component?: unknown
}
/** The host's slot ledger as this module uses it: inject fires, register is kept. */
function makeSlots() {
const registrations: Registration[] = []
const slots = {
inject: (_key: string, callback: () => () => void) => callback(),
register: (options: Registration, component: unknown) => {
const entry: Registration = { ...options, component }
registrations.push(entry)
return () => {
const index = registrations.indexOf(entry)
if (index >= 0) registrations.splice(index, 1)
}
},
}
return { registrations, slots }
}
/** A context whose native right column reports one on-screen session. */
function makeCtx(mounted: string | undefined): Context {
return {
get: (name: string) => (name === 'sidebarRight' ? { mounted: { getSnapshot: () => mounted, subscribe: () => () => {} } } : undefined),
} as unknown as Context
}
/** One slot entry of a ledger, by its id. */
function entryOf(ledger: Registration[], id: string): Registration {
const entry = ledger.find(candidate => candidate.id === id)
if (entry === undefined) throw new Error(`no registration for ${id}`)
return entry
}
/** The element the ledger's entry renders for one slot session. */
function elementOf(ledger: Registration[], sessionId = 's1'): ReactNode {
const entry = entryOf(ledger, 'dsh-better-sidebar:context-diagnostics')
if (entry.inject === undefined) throw new Error('the entry carries no inject')
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- the module's own slot component
const Component = entry.component as (props: any) => ReactNode
return createElement(Component, entry.inject(sessionId) as Record<string, unknown>)
}
/** The entry point's control, or null when the surface hides itself. */
function entryButton(container: HTMLElement, kind: string): HTMLButtonElement | null {
return container.querySelector(`button[data-dsh-ctx-entry="${kind}"]`)
}
beforeEach(() => { attachZhLocale() })
afterEach(() => {
attachLocale(undefined)
for (const el of document.querySelectorAll('body > div')) el.remove()
})
describe('registerContextDiagnosticsUI', () => {
it('contributes one header entry and one overlay entry, both in the plugin\'s id space', () => {
const slots = makeSlots()
const fake = makeController({ available: true, busy: false })
const dispose = registerContextDiagnosticsUI(
{ ...makeCtx('s1'), slots: slots.slots } as unknown as Context,
fake.controller,
)
expect(slots.registrations.map(entry => entry.name).sort())
.toEqual(['conversation.session.header.utilities', 'shell.overlay'])
for (const entry of slots.registrations) {
expect(entry.id).toBe('dsh-better-sidebar:context-diagnostics')
expect(entry.order).toBe(20)
}
// The disposer releases both entries (HMR / plugin disable).
dispose()
expect(slots.registrations).toHaveLength(0)
})
it('registers into both slot keys through slots.inject (a late declaration still lands)', () => {
const injected: string[] = []
const ctx = {
...makeCtx('s1'),
slots: {
inject: (key: string, callback: () => () => void) => {
injected.push(key)
return callback()
},
register: () => () => {},
},
} as unknown as Context
const fake = makeController({ available: true, busy: false })
registerContextDiagnosticsUI(ctx, fake.controller)
expect(injected).toEqual(['conversation.session.header.utilities', 'shell.overlay'])
})
})
describe('the header control', () => {
it('renders nothing while the capability is unavailable, and appears when it does', async () => {
const fake = makeController({ available: false, busy: false })
const slots = makeSlots()
registerContextDiagnosticsUI({ ...makeCtx('s1'), slots: slots.slots } as unknown as Context, fake.controller)
const { container, unmount } = renderRoot(elementOf(slots.registrations))
expect(entryButton(container, 'session')).toBeNull()
// dsh-context installed while the page is open: the control must appear
// without a reload, and open the session the slot was mounted for.
await act(async () => { fake.publish({ available: true, busy: false }) })
const button = entryButton(container, 'session')
expect(button).not.toBeNull()
expect(button?.getAttribute('aria-label')).toBe('上下文诊断')
expect(button?.getAttribute('aria-busy')).toBeNull()
await act(async () => { button?.click() })
expect(fake.opens).toEqual([{ sessionId: 's1', label: '当前会话' }])
unmount()
})
it('is DISABLED and announced busy while an open is in flight', async () => {
const fake = makeController({ available: true, busy: true })
const slots = makeSlots()
registerContextDiagnosticsUI({ ...makeCtx('s1'), slots: slots.slots } as unknown as Context, fake.controller)
const { container, unmount } = renderRoot(elementOf(slots.registrations))
const button = entryButton(container, 'session')
expect(button?.disabled).toBe(true)
expect(button?.getAttribute('aria-busy')).toBe('true')
await act(async () => { button?.click() })
expect(fake.opens).toEqual([])
unmount()
})
it('refuses to act when the session it was drawn for is no longer on screen', async () => {
// The stale-header window: the host has switched to `s2` while an entry
// contributed for `s1` is still mounted (re-registration is not synchronous
// with the switch). Acting would open s1's Context view over s2.
const fake = makeController({ available: true, busy: false })
const current = makeSlots()
registerContextDiagnosticsUI({ ...makeCtx('s1'), slots: current.slots } as unknown as Context, fake.controller)
const live = renderRoot(elementOf(current.registrations, 's1'))
await act(async () => { entryButton(live.container, 'session')?.click() })
expect(fake.opens, 'the header drew s1 while s1 was on screen').toHaveLength(1)
const stale = makeSlots()
registerContextDiagnosticsUI({ ...makeCtx('s2'), slots: stale.slots } as unknown as Context, fake.controller)
const old = renderRoot(elementOf(stale.registrations, 's1'))
const button = entryButton(old.container, 'session')
expect(button).not.toBeNull()
await act(async () => { button?.click() })
expect(fake.opens, 'a click on a stale header must not navigate').toHaveLength(1)
live.unmount()
old.unmount()
})
})
describe('the frame-wide alert', () => {
it('shows ONE role=alert with the reason, and dismisses through the controller', async () => {
const fake = makeController({
available: true,
busy: false,
error: { reason: 'timeout', targetLabel: '子代理 0' },
})
const { container, unmount } = renderRoot(createElement(ContextDiagnosticsAlert, { controller: fake.controller }))
const alerts = container.querySelectorAll('[role="alert"]')
expect(alerts).toHaveLength(1)
expect(alerts[0]!.textContent).toContain('无法打开「子代理 0」的上下文诊断')
expect(alerts[0]!.textContent).toContain('打开超时,请重试')
expect(container.querySelector('[data-dsh-ctx-alert]')).not.toBeNull()
// The alert is not a modal: it names no dialog role and traps nothing.
expect(container.querySelectorAll('[role="dialog"]')).toHaveLength(0)
const dismiss = container.querySelector('button[aria-label="关闭提示"]') as HTMLButtonElement
expect(dismiss).not.toBeNull()
await act(async () => { dismiss.click() })
expect(fake.dismissals).toHaveLength(1)
// The controller cleared its own error: the alert goes with it.
await act(async () => { fake.publish({ available: true, busy: false }) })
expect(container.querySelectorAll('[role="alert"]')).toHaveLength(0)
unmount()
})
it('still reports an open that failed because the capability went away', () => {
// The controller publishes `available: false` WITH the error (an open in
// flight when dsh-context disappeared): the entry points are gone, but the
// failure the reader triggered must still be reported.
const fake = makeController({
available: false,
busy: false,
error: { reason: 'unavailable', targetLabel: '主会话' },
})
const { container, unmount } = renderRoot(createElement(ContextDiagnosticsAlert, { controller: fake.controller }))
expect(container.querySelectorAll('[role="alert"]')).toHaveLength(1)
expect(container.textContent).toContain('dsh-context 的「上下文」页面不可用')
unmount()
})
it('renders nothing without an error', () => {
const fake = makeController({ available: true, busy: false })
const { container, unmount } = renderRoot(createElement(ContextDiagnosticsAlert, { controller: fake.controller }))
expect(container.textContent).toBe('')
unmount()
})
it('reports each failure reason in its own words', () => {
for (const [reason, wording] of [
['navigation', '无法定位到该会话'],
['open', '页面打开失败'],
] as const) {
const fake = makeController({ available: true, busy: false, error: { reason, targetLabel: '主会话' } })
const { container, unmount } = renderRoot(createElement(ContextDiagnosticsAlert, { controller: fake.controller }))
expect(container.textContent).toContain(wording)
unmount()
}
})
})
describe('per-activation isolation', () => {
it('two providers keep their own controllers: unmounting one leaves the other working', async () => {
const first = makeController({ available: true, busy: false })
const second = makeController({ available: true, busy: false })
const target: ContextDiagnosticTarget = { sessionId: 's1', label: '当前会话' }
const firstRoot = renderRoot(createElement(
ContextDiagnosticsHost,
{ controller: first.controller },
createElement(ContextDiagnosticsButton, { kind: 'session', target, iconSize: 14 }),
))
const secondRoot = renderRoot(createElement(
ContextDiagnosticsHost,
{ controller: second.controller },
createElement(ContextDiagnosticsButton, { kind: 'session', target, iconSize: 14 }),
))
await act(async () => { entryButton(secondRoot.container, 'session')?.click() })
expect(second.opens).toHaveLength(1)
expect(first.opens, 'the click went to the other activation\'s controller').toHaveLength(0)
// The second activation goes away; the first must be untouched — no
// module-level "current controller" may be cleared by a sibling unmount.
secondRoot.unmount()
const surviving = entryButton(firstRoot.container, 'session')
expect(surviving).not.toBeNull()
await act(async () => { surviving?.click() })
expect(first.opens).toEqual([target])
// …and the first's own availability still drives its own control.
await act(async () => { first.publish({ available: false, busy: false }) })
expect(entryButton(firstRoot.container, 'session')).toBeNull()
firstRoot.unmount()
})
it('renders no entry point where no provider supplied a controller', () => {
const fake = makeController({ available: true, busy: false })
const { container, unmount } = renderRoot(createElement(
ContextDiagnosticsHost,
undefined,
createElement(ContextDiagnosticsButton, {
kind: 'agent',
target: { sessionId: 's1' },
iconSize: 14,
}),
))
expect(entryButton(container, 'agent')).toBeNull()
// A controller that exists elsewhere in the process is not adopted: the
// store is the provider's, never a module-level registration.
void fake
unmount()
})
it('hides the entry point while the controller reports the capability unavailable', () => {
const fake = makeController({ available: false, busy: false })
const { container, unmount } = renderRoot(createElement(
ContextDiagnosticsHost,
{ controller: fake.controller },
createElement(ContextDiagnosticsButton, { kind: 'job', target: { sessionId: 's1' }, iconSize: 12 }),
))
expect(entryButton(container, 'job')).toBeNull()
unmount()
})
it('hides the entry point when the caller has no target (an unmapped job owner)', () => {
const fake = makeController({ available: true, busy: false })
const { container, unmount } = renderRoot(createElement(
ContextDiagnosticsHost,
{ controller: fake.controller },
createElement(ContextDiagnosticsButton, { kind: 'job', target: undefined, iconSize: 12 }),
))
expect(entryButton(container, 'job')).toBeNull()
unmount()
})
})
+397
View File
@@ -0,0 +1,397 @@
/**
* Context diagnostics must remain optional, session-correct and cancellable.
* Includes real Cordis child-fiber lifetimes, not only structural service mocks.
*/
import { Context as CordisContext } from '@deepseek-ai/cordis'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createContextDiagnostics, type ContextDiagnostics } from '../src/client/context-diagnostics.ts'
import type { Context, SidebarSubagentAddress } from '../src/context-types.ts'
function observable<T>(initial: T) {
let value = initial
const listeners = new Set<() => void>()
return {
getSnapshot: () => value,
subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } },
set: (next: T) => { value = next; for (const listener of listeners) listener() },
count: () => listeners.size,
}
}
const child: SidebarSubagentAddress = { parentSessionId: 'parent', childSessionId: 'child', mode: 'continuable' }
const target = { sessionId: 'child', label: 'Child agent', address: child }
const disposers: Array<() => void> = []
afterEach(() => {
for (const dispose of disposers.splice(0).reverse()) dispose()
vi.useRealTimers()
})
function harness() {
const mounted = observable<string | undefined>('parent')
const tabs = observable<Array<{ sessionId: string; tabId: string; kind: string }>>([])
const registry = observable(true)
const bodies = observable(true)
const calls: string[] = []
let selectedTab: string | undefined
let navigation = new AbortController()
const state = {
ready: true, autoSwitch: true, expanded: false, openError: undefined as Error | undefined,
typeId: 'dsh-context', bodyId: 'dsh-context',
}
const right = {
mounted,
openTabs: tabs,
openTab: vi.fn((kind: string) => {
calls.push(`open:${mounted.getSnapshot()}:${kind}`)
if (!state.ready) throw new Error('sidebarRight: no session surface is mounted')
if (state.openError !== undefined) throw state.openError
const sessionId = mounted.getSnapshot()
if (sessionId === undefined) throw new Error('sidebarRight: no session surface is mounted')
const tabId = `tab${tabs.getSnapshot().length + 1}`
tabs.set([...tabs.getSnapshot(), { sessionId, tabId, kind }])
selectedTab = tabId
state.expanded = true
}),
active: () => state.ready && selectedTab !== undefined ? { id: selectedTab } : undefined,
focus: vi.fn((tabId: string) => { if (state.ready) selectedTab = tabId }),
isExpanded: () => state.expanded,
toggleExpanded: vi.fn(() => { if (state.ready) state.expanded = !state.expanded }),
}
const workspace = {
openSession: vi.fn((address: string | SidebarSubagentAddress) => {
const id = typeof address === 'string' ? address : address.childSessionId
calls.push(`switch:${id}`)
// The real workspace selects the conversation panel and aborts older navigation.
navigation.abort()
if (state.autoSwitch) mounted.set(id)
}),
}
const services: Record<string, unknown> = {
sidebarRight: right,
sidebarRightTabs: {
get: (kind: string) => kind === 'dsh-context' && registry.getSnapshot() ? { id: state.typeId, kind } : undefined,
subscribe: registry.subscribe,
},
slots: {
entriesOfSlot: (key: string) => key === 'sidebar.right.pane.tab' && bodies.getSnapshot() ? [{ options: { key: state.bodyId } }] : [],
subscribe: (_key: string, listener: () => void) => bodies.subscribe(listener),
},
uiWorkspace: workspace,
layout: {
beginNavigation: () => { navigation.abort(); navigation = new AbortController(); return navigation.signal },
},
}
let detach: (() => void) | undefined
let attach: (() => void) | undefined
const ctx = {
get: (name: string) => services[name],
inject: (_deps: string[], callback: (ctx: Context) => (() => void) | undefined) => {
attach = () => { detach = callback(ctx as unknown as Context) }
attach()
return { dispose: () => { detach?.(); detach = undefined } }
},
} as unknown as Context
const controller = createContextDiagnostics(ctx)
disposers.push(() => { controller.dispose() })
return {
controller, services, right, workspace, mounted, tabs, registry, bodies, calls, state,
leave: (id?: string) => { navigation.abort(); mounted.set(id) },
disconnect: () => { detach?.(); detach = undefined },
reconnect: () => { attach?.() },
}
}
describe('Context diagnostics navigation', () => {
it('reacts to both type and body registration without idle work or redundant notifications', () => {
vi.useFakeTimers()
const h = harness()
const notify = vi.fn()
h.controller.subscribe(notify)
expect(h.controller.getSnapshot()).toEqual({ available: true, busy: false })
h.registry.set(true)
h.bodies.set(true)
expect(notify).not.toHaveBeenCalled()
h.bodies.set(false)
expect(h.controller.getSnapshot().available).toBe(false)
h.registry.set(false)
h.bodies.set(true)
expect(h.controller.getSnapshot().available).toBe(false)
h.registry.set(true)
expect(h.controller.getSnapshot().available).toBe(true)
expect(notify).toHaveBeenCalledTimes(2)
expect(vi.getTimerCount()).toBe(0)
expect(h.mounted.count()).toBe(0)
expect(h.tabs.count()).toBe(0)
})
it('matches the active type implementation to its body, not id to kind', () => {
const h = harness()
h.state.typeId = 'context-implementation'
h.registry.set(true)
expect(h.controller.getSnapshot().available).toBe(false)
h.state.bodyId = 'context-implementation'
h.bodies.set(true)
expect(h.controller.getSnapshot().available).toBe(true)
})
it('does not issue a second creation while successful open inventory publication is delayed', () => {
vi.useFakeTimers()
const h = harness()
h.right.openTab.mockImplementation(() => {})
h.controller.open(target)
vi.advanceTimersByTime(500)
expect(h.right.openTab).toHaveBeenCalledTimes(1)
h.tabs.set([{ sessionId: 'child', tabId: 'late-context', kind: 'dsh-context' }])
expect(h.controller.getSnapshot().busy).toBe(false)
expect(h.right.active()?.id).toBe('late-context')
expect(vi.getTimerCount()).toBe(0)
})
it('reports a rejected navigation and releases the request without opening a tab', () => {
vi.useFakeTimers()
const h = harness()
h.workspace.openSession.mockImplementation(() => { throw new Error('unknown session') })
h.controller.open(target)
expect(h.controller.getSnapshot().error?.reason).toBe('navigation')
expect(h.right.openTab).not.toHaveBeenCalled()
expect(h.mounted.count()).toBe(0)
expect(h.tabs.count()).toBe(0)
expect(vi.getTimerCount()).toBe(0)
})
it('switches using the complete child address, then opens the child, without self-cancelling', () => {
vi.useFakeTimers()
const h = harness()
h.controller.open(target)
expect(h.workspace.openSession).toHaveBeenCalledWith(child)
expect(h.calls).toEqual(['switch:child', 'open:child:dsh-context'])
expect(h.right.active()?.id).toBe('tab1')
expect(h.controller.getSnapshot()).toEqual({ available: true, busy: false })
expect(vi.getTimerCount()).toBe(0)
expect(h.mounted.count()).toBe(0)
expect(h.tabs.count()).toBe(0)
})
it('does not navigate when the exact target is already mounted', () => {
const h = harness()
h.mounted.set('child')
h.controller.open(target)
expect(h.workspace.openSession).not.toHaveBeenCalled()
expect(h.calls).toEqual(['open:child:dsh-context'])
})
it('does not open in the parent while a delayed child selection is pending', () => {
vi.useFakeTimers()
const h = harness()
h.state.autoSwitch = false
h.controller.open(target)
expect(h.right.openTab).not.toHaveBeenCalled()
h.mounted.set(undefined)
expect(h.controller.getSnapshot().busy).toBe(true)
h.mounted.set('child')
expect(h.calls).toEqual(['switch:child', 'open:child:dsh-context'])
expect(h.controller.getSnapshot().busy).toBe(false)
})
it('waits for the arriving sidebar store and cleans up the bounded retry', () => {
vi.useFakeTimers()
const h = harness()
h.state.ready = false
h.controller.open(target)
expect(h.controller.getSnapshot().busy).toBe(true)
vi.advanceTimersByTime(100)
h.state.ready = true
vi.advanceTimersByTime(50)
expect(h.controller.getSnapshot()).toEqual({ available: true, busy: false })
expect(h.tabs.getSnapshot()).toHaveLength(1)
expect(vi.getTimerCount()).toBe(0)
})
it('reuses a Context in another pane and expands its collapsed sidebar', () => {
const h = harness()
h.tabs.set([
{ sessionId: 'parent', tabId: 'parent-context', kind: 'dsh-context' },
{ sessionId: 'child', tabId: 'child-context', kind: 'dsh-context' },
])
h.controller.open(target)
expect(h.right.openTab).not.toHaveBeenCalled()
expect(h.right.focus).toHaveBeenCalledWith('child-context')
expect(h.right.toggleExpanded).toHaveBeenCalledTimes(1)
expect(h.right.active()?.id).toBe('child-context')
})
it('does not treat a saved tab as a ready surface when focus is still a no-op', () => {
vi.useFakeTimers()
const h = harness()
h.tabs.set([{ sessionId: 'child', tabId: 'saved-context', kind: 'dsh-context' }])
h.state.ready = false
h.controller.open(target)
expect(h.controller.getSnapshot().busy).toBe(true)
h.state.ready = true
vi.advanceTimersByTime(50)
expect(h.controller.getSnapshot().busy).toBe(false)
expect(h.right.active()?.id).toBe('saved-context')
expect(h.right.openTab).not.toHaveBeenCalled()
})
it('deduplicates simultaneous entry clicks and releases source subscriptions independently', () => {
vi.useFakeTimers()
const h = harness()
h.state.autoSwitch = false
const unmountSource = h.controller.subscribe(() => {})
h.controller.open(target)
h.controller.open({ sessionId: 'other' })
unmountSource()
h.mounted.set('child')
expect(h.workspace.openSession).toHaveBeenCalledTimes(1)
expect(h.calls).toEqual(['switch:child', 'open:child:dsh-context'])
expect(vi.getTimerCount()).toBe(0)
})
it.each(['other', undefined])('cancels when the user navigates to %s and never replays later', (id) => {
vi.useFakeTimers()
const h = harness()
h.state.autoSwitch = false
h.controller.open(target)
h.leave(id)
h.mounted.set('child')
vi.advanceTimersByTime(20_000)
expect(h.right.openTab).not.toHaveBeenCalled()
expect(h.controller.getSnapshot()).toEqual({ available: true, busy: false })
expect(vi.getTimerCount()).toBe(0)
})
it('times out after ten seconds without opening a late-arriving target', () => {
vi.useFakeTimers()
const h = harness()
h.state.autoSwitch = false
h.controller.open(target)
vi.advanceTimersByTime(9_999)
expect(h.controller.getSnapshot().busy).toBe(true)
vi.advanceTimersByTime(1)
expect(h.controller.getSnapshot().error).toEqual({ reason: 'timeout', targetLabel: 'Child agent' })
h.mounted.set('child')
expect(h.right.openTab).not.toHaveBeenCalled()
h.controller.dismissError()
expect(h.controller.getSnapshot().error).toBeUndefined()
expect(vi.getTimerCount()).toBe(0)
})
it('reports capability loss mid-flight and does not resume when it returns', () => {
vi.useFakeTimers()
const h = harness()
h.state.ready = false
h.controller.open(target)
h.bodies.set(false)
expect(h.controller.getSnapshot()).toEqual({ available: false, busy: false, error: { reason: 'unavailable', targetLabel: 'Child agent' } })
h.bodies.set(true)
h.state.ready = true
const count = h.right.openTab.mock.calls.length
vi.advanceTimersByTime(20_000)
expect(h.right.openTab).toHaveBeenCalledTimes(count)
expect(vi.getTimerCount()).toBe(0)
})
it('reports non-readiness errors once instead of retrying arbitrary failures', () => {
vi.useFakeTimers()
const h = harness()
h.state.openError = new Error('broken registration')
h.controller.open(target)
expect(h.controller.getSnapshot().error?.reason).toBe('open')
expect(h.right.openTab).toHaveBeenCalledTimes(1)
expect(vi.getTimerCount()).toBe(0)
})
it('rejects a mismatched child identity before changing the current session', () => {
const h = harness()
h.controller.open({ sessionId: 'other', address: child })
expect(h.workspace.openSession).not.toHaveBeenCalled()
expect(h.controller.getSnapshot().error?.reason).toBe('navigation')
})
it('never navigates after a busy-state listener disposes the plugin synchronously', () => {
vi.useFakeTimers()
const h = harness()
h.controller.subscribe(() => {
if (h.controller.getSnapshot().busy) h.controller.dispose()
})
h.controller.open(target)
expect(h.workspace.openSession).not.toHaveBeenCalled()
expect(h.right.openTab).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
})
it('prevents a final-state listener from opening a new request during disposal', () => {
vi.useFakeTimers()
const h = harness()
h.state.autoSwitch = false
h.controller.open(target)
let reopened = false
h.controller.subscribe(() => {
if (!h.controller.getSnapshot().busy && !reopened) {
reopened = true
h.controller.open({ sessionId: 'other' })
}
})
h.controller.dispose()
expect(h.workspace.openSession).toHaveBeenCalledTimes(1)
expect(h.mounted.count()).toBe(0)
expect(h.tabs.count()).toBe(0)
expect(vi.getTimerCount()).toBe(0)
})
it('unwinds all event resources on service replacement and plugin disposal', () => {
vi.useFakeTimers()
const h = harness()
h.state.autoSwitch = false
h.controller.open(target)
h.disconnect()
expect(h.registry.count()).toBe(0)
expect(h.bodies.count()).toBe(0)
expect(h.mounted.count()).toBe(0)
expect(h.tabs.count()).toBe(0)
expect(vi.getTimerCount()).toBe(0)
h.reconnect()
expect(h.registry.count()).toBe(1)
expect(h.bodies.count()).toBe(1)
h.controller.open(target)
h.controller.dispose()
expect(h.registry.count()).toBe(0)
expect(h.bodies.count()).toBe(0)
expect(h.mounted.count()).toBe(0)
expect(vi.getTimerCount()).toBe(0)
h.mounted.set('child')
expect(h.right.openTab).not.toHaveBeenCalled()
})
})
it('uses real Cordis optional child fibers for late services and replacement', async () => {
const runtime = new CordisContext()
const h = harness()
let controller: ContextDiagnostics | undefined
const owner = await runtime.plugin((ctx) => {
controller = createContextDiagnostics(ctx as Context)
return () => { controller?.dispose() }
})
expect(controller?.getSnapshot().available).toBe(false)
const install = () => runtime.plugin((ctx) => {
for (const [name, service] of Object.entries(h.services)) ctx.provide(name as never, service as never)
})
let host = await install()
try {
await vi.waitFor(() => { expect(controller?.getSnapshot().available).toBe(true) })
await host.dispose()
await vi.waitFor(() => { expect(controller?.getSnapshot().available).toBe(false) })
host = await install()
await vi.waitFor(() => { expect(controller?.getSnapshot().available).toBe(true) })
controller?.open(target)
expect(h.calls).toEqual(['switch:child', 'open:child:dsh-context'])
} finally {
await owner.dispose()
await host.dispose()
}
// Only the independent structural harness remains subscribed.
expect(h.registry.count()).toBe(1)
expect(h.bodies.count()).toBe(1)
})
+342
View File
@@ -0,0 +1,342 @@
/**
* Real dual-plugin lane: `dsh-better-sidebar` + the REAL `dsh-context@0.72.0`
* mounted side by side into one scratch `dsh web` profile (see
* `scripts/e2e-context.sh`), driven headless by Chromium.
*
* What it proves, and how — the three entry points of
* `src/client/context-diagnostics-ui.tsx` against the REAL third-party plugin
* (never a stub of it):
*
* 1. `session` (the session header's utilities row) — renders only while the
* `dsh-context` tab type AND its keyed body are both registered, opens the
* Context view of the CURRENT session, and REUSES the pane's existing
* Context tab instead of minting a second one;
* 2. `agent` (an agent card's detail popover on the Tasks page) — opens the
* CHILD conversation's Context view: the controller switches the mounted
* session to the child and focuses the child's own Context pane, which is
* a different host-owned subtree from the parent's;
* 3. `job` (a background job's output window) — targets the job's REAL
* `owner`, not the session the reader happens to be on.
*
* The `no-context` variant of the same spec boots the SAME profile shape
* WITHOUT dsh-context and proves the entries and the tab type are simply
* absent (the plugin still mounts).
*
* Provenance of the data (stated plainly, because it is not model execution):
* the parent session is created by this spec through the public
* `session/create` RPC; the child session and the background job are seeded by
* the lane's host fixture (`./context-fixture-plugin.mjs`, installed ONLY into
* the lane's scratch profile) through the host's public `ctx.agents` /
* `ctx.jobs` services, with the standard version-3 `subagent/descriptor` seed.
* No agent turn is started: content is appended as fixture data, so nothing
* here claims a real model execution ran.
*
* Not covered here (see the lane report): the controller's 10 s deadline, the
* user-navigation cancel and the continue-after-source-unmount paths need a
* target that never becomes ready or a precisely timed navigation; they are
* covered by `tests/context-diagnostics.spec.ts` on a real cordis lifecycle
* instead of being raced here.
*/
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test, expect, type APIRequestContext, type Page } from '@playwright/test'
import { createHostApi, gotoPage } from './host'
import {
ALERT_SELECTOR,
CHILD_LABEL,
CHILD_SESSION_ID,
CONTEXT_INSIGHTS_LABEL,
CONTEXT_KIND,
CONTEXT_TAB_NAME,
DASHBOARD_CARD,
JOB_LABEL,
PARENT_SESSION_ID,
activeTabTexts,
dismissOnboarding,
entrySelector,
expectActiveTab,
onScreenCount,
openGuideEntry,
seedParentSession,
sessionOwner,
sessionRow,
} from './context-fixture'
/** The dedicated runner selects dual, tab-only, or no-context. */
const VARIANT = process.env.DSH_E2E_CONTEXT_VARIANT
test.skip(VARIANT === undefined, 'requires the dedicated Context integration profile')
/** The lane's workspace (the script owns the directory). */
const WORKSPACE_PATH = process.env.DSH_E2E_WORKSPACE ?? join(tmpdir(), 'dsh-e2e-context-workspace')
let api: APIRequestContext
test.beforeAll(async () => {
api = await createHostApi()
await seedParentSession(api, WORKSPACE_PATH)
})
test.afterAll(async () => {
await api?.dispose()
})
/**
* The header's utilities row is live: the blank-session lane documents that
* DSH 0.2.0 draws the header's utilities only for a session with content (in
* the blank state the plugin's own dock fallback stands in) — and that row is
* exactly where the `session` entry rides.
*/
async function expectHeaderRowLive(page: Page): Promise<void> {
await expect(page.locator('[data-dsh-bottom-toggle]').first()).toBeVisible({ timeout: 60_000 })
await expect(
page.locator('[data-dsh-dock-fallback]'),
'the session must have left the blank state (header utilities row live)',
).toHaveCount(0, { timeout: 60_000 })
}
/** Collect the shell's crash markers for the frame. */
function watchFrame(page: Page): { pageErrors: string[]; consoleErrors: string[] } {
const pageErrors: string[] = []
const consoleErrors: string[] = []
page.on('pageerror', (error) => pageErrors.push(String(error)))
page.on('console', (message) => {
if (message.type() === 'error') consoleErrors.push(message.text())
})
return { pageErrors, consoleErrors }
}
/** Load the shell and wait for the plugin's host element. */
async function boot(page: Page): Promise<void> {
await gotoPage(page)
await dismissOnboarding(page)
await expect(page.locator('#root > *')).not.toHaveCount(0, { timeout: 90_000 })
await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 90_000 })
}
/**
* Mount one seeded session in the main column through the host's own workspace
* tree (`data-row-key="session:<id>"`, `role="treeitem"`: click = open). The
* blank-session lane documents that the session's header only grows its
* utilities row once the conversation has content, so the caller sends a first
* message afterwards.
*/
async function mountSession(page: Page, sessionId: string): Promise<void> {
const row = sessionRow(page, sessionId)
await expect(
row,
`host session row [data-row-key="session:${sessionId}"] must be visible in the workspace tree `
+ '(if this fails, check whether the shell renders/expands the workspace tree by default — '
+ 'the lane needs the host’s own row to open the seeded session)',
).toBeVisible({ timeout: 60_000 })
await row.click()
await expect(row, `clicking the row must open ${sessionId}`).toHaveAttribute('aria-selected', 'true', { timeout: 30_000 })
}
test('without dsh-context the diagnostics entries never render', async ({ page }) => {
test.skip(VARIANT !== 'no-context', 'dual variant: covered by the next test')
const { pageErrors, consoleErrors } = watchFrame(page)
await boot(page)
await mountSession(page, PARENT_SESSION_ID)
await expectHeaderRowLive(page)
// The third-party tab type is genuinely absent from this profile …
await page.locator('[data-sidebar-right-expand]').first().click()
if (await page.locator('[data-sidebar-right-guide]').count() === 0) {
await page.locator('[data-dockkit-add-tab]').first().click()
}
await expect(page.locator('[data-sidebar-right-guide]')).toBeVisible({ timeout: 30_000 })
await expect(
page.locator(`[data-sidebar-right-guide-entry="${CONTEXT_KIND}"]`),
'dsh-context must NOT be installed in this variant',
).toHaveCount(0)
// … so no entry point of any kind may render (not one, not a disabled one).
await expect(page.locator('[data-dsh-ctx-entry]'), 'no entry may render without dsh-context').toHaveCount(0)
await expect(page.locator(ALERT_SELECTOR), 'no alert may render without dsh-context').toHaveCount(0)
expect(pageErrors, 'uncaught page errors').toEqual([])
expect(consoleErrors, 'console errors').toEqual([])
})
test('with dsh-context placed as a conversation view only, the entries hide', async ({ page }) => {
test.skip(VARIANT !== 'tab-only', 'the tab-only variant of the same profile shape')
const { pageErrors, consoleErrors } = watchFrame(page)
await boot(page)
await mountSession(page, PARENT_SESSION_ID)
await expectHeaderRowLive(page)
// dsh-context IS mounted — its placement-independent Context Insights panel
// entry is on the host's panel list — but this profile was configured (with
// the plugin's own `defaultPlacement: tab` setting) to keep its Context view
// in the conversation and to register NO right-column tab type …
await expect(
page.getByRole('button', { name: CONTEXT_INSIGHTS_LABEL }).first(),
'dsh-context must still be mounted in this variant (its Insights panel entry proves it)',
).toBeVisible({ timeout: 60_000 })
await page.locator('[data-sidebar-right-expand]').first().click()
if (await page.locator('[data-sidebar-right-guide]').count() === 0) {
await page.locator('[data-dockkit-add-tab]').first().click()
}
await expect(page.locator('[data-sidebar-right-guide]')).toBeVisible({ timeout: 30_000 })
await expect(
page.locator(`[data-sidebar-right-guide-entry="${CONTEXT_KIND}"]`),
'defaultPlacement=tab must leave the right column without the dsh-context type',
).toHaveCount(0)
// … so no entry point of any kind may render — the controller's own rule is
// "the tab type AND its keyed body, or nothing".
await expect(page.locator('[data-dsh-ctx-entry]'), 'no entry may render without the type').toHaveCount(0)
await expect(page.locator(ALERT_SELECTOR), 'no alert may render without the type').toHaveCount(0)
expect(pageErrors, 'uncaught page errors').toEqual([])
expect(consoleErrors, 'console errors').toEqual([])
})
test('the three entries drive the REAL dsh-context view for parent and child', async ({ page }) => {
test.skip(VARIANT !== 'dual', 'no-context variant: covered by the previous test')
const { pageErrors, consoleErrors } = watchFrame(page)
const details = new Map<string, unknown>()
page.on('response', (response) => {
if (new URL(response.url()).pathname !== '/api/dsh-context/detail') return
const request = response.request()
if (request.method() !== 'POST') return
const sessionId = (request.postDataJSON() as { sessionId: string }).sessionId
void response.json().then(
(body: unknown) => { details.set(sessionId, body) },
(error: unknown) => { consoleErrors.push(String(error)) },
)
})
await boot(page)
await mountSession(page, PARENT_SESSION_ID)
await expectHeaderRowLive(page)
// ── 0. The real third-party plugin is mounted ─────────────────────────────
// Its own guide row opens its tab; this is the ground truth the entries must
// ride on (and it also opens the parent's Context pane, so the `session`
// entry below exercises the REUSE branch).
const pane = await openGuideEntry(page, CONTEXT_KIND)
const parent = sessionOwner(page, PARENT_SESSION_ID)
await expectActiveTab(parent, CONTEXT_TAB_NAME)
await expect(
parent.getByText(DASHBOARD_CARD).first(),
'the real dsh-context dashboard must render inside the parent session owner',
).toBeVisible({ timeout: 30_000 })
expect(await pane.count(), 'the native right panel must exist').toBeGreaterThan(0)
const contextTabs = parent.getByRole('tab').filter({ hasText: CONTEXT_TAB_NAME })
const tabsBefore = await contextTabs.count()
expect(tabsBefore, 'opening the Context guide entry must create its tab').toBeGreaterThan(0)
// ── 1. `session`: the header utilities entry reuses the current pane ─────
// Select another type first, so the entry has something to re-focus.
await openGuideEntry(page, 'files')
await expect.poll(async () => (await activeTabTexts(parent)).join('|'), { timeout: 30_000 }).not.toMatch(CONTEXT_TAB_NAME)
const sessionEntry = page.locator(entrySelector('session'))
await expect.poll(() => onScreenCount(page, entrySelector('session')), {
timeout: 60_000,
message: 'exactly one session entry must be on screen for the mounted session',
}).toBe(1)
await sessionEntry.click()
await expectActiveTab(parent, CONTEXT_TAB_NAME)
// Reuse, not mint: this session's pane gains no second Context tab.
await expect(
contextTabs,
'the entry must focus the existing Context tab, never mint a second one',
).toHaveCount(tabsBefore)
await expect(page.locator(ALERT_SELECTOR), 'a successful open must not alert').toHaveCount(0)
// ── 2. `agent`: a child agent's detail popover opens the CHILD's view ────
await openGuideEntry(page, 'subagent')
const childCard = page.locator(`[data-graph-node="${CHILD_SESSION_ID}"]`)
const completed = page.getByRole('button', { name: /^(Expand the completed nodes|展开已完成的节点)$/ })
await expect(childCard.or(completed).first()).toBeVisible({ timeout: 60_000 })
if (await completed.isVisible()) await completed.click()
await expect(
childCard,
`the fixture child "${CHILD_LABEL}" must be a node of the parent's topology`,
).toBeVisible({ timeout: 60_000 })
await childCard.click()
const agentEntry = page.locator(entrySelector('agent'))
await expect(agentEntry, 'the agent detail popover must offer the Context entry').toBeVisible({ timeout: 30_000 })
await page.screenshot({ animations: 'disabled', path: test.info().outputPath('context-agent.png') })
await agentEntry.click()
await expect(agentEntry, 'the source detail popover must close').toHaveCount(0)
const child = sessionOwner(page, CHILD_SESSION_ID)
await expectActiveTab(child, CONTEXT_TAB_NAME)
await expect(child.getByText(DASHBOARD_CARD).first()).toBeVisible({ timeout: 30_000 })
await expect.poll(() => details.get(CHILD_SESSION_ID), { timeout: 30_000 }).toMatchObject({
ok: true,
value: { nodes: expect.arrayContaining([expect.objectContaining({ text: 'E2E_CHILD_CONTEXT_MARKER' })]) },
})
expect(JSON.stringify(details.get(CHILD_SESSION_ID))).not.toContain('E2E_PARENT_CONTEXT_MARKER')
await expect.poll(() => details.get(PARENT_SESSION_ID), { timeout: 30_000 }).toMatchObject({
ok: true,
value: { nodes: expect.arrayContaining([expect.objectContaining({ text: 'E2E_PARENT_CONTEXT_MARKER' })]) },
})
// Focus really moved: the CHILD's right column is the one on screen.
await expect.poll(() => onScreenCount(page, `[data-sidebar-right-session="${CHILD_SESSION_ID}"]`), {
timeout: 30_000,
message: 'the controller must switch the mounted session to the child',
}).toBeGreaterThan(0)
await expect.poll(() => onScreenCount(page, `[data-sidebar-right-session="${PARENT_SESSION_ID}"]`), {
timeout: 30_000,
message: 'the parent column must leave the screen once the child is mounted',
}).toBe(0)
await expect(page.locator(ALERT_SELECTOR), 'a successful child open must not alert').toHaveCount(0)
// ── 3. `job`: the entry targets the job's REAL owner (the parent) ────────
// The reader is on the CHILD now and the job is owned by the PARENT, so the
// entry can only succeed by resolving `job.owner`. The Tasks page is
// per-session chrome: reopen it in the CHILD's pane (native tabs are keyed
// per session — the parent's copy is parked, not on screen).
await openGuideEntry(page, 'subagent', CHILD_SESSION_ID)
const jobRow = child.getByRole('button', { name: new RegExp(`^${JOB_LABEL}`) })
await expect(
jobRow,
'the fixture job (owned by the parent) must appear in the tree’s jobs drawer',
).toBeVisible({ timeout: 60_000 })
await jobRow.click()
const jobWindow = page.getByRole('dialog').filter({ hasText: JOB_LABEL }).last()
await expect(jobWindow, 'the job output window must open').toBeVisible({ timeout: 30_000 })
const jobEntry = jobWindow.locator(entrySelector('job'))
await expect(jobEntry, 'the job window must offer the Context entry').toBeVisible({ timeout: 30_000 })
await page.screenshot({ animations: 'disabled', path: test.info().outputPath('context-job.png') })
await jobEntry.click()
await expect(jobWindow, 'the source output window must close').toHaveCount(0)
await expectActiveTab(parent, CONTEXT_TAB_NAME)
await expect.poll(() => onScreenCount(page, `[data-sidebar-right-session="${PARENT_SESSION_ID}"]`), {
timeout: 30_000,
message: 'the job entry must bring the OWNER session (the parent) back on screen',
}).toBeGreaterThan(0)
await expect.poll(() => onScreenCount(page, `[data-sidebar-right-session="${CHILD_SESSION_ID}"]`), {
timeout: 30_000,
message: 'the mounted child column must leave the screen after the owner switch',
}).toBe(0)
await expect(page.locator(ALERT_SELECTOR), 'a successful job open must not alert').toHaveCount(0)
// Both conversations retain their own tab identity. dsh-context does not
// request keepMounted, so its inactive body is intentionally unmounted.
await expectActiveTab(parent, CONTEXT_TAB_NAME)
await expect(child.getByRole('tab', { includeHidden: true }).filter({ hasText: CONTEXT_TAB_NAME })).toHaveCount(1)
await expect(contextTabs, 'returning to the owner must reuse its Context tab').toHaveCount(tabsBefore)
await expect(
parent.getByText(DASHBOARD_CARD).first(),
'the parent Context pane must still render its dashboard',
).toBeVisible({ timeout: 30_000 })
await page.screenshot({ animations: 'disabled', path: test.info().outputPath('context-desktop.png') })
await page.setViewportSize({ width: 390, height: 844 })
await page.screenshot({ animations: 'disabled', path: test.info().outputPath('context-narrow.png') })
expect(pageErrors, 'uncaught page errors').toEqual([])
expect(consoleErrors, 'console errors').toEqual([])
})
+213
View File
@@ -0,0 +1,213 @@
/**
* e2e-only HOST fixture for the Context-diagnostics lane
* (`scripts/e2e-context.sh` → `tests/e2e/context-diagnostics.e2e.ts`).
*
* NOTHING here ships: the lane copies this file into a throwaway package under
* its scratch directory and installs it with the official `dsh plugin add`
* channel, exactly like `tests/fixtures/aggregate-better-sidebar` (see
* `build_fixture_package` in the lane script).
*
* Why a fixture exists at all: the lane must not call a real model, and a
* keyless `dsh web` can produce neither a durable child session nor a
* background job through any public RPC — `job/*` exposes list/follow/kill
* only, and `session/fork` needs a completed turn that only a model can make.
* So this row seeds, through the host's PUBLIC services and nothing else:
*
* - one subagent child session under the lane's parent session, using the
* same `ctx.agents.create` shape (standard `subagent/descriptor` seed +
* fork markers + `inbox.clear()`) that `src/sidechat-routes.ts` uses in
* production, plus the official parent's `subagent/catalog` event so both
* the host catalog and the plugin's Tasks topology discover the child;
* - one RUNNING background job owned by that parent, through
* `ctx.jobs.start` (the same registry `dsh-tool-subagent` uses for
* background delegations).
*
* This is SERVER-SIDE DATA CONSTRUCTION, not model execution: nothing here
* runs an agent turn, calls an LLM, or touches a production route. The lane
* reports it that way.
*
* The parent session itself is created by the SPEC through the public
* `session/create` RPC with the fixed id below, which is how this row knows
* what to attach to without inventing a channel.
*/
import { SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent'
/** The parent session the lane creates through `session/create`. */
const PARENT_ID = 'session-e2e-context-parent'
/** The fixture child session (visible to the host's subagent catalog). */
const CHILD_ID = 'session-e2e-context-child'
/** The child's descriptor label — deliberately NOT the 'Side: ' prefix, which
* the plugin's topology filters out as a side-chat thread. */
const CHILD_LABEL = 'Context fixture child'
/** The background job's model-facing label. */
const JOB_LABEL = 'e2e context fixture job'
/** Poll cadence / budget for the parent session's arrival. */
const POLL_MS = 200
const POLL_LIMIT = 300
/** Failed seeding attempts (logged each) before the fixture stops retrying. */
const MAX_FAILURES = 5
/** How long the fixture job stays running before it settles itself. */
const JOB_TTL_MS = 600_000
/** Plugin name (the row this fixture's bundle patch inserts). */
export const name = 'fixture-context-seed'
/** One line in the host log, so the lane can prove the seeding happened. */
function log(message) {
console.log(`[e2e-context-fixture] ${message}`)
}
/**
* Seed the child session and the job once the parent exists.
* @param ctx - host context (public services only).
* @returns whether the seeding is complete (false = keep polling).
*/
async function seed(ctx) {
const agents = ctx.get('agents')
if (agents === undefined || typeof agents.get !== 'function') return false
const parent = agents.get(PARENT_ID)
if (parent === undefined) return false
const cwd = process.env.DSH_E2E_CONTEXT_WORKSPACE ?? parent.session?.header?.cwd
const descriptor = {
version: SUBAGENT_DESCRIPTOR_VERSION,
mode: 'one-shot',
provider: 'e2e-context-fixture',
label: CHILD_LABEL,
}
const message = (id, text) => ({ id, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text }] })
const parentMarker = 'E2E_PARENT_CONTEXT_MARKER'
const childMarker = 'E2E_CHILD_CONTEXT_MARKER'
if (!parent.session.snapshotEvents().some(event => event.type === 'user/message' && event.data.id === 'fixture-parent-message')) {
parent.session.append('user/message', message('fixture-parent-message', parentMarker), { surfaceOp: 'append' })
}
const seedEvents = [
{ type: 'subagent/descriptor', seq: 0, time: Date.now(), data: descriptor },
{ type: 'user/message', seq: 1, time: Date.now(), data: message('fixture-child-message', childMarker), surfaceOp: 'append' },
]
if (agents.get(CHILD_ID) === undefined) {
const handle = await agents.create({
sessionId: CHILD_ID,
meta: {
...(typeof cwd === 'string' && cwd !== '' ? { cwd } : {}),
parentSession: PARENT_ID,
isSeeded: true,
origin: 'subagent',
delegationDepth: 1,
},
seed: seedEvents,
inheritedEventCount: seedEvents.length,
agentOptions: { ...parent.options },
})
// Same fencing the production sidechat seed performs: the runtime inbox
// projection folds the FULL log (inherited prefix included), so a fresh
// fixture child must not inherit anything the parent left unclaimed.
handle.agent.inbox.clear()
const header = handle.agent.session.header
parent.session.append('subagent/catalog', {
version: 0,
childId: header.id,
childCreatedAt: header.createdAt,
mode: 'one-shot',
label: CHILD_LABEL,
})
log(`seeded child session ${CHILD_ID} under ${PARENT_ID}`)
}
const jobs = ctx.get('jobs')
if (jobs !== undefined && typeof jobs.start === 'function') {
const running = jobs.list(PARENT_ID).filter(view => view.label === JOB_LABEL)
if (running.length === 0) {
const id = jobs.start({
kind: 'bash',
label: JOB_LABEL,
owner: PARENT_ID,
run: (job) => {
job.append('e2e context fixture job started\n', { channel: 'stdout' })
job.append('e2e context fixture output line 1\n', { channel: 'stdout' })
job.updateProgress('fixture 1/1')
let settle
const done = new Promise((resolve) => { settle = resolve })
let settled = false
let timer
const finish = (status, detail) => {
if (settled) return
settled = true
clearTimeout(timer)
settle(detail === undefined ? { status } : { status, detail })
}
timer = setTimeout(() => {
job.append('e2e context fixture job done\n', { channel: 'stdout' })
finish('completed', 'exit code: 0')
}, JOB_TTL_MS)
return {
cancel: (reason) => { finish('killed', typeof reason === 'string' ? reason : 'canceled by fixture') },
done,
}
},
})
log(`started job ${id} owned by ${PARENT_ID}`)
}
}
log(`seeding complete for ${PARENT_ID}`)
return true
}
/**
* Mount the fixture: poll (bounded) for the lane's parent session, then seed
* once. No timers survive the seeding, and none survive disposal.
* @param ctx - host context.
*/
export function apply(ctx) {
let timer
let polls = 0
let failures = 0
let running = false
const stop = () => {
if (timer !== undefined) clearInterval(timer)
timer = undefined
}
const tick = async () => {
if (running) return
running = true
try {
polls += 1
if (await seed(ctx)) {
stop()
return
}
if (polls >= POLL_LIMIT) {
stop()
log(`gave up waiting for ${PARENT_ID} after ${POLL_LIMIT} polls`)
}
} catch (error) {
failures += 1
log(`seeding attempt ${failures} failed: ${error instanceof Error ? error.message : String(error)}`)
if (failures >= MAX_FAILURES) {
stop()
log(`gave up after ${MAX_FAILURES} failed seeding attempts`)
}
} finally {
running = false
}
}
log(`mounted (waiting for ${PARENT_ID})`)
timer = setInterval(() => { void tick() }, POLL_MS)
void tick()
if (typeof ctx.effect === 'function') {
ctx.effect(() => () => { stop() }, 'e2e-context-fixture.poll')
}
}
+206
View File
@@ -0,0 +1,206 @@
/**
* Shared fixtures of the Context-diagnostics lane
* (`scripts/e2e-context.sh` → `./context-diagnostics.e2e.ts`).
*
* Two jobs, both deliberately thin:
*
* 1. The ONE source of truth for the ids the lane's host fixture
* (`./context-fixture-plugin.mjs`) attaches to. The spec creates the parent
* session itself through the public `session/create` RPC with
* {@link PARENT_SESSION_ID}; the fixture row (installed only in this lane's
* scratch profiles) then seeds the child session
* and the background job off that fixed id. No channel, no private API.
*
* 2. The DOM handles the lane asserts on, all of them the HOST's or the
* PLUGIN's own public markers — never an internal:
* - `[data-sidebar-right-session="<sid>"]` — the host's per-session right
* column owner (the host's own client bundle addresses panes this way),
* - `[role="tab"]` — a native tab button (dsh-context's own bundle finds its
* tab by `button[role="tab"]` + text),
* - `[data-row-key="session:<sid>"]` — a session row of the host's workspace
* tree (`role="treeitem"`, click = open),
* - `[data-graph-node="<sid>"]` — an agent card of the plugin's Tasks graph
* (click = the node's detail popover),
* - `[data-dsh-ctx-entry="session|agent|job"]` / `[data-dsh-ctx-alert]` —
* the plugin's own entry-point and alert testids
* (`src/client/context-diagnostics-ui.tsx`).
*/
import { mkdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { expect, type APIRequestContext, type Locator, type Page } from '@playwright/test'
import { hostRpc } from './host'
/** The parent session the SPEC creates through `session/create` (the fixture
* plugin attaches to exactly this id — see the module header). */
export const PARENT_SESSION_ID = 'session-e2e-context-parent'
/** The child (subagent-origin) session the fixture row creates. */
export const CHILD_SESSION_ID = 'session-e2e-context-child'
/** The child's descriptor label (deliberately not a `Side: ` side-thread). */
export const CHILD_LABEL = 'Context fixture child'
/** The fixture job's label (its row's accessible name starts with it). */
export const JOB_LABEL = 'e2e context fixture job'
/** A file in the lane's workspace, so the seeded workspace is not empty. */
export const SEED_FILE = 'context-lane.txt'
/** The dsh-context tab/bundle identity (its `TabDescriptor.id` and kind). */
export const CONTEXT_KIND = 'dsh-context'
/** The Context tab's localized title (en / zh dictionaries). */
export const CONTEXT_TAB_NAME = /^(Context|上下文)$/
/** A card title the real dsh-context dashboard renders (en / zh). */
export const DASHBOARD_CARD = /Token Stats|Token 统计/
/**
* The panel-list label of dsh-context's placement-independent "Context
* Insights" page (`ov.title` in its own dictionaries). It exists whenever the
* plugin is mounted, whatever `defaultPlacement` says — which is what makes it
* the guard for the `tab-only` variant: the entries must be hidden there
* because the RIGHT COLUMN type is off, not because dsh-context failed to
* mount.
*/
export const CONTEXT_INSIGHTS_LABEL = /^(Context Insights|上下文洞察)$/
/** Testid of one entry point (its `kind` is `session` / `agent` / `job`). */
export function entrySelector(kind: 'session' | 'agent' | 'job'): string {
return `[data-dsh-ctx-entry="${kind}"]`
}
/** Testid of the frame-wide error alert (one at a time). */
export const ALERT_SELECTOR = '[data-dsh-ctx-alert]'
/** The host's per-session right-column owner element. */
export function sessionOwner(page: Page, sessionId: string): Locator {
return page.locator(`[data-sidebar-right-session="${sessionId}"]`)
}
/** The host's workspace-tree row for one session (subagent rows are absent by
* the HOST's own rule — `origin === 'subagent'` rows are filtered out). */
export function sessionRow(page: Page, sessionId: string): Locator {
return page.locator(`[data-row-key="session:${sessionId}"]`)
}
/**
* Seed the lane's workspace and its parent session through the host's public
* unary RPC (`workspace.create` + `session.create`), the same calls the UI
* makes. The session id is PINNED so the fixture row can attach to it without
* any extra channel.
* @param api - authenticated host request context (`createHostApi`).
* @param workspacePath - the lane's workspace directory (created if absent).
*/
export async function seedParentSession(api: APIRequestContext, workspacePath: string): Promise<void> {
mkdirSync(workspacePath, { recursive: true })
writeFileSync(join(workspacePath, SEED_FILE), 'context diagnostics lane\n')
const workspace = await hostRpc<{ workspace: { workspaceId: string } }>(
api, 'workspace.create', { path: workspacePath },
)
await hostRpc(api, 'session.create', {
workspaceId: workspace.value.workspace.workspaceId,
sessionId: PARENT_SESSION_ID,
})
}
/**
* Dismiss the keyless boot's onboarding takeovers, which mask the whole shell
* (the versioned welcome notice, then the provider-config dialog). Same shape
* as the other lanes' helper: wait (bounded) for one to appear, then click
* whatever is clickable until none remain.
* @param page - the lane's page.
*/
export async function dismissOnboarding(page: Page): Promise<void> {
try {
await expect
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
.toBeGreaterThan(0)
} catch {
console.warn('[e2e] no onboarding takeover appeared; proceeding without dismissal')
}
for (let round = 0; round < 8; round++) {
let dismissed = false
for (const name of ['Continue', 'Configure later']) {
const button = page.getByRole('button', { name, exact: true }).first()
if ((await button.count()) === 0) continue
try {
await button.click({ timeout: 4_000 })
dismissed = true
await page.waitForTimeout(1_000)
} catch {
// Masked by the takeover stacked above it; the next round tries the
// other button first.
}
}
if (!dismissed) break
}
}
/**
* Count the elements matching `selector` that INTERSECT the viewport. The host
* keeps a hidden copy of every retained session's chrome (translated out of
* view, its rect still non-empty), so a plain count would see duplicates the
* reader cannot see — the blank-session lane documents the same hazard.
* @param page - the lane's page.
* @param selector - a CSS selector.
* @returns how many matches are really on screen.
*/
export async function onScreenCount(page: Page, selector: string): Promise<number> {
return page.evaluate((sel) => {
let seen = 0
for (const element of document.querySelectorAll(sel)) {
const rect = element.getBoundingClientRect()
if (rect.width > 0 && rect.height > 0
&& rect.bottom > 0 && rect.right > 0
&& rect.top < window.innerHeight && rect.left < window.innerWidth) seen += 1
}
return seen
}, selector)
}
/**
* Bring the native right column up and open one guide entry. Idempotent: the
* expand control only exists while the column is collapsed, and the guide page
* only shows while the pane holds no tabs (the same two-step the mount lane
* performs inline).
* @param page - the lane's page.
* @param kind - the guide entry's kind (`files` / `subagent` / `dsh-context`).
*/
export async function openGuideEntry(page: Page, kind: string, sessionId = PARENT_SESSION_ID): Promise<Locator> {
const owner = sessionOwner(page, sessionId)
const viewport = page.viewportSize()
for (const expand of await page.locator('[data-sidebar-right-expand]').all()) {
const rect = await expand.boundingBox()
if (rect !== null && viewport !== null && rect.x + rect.width > 0 && rect.y + rect.height > 0
&& rect.x < viewport.width && rect.y < viewport.height) {
await expand.click()
break
}
}
if (await owner.locator('[data-sidebar-right-guide]').count() === 0) {
await owner.locator('[data-dockkit-add-tab]').first().click()
}
await owner.locator(`[data-sidebar-right-guide-entry="${kind}"]`).click()
return owner
}
/**
* The texts of the ACTIVE tab buttons inside one container (0..n — a pane
* without a selected tab answers `[]`).
* @param scope - a page or an owner-element locator.
*/
export async function activeTabTexts(scope: Page | Locator): Promise<string[]> {
return scope.locator('[role="tab"][aria-selected="true"]').allTextContents()
}
/**
* Wait until one container's active tab is titled `name`.
* @param scope - the owner element (or page) to read.
* @param name - the expected tab title pattern.
*/
export async function expectActiveTab(scope: Page | Locator, name: RegExp): Promise<void> {
await expect
.poll(async () => (await activeTabTexts(scope)).filter(text => name.test(text.trim())).length, { timeout: 30_000 })
.toBeGreaterThan(0)
}
+97 -1
View File
@@ -5,10 +5,12 @@
* (src/client/service.ts `setSurface`).
*/
import { describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createElement, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { createNativeTabRecords, NativeTabBody, NativeTabTitle } from '../src/client/native/tab-adapter.tsx'
import { ContextDiagnosticsButton } from '../src/client/context-diagnostics-ui.tsx'
import type { ContextDiagnosticTarget, ContextDiagnostics, ContextDiagnosticsSnapshot } from '../src/client/context-diagnostics.ts'
import { createNativeSurface } from '../src/client/native/surface.ts'
import { fileParamsOf, registerNativeSurface } from '../src/client/native/index.ts'
import { createBetterSidebarService, type SidebarSurface, type TabComponentProps } from '../src/client/service.ts'
@@ -830,6 +832,100 @@ describe('NativeTabBody full-height host wrapper', () => {
})
})
/**
* The diagnostics controller reaches a native tab body through the injected
* bag (`NativeSurfaceDeps.diagnostics` → `inject()` → `NativeTabBody`'s
* provider): a body renders in the HOST's tree, so the plugin shell's own
* provider cannot reach it. A body whose registration carried no controller
* renders exactly as before — no entry point, no crash.
*/
describe('NativeTabBody — the diagnostics provider comes from the injected bag', () => {
/** A snapshot-driven controller double; it records the targets it is asked to open. */
const makeDiagnostics = (): { controller: ContextDiagnostics; opens: ContextDiagnosticTarget[] } => {
const opens: ContextDiagnosticTarget[] = []
const snapshot: ContextDiagnosticsSnapshot = { available: true, busy: false }
const controller: ContextDiagnostics = {
getSnapshot: () => snapshot,
subscribe: () => () => {},
open: (target: ContextDiagnosticTarget) => { opens.push(target) },
dismissError: () => {},
dispose: () => {},
}
return { controller, opens }
}
function renderBody(diagnostics?: ContextDiagnostics): { host: HTMLDivElement; root: Root } {
const store = createSidebarStore()
store.setSession('s1')
const service = createBetterSidebarService(store)
// The body asks for the diagnostics entry point of a job; the value it can
// address comes from the provider, so it exists only where the bag carried
// a controller down to this body.
const component = (): ReactNode => createElement(ContextDiagnosticsButton, {
kind: 'job',
target: { sessionId: 's1', label: 'job owner' },
iconSize: 12,
})
service.registerTab({ id: 'probe', title: 'Probe', component })
const records = createNativeTabRecords()
const ctx = { sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: {} }) } } } as never
const info = {
tab: {
id: 'native-11',
kind: 'probe',
title: 'Probe',
contentId: 'sidebar://probe',
visible: true,
navigation: { address: 'sidebar://probe', params: undefined, revision: 0 },
signal: new AbortController().signal,
},
}
const host = document.createElement('div')
document.body.appendChild(host)
let root: Root | undefined
act(() => {
root = createRoot(host)
root.render(createElement(NativeTabBody, {
sessionId: 's1',
ctx,
store,
service,
records,
descriptorId: 'probe',
useTabInfo: () => info,
...(diagnostics === undefined ? {} : { diagnostics }),
}))
})
return { host, root: root! }
}
it('offers no entry point without a controller, and renders one with it', async () => {
const bare = renderBody()
expect(bare.host.querySelector('[data-dsh-ctx-entry="job"]')).toBeNull()
act(() => { bare.root.unmount() })
bare.host.remove()
const fake = makeDiagnostics()
const wired = renderBody(fake.controller)
const button = wired.host.querySelector('[data-dsh-ctx-entry="job"]') as HTMLButtonElement
expect(button, 'the injected controller must reach the body').not.toBeNull()
await act(async () => { button.click() })
expect(fake.opens).toEqual([{ sessionId: 's1', label: 'job owner' }])
act(() => { wired.root.unmount() })
wired.host.remove()
})
it('keeps the full-height host wrapper contract with the provider in place', () => {
const fake = makeDiagnostics()
const { host, root } = renderBody(fake.controller)
const wrapper = host.querySelector('[data-dsh-native-tab-host=""]')
expect(wrapper, 'the paneBody fill contract is unchanged').not.toBeNull()
expect(wrapper!.querySelector('[data-dsh-ctx-entry="job"]'), 'the entry point lives in the wrapper').not.toBeNull()
act(() => { root.unmount() })
host.remove()
})
})
/**
* The revision the adapter READS off the native record is what gates the seed
* meta (the `createNativeTabRecords` cases above pin the gate itself): this
+76
View File
@@ -15,6 +15,12 @@ import { createElement } from 'react'
import { act } from 'react-dom/test-utils'
import { renderRoot } from './test-utils.ts'
import { SubagentView } from '../src/client/SubagentView.tsx'
import { ContextDiagnosticsHost } from '../src/client/context-diagnostics-ui.tsx'
import type {
ContextDiagnosticTarget,
ContextDiagnostics,
ContextDiagnosticsSnapshot,
} from '../src/client/context-diagnostics.ts'
import type {
Context,
SidebarClientJobsService,
@@ -186,6 +192,36 @@ afterEach(() => {
for (const el of document.querySelectorAll('body > div')) el.remove()
})
/**
* Rendering the page WITH a diagnostics controller: the output window carries
* the owner conversation's Context entry, and adding it must not disturb the
* job plumbing this file pins (watch/observe/release/kill go through the host
* client service exactly as before).
*/
function diagnosticsFixture(snapshot: ContextDiagnosticsSnapshot = { available: true, busy: false }) {
const opens: ContextDiagnosticTarget[] = []
let current = snapshot
const listeners = new Set<() => void>()
const controller: ContextDiagnostics = {
getSnapshot: () => current,
subscribe: (listener: () => void) => {
listeners.add(listener)
return () => { listeners.delete(listener) }
},
open: (target: ContextDiagnosticTarget) => { opens.push(target) },
dismissError: () => {},
dispose: () => {},
}
return {
opens,
controller,
publish: (next: ContextDiagnosticsSnapshot): void => {
current = next
for (const listener of [...listeners]) listener()
},
}
}
/** Flush the mount-time requests (routes + the service snapshot). */
async function flushJobs(): Promise<void> {
for (let tick = 0; tick < 4; tick++) {
@@ -466,6 +502,46 @@ describe('SubagentView background jobs', () => {
unmount()
})
it('adds the owner\'s Context entry to the window WITHOUT touching the job plumbing', async () => {
const store = makeStore(baseSnapshot())
const diagnostics = diagnosticsFixture()
const rendered = renderRoot(createElement(
ContextDiagnosticsHost,
{ controller: diagnostics.controller },
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, undefined, jobsFake) }),
))
const { container } = rendered
await flushJobs()
// The tree's jobs keep the host-client-service path: both sessions watched.
expect([...jobsFake.watches].sort()).toEqual(['child', 'root'])
const row = container.querySelector('button[aria-label*="echo hi"]') as HTMLButtonElement
await act(async () => { row.click() })
// The observation still rides the roster's WATCHED session for this job.
expect(jobsFake.observations).toEqual([{ sessionId: 'child', jobId: 'bash-2' }])
const entry = document.querySelector('[data-dsh-ctx-entry="job"]') as HTMLButtonElement
expect(entry).not.toBeNull()
// The kill control is untouched beside it, and the entry opens the OWNING
// conversation (the row's own roster key IS the owner in this fixture).
expect(document.querySelectorAll('[data-floating-window] button[aria-label="终止"]')).toHaveLength(0)
await act(async () => { entry.click() })
expect(diagnostics.opens).toEqual([{
sessionId: 'child',
label: '子代理',
address: { parentSessionId: 'root', childSessionId: 'child', mode: 'continuable' },
}])
await act(async () => {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
})
expect(jobsFake.released).toContain('bash-2')
await act(async () => { rendered.unmount() })
// One row was open, so ONE observation was ever taken: the watchers ride
// the page's lifetime, the observation rides the open row's.
expect(jobsFake.observations).toEqual([{ sessionId: 'child', jobId: 'bash-2' }])
expect([...jobsFake.releases].sort()).toEqual(['child', 'root'])
})
it('flags a gap and a producer error in the observed stream', async () => {
const store = makeStore(baseSnapshot())
const { container, unmount } = await renderPage(store)
+212 -1
View File
@@ -6,12 +6,18 @@
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createElement, type ReactElement } from 'react'
import { act } from 'react-dom/test-utils'
import { renderRoot } from './test-utils.ts'
import { SubagentView } from '../src/client/SubagentView.tsx'
import { createSidebarStore } from '../src/client/state.ts'
import { attachLocale } from '../src/client/locales.ts'
import { ContextDiagnosticsHost } from '../src/client/context-diagnostics-ui.tsx'
import type {
ContextDiagnosticTarget,
ContextDiagnostics,
ContextDiagnosticsSnapshot,
} from '../src/client/context-diagnostics.ts'
import type {
Context,
SidebarClientJobsService,
@@ -26,6 +32,36 @@ import type {
SidebarTeamTaskView,
} from '../src/context-types.ts'
/**
* A diagnostics controller double: the snapshot is driven by the test, and
* every `open` is recorded so the page's addressing can be asserted.
*/
function makeController(initial: ContextDiagnosticsSnapshot) {
let snapshot = initial
const listeners = new Set<() => void>()
const opens: ContextDiagnosticTarget[] = []
const controller: ContextDiagnostics = {
getSnapshot: () => snapshot,
subscribe: (listener: () => void) => {
listeners.add(listener)
return () => { listeners.delete(listener) }
},
open: (target: ContextDiagnosticTarget) => { opens.push(target) },
dismissError: () => {},
dispose: () => {},
}
return {
controller,
opens,
publish: (next: ContextDiagnosticsSnapshot): void => {
snapshot = next
for (const listener of [...listeners]) listener()
},
}
}
type ControllerFake = ReturnType<typeof makeController>
/** A subscribable sessions-list snapshot (mirror of the runtime list feed). */
function makeStore(initial: SidebarSessionList) {
let snapshot = initial
@@ -1684,3 +1720,178 @@ describe('Tasks page: the tree disclosure', () => {
unmount()
})
})
/**
* The optional dsh-context diagnostics entry points on this page: the agent
* node's detail card and a job's output window. Both are gated on the
* controller `SubagentView` reaches through the provider, and both address the
* conversation through the TREE MODEL — never through the jobs roster's
* `ownerSessionId`, which names the session a job was watched under rather than
* the session that owns it.
*/
describe('Tasks page: the context diagnostics entry points', () => {
/** A controller double plus the provider-wrapped page under test. */
function pageWithDiagnostics(
content: (ctx: Context) => ReactElement,
snapshot: ContextDiagnosticsSnapshot = { available: true, busy: false },
): { controller: ControllerFake; container: HTMLDivElement; unmount: () => void } {
const controller = makeController(snapshot)
const store = makeStore(snapshotWithChildren(1))
const rendered = renderRoot(createElement(
ContextDiagnosticsHost,
{ controller: controller.controller },
content(makeCtx(store)),
))
return { controller, container: rendered.container, unmount: rendered.unmount }
}
/** The page element for one context. */
function page(ctx: Context): ReactElement {
return createElement(SubagentView, { sessionId: 'root', active: true, ctx })
}
it('offers NO entry point on a page without a controller', async () => {
const store = makeStore(snapshotWithChildren(1))
const { container, unmount } = renderRoot(page(makeCtx(store)))
const foldToggle = container.querySelector('button[aria-label="展开已完成的节点"]') as HTMLButtonElement
await act(async () => { foldToggle.click() })
await act(async () => { (container.querySelector('[data-graph-node="child-0"]') as HTMLElement).click() })
expect(document.querySelector('[data-dsh-ctx-entry="agent"]')).toBeNull()
await act(async () => { unmount() })
})
it("opens a CHILD node's conversation from its card, addressed by the tree model", async () => {
const rendered = pageWithDiagnostics(page)
const { container } = rendered
const foldToggle = container.querySelector('button[aria-label="展开已完成的节点"]') as HTMLButtonElement
await act(async () => { foldToggle.click() })
await act(async () => { (container.querySelector('[data-graph-node="child-0"]') as HTMLElement).click() })
const button = document.querySelector('[data-dsh-ctx-entry="agent"]') as HTMLButtonElement
expect(button).not.toBeNull()
expect(button.getAttribute('aria-busy')).toBeNull()
await act(async () => { button.click() })
// The node's OWN address (parent + child + mode), never a guess from the
// rendered label.
expect(rendered.controller.opens).toEqual([{
sessionId: 'child-0',
label: '子代理 0',
address: { parentSessionId: 'root', childSessionId: 'child-0', mode: 'one-shot' },
}])
expect(button.isConnected, 'the source overlay must close after dispatch').toBe(false)
await act(async () => { rendered.unmount() })
})
it('addresses the ROOT node by its session id (the root has no child address)', async () => {
const rendered = pageWithDiagnostics(page)
await act(async () => {
(rendered.container.querySelector('[data-graph-node="root"]') as HTMLElement).click()
})
const button = document.querySelector('[data-dsh-ctx-entry="agent"]') as HTMLButtonElement
expect(button).not.toBeNull()
await act(async () => { button.click() })
expect(rendered.controller.opens).toEqual([{ sessionId: 'root', label: '主会话' }])
await act(async () => { rendered.unmount() })
})
it('addresses a job by its OWNER resolved in the tree, never by the watched roster key', async () => {
// The roster announces the job under `root` (the watched session) while the
// job's owner is `child-0`: the button must target the owner's node —
// addressed by the model — and the roster key must not leak into it.
jobsFake.emit({
rows: {
root: [{
id: 'bash-9', kind: 'bash', label: 'echo owned', status: 'running', startedAt: 1_000, owner: 'child-0',
}],
},
})
const rendered = pageWithDiagnostics(page)
await flushJobs()
// The owner node has to be ON the page: a folded-away node is not part of
// the model, and the page never addresses a conversation it does not show.
await act(async () => {
(rendered.container.querySelector('button[aria-label="展开已完成的节点"]') as HTMLButtonElement).click()
})
const row = rendered.container.querySelector('button[aria-label*="echo owned"]') as HTMLButtonElement
await act(async () => { row.click() })
const button = document.querySelector('[data-dsh-ctx-entry="job"]') as HTMLButtonElement
expect(button).not.toBeNull()
await act(async () => { button.click() })
expect(rendered.controller.opens).toEqual([{
sessionId: 'child-0',
label: '子代理 0',
address: { parentSessionId: 'root', childSessionId: 'child-0', mode: 'one-shot' },
}])
expect(button.isConnected, 'the source overlay must close after dispatch').toBe(false)
await act(async () => { rendered.unmount() })
})
it('offers no job entry point while the owning node is not on the page', async () => {
// The owner is a real tree member, but FOLDED away: the model has no node
// for it, so the window has nothing to address. Unfolding the node brings
// the control back — the entry point follows the model, not the roster.
jobsFake.emit({
rows: {
root: [{
id: 'bash-8', kind: 'bash', label: 'folded owner job', status: 'running', startedAt: 1_000, owner: 'child-0',
}],
},
})
const rendered = pageWithDiagnostics(page)
await flushJobs()
const row = rendered.container.querySelector('button[aria-label*="folded owner job"]') as HTMLButtonElement
await act(async () => { row.click() })
expect(document.querySelector('[data-dsh-ctx-entry="job"]')).toBeNull()
expect(rendered.controller.opens).toEqual([])
const foldToggle = rendered.container.querySelector('button[aria-label="展开已完成的节点"]') as HTMLButtonElement
await act(async () => { foldToggle.click() })
const button = document.querySelector('[data-dsh-ctx-entry="job"]') as HTMLButtonElement
expect(button, 'the owner is on the page now').not.toBeNull()
await act(async () => { button.click() })
expect(rendered.controller.opens).toEqual([{
sessionId: 'child-0',
label: '子代理 0',
address: { parentSessionId: 'root', childSessionId: 'child-0', mode: 'one-shot' },
}])
expect(button.isConnected, 'the source overlay must close after dispatch').toBe(false)
await act(async () => { rendered.unmount() })
})
it('never diagnoses the watching session for an unowned job', async () => {
const rendered = pageWithDiagnostics(page)
await flushJobs()
const row = rendered.container.querySelector('button[aria-label*="sleep 300"]') as HTMLButtonElement
await act(async () => { row.click() })
expect(document.querySelector('[data-dsh-ctx-entry="job"]')).toBeNull()
expect(rendered.controller.opens).toEqual([])
expect(jobsFake.observations).toContainEqual({ sessionId: 'root', jobId: 'bash-1' })
await act(async () => { rendered.unmount() })
})
it('hides the job entry point while the controller reports the capability unavailable', async () => {
jobsFake.emit({ rows: { root: [{ id: 'bash-1', kind: 'bash', label: 'sleep 300', status: 'running', startedAt: 1_000, owner: 'root' }] } })
const rendered = pageWithDiagnostics(page, { available: false, busy: false })
await flushJobs()
const row = rendered.container.querySelector('button[aria-label*="sleep 300"]') as HTMLButtonElement
await act(async () => { row.click() })
expect(document.querySelector('[data-dsh-ctx-entry="job"]')).toBeNull()
await act(async () => { rendered.unmount() })
})
it('disables every entry point while an open is in flight', async () => {
jobsFake.emit({ rows: { root: [{ id: 'bash-1', kind: 'bash', label: 'sleep 300', status: 'running', startedAt: 1_000, owner: 'root' }] } })
const rendered = pageWithDiagnostics(page, { available: true, busy: true })
await flushJobs()
const row = rendered.container.querySelector('button[aria-label*="sleep 300"]') as HTMLButtonElement
await act(async () => { row.click() })
const button = document.querySelector('[data-dsh-ctx-entry="job"]') as HTMLButtonElement
expect(button).not.toBeNull()
expect(button.disabled).toBe(true)
expect(button.getAttribute('aria-busy')).toBe('true')
await act(async () => { button.click() })
expect(rendered.controller.opens).toEqual([])
await act(async () => { rendered.unmount() })
})
})
+11
View File
@@ -117,6 +117,17 @@ function moduleStylesheets(): string[] {
}
describe('skin contract: the plugin owns no color of its own', () => {
it('keeps Context diagnostics feedback themed and bounded on narrow viewports', () => {
const source = readFileSync(resolve(ROOT, 'src/client/context-diagnostics.module.css'), 'utf8')
expect(source).toContain('var(--dsw-alias-bg-layer-3)')
expect(source).toContain('var(--dsw-alias-state-warn-primary)')
expect(source).toContain('calc(100vw - 24px)')
expect(source).toContain('overflow-wrap: anywhere')
const tokens = [...source.matchAll(/var\((--[\w-]+)/g)].map(match => match[1])
expect(tokens.length).toBeGreaterThan(0)
for (const token of tokens) expect(token).toMatch(/^--(?:dsw-alias-|dsw-font-|ds-)/)
})
it('the icon modules carry no color literals', () => {
for (const file of ['src/client/file-icons.tsx', 'src/client/icons.tsx']) {
const source = readFileSync(resolve(ROOT, file), 'utf8')