merge: 合入最新 main(#353 agent-open-tools / #360 markdown-html-toc 等),解决 PR 合并性

# Conflicts:
#	src/client/EditorHost.tsx
#	tests/prefs.spec.ts
This commit is contained in:
HuanLinOTO committed 2026-08-24 16:41:02 +08:00
commit 15e90d936e
58 files changed
+2685 -91

No files matched your search

+232
View File
@@ -0,0 +1,232 @@
/**
* Unit tests for the `sidebar_open` tool layer: registry semantics
* (per-session queue, consume-on-send delivery, attach replay, drain) and
* the tool itself (URL/file/folder classification, relative-path resolution,
* schema-valid canonical output, target-tab gating). The registry is real;
* no WebSocket or browser is needed — the sender callbacks are captured.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { validateJsonSchemaValue, type ToolDefinition, type ToolRunContext } from '@deepseek-ai/dsh-tools'
import { AgentOpenRegistry, registerOpenTool } from '../src/agent-opens.ts'
import type { Context } from '../src/context-types.ts'
import { SIDEBAR_PREFS_DEFAULTS, type SidebarPrefs } from '../src/prefs-shared.ts'
/** One registration captured by the fake tools service. */
interface CapturedTool {
definition: ToolDefinition
}
/** A minimal ToolRunContext for one calling session. */
function exec(sessionId: string): ToolRunContext {
return {
signal: { throwIfAborted: () => {}, aborted: false },
agent: { session: { id: sessionId } },
} as unknown as ToolRunContext
}
/** Register the tool against a fake service + real registry. */
function mount(overrides: { prefs?: Partial<SidebarPrefs>; resolveCwd?: (sessionId: string) => string } = {}) {
const captured: CapturedTool[] = []
let disposeCount = 0
const ctx = {
tools: {
register: (tool: unknown): (() => void) => {
captured.push({ definition: tool as ToolDefinition })
return () => { disposeCount += 1 }
},
},
} as unknown as Context
const registry = new AgentOpenRegistry()
const prefs: SidebarPrefs = { ...SIDEBAR_PREFS_DEFAULTS, ...overrides.prefs }
const dispose = registerOpenTool(
ctx,
registry,
overrides.resolveCwd ?? (() => '/cwd'),
() => prefs,
)
return { captured, registry, prefs, dispose: () => { dispose(); return disposeCount } }
}
/** The captured definition for one tool name. */
function toolOf(captured: CapturedTool[], name: string): ToolDefinition {
const found = captured.find(candidate => candidate.definition.name === name)
if (found === undefined) throw new Error(`tool "${name}" was not registered`)
return found.definition
}
describe('AgentOpenRegistry', () => {
it('queues without a subscriber, replays on attach (consume-on-send), and reports delivered', () => {
const registry = new AgentOpenRegistry()
const queued = registry.enqueue('s1', 'folder', '/work/src', 'src')
expect(queued.delivered).toBe(false)
const received: unknown[] = []
const detach = registry.attach('s1', (request) => { received.push(request) })
expect(received).toHaveLength(1)
expect(received[0]).toMatchObject({ kind: 'folder', target: '/work/src', title: 'src', sessionId: 's1' })
// The request was consumed on send: a second attach sees nothing.
const later: unknown[] = []
const detach2 = registry.attach('s1', (request) => { later.push(request) })
expect(later).toHaveLength(0)
detach()
detach2()
})
it('delivers immediately and does not queue when a subscriber is attached', () => {
const registry = new AgentOpenRegistry()
const received: unknown[] = []
const detach = registry.attach('s2', (request) => { received.push(request) })
const result = registry.enqueue('s2', 'url', 'https://example.com/', 'example.com')
expect(result.delivered).toBe(true)
expect(received).toHaveLength(1)
// Consumed on send: a reconnect never replays (no duplicate browser tabs).
const later: unknown[] = []
const detach2 = registry.attach('s2', (request) => { later.push(request) })
expect(later).toHaveLength(0)
detach()
detach2()
})
it('owner-scopes the queue: one session never leaks into another', () => {
const registry = new AgentOpenRegistry()
registry.enqueue('s1', 'file', '/a.txt', 'a.txt')
const other: unknown[] = []
const detach = registry.attach('s2', (request) => { other.push(request) })
expect(other).toHaveLength(0)
const own: unknown[] = []
const detach2 = registry.attach('s1', (request) => { own.push(request) })
expect(own).toHaveLength(1)
detach()
detach2()
})
it('drainAll drops the queue and dispose drops subscribers', () => {
const registry = new AgentOpenRegistry()
registry.enqueue('s1', 'file', '/a.txt', 'a.txt')
registry.drainAll()
const received: unknown[] = []
const detach = registry.attach('s1', (request) => { received.push(request) })
expect(received).toHaveLength(0)
registry.dispose()
// After dispose the previously-returned disposer is a no-op (idempotent).
detach()
detach()
})
})
describe('sidebar_open tool', () => {
it('registers the single tool and the disposer unregisters it', () => {
const { captured, dispose } = mount()
expect(captured.map(candidate => candidate.definition.name)).toEqual(['sidebar_open'])
expect(dispose()).toBe(1)
expect(() => mount().dispose()).not.toThrow()
})
it('opens an existing file (schema-valid output, delivered with a subscriber)', async () => {
const dir = mkdtempSync(join(tmpdir(), 'sidebar-open-'))
try {
const file = join(dir, 'a.txt')
writeFileSync(file, 'hello')
const { captured, registry } = mount({ resolveCwd: () => dir })
const received: unknown[] = []
const detach = registry.attach('s1', (request) => { received.push(request) })
const tool = toolOf(captured, 'sidebar_open')
const value = await tool.execute({ target: file }, exec('s1'))
expect(value).toEqual({ kind: 'file', target: file, title: 'a.txt', delivered: true })
expect(validateJsonSchemaValue(tool.output.schema, value, 'value')).toEqual([])
expect(received).toHaveLength(1)
detach()
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('resolves a relative path against the session cwd and queues when no view is attached', async () => {
const dir = mkdtempSync(join(tmpdir(), 'sidebar-open-'))
try {
writeFileSync(join(dir, 'note.md'), '# hi')
const { captured, registry } = mount({ resolveCwd: () => dir })
const tool = toolOf(captured, 'sidebar_open')
const value = await tool.execute({ target: 'note.md' }, exec('s1'))
expect(value).toMatchObject({ kind: 'file', target: join(dir, 'note.md'), title: 'note.md', delivered: false })
// Queued: a later attach replays it.
const received: unknown[] = []
const detach = registry.attach('s1', (request) => { received.push(request) })
expect(received).toHaveLength(1)
detach()
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('classifies a directory as folder and applies a custom title', async () => {
const dir = mkdtempSync(join(tmpdir(), 'sidebar-open-'))
try {
const sub = join(dir, 'src')
mkdirSync(sub)
const { captured } = mount({ resolveCwd: () => dir })
const tool = toolOf(captured, 'sidebar_open')
const value = await tool.execute({ target: sub, title: 'Sources' }, exec('s1'))
expect(value).toEqual({ kind: 'folder', target: sub, title: 'Sources', delivered: false })
expect(validateJsonSchemaValue(tool.output.schema, value, 'value')).toEqual([])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('classifies an http(s) URL, titles it by hostname, and never stats it', async () => {
const { captured } = mount()
const tool = toolOf(captured, 'sidebar_open')
const value = await tool.execute({ target: 'https://example.com/docs' }, exec('s1'))
expect(value).toEqual({ kind: 'url', target: 'https://example.com/docs', title: 'example.com', delivered: false })
})
it('rejects non-http(s) schemes', async () => {
const { captured } = mount()
const tool = toolOf(captured, 'sidebar_open')
for (const target of ['javascript:alert(1)', 'file:///etc/passwd', 'vscode://file/x']) {
await expect(tool.execute({ target }, exec('s1'))).rejects.toThrow(/only accepts http/)
}
})
it('reports a missing local path instead of opening it', async () => {
const { captured } = mount({ resolveCwd: () => '/definitely/missing' })
const tool = toolOf(captured, 'sidebar_open')
await expect(tool.execute({ target: '/definitely/missing/nope.txt' }, exec('s1')))
.rejects.toThrow(/does not exist/)
})
it('refuses a disabled target tab type with a clear cause', async () => {
const { captured } = mount({ prefs: { tabsEnabled: { browser: false } } })
const tool = toolOf(captured, 'sidebar_open')
await expect(tool.execute({ target: 'https://example.com/' }, exec('s1')))
.rejects.toThrow(/browser tab is disabled/)
const dir = mkdtempSync(join(tmpdir(), 'sidebar-open-'))
try {
writeFileSync(join(dir, 'f.txt'), 'x')
const { captured: fileCaptured } = mount({ resolveCwd: () => dir, prefs: { tabsEnabled: { editor: false } } })
const fileTool = toolOf(fileCaptured, 'sidebar_open')
// A URL is unaffected by the editor gate; a path is refused with cause.
await expect(fileTool.execute({ target: 'https://example.com/' }, exec('s1'))).resolves.toMatchObject({ kind: 'url' })
await expect(fileTool.execute({ target: 'f.txt' }, exec('s1'))).rejects.toThrow(/editor tab is disabled/)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('throws the canonical no-agent error when executed without an agent', async () => {
const { captured } = mount()
const tool = toolOf(captured, 'sidebar_open')
await expect(tool.execute({ target: '/tmp/x' }, { signal: { throwIfAborted: () => {}, aborted: false } } as unknown as ToolRunContext))
.rejects.toThrow(/requires an initiating agent/)
})
})
+13 -3
View File
@@ -44,6 +44,9 @@ interface MountedSidebar {
}
/** Mount the real Sidebar shell against a minimal context (real store + service). */
/** Unique per-test session ids (see the comment inside). */
let sessionSeq = 0
function mountSidebar(): MountedSidebar {
vi.stubGlobal('WebSocket', FakeWebSocket)
const container = document.createElement('div')
@@ -52,14 +55,18 @@ function mountSidebar(): MountedSidebar {
const service = createBetterSidebarService(store)
// Fresh-session seed: the right panel starts OPEN, the bottom panel closed
// (bottomOpen false → the first expansion is a false→true TRANSITION).
store.setSession('s1')
// Unique session per test — the store persists per-session state to
// localStorage (200ms debounce); a shared id lets a previous test's late
// write leak into this store's setSession restore.
const sessionId = `s1-${++sessionSeq}`
store.setSession(sessionId)
// useSyncExternalStore requires STABLE snapshots across calls (the real DSH
// services return stable objects) — a fresh object per call loops forever.
const localeSnapshot = { active: 'en' }
const sessionsSnapshot = {
current: 's1',
current: sessionId,
// cwd present → api.sessionCwd is never called in these tests.
byId: { s1: { cwd: '/tmp' } },
byId: { [sessionId]: { cwd: '/tmp' } },
}
const ctx = {
locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot },
@@ -82,6 +89,9 @@ function mountSidebar(): MountedSidebar {
afterEach(() => {
document.body.innerHTML = ''
// Belt and braces: drop any persisted layout a pending 200ms debounce
// write left behind between tests (unique session ids already isolate).
localStorage.clear()
vi.unstubAllGlobals()
})
+109
View File
@@ -48,6 +48,11 @@ const SEEDED_FILE = 'hello.txt'
* and render a sanitized SVG diagram. */
const SEEDED_MD_FILE = 'diagram.md'
/** A GitHub-style README markdown (badge div, <details> nesting markdown,
* inline tags in table cells), opened through the Files window's tree to
* prove raw-HTML runs render as sanitized DOM and the TOC outline works. */
const SEEDED_README_FILE = 'readme-style.md'
/**
* The plugin's crash markers. The client mounts inside an error boundary that
* renders a strip whose text starts with these prefixes instead of crashing
@@ -87,6 +92,41 @@ async function seedSession(): Promise<void> {
'tail text',
'',
].join('\n'))
// The README-style probe file: raw-HTML runs (badge wall div with an
// embedded script, a <details> nesting a fence + heading) plus inline tags
// inside a table cell. The script must be sanitized away in the preview.
writeFileSync(join(WORKSPACE_PATH, SEEDED_README_FILE), [
'# Readme Style',
'',
'<div align="center">',
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
' <script>alert(1)</script>',
'</div>',
'',
'## Setup',
'',
'[docs link][def]',
'',
'<details>',
'<summary><b>Steps</b></summary>',
'',
'### Inside',
'',
'```sh',
'dsh plugin --profile web add x',
'```',
'',
'</details>',
'',
'## Table',
'',
'| col | note |',
'| --- | --- |',
'| alpha | line one<br/>line two |',
'',
'[def]: https://example.com/def',
'',
].join('\n'))
const workspace = await api.post(`${BASE_URL}/api/workspace.create`, {
data: { type: 'client-request', rpcId: 'e2e-workspace', method: 'workspace.create', payload: { path: WORKSPACE_PATH } },
})
@@ -433,6 +473,75 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
).toBeHidden()
await assertNoCrash()
// README-style markdown (raw-HTML runs + TOC): open the seeded file and
// require the full round-trip — sanitized HTML leaves (badge image as a
// real element, active content stripped), markdown nested inside the
// unclosed <details> run, the inline pass turning the table cell's <br/>
// into an element, the reference link resolving across the HTML run, and
// the TOC outline jumping into the collapsed details (auto-expanding it).
await sidebar.locator('[title="Files"][draggable="true"]').first().click()
const readmeRow = sidebar.locator(`[role="button"][title$="${SEEDED_README_FILE}"]:visible`)
await expect(
readmeRow,
`the seeded "${SEEDED_README_FILE}" file must appear in the files window's tree`,
).toHaveCount(1, { timeout: 30_000 })
await readmeRow.click({ position: { x: 8, y: 8 } })
await expect(
sidebar.locator(`[title="${SEEDED_README_FILE}"][draggable="true"]`),
'separate mode opens a new tab for the README-style markdown file',
).toHaveCount(1, { timeout: 30_000 })
// The hero div renders as a sanitized leaf with the badge image as a real
// element (the remote src may not load in the sandboxed lane; the ELEMENT
// is the proof of rendering, not the bytes).
await expect(
sidebar.locator('[data-dsh-html-segment] img[src*="img.shields.io"]'),
'the badge-wall div must render its image as a real element',
).toHaveCount(1, { timeout: 30_000 })
// Active content never survives sanitization.
await expect(
sidebar.locator('script'),
'the embedded <script> must be sanitized away',
).toHaveCount(0)
// The unclosed <details> run lowers the following markdown inside itself.
const details = sidebar.locator('details')
await expect(
details,
'the details run must render as a real element',
).toHaveCount(1, { timeout: 30_000 })
await expect(details.locator('summary'), 'the details summary must render').toHaveCount(1)
await expect(
details.locator('h3', { hasText: 'Inside' }),
'the heading between the details tags must nest inside the element',
).toHaveCount(1)
// The inline pass: the table cell's literal <br/> became a real element.
await expect(
sidebar.locator('[data-html-inline] br'),
'the table cell <br/> must render as a real element',
).toHaveCount(1, { timeout: 30_000 })
// The reference link resolves although its definition sits after an HTML run.
await expect(
sidebar.locator('a[href="https://example.com/def"]'),
'reference links must resolve across lifted HTML runs',
).toHaveCount(1, { timeout: 30_000 })
// TOC: the outline button appears (4 headings), opens the panel, and
// jumping into the collapsed details expands it.
const tocButton = sidebar.locator('[data-dsh-md-toc]')
await expect(
tocButton,
'the TOC button must appear once the document has enough headings',
).toHaveCount(1, { timeout: 30_000 })
await tocButton.click()
const tocPanel = sidebar.locator('[data-dsh-md-toc-panel]')
await expect(tocPanel, 'the TOC panel must open').toHaveCount(1)
const insideItem = tocPanel.locator('button', { hasText: 'Inside' })
await expect(insideItem, 'the nested heading must appear in the outline').toHaveCount(1)
await insideItem.click()
await expect(
details,
'jumping into a collapsed details must expand it',
).toHaveAttribute('open', '')
await assertNoCrash()
// The plugin's own console prefix must never appear in errors, and no
// unhandled rejection may escape the sweep.
const pluginErrors = consoleErrors.filter((text) => /dsh-better-sidebar|Unhandled/.test(text))
+27
View File
@@ -294,4 +294,31 @@ describe('EditorHost (files window)', () => {
unmount()
}
})
it('a folder tab (meta.dir) renders the tree rooted at the folder, no editor chrome', () => {
const { store, ctx } = setup()
ctx.betterSidebar!.openTab({
type: 'editor',
title: 'src',
path: '/work/src',
id: 'editor:/work/src',
meta: { dir: true },
}, { sessionId: 'editor-home-session' })
const dirTab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
.find(tab => tab.path === '/work/src')!
const { container, unmount } = mountHost(ctx, store, dirTab)
try {
const html = container.innerHTML
// The folder window is the full tree surface: the folder basename is
// the tree root row and the search box is present; the editor empty
// hint and the file path input are NOT.
expect(html).toContain('src')
expect(html).toContain('Search files by name…')
expect(html).not.toContain('Pick a file from the tree panel')
expect(html).not.toContain('File path (relative')
} finally {
unmount()
}
})
})
+18 -5
View File
@@ -60,7 +60,10 @@ interface Mounted {
unmount: () => void
}
function mountSidebar(): Mounted {
/** Unique per-test session ids (see the comment inside). */
let sessionSeq = 0
function mountSidebar(sessionId: string = `s1-${++sessionSeq}`): Mounted {
vi.stubGlobal('WebSocket', FakeWebSocket)
if (!('ResizeObserver' in globalThis)) {
vi.stubGlobal('ResizeObserver', class {
@@ -83,9 +86,15 @@ function mountSidebar(): Mounted {
component: ({ visible }) => createElement('div', { 'data-visible': String(visible) }, 'notes body'),
})
store.setPrefs({ ...store.getPrefs(), openByDefault: true })
store.setSession('s1')
// The default session id is unique per test: the store persists
// per-session state to localStorage on a 200ms debounce, and a shared id
// let a PREVIOUS test's late timer write leak into this store's
// setSession restore (the portaled-menu/resize flakes — a stale float at
// the old drop point won the querySelector race on slow runners). The
// persistence round-trip test passes its own fixed id instead.
store.setSession(sessionId)
const localeSnapshot = { active: 'en' }
const sessionsSnapshot = { current: 's1', byId: { s1: { cwd: '/tmp' } } }
const sessionsSnapshot = { current: sessionId, byId: { [sessionId]: { cwd: '/tmp' } } }
const ctx = {
locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot },
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } },
@@ -132,6 +141,10 @@ afterEach(() => {
document.body.innerHTML = ''
document.documentElement.style.cssText = ''
vi.unstubAllGlobals()
// Belt and braces (after unstub, so a test's storage stub never sees it):
// drop any persisted layout a pending 200ms debounce write left behind
// between tests — unique session ids already isolate the stores.
localStorage.clear()
})
describe('free windows: drag-out detection', () => {
@@ -380,7 +393,7 @@ describe('free windows: the window', () => {
const getItem = vi.fn((key: string): string | null => saved.get(key) ?? null)
const setItem = vi.fn((key: string, value: string): void => { saved.set(key, value) })
vi.stubGlobal('localStorage', { getItem, setItem, removeItem: () => {} })
const first = mountSidebar()
const first = mountSidebar('s1')
try {
act(() => { first.service.openTab({ type: 'notes', title: 'Notes' }) })
act(() => { first.store.reduce(s => floatTabReducer(s, 'notes', 512, 384)) })
@@ -390,7 +403,7 @@ describe('free windows: the window', () => {
} finally {
first.unmount()
}
const second = mountSidebar()
const second = mountSidebar('s1')
try {
const state = second.store.getSnapshot().state!
expect(state.floats).toHaveLength(1)
+8 -5
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { spawnSync } from 'node:child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { parseWorktreeList, resolveWorktree, status, worktrees } from '../src/git.ts'
@@ -67,13 +67,16 @@ describe('linked Git worktrees', () => {
git(main, ['commit', '-q', '-m', 'base'])
git(main, ['worktree', 'add', '-q', '-b', 'agent', agent])
writeFileSync(join(agent, 'tracked.txt'), 'changed by agent\n')
// macOS tmpdir() keeps the /var symlink while git reports the resolved
// /private/var prefix — canonicalize every path handed to git APIs.
const agentPath = realpathSync(agent)
const listed = await worktrees(main)
expect(listed).toHaveLength(2)
expect(listed.find(entry => entry.current)).toMatchObject({ branch: 'main', changes: 0 })
expect(listed.find(entry => !entry.current)).toMatchObject({ branch: 'agent', changes: 1 })
expect(resolve(await resolveWorktree(main, agent))).toBe(resolve(agent))
expect((await status(await resolveWorktree(main, agent))).entries).toEqual([
expect(resolve(await resolveWorktree(main, agentPath))).toBe(resolve(agentPath))
expect((await status(await resolveWorktree(main, agentPath))).entries).toEqual([
{ path: 'tracked.txt', xy: ' M' },
])
await expect(resolveWorktree(main, root)).rejects.toThrow('unknown linked worktree')
@@ -84,9 +87,9 @@ describe('linked Git worktrees', () => {
rmSync(agent, { recursive: true, force: true })
const remaining = await worktrees(main)
expect(remaining).toHaveLength(1)
expect(resolve(remaining[0]!.path)).toBe(resolve(main))
expect(resolve(remaining[0]!.path)).toBe(resolve(realpathSync(main)))
expect(remaining[0]!.current).toBe(true)
await expect(resolveWorktree(main, agent)).rejects.toThrow('unknown linked worktree')
await expect(resolveWorktree(main, agentPath)).rejects.toThrow('unknown linked worktree')
} finally {
try { git(main, ['worktree', 'remove', '--force', agent]) } catch { /* fixture may not be fully initialized */ }
rmSync(root, { recursive: true, force: true })
+8 -5
View File
@@ -1,5 +1,5 @@
import { execFile, execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { mkdir, mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -10,6 +10,9 @@ import { parseLogLines, parsePorcelainZ, repoRoots, status } from '../src/git.ts
const execFileAsync = promisify(execFile)
const normalizePath = (path: string): string => path.replaceAll('\\', '/')
// macOS tmpdir() is the /var symlink while git reports the resolved
// /private/var prefix — canonicalize both sides before comparing.
const canonical = (path: string): string => normalizePath(realpathSync(path))
describe('git parsing', () => {
it('discovers and selects direct child repositories under a workspace directory', async () => {
@@ -23,11 +26,11 @@ describe('git parsing', () => {
execFileAsync('git', ['-C', second, 'init']),
])
await expect(repoRoots(workspace)).resolves.toEqual([normalizePath(first), normalizePath(second)])
await expect(status(workspace, normalizePath(second))).resolves.toMatchObject({
await expect(repoRoots(workspace)).resolves.toEqual([canonical(first), canonical(second)])
await expect(status(workspace, canonical(second))).resolves.toMatchObject({
isRepo: true,
root: normalizePath(second),
repositories: [normalizePath(first), normalizePath(second)],
root: canonical(second),
repositories: [canonical(first), canonical(second)],
})
} finally {
await rm(workspace, { recursive: true, force: true })
+176
View File
@@ -0,0 +1,176 @@
/**
* MarkdownDocument spec: the split-document renderer — sanitized HTML leaves
* (denylist + anchor hardening + local media rewrite), `<details>` nesting of
* in-between markdown, cross-segment reference definitions, and the inline
* pass that turns tag text inside rendered markdown back into elements.
* Renders with the real shared MarkdownText in jsdom (same pattern as
* tests/mermaid-markdown.spec.tsx).
*/
// @vitest-environment jsdom
import { describe, expect, it, beforeEach } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { MarkdownDocument, type MarkdownHtmlMedia } from '../src/client/MarkdownHtml.tsx'
import { analyzeMarkdownHtml } from '../src/client/markdown-html.ts'
// The act() environment flag (React 18.2 reads it before flushing effects).
;(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true
const media: MarkdownHtmlMedia = {
scope: { sessionId: 's1', cwd: '/ws' },
path: '/ws/docs/README.md',
origin: 'http://gui.origin',
}
const codeLabels = { copyLabel: 'Copy', copiedLabel: 'Copied' }
async function renderDocument(text: string): Promise<{ container: HTMLElement; root: Root }> {
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
await act(async () => {
root.render(createElement(MarkdownDocument, {
info: analyzeMarkdownHtml(text),
media,
codeLabels,
}))
// Let the MutationObserver's queued inline pass settle inside the act scope.
await new Promise((resolve) => { setTimeout(resolve, 0) })
})
return { container, root }
}
async function unmount(root: Root): Promise<void> {
await act(async () => { root.unmount() })
}
beforeEach(() => {
document.body.innerHTML = ''
})
describe('MarkdownDocument (HTML leaves)', () => {
it('renders a balanced HTML block as sanitized DOM, not literal text', async () => {
const { container, root } = await renderDocument([
'# Title',
'',
'<div align="center">',
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
'</div>',
].join('\n'))
const leaf = container.querySelector('[data-dsh-html-segment]')
expect(leaf, 'the html run must render as a sanitized leaf').not.toBeNull()
expect(leaf?.querySelector('img[src*="img.shields.io"]')).not.toBeNull()
expect(leaf?.firstElementChild?.getAttribute('align')).toBe('center')
expect(container.textContent).not.toContain('<div')
await unmount(root)
})
it('strips denied tags and hardens anchors', async () => {
const { container, root } = await renderDocument([
'<div>',
' <script>alert(1)</script>',
' <a href="https://example.com">link</a>',
'</div>',
].join('\n'))
expect(container.querySelector('script')).toBeNull()
const anchor = container.querySelector('a[href="https://example.com"]')
expect(anchor).not.toBeNull()
expect(anchor?.getAttribute('target')).toBe('_blank')
expect(anchor?.getAttribute('rel')).toBe('noopener noreferrer')
await unmount(root)
})
it('rewrites local media sources through the /sidebar/file route', async () => {
const { container, root } = await renderDocument('<picture><img src="./shot.png" alt="shot"/></picture>')
const img = container.querySelector('img')
expect(img?.getAttribute('src')).toBe('http://gui.origin/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws')
await unmount(root)
})
})
describe('MarkdownDocument (nesting + markdown runs)', () => {
it('nests markdown runs inside an unclosed <details> element', async () => {
const { container, root } = await renderDocument([
'<details>',
'<summary><b>更新</b></summary>',
'',
'```sh',
'dsh plugin --profile web add x',
'```',
'',
'</details>',
'',
'after the fold',
].join('\n'))
const details = container.querySelector('details')
expect(details, 'the open part must lower following runs into a details element').not.toBeNull()
expect(details?.querySelector('summary')).not.toBeNull()
expect(details?.textContent).toContain('dsh plugin --profile web add x')
// The close part pops the frame: the trailing markdown is a sibling.
expect(details?.textContent).not.toContain('after the fold')
expect(container.querySelector('details')?.nextElementSibling?.textContent).toContain('after the fold')
await unmount(root)
})
it('keeps reference definitions resolving across lifted HTML runs', async () => {
const { container, root } = await renderDocument([
'see [the docs][shared]',
'',
'<div align="center">badges</div>',
'',
'[shared]: https://example.com/docs',
].join('\n'))
const anchor = container.querySelector('a[href="https://example.com/docs"]')
expect(anchor, 'a definition after an HTML run must still resolve').not.toBeNull()
expect(anchor?.textContent).toContain('the docs')
await unmount(root)
})
it('renders a forbidden wrapper as transparent (children survive)', async () => {
const { container, root } = await renderDocument([
'<form action="/x">',
'',
'inner text',
'',
'</form>',
].join('\n'))
expect(container.querySelector('form')).toBeNull()
expect(container.textContent).toContain('inner text')
await unmount(root)
})
})
describe('MarkdownDocument (inline pass)', () => {
it('turns tag text in table cells back into elements', async () => {
const { container, root } = await renderDocument([
'| feature | notes |',
'|---|---|',
'| alpha | line one<br/>line two |',
].join('\n'))
const cell = [...container.querySelectorAll('td')].find((td) => td.textContent?.includes('line one'))
expect(cell?.querySelector('[data-html-inline] br'), 'the <br/> must render as a real element').not.toBeNull()
await unmount(root)
})
it('leaves rendered code and comparison prose untouched', async () => {
const { container, root } = await renderDocument([
'a < b comparison stays text',
'',
'```html',
'<div>demo</div>',
'```',
].join('\n'))
expect(container.querySelectorAll('[data-html-inline]').length).toBe(0)
expect(container.textContent).toContain('a < b comparison stays text')
const code = container.querySelector('code')
expect(code?.textContent).toContain('<div>demo</div>')
await unmount(root)
})
it('rewrites local image src inside inline-swapped tags', async () => {
const { container, root } = await renderDocument('text <img src="./icon.png" alt="i"/> tail')
const img = container.querySelector('[data-html-inline] img')
expect(img?.getAttribute('src')).toContain('/sidebar/file?')
await unmount(root)
})
})
+196
View File
@@ -0,0 +1,196 @@
/**
* markdown-html splitter spec: the pure lifting of raw-HTML runs out of the
* markdown stream (fence-aware), the tag-balance part analysis (unclosed
* `<details>` → wrapper opens, stray closes → pops), the doc-wide reference
* definition collection, and the inline-html gate.
*/
import { describe, expect, it } from 'vitest'
import {
analyzeHtmlSegment,
analyzeMarkdownHtml,
collectReferenceDefinitions,
splitHtmlBlocks,
type HtmlPart,
} from '../src/client/markdown-html.ts'
/** Structural view of parts: html parts as [html <text>], opens/closes by kind. */
function shape(parts: readonly HtmlPart[]): string[] {
return parts.map((part) => part.kind === 'html'
? `html(${part.html})`
: part.kind === 'open'
? `open(${part.tag}${part.attrs.trim() !== '' ? ` ${part.attrs.trim()}` : ''})`
: `close(${part.tag})`)
}
describe('splitHtmlBlocks', () => {
it('returns one markdown segment for plain markdown (no HTML)', () => {
const text = '# Title\n\nsome **markdown**\n\n- a\n- b\n'
expect(splitHtmlBlocks(text)).toEqual([{ kind: 'markdown', text: text.replace(/\n$/, '') }])
})
it('lifts a balanced block-tag run out of the markdown stream', () => {
const segments = splitHtmlBlocks([
'# Title',
'',
'<div align="center">',
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
'</div>',
'',
'tail text',
].join('\n'))
expect(segments).toEqual([
{ kind: 'markdown', text: '# Title' },
{ kind: 'html', text: '<div align="center">\n <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />\n</div>' },
{ kind: 'markdown', text: 'tail text' },
])
})
it('ends an HTML run at a blank line', () => {
const segments = splitHtmlBlocks('<p>a</p>\n\nafter')
expect(segments).toEqual([
{ kind: 'html', text: '<p>a</p>' },
{ kind: 'markdown', text: 'after' },
])
})
it('does not lift tag-like lines inside fenced code blocks', () => {
const segments = splitHtmlBlocks([
'```html',
'<div class="demo">',
' <p>example</p>',
'</div>',
'```',
'',
'<div align="center">real</div>',
].join('\n'))
expect(segments).toEqual([
{ kind: 'markdown', text: '```html\n<div class="demo">\n <p>example</p>\n</div>\n```' },
{ kind: 'html', text: '<div align="center">real</div>' },
])
})
it('does not lift inline-only tags or prose starting with a comparison', () => {
const segments = splitHtmlBlocks([
'a < b and <code>x</code> inline',
'<br/> alone on its line',
].join('\n'))
expect(segments).toEqual([
{ kind: 'markdown', text: 'a < b and <code>x</code> inline\n<br/> alone on its line' },
])
})
it('treats a close-tag-only line as an HTML run', () => {
const segments = splitHtmlBlocks('text\n\n</details>\n\nmore')
expect(segments).toEqual([
{ kind: 'markdown', text: 'text' },
{ kind: 'html', text: '</details>' },
{ kind: 'markdown', text: 'more' },
])
})
it('accumulates a comment run until the closing marker line', () => {
const segments = splitHtmlBlocks('<!-- section\n banner\n-->\n\nbody')
expect(segments).toEqual([
{ kind: 'html', text: '<!-- section\n banner\n-->' },
{ kind: 'markdown', text: 'body' },
])
})
it('keeps an unterminated fence as markdown (CommonMark recovery)', () => {
const segments = splitHtmlBlocks('```\n<div>x</div>')
expect(segments).toEqual([{ kind: 'markdown', text: '```\n<div>x</div>' }])
})
it('keeps the README details shape as three segments', () => {
const segments = splitHtmlBlocks([
'<details>',
'<summary><b>更新</b></summary>',
'',
'```sh',
'dsh plugin --profile web add x',
'```',
'',
'</details>',
].join('\n'))
expect(segments.map((segment) => segment.kind)).toEqual(['html', 'markdown', 'html'])
expect(segments[0]).toEqual({ kind: 'html', text: '<details>\n<summary><b>更新</b></summary>' })
expect(segments[2]).toEqual({ kind: 'html', text: '</details>' })
})
})
describe('analyzeHtmlSegment', () => {
it('reduces a balanced run to a single html part', () => {
expect(shape(analyzeHtmlSegment('<div align="center"><img src="https://x/y.png"/></div>').parts))
.toEqual(['html(<div align="center"><img src="https://x/y.png"/></div>)'])
})
it('surfaces an unclosed open tag as a wrapper with its inner html', () => {
expect(shape(analyzeHtmlSegment('<details>\n<summary><b>更新</b></summary>').parts))
.toEqual(['open(details)', 'html(\n<summary><b>更新</b></summary>)'])
})
it('surfaces an unmatched close as a pop', () => {
expect(shape(analyzeHtmlSegment('</details>').parts)).toEqual(['close(details)'])
})
it('orders mixed leading closes before following html and closes', () => {
expect(shape(analyzeHtmlSegment('</div> mid </details>').parts))
.toEqual(['close(div)', 'html( mid )', 'close(details)'])
})
it('nests multiple unclosed opens outermost-first', () => {
expect(shape(analyzeHtmlSegment('<div align="center"><details>').parts))
.toEqual(['open(div align="center")', 'open(details)'])
})
it('keeps attrs of the open token for the wrapper', () => {
const parts = analyzeHtmlSegment('<details open class="x">body').parts
expect(parts[0]).toEqual({ kind: 'open', tag: 'details', attrs: ' open class="x"' })
})
it('ignores void and self-closing tags for balance', () => {
expect(shape(analyzeHtmlSegment('<img src="x"><br/><span/>after').parts))
.toEqual(['html(<img src="x"><br/><span/>after)'])
})
it('ignores tags inside comments', () => {
expect(shape(analyzeHtmlSegment('<!-- <div> commented out -->').parts))
.toEqual(['html(<!-- <div> commented out -->)'])
})
it('pops implicitly through a mismatched close', () => {
// <p> is implicitly closed by </div>: nothing structural remains.
expect(shape(analyzeHtmlSegment('<div><p>text</div>').parts))
.toEqual(['html(<div><p>text</div>)'])
})
})
describe('collectReferenceDefinitions + analyzeMarkdownHtml', () => {
it('collects definitions from markdown runs only, in document order', () => {
const info = analyzeMarkdownHtml([
'intro [link][shared]',
'',
'<div align="center">badges</div>',
'',
'[shared]: https://example.com',
'[img]: ./local.png',
].join('\n'))
expect(info.referenceDefinitions).toBe('[shared]: https://example.com\n[img]: ./local.png')
expect(collectReferenceDefinitions(info.segments)).toBe(info.referenceDefinitions)
})
it('reports hasBlockHtml only when a run was lifted', () => {
expect(analyzeMarkdownHtml('# plain\ntext').hasBlockHtml).toBe(false)
expect(analyzeMarkdownHtml('<div>x</div>').hasBlockHtml).toBe(true)
// Inline-only tags: no block html, but the inline gate is on.
const inline = analyzeMarkdownHtml('| a | b |\n|---|---|\n| x<br/>y | z |')
expect(inline.hasBlockHtml).toBe(false)
expect(inline.hasInlineHtml).toBe(true)
})
it('gates inline html on tag-like source text', () => {
expect(analyzeMarkdownHtml('a < b').hasInlineHtml).toBe(false)
expect(analyzeMarkdownHtml('a <b>bold</b>').hasInlineHtml).toBe(true)
expect(analyzeMarkdownHtml('plain markdown').hasInlineHtml).toBe(false)
})
})
+152
View File
@@ -0,0 +1,152 @@
/**
* MdToc spec: the markdown preview's outline button + popover. Covers the
* minimum-headings gate, collection from the rendered DOM (including headings
* inside HTML `<details>` runs, which appear late through the observer),
* jump behavior (smooth scroll + flash + auto-expanding collapsed ancestors)
* and Esc-to-close.
*/
// @vitest-environment jsdom
import { describe, expect, it, beforeEach, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { MdToc, TOC_MIN_HEADINGS } from '../src/client/md-toc.tsx'
// The act() environment flag (React 18.2 reads it before flushing effects).
;(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true
const scrollIntoView = vi.fn()
Element.prototype.scrollIntoView = scrollIntoView
/** The preview-harness shape MdToc mounts in: the bar is a direct child of
* the scroll container, headings are siblings (inside or outside details). */
interface HeadingSpec {
tag: string
text: string
insideClosedDetails?: boolean
}
function Harness({ specs }: { specs: readonly HeadingSpec[] }): React.ReactElement {
return createElement(
'div',
null,
createElement(MdToc),
...specs.map((spec) => spec.insideClosedDetails === true
? createElement('details', null, createElement(spec.tag, null, spec.text))
: createElement(spec.tag, null, spec.text)),
)
}
/** Render the harness; returns the scroll container (the bar's parent). */
async function mountToc(specs: readonly HeadingSpec[]): Promise<{ container: HTMLDivElement; root: Root }> {
const host = document.createElement('div')
document.body.appendChild(host)
const root = createRoot(host)
await act(async () => {
root.render(createElement(Harness, { specs }))
await new Promise((resolve) => { setTimeout(resolve, 0) })
})
const container = host.firstElementChild as HTMLDivElement
return { container, root }
}
async function unmount(root: Root): Promise<void> {
await act(async () => { root.unmount() })
}
beforeEach(() => {
document.body.innerHTML = ''
scrollIntoView.mockClear()
})
describe('MdToc', () => {
it('exposes the minimum-headings threshold', () => {
expect(TOC_MIN_HEADINGS).toBe(3)
})
it('stays hidden below the heading threshold', async () => {
const { container, root } = await mountToc([
{ tag: 'h1', text: 'One' },
{ tag: 'h2', text: 'Two' },
])
expect(container.querySelector('[data-dsh-md-toc]')).toBeNull()
await unmount(root)
})
it('shows the button and lists collected headings', async () => {
const { container, root } = await mountToc([
{ tag: 'h1', text: 'Title' },
{ tag: 'h2', text: 'Install' },
{ tag: 'h2', text: 'Usage' },
{ tag: 'h3', text: 'Deep' },
])
const button = container.querySelector<HTMLButtonElement>('[data-dsh-md-toc]')
expect(button).not.toBeNull()
await act(async () => { button!.click() })
const panel = container.querySelector('[data-dsh-md-toc-panel]')
expect(panel).not.toBeNull()
const items = [...panel!.querySelectorAll('button')]
expect(items.map((item) => item.textContent)).toEqual(['1Title', '2Install', '2Usage', '3Deep'])
await unmount(root)
})
it('jumps: expands collapsed details ancestors, smooth-scrolls, flashes, closes', async () => {
// Mount with real timers (the settle await needs them), then fake only the
// flash-removal timeout window.
const { container, root } = await mountToc([
{ tag: 'h1', text: 'Title' },
{ tag: 'h2', text: 'Outside' },
{ tag: 'h3', text: 'Hidden', insideClosedDetails: true },
])
vi.useFakeTimers()
try {
const button = container.querySelector<HTMLButtonElement>('[data-dsh-md-toc]')!
await act(async () => { button.click() })
const target = [...container.querySelectorAll('h3')].find((h) => h.textContent === 'Hidden')!
const item = [...container.querySelectorAll<HTMLButtonElement>('[data-dsh-md-toc-panel] button')]
.find((candidate) => candidate.textContent?.includes('Hidden'))!
await act(async () => { item.click() })
expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth', block: 'start' })
expect(target.closest('details')?.hasAttribute('open'), 'the collapsed ancestor must open').toBe(true)
expect(target.className, 'the jumped-to heading must flash').not.toBe('')
expect(container.querySelector('[data-dsh-md-toc-panel]'), 'the panel must close on jump').toBeNull()
vi.advanceTimersByTime(1300)
expect(target.className, 'the flash class must clear after the timeout').toBe('')
await unmount(root)
} finally {
vi.useRealTimers()
}
})
it('collects headings that appear after mount (observer path)', async () => {
const { container, root } = await mountToc([
{ tag: 'h1', text: 'Title' },
{ tag: 'h2', text: 'Only two so far' },
])
expect(container.querySelector('[data-dsh-md-toc]')).toBeNull()
const late = document.createElement('h2')
late.textContent = 'Late'
await act(async () => {
container.appendChild(late)
await new Promise((resolve) => { setTimeout(resolve, 0) })
})
expect(container.querySelector('[data-dsh-md-toc]'), 'late headings must surface the button').not.toBeNull()
await unmount(root)
})
it('closes the popover on Escape', async () => {
const { container, root } = await mountToc([
{ tag: 'h1', text: 'Title' },
{ tag: 'h2', text: 'A' },
{ tag: 'h2', text: 'B' },
])
const button = container.querySelector<HTMLButtonElement>('[data-dsh-md-toc]')!
await act(async () => { button.click() })
expect(container.querySelector('[data-dsh-md-toc-panel]')).not.toBeNull()
await act(async () => {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
})
expect(container.querySelector('[data-dsh-md-toc-panel]')).toBeNull()
await unmount(root)
})
})
+3 -1
View File
@@ -65,6 +65,8 @@ describe('dsh-better-sidebar plugin export shape', () => {
// The terminal tools default OFF (the feature is dormant until the user
// enables it in the side card settings).
expect(resolved.agentTerminalTools).toBe(false)
// The sidebar-open tool defaults OFF too (same dormant-until-enabled rule).
expect(resolved.agentOpenTools).toBe(false)
// The terminal font customizations default to the theme (empty family)
// and 13px.
expect(resolved.terminalFontFamily).toBe('')
@@ -92,6 +94,6 @@ describe('dsh-better-sidebar plugin export shape', () => {
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: false, terminalShell: '', terminalShellArgs: '', 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, agentOpenTools: 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: {} })
})
})
+15 -8
View File
@@ -37,7 +37,7 @@ describe('side card preferences', () => {
defaultWidthPercent: 60,
autoOpenSubagent: false,
autoOpenJobs: true,
agentTerminalTools: true,
agentTerminalTools: true, agentOpenTools: false,
bottomPanelAutoTerminal: true,
terminalFontFamily: '',
terminalFontSize: 13,
@@ -69,7 +69,7 @@ describe('side card preferences', () => {
defaultWidthPercent: 33,
autoOpenSubagent: true,
autoOpenJobs: true,
agentTerminalTools: false,
agentTerminalTools: false, agentOpenTools: false,
bottomPanelAutoTerminal: true,
terminalFontFamily: '',
terminalFontSize: 13,
@@ -101,7 +101,7 @@ describe('side card preferences', () => {
defaultWidthPercent: 40,
autoOpenSubagent: true,
autoOpenJobs: true,
agentTerminalTools: false,
agentTerminalTools: false, agentOpenTools: false,
bottomPanelAutoTerminal: true,
terminalFontFamily: '',
terminalFontSize: 13,
@@ -133,6 +133,13 @@ describe('side card preferences', () => {
.toBe(false)
expect((await loadPrefs(wire({ openByDefault: true, defaultWidthPercent: 40, agentTerminalTools: true }))).agentTerminalTools)
.toBe(true)
// The sidebar-open tool is OFF by default too; only an explicit true turns it on.
expect((await loadPrefs(wire({ openByDefault: true, defaultWidthPercent: 40 }))).agentOpenTools)
.toBe(false)
expect((await loadPrefs(wire({ openByDefault: true, defaultWidthPercent: 40, agentOpenTools: 1 }))).agentOpenTools)
.toBe(false)
expect((await loadPrefs(wire({ openByDefault: true, defaultWidthPercent: 40, agentOpenTools: true }))).agentOpenTools)
.toBe(true)
// The job auto-open is ON by default; only an explicit false turns it off.
expect((await loadPrefs(wire({ openByDefault: true, defaultWidthPercent: 40, autoOpenJobs: 1 }))).autoOpenJobs)
.toBe(true)
@@ -260,9 +267,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, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, browserAllowedLoopback: "", tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
store.setPrefs({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, agentOpenTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', 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, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, browserAllowedLoopback: "", tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
expect(store.getPrefs()).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, agentOpenTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', 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)
@@ -298,7 +305,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, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, browserAllowedLoopback: "", tabsEnabled: { editor: false }, viewersEnabled: {}, pluginSettings: {} })
store.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, agentOpenTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer: true, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', 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)
@@ -308,7 +315,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, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, browserAllowedLoopback: "", tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
openStore.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, agentOpenTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', 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'])
@@ -318,7 +325,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, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, browserAllowedLoopback: "", tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
store.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, agentOpenTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, editorExplorer, terminalShell: '', terminalShellArgs: '', titleBarScheme: 'auto', titleBarPresetId: '', customCss: '', 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)
+4 -4
View File
@@ -178,10 +178,10 @@ describe('SideCardSection declarative inventory', () => {
expect(html).toContain('Pick the title-bar compatibility scheme: auto-detect (default, conservative) / DSH official web / known desktop shells / custom (shift distance + custom CSS)')
expect(html).not.toContain('<select')
expect(html).toContain('>Auto-detect<')
// Two general-row switches remain (openByDefault + interceptOpenPath),
// only interceptOpenPath checked by default — the scheme row is a
// dropdown, not a switch.
expect(html.match(/type="checkbox"/g)?.length).toBe(2)
// Three general-row switches remain (openByDefault + interceptOpenPath
// + agentOpenTools), only interceptOpenPath checked by default — the
// scheme row is a dropdown, not a switch.
expect(html.match(/type="checkbox"/g)?.length).toBe(3)
expect(html.match(/checked=""/g)?.length).toBe(1)
// Auto (default) needs no further settings → no gear.
expect(html).not.toContain('Position compatibility mode Feature settings')
+13 -3
View File
@@ -47,6 +47,9 @@ interface MountedSidebar {
}
/** Mount the real Sidebar shell against a minimal context (real store + service). */
/** Unique per-test session ids (see the comment inside). */
let sessionSeq = 0
function mountSidebar(): MountedSidebar {
vi.stubGlobal('WebSocket', FakeWebSocket)
const container = document.createElement('div')
@@ -55,14 +58,18 @@ function mountSidebar(): MountedSidebar {
const service = createBetterSidebarService(store)
// Fresh-session seed: open the panel explicitly (openByDefault defaults off).
store.setPrefs({ ...store.getPrefs(), openByDefault: true })
store.setSession('s1')
// Unique session per test — the store persists per-session state to
// localStorage (200ms debounce); a shared id lets a previous test's late
// write leak into this store's setSession restore.
const sessionId = `s1-${++sessionSeq}`
store.setSession(sessionId)
// useSyncExternalStore requires STABLE snapshots across calls (the real DSH
// services return stable objects) — a fresh object per call loops forever.
const localeSnapshot = { active: 'en' }
const sessionsSnapshot = {
current: 's1',
current: sessionId,
// cwd present → api.sessionCwd is never called in these tests.
byId: { s1: { cwd: '/tmp' } },
byId: { [sessionId]: { cwd: '/tmp' } },
}
const ctx = {
locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot },
@@ -85,6 +92,9 @@ function mountSidebar(): MountedSidebar {
afterEach(() => {
document.body.innerHTML = ''
// Belt and braces: drop any persisted layout a pending 200ms debounce
// write left behind between tests (unique session ids already isolate).
localStorage.clear()
vi.unstubAllGlobals()
})
+56 -3
View File
@@ -110,7 +110,7 @@ describe('host plugin smoke', () => {
'/sidebar/file',
'/sidebar/html',
])
expect(upgrades.map(route => route.path)).toEqual(['/sidebar/ws/terminal', '/sidebar/ws/agent-terminals'])
expect(upgrades.map(route => route.path)).toEqual(['/sidebar/ws/terminal', '/sidebar/ws/agent-terminals', '/sidebar/ws/agent-opens'])
// Teardown runs without throwing (pty manager has nothing open).
for (const cleanup of effects) cleanup()
})
@@ -891,7 +891,7 @@ describe('side card settings routes', () => {
defaultWidthPercent: 35,
autoOpenSubagent: true,
autoOpenJobs: true,
agentTerminalTools: false,
agentTerminalTools: false, agentOpenTools: false,
bottomPanelAutoTerminal: true,
terminalFontFamily: '',
terminalFontSize: 13,
@@ -1067,6 +1067,59 @@ describe('agent terminal tool gating', () => {
expect(live()).toBe(8)
expect(registered).toBe(16)
})
})
describe('agent sidebar-open tool gating', () => {
it('injects the one open tool only when the side-card setting is enabled (default off)', () => {
let registered = 0
let disposed = 0
const live = (): number => registered - disposed
const watcherRef: { current: (() => void) | null } = { current: null }
let enabled = false
const settings = {
register() {
return {
get: () => ({ agentOpenTools: enabled, tabsEnabled: {} }),
watch: (callback: () => void) => { watcherRef.current = callback; return () => {} },
update: async () => {},
replace: async () => {},
}
},
describe: () => [],
async update() {},
}
const ctx = {
webRuntime: { trustedHosts: [] },
webServer: {
register: (route: SidebarWebRoute) => { void route; return () => {} },
registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
},
sessions: { get: () => undefined },
tools: { register: () => { registered += 1; return () => { disposed += 1 } } },
effect: (fn: () => void | (() => void)) => { fn() },
inject: (deps: readonly string[], callback: (sctx: { settings: unknown }) => void) => {
if (deps.includes('settings')) callback({ settings })
return () => {}
},
get: () => undefined,
}
apply(ctx as never)
// Default off: no open tool is registered even though the settings service is mounted.
expect(live()).toBe(0)
// Flipping the setting on registers the single sidebar_open tool.
enabled = true
watcherRef.current?.()
expect(live()).toBe(1)
expect(disposed).toBe(0)
// Flipping it back off unregisters it (and drains the undelivered queue).
enabled = false
watcherRef.current?.()
expect(live()).toBe(0)
expect(disposed).toBe(1)
// And a redundant toggle registers it fresh (no double-registration).
enabled = true
watcherRef.current?.()
expect(live()).toBe(1)
expect(registered).toBe(2)
})
})