feat(injection): 统一面板宿主注入重构——含块层+几何写路径+chunk缓存+锚点弱化+桌面/移动适配 (#232)

* feat(injection): 统一面板宿主——固定含块层 + 挂载自检降级 + body 锚点守卫

- Sidebar 渲染根包 [data-dsh-panel-host](fixed inset-0 pointer-events:none)
- 面板/开关簇由 fixed 改 absolute(层内视口坐标等价),免疫套壳中间层 transform 劫持
- 挂载后一次性几何自检:页面级 transform 时降级 absolute + rAF 视口同步
- MutationObserver(body childList)守卫锚点被宿主清空时重挂

* perf(injection): 几何写路径统一为 writeGeometry + 面板 layout 隔离

- 拖拽帧与打开态共用单一推挤写入器(--dsh-sidebar-width/height)
- .panel/.bottomPanel contain: layout style——内部重排不外泄
- 拖拽期(body[data-dsh-sidebar-dragging])才挂 will-change: transform

* perf(chunks): HMR 激活保留未变 chunk 的已解析 exports + ETag HEAD 重验证

- 新增 revalidateChunksOnReactivate():激活时 HEAD 每个已加载 chunk 对比 ETag,
  未变保留内存缓存(跳过重注入/重执行),变更或不可达则 fail-open 重取
- 测试夹具与孤儿缓存条目不跨激活存活
- index.tsx 激活路径由 resetChunks() 改为 revalidateChunksOnReactivate()

* fix(layout): 推挤锚点改 data 属性 + #root calc 宽度防桌面壳溢出

- nth-child(2) → #root [data-dsh-frame] > [data-pane="conversation"](实证同元素)
- #root 宽度 calc(100% - var) 与 margin 同步过渡:web 视觉不变(实测 1140+300=1440 无溢出),
  Desktop 壳(#208)width:100% 的加性溢出根因消除

* feat(desktop): 桌面信号自动探测 + win32 顶栏 overlay 自动避让 + 键盘/safe-area 适配

- 新增 desktop-env.ts:解析 dsh-desktop-mode/platform URL 信号与 preload 标记
- win32 advanced 壳自动启用 titleBarCompat(32px overlay),手动 pref 仍可覆盖
- visualViewport 键盘 inset:底部面板/窄屏抽屉键盘弹起时上移
- 面板与开关簇 safe-area-inset 适配(env() 桌面端为 0)
- 单测 7 例(含 URLSearchParams 前导 ? 剥除修复)

* docs+e2e: 注入方案实施记录(路线B关闭、偏差记录、基线数据)+ 契约同步 + e2e 新断言

- 设计文档:路线 B 标记关闭、§8.1 改单 PR 步骤(含 commit 对照)、拖拽基线数据、实施偏差记录
- AGENTS.md §8:data-dsh-panel-host 含块层、推挤锚点契约(禁 nth-child)、桌面信号
- mount.e2e:data-dsh-panel-host 断言 + win32 advanced 桌面信号场景

* fix(cr): 响应 #232 CR 三条 findings

- P1 降级同步:按未修正几何判定(跟踪自身补偿量),祖先 transform 消失才退出循环——
  修正后矩形不再被误判为无需修正(自清除缺陷)
- P1 chunk 重验证成为 loadChunk 屏障:重验证挂起期间不提供缓存,杜绝 HMR 竞态陈旧 exports;
  测试夹具加载不再被误记为生产加载
- P2 键盘 inset:innerHeight - (vv.height + vv.offsetTop),并监听 scroll(offsetTop 变化)
- 新增屏障单测 1 例;设计文档偏差记录更新

* fix(chunks): 屏障 HEAD 加超时兜底 + resetChunks 清 revalidation

- revalidateChunksOnReactivate 的 HEAD 与 recordEtag 均带
  AbortSignal.timeout(5s):路由挂起时 fail-open(drop + 重取),
  屏障不再可能无限期阻塞所有懒加载 chunk(CR #232 P1 修复的健壮性缺口)
- resetChunks 同步清 revalidation:重验证挂起期间重置后,
  loadChunk 不再等待已丢弃状态的孤儿任务(finally 身份判断 no-op)
- 单测 +2:HEAD 挂起超时 fail-open(fake AbortSignal.timeout 触发中止)、
  resetChunks 清屏障后 loadChunk 立即放行

* fix(deps): align @deepseek-ai/* peers with DSH 0.1.0-rc.8

- peer/devDependencies: 13 个 @deepseek-ai/* 从 ^0.1.0-rc.7 升至
  ^0.1.0-rc.8;删除随 rc.8 消失的 dsh-client-web-react / dsh-client-schema-form
  (无 rc.8 发布、rc.8 依赖树与壳 bundle 零引用、插件 src 零引用);
  cordis peer/devDep 同步升 ^4.0.0-rc.8
- 版本 0.13.1 -> 0.14.0(package.json / dsh.plugin.json /
  SIDEBAR_SERVICE_VERSION 三处同步)
- CHUNK_EXTERNALS / CLIENT_EXTERNALS / CLIENT_REQUIRE_ALLOWED 三处镜像
  同步删除两个死包(primitives/slots 仍是 rc.8 壳静态模块表种子,保留)
- CI 挂载冒烟钉版 @deepseek-ai/dsh@0.1.0-rc.7 -> rc.8
- pnpm clean --lockfile 全量重解析:lockfile 内 @deepseek-ai/* rc.7 残留
  清零(传递链同升 rc.8,杜绝 #206 式混用树);pnpm-workspace.yaml
  minimumReleaseAgeExclude 按 #207 模式整体换为 rc.8 列表
- 文档同步:README 安装说明、AGENTS.md CI 钉版、外部插件指南与设计文档
  cordis 示例、issue 模板版本示例

* feat(prefs): editorExplorer 默认独立(关)——文件各自新开 tab

- SIDEBAR_PREFS_DEFAULTS 与 host PrefsSchema 的 editorExplorer 默认
  true -> false:新会话树点击/打开文件按 path 新开 tab,无路径窗口即
  纯资源管理器;合并模式保留为可选手动开启(持久化过的用户设置不受影响)
- 测试同步:prefs.spec 默认断言翻转、plugin-shape.spec 与 smoke.spec
  默认对象翻转;editor-host 合并模式用例显式开启 editorExplorer(split
  用例本已显式);side-card-section-rows 的 select 行用例固定选中 Merged
- e2e 重写:mount.e2e 文件打开流程从 in-place 断言改为独立模式
  (新开 hello.txt tab、Files home tab 保留),文件头注释同步
- 契约文档同步:AGENTS.md §3.4 editor 行默认描述翻转 + CI 冒烟描述、
  README/README_EN v0.13.0 特性描述 + v0.14.0 changelog

* fix(client): rc.8 模块系统经 ctx.modules 注入 + chunk 副本全局共享

rc.8 不再暴露 window.__DSH_MODULES__ 页面全局(改由 ctx.modules 服务
提供),chunk 外部依赖解析全面失效(terminal/editor/mermaid 全部
"client module system unavailable")。修复:

- src/client/index.tsx: inject 增加 'modules'(Cordis 服务访问守卫,
  此前直接读 ctx.modules 抛 "cannot get property modules without
  inject");apply() 激活时 setChunkModuleSystem(ctx.modules)
- package.json dsh.client.inject 增加 @deepseek-ai/dsh-client-modules
- chunk-loader: 注入写插件自有页面全局 __dshSidebarModuleSystem__——
  懒加载 chunk bundle 各自内联一份 loader(rc.7 靠官方全局回退工作,
  rc.8 全局消失后副本注入变量恒空);moduleSystem() 按
  注入变量 → 插件全局 → rc.7 全局回退解析
- context-types: Context 镜像补 modules 服务声明(client half)
- e2e: assertNoCrash 失败时输出错误条文本;独立模式断言修正
  (Files 数量按存在性、mermaid 流程先切回 Files、md 预览 locator 去掉
  重复的 [data-dsh-better-sidebar] 嵌套)

验证:typecheck / 639 测试全绿;本地 rc.8 CLI + Chromium 挂载冒烟 3/3
通过(drag-layout、mount 深扫含 editor/mermaid chunk、桌面信号)

* feat(settings): 终端 shell/shellArgs 可在设置页配置(bash 管理)

- SidebarPrefs 新增 terminalShell / terminalShellArgs(默认空 = 保持
  yaml config.shell → $SHELL / 登录 shell / powershell.exe 的既有解析)
- 终端卡齿轮二级页面新增两行 text 配置(与字体行同列)
- host 侧生效链路:UI 终端 WS 打开与 agent terminal_create 均读取
  设置文档覆盖(ptyManager.open / AgentPtyRegistry.create 增加可选
  shell 覆盖参数;shellOverridesOf 解析设置文档);设置页写入即时
  影响之后打开的终端(既有 pty 保持原 shell)
- locales zh/en 文案;parsePrefs 校验新字段;测试同步

* feat(settings): 侧边卡片设置页加 DSH-better-sidebar 版本徽标

- 设置页 intro 下新增身份徽标:名称 + v{service.version}(服务实例
  版本,与 package.json 由 tests/service.spec.ts 保持同步)
- token 驱动样式(--dsw-alias-*),名称/版本 pill 布局

* fix(drag): 快速拖动提交最后位置 + HMR 后中心列重定位兜底

快速释放(浏览器合并/丢失 pointermove 突发,超快速 flick 甚至可能
完全无 move)时的回退问题:
- pointerup 优先采用最后一次已知拖动值(rAF pending),而非 up 位置
  (事件合并时可能等于按下位置)
- pointercancel / lostpointercapture 中断时同样提交最后已知位置;
  无 move 时用中断事件自身的坐标计算(clamp 后提交)——只有真正
  未产生位移的拖动才回滚
- commitDrag 统一 flush + 同值提交 + 立即重测中心列(消除提交后
  React 用旧 centerRect 覆盖底栏 right 的中间帧)

HMR 重激活后底栏空白(输入框被推挤上移、强制刷新恢复):
- 根因:新组件实例重跑 locate 时壳的 centerCol 尚未就绪,而壳重建
  复用 #root 子节点(childList 观察器不触发)→ centerRect 卡 {0,0}
  → 底栏 visibility:hidden 永久空白
- 修复:额外观察 <html> 的 style 属性(layout push 写回 --dsh-sidebar-*
  时重定位重测);底栏打开时 effect 重跑 locate/measure 兜底
- 底栏未测量时由「不渲染」改为 visibility:hidden(渲染链不被几何
  门控,jsdom 测试不回归)

e2e 新增:极快拖动(单 move 立即 up)提交拖动位置、稳定后不回退

* feat(plugins): 添加插件目录支持搜索/分组/独立滚动(多插件场景)

- PluginListBody 顶部加实时搜索框(按名称/id/描述过滤,空结果提示)
- PluginEntry 增加可选 category 分组字段(i18n 友好),目录条目按组
  渲染(未分类条目保持平铺);数量徽标跟随过滤结果
- 条目列表 max-height + overflow-y 独立滚动,插件多时弹窗不再无限
  增长;渲染数量由搜索天然收敛
- locales zh/en(搜索占位、无匹配);测试文件固定英文环境
  (vitest 4.1.11+ jsdom 跟随系统 locale,本机 zh-CN 导致英文文案
  断言漂移)

* chore(deps): 适配 pnpm 11.8 supply-chain 校验(exclude 通配)

pnpm 11.8.0 起对 lockfile 既有条目强制 minimumReleaseAge 校验,
且精确 exclude(@scope/pkg@version)对带 peer 依赖后缀的解析条目
匹配失效(44 条误报违规,CI 全红)。@deepseek-ai/* scope 为官方
可信 scope,minimumReleaseAgeExclude 改为 '@deepseek-ai/*' 通配
(保留 rc.1 历史与 stable 条目);通配经实测通过全部 504 条校验。

* docs: v0.14.0 changelog 补全(自 v0.13.1 全部更改 + 特别声明 rc.8 适配)

新增条目:终端 shell/shellArgs 设置页配置、设置页版本徽标、
添加插件目录搜索/分组/滚动、rc.8 模块系统迁移、拖拽健壮性修复;
版本说明块醒目声明本版适配 DSH 0.1.0-rc.8(rc.7 及更早无法解析依赖)
This commit is contained in:
Atlas Zeng
2026-08-20 02:09:36 +08:00
committed by GitHub
parent 14ef8e4df8
commit 6c891514b5
48 changed files with 2610 additions and 1240 deletions
+3
View File
@@ -55,6 +55,9 @@ if (g.window === undefined) {
innerWidth: 1024,
innerHeight: 768,
getComputedStyle: () => ({ getPropertyValue: () => '' }),
// desktop-env.ts reads the shell's URL stamps from location.search
// (Sidebar renders with parseDesktopEnv even in specs).
location: { search: '' },
}
}
+14 -8
View File
@@ -67,19 +67,25 @@ describe('built-in tab registrations', () => {
expect(options.every(o => o.icon !== undefined && o.title !== undefined)).toBe(true)
})
it('the terminal tab declares the model terminal-tools, auto-terminal and custom-font settings', () => {
it('the terminal tab declares the model terminal-tools, auto-terminal, shell and custom-font settings', () => {
const { service } = setup()
const toggles = service.getTab('terminal')?.settings?.toggles ?? []
expect(toggles.map(t => t.key)).toEqual(['agentTerminalTools', 'bottomPanelAutoTerminal', 'terminalFontFamily', 'terminalFontSize'])
// The font rows are text/number inputs (not switches), with the size
// row bounded by the shared 9–32 contract.
expect(toggles.map(t => t.key)).toEqual(['agentTerminalTools', 'bottomPanelAutoTerminal', 'terminalShell', 'terminalShellArgs', 'terminalFontFamily', 'terminalFontSize'])
// The shell rows are text inputs (empty = yaml/auto resolution), the
// font rows text/number inputs (not switches), with the size row bounded
// by the shared 9–32 contract.
expect(toggles[2]?.type).toBe('text')
expect(toggles[2]?.title).toBeDefined()
expect(toggles[2]?.placeholder).toBeDefined()
expect(toggles[3]?.type).toBe('number')
expect(toggles[3]?.min).toBe(9)
expect(toggles[3]?.max).toBe(32)
expect(toggles[3]?.unit).toBe('px')
expect(toggles[3]?.type).toBe('text')
expect(toggles[3]?.title).toBeDefined()
expect(toggles[4]?.type).toBe('text')
expect(toggles[4]?.title).toBeDefined()
expect(toggles[4]?.placeholder).toBeDefined()
expect(toggles[5]?.type).toBe('number')
expect(toggles[5]?.min).toBe(9)
expect(toggles[5]?.max).toBe(32)
expect(toggles[5]?.unit).toBe('px')
// The first two rows stay plain boolean switches.
expect(toggles[0]?.type ?? 'switch').toBe('switch')
expect(toggles[1]?.type ?? 'switch').toBe('switch')
+216 -3
View File
@@ -18,13 +18,15 @@ import {
CHUNK_EXTERNALS,
loadChunk,
registerChunkForTests,
revalidateChunksOnReactivate,
resetChunks,
setChunkModuleSystem,
setChunkScriptLoaderForTests,
} from '../src/client/chunk-loader.ts'
import type { ChunkExports } from '../src/client/chunk-loader.ts'
interface FakeModuleSystem {
import: ReturnType<typeof vi.fn>
import: (specifier: string) => Promise<unknown>
}
function installModuleSystem(): FakeModuleSystem {
@@ -53,6 +55,7 @@ function simulateScript(name: string, factory: (require: (spec: string) => unkno
beforeEach(() => {
removeModuleSystem()
setChunkModuleSystem(undefined)
delete (globalThis as Record<string, unknown>).__dshChunks__
resetChunks()
setChunkScriptLoaderForTests(null)
@@ -89,6 +92,34 @@ describe('test-registry path (vitest / jsdom-less environments)', () => {
})
describe('production path (script injection + global registry + externals require)', () => {
it('resolves externals through an injected ctx.modules system (rc.8 — no page global)', async () => {
const modules = installModuleSystem()
// rc.8 drops window.__DSH_MODULES__; the client half injects ctx.modules.
removeModuleSystem()
setChunkModuleSystem(modules)
const loaded: string[] = []
setChunkScriptLoaderForTests(async (src) => {
loaded.push(src)
simulateScript('editor', (require) => ({ TextEditor: `view:${String(require('react'))}` }))
})
const exports = await loadChunk('editor')
expect(loaded).toEqual(['/sidebar/bundle/editor.js'])
expect(exports).toEqual({ TextEditor: 'view:[object Object]' })
expect(modules.import).toHaveBeenCalledTimes(CHUNK_EXTERNALS.length)
// The injection also lands on a plugin-owned global so chunk-bundle
// copies of this loader (which inline their own module instance and
// never run apply()) can resolve externals too — rc.8 has no shell
// page global anymore.
expect((globalThis as Record<string, unknown>).__dshSidebarModuleSystem__).toBe(modules)
// The injection survives resetChunks (shell state, not chunk state).
resetChunks()
setChunkScriptLoaderForTests(async () => {
simulateScript('editor', () => ({ TextEditor: 'editor-view' }))
})
await loadChunk('editor')
expect(modules.import).toHaveBeenCalledTimes(CHUNK_EXTERNALS.length * 2)
})
it('injects the chunk script, then materializes the factory with externals from the module table', async () => {
const modules = installModuleSystem()
const loaded: string[] = []
@@ -192,6 +223,190 @@ describe('production path (script injection + global registry + externals requir
})
})
describe('revalidateChunksOnReactivate (HMR re-activation keeps unchanged chunks)', () => {
/** Stub the bundle route's HEAD endpoint with per-name ETags (Error = unreachable). */
function stubBundleHead(etagFor: (name: string) => string | null | Error): void {
vi.stubGlobal('fetch', vi.fn(async (input: unknown) => {
const url = String(input)
const name = url.endsWith('terminal.js') ? 'terminal' : 'editor'
const etag = etagFor(name)
if (etag instanceof Error) throw etag
return {
headers: { get: (key: string) => (key.toLowerCase() === 'etag' ? etag : null) },
} as unknown as Response
}))
}
/** Let the fire-and-forget ETag recorder (recordEtag) settle. */
const settleEtag = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5))
it('keeps the resolved exports of an unchanged chunk — no re-inject / re-execute', async () => {
installModuleSystem()
let scriptCalls = 0
setChunkScriptLoaderForTests(async () => {
scriptCalls += 1
simulateScript('editor', () => ({ TextEditor: 'editor-view' }))
})
stubBundleHead(() => '"v1"')
const first = await loadChunk('editor')
expect(scriptCalls).toBe(1)
await settleEtag()
await revalidateChunksOnReactivate()
const second = await loadChunk('editor')
expect(second).toBe(first)
expect(scriptCalls).toBe(1)
})
it('drops a chunk whose ETag changed on disk — the next open re-injects and re-executes', async () => {
installModuleSystem()
let scriptCalls = 0
setChunkScriptLoaderForTests(async () => {
scriptCalls += 1
simulateScript('editor', () => ({ TextEditor: `editor-view:${scriptCalls}` }))
})
let etag = '"v1"'
stubBundleHead(() => etag)
const first = await loadChunk('editor')
await settleEtag()
etag = '"v2"'
await revalidateChunksOnReactivate()
const second = await loadChunk('editor')
expect(second).not.toBe(first)
expect(scriptCalls).toBe(2)
})
it('fails open when revalidation cannot reach the bundle route', async () => {
installModuleSystem()
let scriptCalls = 0
setChunkScriptLoaderForTests(async () => {
scriptCalls += 1
simulateScript('terminal', () => ({ TerminalView: 'tv' }))
})
stubBundleHead(() => new Error('HEAD unreachable'))
await loadChunk('terminal')
await settleEtag()
await revalidateChunksOnReactivate()
await loadChunk('terminal')
expect(scriptCalls).toBe(2)
})
it('loadChunk is a barrier: a pending revalidation never serves stale exports (CR P1)', async () => {
installModuleSystem()
let scriptCalls = 0
setChunkScriptLoaderForTests(async () => {
scriptCalls += 1
simulateScript('editor', () => ({ TextEditor: `editor-view:${scriptCalls}` }))
})
// First load: etag "v1", recorded after settlement.
let etag = '"v1"'
stubBundleHead(() => etag)
const first = await loadChunk('editor')
await settleEtag()
expect(scriptCalls).toBe(1)
// The chunk changed on disk; the revalidation HEAD is gated (pending).
etag = '"v2"'
let release: (() => void) | undefined
const gate = new Promise<void>((resolve) => { release = resolve })
vi.stubGlobal('fetch', vi.fn(async () => {
await gate
return { headers: { get: () => etag } } as unknown as Response
}))
const revalidating = revalidateChunksOnReactivate()
// A lazy open DURING the pending revalidation must NOT get the old cache.
let resolved = false
let pendingLoad: Promise<ChunkExports> | null = null
pendingLoad = loadChunk('editor').then((exports) => { resolved = true; return exports })
await new Promise((resolve) => setTimeout(resolve, 5))
expect(resolved, 'loadChunk must await the pending revalidation').toBe(false)
// Release the HEAD; the barrier lifts and the load re-injects fresh exports.
release?.()
await revalidating
const after = await pendingLoad
expect(after).not.toBe(first)
expect(scriptCalls).toBe(2)
})
it('a HEAD that never answers is bounded by a timeout signal and fails open (barrier cannot wedge loads forever)', async () => {
installModuleSystem()
let scriptCalls = 0
setChunkScriptLoaderForTests(async () => {
scriptCalls += 1
simulateScript('editor', () => ({ TextEditor: `editor-view:${scriptCalls}` }))
})
// First load settles an ETag under a healthy HEAD route.
stubBundleHead(() => '"v1"')
const first = await loadChunk('editor')
await settleEtag()
expect(scriptCalls).toBe(1)
// The revalidation HEAD now hangs. The loader must hand the fetch a
// timeout signal and, when it fires, fail open (drop + re-fetch) — the
// barrier must never block lazy loads indefinitely.
const controller = new AbortController()
const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(controller.signal)
vi.stubGlobal('fetch', vi.fn(async (_input, init?: RequestInit) => {
await new Promise<void>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(new DOMException('timed out', 'AbortError')))
})
}))
const revalidating = revalidateChunksOnReactivate()
let resolved = false
const pendingLoad = loadChunk('editor').then((exports) => { resolved = true; return exports })
await new Promise((resolve) => setTimeout(resolve, 5))
expect(resolved, 'loadChunk must await the pending revalidation').toBe(false)
controller.abort() // the timeout fires
await revalidating
const after = await pendingLoad
expect(after).not.toBe(first)
expect(scriptCalls).toBe(2)
expect(timeoutSpy).toHaveBeenCalledWith(expect.any(Number))
timeoutSpy.mockRestore()
})
it('resetChunks clears a pending revalidation barrier (the next load does not wait on the orphaned task)', async () => {
installModuleSystem()
let scriptCalls = 0
setChunkScriptLoaderForTests(async () => {
scriptCalls += 1
simulateScript('editor', () => ({ TextEditor: `editor-view:${scriptCalls}` }))
})
let etag = '"v1"'
stubBundleHead(() => etag)
await loadChunk('editor')
await settleEtag()
// Gate the revalidation HEAD so the barrier stays pending.
let release: (() => void) | undefined
const gate = new Promise<void>((resolve) => { release = resolve })
vi.stubGlobal('fetch', vi.fn(async () => {
await gate
return { headers: { get: () => etag } } as unknown as Response
}))
const revalidating = revalidateChunksOnReactivate()
// resetChunks mid-revalidation: the barrier guarded only the state being
// dropped, so the next load must proceed without waiting for the HEAD.
resetChunks()
const after = await loadChunk('editor')
expect(after).toEqual({ TextEditor: 'editor-view:2' })
expect(scriptCalls).toBe(2)
// The orphaned task still settles; its identity-guarded finally no-ops.
// (Its sweep may later drop the freshly loaded entry — chunkEtags was
// cleared by resetChunks, so the old ETag no longer matches. That is the
// fail-safe direction: never serve stale, at worst one redundant fetch.)
release?.()
await revalidating
})
it('clears test-registry fixtures on re-activation (per-test stubs never leak)', async () => {
let testCalls = 0
registerChunkForTests('editor', async () => { testCalls += 1; return { TextEditor: 'test-view' } })
await loadChunk('editor')
expect(testCalls).toBe(1)
await revalidateChunksOnReactivate()
// Test fixture gone: the production path runs and fails fast (no module system).
await expect(loadChunk('editor')).rejects.toThrow('client module system unavailable')
expect(testCalls).toBe(1)
})
})
describe('externals contract', () => {
it('the loader resolves exactly the platform externals the chunk builds keep external', () => {
expect(CHUNK_EXTERNALS).toEqual([
@@ -201,9 +416,7 @@ describe('externals contract', () => {
'react-dom/client',
'cordis',
'@deepseek-ai/dsh-client-ui-slots',
'@deepseek-ai/dsh-client-web-react',
'@deepseek-ai/dsh-client-ui-primitives',
'@deepseek-ai/dsh-client-schema-form',
'@deepseek-ai/dsh-client-runtime/client',
])
})
+72
View File
@@ -0,0 +1,72 @@
/**
* Desktop-shell detection tests: URL stamps (dsh-desktop-mode/platform)
* from the official Electron shell, the preload marker
* (__DSH_DESKTOP_FILE_PATH__), and the win32 advanced overlay adaptation.
*/
import { beforeEach, describe, expect, it } from 'vitest'
import './browser-globals.ts'
import { parseDesktopEnv, resetDesktopEnvForTests } from '../src/client/desktop-env.ts'
function setSearch(search: string): void {
;(window.location as { search: string }).search = search
}
beforeEach(() => {
resetDesktopEnvForTests()
delete (window as unknown as Record<string, unknown>).__DSH_DESKTOP_FILE_PATH__
setSearch('/')
})
describe('parseDesktopEnv', () => {
it('reports a plain browser page as non-desktop', () => {
expect(parseDesktopEnv()).toEqual({ desktop: false, mode: null, platform: null, win32OverlayTop: 0 })
})
it('parses win32 advanced stamps with the 32px window-control overlay', () => {
setSearch('?dsh-desktop-mode=advanced&dsh-desktop-platform=win32')
const env = parseDesktopEnv()
expect(env.desktop).toBe(true)
expect(env.mode).toBe('advanced')
expect(env.platform).toBe('win32')
expect(env.win32OverlayTop).toBe(32)
})
it('parses darwin advanced stamps without an overlay (traffic lights are top-left)', () => {
setSearch('?dsh-desktop-mode=advanced&dsh-desktop-platform=darwin')
const env = parseDesktopEnv()
expect(env.desktop).toBe(true)
expect(env.platform).toBe('darwin')
expect(env.win32OverlayTop).toBe(0)
})
it('parses compatibility mode as desktop with the native frame (no adaptation)', () => {
setSearch('?dsh-desktop-mode=compatibility&dsh-desktop-platform=win32')
const env = parseDesktopEnv()
expect(env.desktop).toBe(true)
expect(env.mode).toBe('compatibility')
expect(env.win32OverlayTop).toBe(0)
})
it('detects the desktop preload marker even without URL stamps', () => {
;(window as unknown as Record<string, unknown>).__DSH_DESKTOP_FILE_PATH__ = { getPathForFile: () => '' }
const env = parseDesktopEnv()
expect(env.desktop).toBe(true)
expect(env.mode).toBeNull()
expect(env.win32OverlayTop).toBe(0)
})
it('ignores unknown mode values (exotic shells keep plain-browser semantics)', () => {
setSearch('?dsh-desktop-mode=weird&dsh-desktop-platform=win32')
expect(parseDesktopEnv().mode).toBeNull()
expect(parseDesktopEnv().desktop).toBe(false)
})
it('memoizes across calls until the test hook resets', () => {
setSearch('?dsh-desktop-mode=advanced&dsh-desktop-platform=win32')
const first = parseDesktopEnv()
setSearch('/')
expect(parseDesktopEnv()).toBe(first)
resetDesktopEnvForTests()
expect(parseDesktopEnv().desktop).toBe(false)
})
})
+103
View File
@@ -256,3 +256,106 @@ test('width drag tracks the shell 1:1 with transitions disabled (issue #92)', as
const convoTravel = first!.convoRight - last!.convoRight
expect(Math.abs(convoTravel - stripTravel), 'conversation must track the panel edge 1:1').toBeLessThanOrEqual(8)
})
test('a very fast width drag still commits the dragged position (no rollback on quick release)', async ({ page }) => {
await page.goto(BASE_URL, { waitUntil: 'domcontentloaded' })
await expect(page.locator('#root > *')).not.toHaveCount(0, { timeout: 90_000 })
const sidebar = page.locator('[data-dsh-better-sidebar]')
await expect(sidebar).toBeAttached({ timeout: 90_000 })
// Dismiss whatever onboarding takeover is present (same dance as the
// main lane) so the pointer can reach the strip.
try {
await expect
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
.toBeGreaterThan(0)
} catch {
console.warn('[e2e-drag-fast] no onboarding takeover appeared; proceeding')
}
for (let round = 0; round < 8; round++) {
let dismissed = false
for (const name of ['Continue', 'Configure later']) {
const button = page.getByRole('button', { name, exact: true }).first()
if ((await button.count()) === 0) continue
try {
await button.click({ timeout: 4_000 })
dismissed = true
await page.waitForTimeout(1_000)
} catch {
// Masked by a takeover stacked above; retry in the next round.
}
}
if (!dismissed) break
}
const expandButton = sidebar.getByRole('button', { name: 'Expand sidebar' })
await expect(expandButton, 'the collapsed toggle cluster must offer the expand button').toHaveCount(1)
await expandButton.click()
await expect
.poll(async () => {
const value = await page.evaluate(() => document.documentElement.style.getPropertyValue('--dsh-sidebar-width'))
return value !== '' && value !== '0px'
}, { timeout: 90_000 })
.toBe(true)
const readWidth = (): Promise<number> => page.evaluate(() => {
const value = parseFloat(document.documentElement.style.getPropertyValue('--dsh-sidebar-width'))
return Number.isNaN(value) ? 0 : value
})
const widthBefore = await readWidth()
const stripBox = await page.evaluate(() => {
const host = document.querySelector('[data-dsh-better-sidebar]')
if (host === null) return null
const boxes = [...host.querySelectorAll('*')]
.filter(el => getComputedStyle(el).cursor === 'col-resize')
.map(el => el.getBoundingClientRect())
.filter(r => r.width > 0 && r.height > 0)
.sort((a, b) => a.x - b.x)
const r = boxes[0]
if (r === undefined) return null
const varWidth = parseFloat(document.documentElement.style.getPropertyValue('--dsh-sidebar-width'))
return {
x: r.x, y: r.y, width: r.width, height: r.height,
varWidth: Number.isNaN(varWidth) ? 0 : varWidth,
innerWidth: window.innerWidth,
}
})
expect(stripBox, 'the width drag strip must be present').not.toBeNull()
await expect
.poll(async () => {
const box = await page.evaluate(() => {
const host = document.querySelector('[data-dsh-better-sidebar]')
const el = [...host!.querySelectorAll('*')]
.filter(e => getComputedStyle(e).cursor === 'col-resize')
.map(e => e.getBoundingClientRect())
.filter(r => r.width > 0 && r.height > 0)
.sort((a, b) => a.x - b.x)[0]
return el === undefined ? null : { x: el.x + el.width, innerWidth: window.innerWidth }
})
if (box === null) return false
const varWidth = await page.evaluate(() => parseFloat(document.documentElement.style.getPropertyValue('--dsh-sidebar-width')) || 0)
return Math.abs(box.x - (box.innerWidth - varWidth)) <= 8
}, { timeout: 30_000 })
.toBe(true)
const startX = stripBox!.x + stripBox!.width / 2
const startY = stripBox!.y + Math.min(120, stripBox!.height / 2 + 60)
// FAST release: a single move and an immediate up — no per-frame waits,
// so the last pointermove may never reach a requestAnimationFrame before
// the release (the exact quick-flick that used to roll back to the
// pre-drag width).
await page.mouse.move(startX, startY)
await page.mouse.down()
await page.mouse.move(startX - 140, startY, { steps: 1 })
await page.mouse.up()
// The committed width must reflect the drag — and stay there (no rollback
// once React settles).
await expect
.poll(async () => await readWidth(), { timeout: 10_000 })
.toBeGreaterThan(widthBefore + 100)
await page.waitForTimeout(600)
expect(await readWidth(), 'the fast drag must not roll back after settling').toBeGreaterThan(widthBefore + 100)
})
+64 -19
View File
@@ -16,11 +16,11 @@
* 4. expands the collapsed panel (openByDefault defaults off), sweeps every
* built-in tab (Files / Source Control / Tasks / Terminal / Browser) —
* including the lazily-fetched terminal chunk — and then opens seeded
* files through the Files window's tree (in-place mode: the seeded home
* tab itself switches to the file, no new tab), while response waits
* armed before goto prove the lazily-fetched editor chunk
* (client-editor.js) and the mermaid chunk (client-mermaid.js, rendered
* SVG diagram + zoom modal) loaded.
* files through the Files window's tree (separate mode: each file opens
* its own new tab, the seeded home "Files" tab stays the explorer),
* while response waits armed before goto prove the lazily-fetched editor
* chunk (client-editor.js) and the mermaid chunk (client-mermaid.js,
* rendered SVG diagram + zoom modal) loaded.
*
* Deterministic by construction: every wait is on a DOM/network marker, the
* suite is serial (one server instance), and any crash trips the very next
@@ -133,6 +133,9 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
await expect(page.locator('#root > *')).not.toHaveCount(0, { timeout: 90_000 })
const sidebar = page.locator('[data-dsh-better-sidebar]')
await expect(sidebar).toBeAttached({ timeout: 90_000 })
// The unified panel host: the fixed containing block every panel lives in
// (data-dsh-panel-host). Its presence is part of the injection contract.
await expect(page.locator('[data-dsh-panel-host]')).toBeAttached({ timeout: 90_000 })
// A keyless boot stacks onboarding takeovers that mask the whole shell: a
// versioned welcome notice ("Continue", persists its acknowledgement to
@@ -193,14 +196,16 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
await expect
.poll(async () => pageErrors, { timeout: 5_000 })
.toEqual([])
const strips = await sidebar.locator('div').evaluateAll(
// Fail with the actual strip text so a regression is diagnosable from
// the test report alone (a strip renders the client fail() message).
const stripTexts = await sidebar.locator('div').evaluateAll(
(nodes, patterns) => nodes.filter((node) => {
const text = (node.textContent ?? '').trim()
return patterns.some((pattern) => pattern.test(text))
}).length,
}).map((node) => (node.textContent ?? '').trim()),
CRASH_STRIP_PATTERNS,
)
expect(strips, 'a dsh-better-sidebar error strip is present in the sidebar').toBe(0)
expect(stripTexts, 'a dsh-better-sidebar error strip is present in the sidebar').toEqual([])
}
// Sweep every built-in tab through the "+" menu (the sidebar's own open-tab
@@ -236,7 +241,7 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
await expect(filesTab, 'the seeded files-window home tab must be in the tab strip').toHaveCount(1)
await filesTab.click()
// Inactive tabs stay mounted (display:none); only the ACTIVE files
// window's embedded tree is visible — match the visible row.
// window's tree is visible — match the visible row.
const fileRow = sidebar.locator(`[role="button"][title$="${SEEDED_FILE}"]:visible`)
await expect(fileRow, `the seeded "${SEEDED_FILE}" file must appear in the files window's tree`).toHaveCount(1, { timeout: 30_000 })
// Click near the row's LEFT edge: hovering reveals an @-reference button at
@@ -244,31 +249,53 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
// (referencing the file into the composer instead of opening it).
await fileRow.click({ position: { x: 8, y: 8 } })
await editorChunk
// In-place mode (editorExplorer default): the SAME tab switches to the
// file — its title is rewritten, no new tab appears. One "Files" tab
// remains: the second files window the sweep opened via the + menu.
// Separate-mode default (editorExplorer off): the tree click OPENS A NEW
// file tab (openSidebarFile, id `editor:<path>`) instead of rewriting the
// home tab in place. The seeded "Files" home tab stays put — it is the
// standalone explorer now, not a file window.
await expect(
sidebar.locator('[title="Files"][draggable="true"]'),
'in-place mode rewrites the activated home tab instead of opening a new one',
sidebar.locator(`[title="${SEEDED_FILE}"][draggable="true"]`),
'separate mode opens a new file tab for the tree click',
).toHaveCount(1)
// The seeded home tab survives (separate mode never rewrites it). The
// sweep's + menu opened a SECOND path-less Files window (each is its own
// explorer in separate mode), so assert presence, not an exact count.
await expect(
sidebar.locator('[title="Files"][draggable="true"]').first(),
'the seeded files-window home tab must survive the file open',
).toHaveCount(1)
const pathInput = sidebar.locator('input[placeholder^="File path"]:visible')
await expect(pathInput, 'the files window header path input shows the opened file').toHaveValue(new RegExp(`${SEEDED_FILE}$`))
await expect(pathInput, 'the file tab header path input shows the opened file').toHaveValue(new RegExp(`${SEEDED_FILE}$`))
await page.waitForTimeout(1_500)
await assertNoCrash()
// The mermaid chunk (client-mermaid.js) only loads when a previewed
// markdown file contains a mermaid fence. Open the seeded diagram file
// from the files window's tree (the embedded tree stays pinned while
// hello.txt is open) and require the full round-trip: chunk fetch +
// sanitized SVG diagram in the preview, so a missing/corrupt mermaid
// chunk or a broken render fails the lane.
// from the files window's tree and require the full round-trip: chunk
// fetch + sanitized SVG diagram in the preview, so a missing/corrupt
// mermaid chunk or a broken render fails the lane. In separate mode the
// tree click above activated the hello.txt tab, so switch back to the
// Files explorer first (its tree is the only one visible while active).
const mermaidChunk = page.waitForResponse(
(response) => response.url().includes('/sidebar/bundle/mermaid.js'),
{ timeout: 30_000 },
)
await sidebar.locator('[title="Files"][draggable="true"]').first().click()
const mdRow = sidebar.locator(`[role="button"][title$="${SEEDED_MD_FILE}"]:visible`)
await expect(mdRow, `the seeded "${SEEDED_MD_FILE}" file must appear in the files window's tree`).toHaveCount(1, { timeout: 30_000 })
await mdRow.click({ position: { x: 8, y: 8 } })
// Separate mode: the md file opens its own tab (like hello.txt above).
await expect(
sidebar.locator(`[title="${SEEDED_MD_FILE}"][draggable="true"]`),
'separate mode opens a new tab for the markdown file',
).toHaveCount(1, { timeout: 30_000 })
// The markdown PREVIEW must render before the mermaid chunk can be
// requested — this assertion separates a preview/render regression from a
// chunk-loading one. (sidebar is already scoped to [data-dsh-better-sidebar].)
await expect(
sidebar.getByText('tail text'),
'the markdown preview must render the seeded document',
).toHaveCount(1, { timeout: 30_000 })
await mermaidChunk
await expect(
sidebar.locator('[data-mermaid-diagram] svg'),
@@ -313,3 +340,21 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
// Final screenshot: the rendered panel with a session is the lane's proof.
await page.screenshot({ path: 'test-results/mount-final.png' })
})
test('desktop shell stamps auto-enable the win32 title-bar compatibility mode', async ({ page }) => {
// The official DSH Desktop shell stamps every render URL with
// dsh-desktop-mode / dsh-desktop-platform (and exposes a preload marker).
// The win32 advanced shell reserves a 32px overlay for the window
// controls where the toggle cluster sits — the sidebar must auto-drop
// below it (body[data-dsh-title-bar-compat]) without any manual pref.
await page.goto(`${BASE_URL}?dsh-desktop-mode=advanced&dsh-desktop-platform=win32`, { waitUntil: 'domcontentloaded' })
await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 90_000 })
await expect(
page.locator('body[data-dsh-title-bar-compat]'),
'win32 advanced shell must auto-enable title-bar compatibility',
).toBeAttached({ timeout: 90_000 })
// The strip variable must be sized to the shell's 32px overlay.
await expect
.poll(() => page.evaluate(() => document.documentElement.style.getPropertyValue('--dsh-title-bar-strip')))
.toBe('32px')
})
+6 -1
View File
@@ -21,7 +21,8 @@ import { allLeaves, createSidebarStore, type SidebarTab } from '../src/client/st
// The act() environment flag (React 18.2 reads it before flushing effects).
;(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true
/** A store with the seeded editor-home tab (default prefs: in-place mode). */
/** A store with the seeded editor-home tab (default prefs: separate mode;
* merged-mode scenarios re-enable editorExplorer explicitly). */
function setup(): {
store: ReturnType<typeof createSidebarStore>
ctx: Context
@@ -91,6 +92,7 @@ function typeAndCommit(input: HTMLInputElement, value: string): void {
describe('EditorHost (files window)', () => {
it('a path-less tab renders the empty-state hint with the tree panel open', () => {
const { store, ctx, homeTab } = setup()
store.setPrefs({ ...store.getPrefs(), editorExplorer: true })
const { container, unmount } = mountHost(ctx, store, homeTab)
try {
const html = container.innerHTML
@@ -112,6 +114,7 @@ describe('EditorHost (files window)', () => {
it('the tree toggle persists meta.treeOpen through updateTab', () => {
const { store, ctx, homeTab } = setup()
store.setPrefs({ ...store.getPrefs(), editorExplorer: true })
expect(homeTab().meta).toEqual({ treeOpen: true })
const { container, rerender, unmount } = mountHost(ctx, store, homeTab)
try {
@@ -136,6 +139,7 @@ describe('EditorHost (files window)', () => {
it('in-place mode: the path input Enter switches the CURRENT tab (stable id, meta kept)', () => {
const { store, ctx, homeTab } = setup()
store.setPrefs({ ...store.getPrefs(), editorExplorer: true })
const { container, unmount } = mountHost(ctx, store, homeTab)
try {
const before = homeTab()
@@ -217,6 +221,7 @@ describe('EditorHost (files window)', () => {
it('dragging the panel edge resizes the dock and persists meta.treeWidth on release', () => {
const { store, ctx, homeTab } = setup()
store.setPrefs({ ...store.getPrefs(), editorExplorer: true })
const { container, unmount } = mountHost(ctx, store, homeTab)
try {
const handle = container.querySelector('[role="separator"]')!
-2
View File
@@ -50,9 +50,7 @@ const CLIENT_REQUIRE_ALLOWED = new Set([
'react-dom/client',
'cordis',
'@deepseek-ai/dsh-client-ui-slots',
'@deepseek-ai/dsh-client-web-react',
'@deepseek-ai/dsh-client-ui-primitives',
'@deepseek-ai/dsh-client-schema-form',
'@deepseek-ai/dsh-client-runtime/client',
])
+4 -3
View File
@@ -76,14 +76,15 @@ describe('dsh-better-sidebar plugin export shape', () => {
// The enable-switch maps resolve to {} (everything on) for old documents.
expect(resolved.tabsEnabled).toEqual({})
expect(resolved.viewersEnabled).toEqual({})
// The merged editor-explorer mode defaults ON.
expect(resolved.editorExplorer).toBe(true)
// The separate file-window mode is the default (each file opens its own
// tab; the merged editor-explorer is opt-in).
expect(resolved.editorExplorer).toBe(false)
// A stored overridden value resolves through (the range contract is
// enforced by the settings service on write); the new pref keeps its
// default when the stored document predates it.
const overridden = (PrefsSchema as unknown as {
(input: Record<string, unknown> | undefined): Record<string, unknown>
})({ openByDefault: false, defaultWidthPercent: 45 })
expect(overridden).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
expect(overridden).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: false, terminalShell: '', terminalShellArgs: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
})
})
+19 -13
View File
@@ -42,7 +42,9 @@ describe('side card preferences', () => {
terminalFontFamily: '',
terminalFontSize: 13,
interceptOpenPath: true,
editorExplorer: true,
editorExplorer: false,
terminalShell: '',
terminalShellArgs: '',
titleBarCompat: false,
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
@@ -69,7 +71,9 @@ describe('side card preferences', () => {
terminalFontFamily: '',
terminalFontSize: 13,
interceptOpenPath: true,
editorExplorer: true,
editorExplorer: false,
terminalShell: '',
terminalShellArgs: '',
titleBarCompat: false,
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
@@ -96,7 +100,9 @@ describe('side card preferences', () => {
terminalFontFamily: '',
terminalFontSize: 13,
interceptOpenPath: true,
editorExplorer: true,
editorExplorer: false,
terminalShell: '',
terminalShellArgs: '',
titleBarCompat: false,
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
@@ -135,11 +141,11 @@ describe('side card preferences', () => {
expect((await loadPrefs(wire({ interceptOpenPath: true }))).interceptOpenPath).toBe(true)
})
it('defaults editorExplorer to true; only an explicit false restores the plain editor', async () => {
// Absent or malformed → on (the merged editor-explorer is the default).
expect((await loadPrefs(wire({}))).editorExplorer).toBe(true)
expect((await loadPrefs(wire({ editorExplorer: 'yes' }))).editorExplorer).toBe(true)
expect((await loadPrefs(wire({ editorExplorer: 0 }))).editorExplorer).toBe(true)
it('defaults editorExplorer to false; only an explicit true enables the merged editor-explorer', async () => {
// Absent or malformed → off (separate file windows are the default).
expect((await loadPrefs(wire({}))).editorExplorer).toBe(false)
expect((await loadPrefs(wire({ editorExplorer: 'yes' }))).editorExplorer).toBe(false)
expect((await loadPrefs(wire({ editorExplorer: 1 }))).editorExplorer).toBe(false)
// Explicit booleans survive verbatim.
expect((await loadPrefs(wire({ editorExplorer: false }))).editorExplorer).toBe(false)
expect((await loadPrefs(wire({ editorExplorer: true }))).editorExplorer).toBe(true)
@@ -217,9 +223,9 @@ describe('side card preferences', () => {
const store = createSidebarStore()
// Node environment: no window → the width falls back to PANEL_DEFAULT,
// while the open flag still follows the preference.
store.setPrefs({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
store.setPrefs({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, terminalShell: '', terminalShellArgs: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
store.setSession('fresh-session')
expect(store.getPrefs()).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
expect(store.getPrefs()).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, terminalShell: '', terminalShellArgs: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
const snapshot = store.getSnapshot()
expect(snapshot.sessionId).toBe('fresh-session')
expect(snapshot.state?.panelOpen).toBe(false)
@@ -255,7 +261,7 @@ describe('side card preferences', () => {
it('skips the default seed tab when the editor (files window) type is disabled', () => {
const store = createSidebarStore()
store.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: { editor: false }, viewersEnabled: {}, pluginSettings: {} })
store.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, terminalShell: '', terminalShellArgs: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: { editor: false }, viewersEnabled: {}, pluginSettings: {} })
store.setSession('no-editor')
const state = store.getSnapshot().state!
const tabs = allLeaves(state.splits).flatMap(leaf => leaf.tabs)
@@ -265,7 +271,7 @@ describe('side card preferences', () => {
// editorExplorer modes.
for (const editorExplorer of [true, false]) {
const openStore = createSidebarStore()
openStore.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer, titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
openStore.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer, terminalShell: '', terminalShellArgs: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
openStore.setSession(`with-editor-${editorExplorer}`)
const openTabs = allLeaves(openStore.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
expect(openTabs.map(tab => tab.type)).toEqual(['editor'])
@@ -275,7 +281,7 @@ describe('side card preferences', () => {
it('seeds the empty editor home tab (files window) in both editorExplorer modes', () => {
for (const editorExplorer of [true, false]) {
const store = createSidebarStore()
store.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer, titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
store.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer, terminalShell: '', terminalShellArgs: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
store.setSession(`fresh-${editorExplorer}`)
const tabs = allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
expect(tabs).toHaveLength(1)
+3 -1
View File
@@ -200,7 +200,9 @@ describe('FeatureSettingsRows select rows (interactive)', () => {
}
const { container, unmount } = mount(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs,
// Merged is the selected option for this scenario (the default is now
// separate — the anchor must render whatever value the prefs carry).
prefs: { ...prefs, editorExplorer: true },
onToggle: () => {},
onSelectValue: (t, next) => { commits.push([t.key, next]) },
}))
+10 -1
View File
@@ -14,10 +14,19 @@
* Rendered with renderToString (mount effects — the settings RPC sync — do
* not run in SSR; the initial store prefs are the render input).
*/
import { describe, expect, it } from 'vitest'
import { beforeAll, describe, expect, it } from 'vitest'
import { renderToString } from 'react-dom/server'
import { createElement } from 'react'
import { createSidebarStore, type SidebarStore } from '../src/client/state.ts'
// The copy assertions below are English; pin the browser language so the
// module-level t()/isZh() resolve en regardless of the host system locale
// (vitest 4.1.11+/jsdom follow the OS locale — zh-CN on this machine).
beforeAll(() => {
Object.defineProperty(navigator, 'language', {
value: 'en-US',
configurable: true,
})
})
import { createBetterSidebarService, type BetterSidebarService } from '../src/client/service.ts'
import { SIDEBAR_PREFS_DEFAULTS } from '../src/prefs-shared.ts'
import { FeatureSettingsRows, mergePluginSetting, SideCardSection, type SideCardSectionProps } from '../src/client/SideCardSection.tsx'
+3 -1
View File
@@ -604,7 +604,9 @@ describe('side card settings routes', () => {
terminalFontFamily: '',
terminalFontSize: 13,
interceptOpenPath: true,
editorExplorer: true,
editorExplorer: false,
terminalShell: '',
terminalShellArgs: '',
titleBarCompat: false,
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
+1 -1
View File
@@ -87,7 +87,7 @@ function mount(): { captured: CapturedTool[]; registry: FakeRegistry; dispose: (
},
} as unknown as Context
const registry = new FakeRegistry()
const dispose = registerTools(ctx, registry as unknown as AgentPtyRegistry, () => '/cwd')
const dispose = registerTools(ctx, registry as unknown as AgentPtyRegistry, () => '/cwd', () => ({}))
return { captured, registry, dispose: () => { dispose(); return disposeCount } }
}