feat(editor): 文件窗口与资源管理器二合一 + 声明式设置 select 行 (#151)

* feat(editor): merged explorer mode — path input, docked file tree, global name search

New editorExplorer pref (default on, editor card gear): the editor tab gains
a path-input header and a toggleable right-docked tree panel (per-tab state
in tab.meta.treeOpen; file tabs default closed, the seeded path-less home
tab defaults open). Fresh sessions seed that empty editor tab instead of
the explorer tab when merged mode is on; the standalone explorer tab stays
in the + menu unchanged.

- Extract FileTree.tsx from ExplorerView (shared by both hosts)
- Host fs.search route: recursive case-insensitive name search rooted at
  the session cwd, budget-capped (200 matches / 100k visited), skips .git,
  never descends symlink dirs
- EditorHost reads the pref reactively (boolean snapshot) and keeps the
  pre-merge layout verbatim when off

* feat(settings): select row type for declarative settings; editorExplorer as iconed select

- SidebarSettingToggle gains type 'select' with options {value,title,desc,icon}
  and multi (default false; stores the picked values as an array in options
  order). Any option carrying an icon renders big-icon option cards in the
  dropdown and the icon in the closed anchor; icon-less rows are one-line text.
- SelectRow in SideCardSection rides the primitives Menu (portal); single-pick
  commits and closes, multi toggles and stays open. Wired for both host-prefs
  toggles and plugin-owned pluginToggles via the new onSelectValue seam.
- The editorExplorer merged-mode pref is now an iconed select (merged vs
  separate) instead of a switch; the stored value stays boolean.
- Advertise the capability as 'settingSelect' in SIDEBAR_FEATURES.

* feat(editor): unify explorer into the editor surface, resizable tree dock, hoisted toolbar

- One tree implementation, two presentations: the shared TreePanel (global
  name search + refresh + FileTree) docks as the editor tab's right panel
  and — in merged mode — fills the explorer tab's window; the pref-off
  explorer keeps its legacy header shell.
- The docked panel drag-resizes from its left edge (160-480px clamp),
  persisted as tab.meta.treeWidth alongside treeOpen.
- The text editor's preview/edit/save toolbar moves into the path-input
  header row: FileViewerProps gains internal toolbar fields ('host' mode
  skips the viewer's own row, reports EditorToolbarState and registers
  EditorToolbarControls); non-merged mode is byte-identical to before.

* feat(editor): single files window with in-place switching; explorer descriptor removed

- editor tab replaces explorer on the + menu (order 10, Files); persisted
  explorer tabs migrate to the editor home tab via sanitizeState
- editorExplorer now only controls open behavior: merged = in-place
  updateTab, independent = openSidebarFile; both modes share the merged
  chrome (path input + hoisted preview/edit/save toolbar + tree toggle)
- file tree context menu gains 'open in new tab' / 'open to the side'
  (mintTabId avoids the id safety net; insertLeafAt splits right)
- tree dock resize uses pointer capture (touch-action none, 6px handle)
- defaults: openByDefault off, sidebar width 35%
- file tree clips horizontal overflow (no sideways scroll)
- e2e: mount lane arms the editor-chunk wait before goto and clicks the
  tree row's left edge (hover @-reference button sits mid-row); drag lane
  expands the panel first (collapsed push writes 0px), waits for the
  slide-in to settle, and picks the leftmost col-resize strip; 'Files'
  title assertions require draggable to skip the bottom panel's welcome
  cards

* feat(editor): split mode turns the path-less window into the standalone explorer

In independent (split) mode a path-less files window renders ONLY the
tree panel (search + FileTree, full-window form) — no path input, no
hoisted toolbar, no tree toggle. File clicks open per-path editor tabs
(full chrome, tree docked closed by default) through openSidebarFile,
unchanged. Merged mode is untouched (chrome + docked tree, in-place
switching). TreePanel's previously reserved 'full' prop now has its
consumer.
This commit is contained in:
Atlas Zeng
2026-08-17 15:00:03 +08:00
committed by GitHub
parent c923fc57b1
commit 6ee1ba11d0
31 changed files with 2054 additions and 263 deletions
+22 -6
View File
@@ -1,5 +1,5 @@
/**
* Built-in registration tests: the plugin registers 7 tabs and 6 file
* Built-in registration tests: the plugin registers 6 tabs and 6 file
* viewers through the same service external plugins use (dogfooding);
* the catch-all `code` viewer, the NUL-sniffing `binary-download` viewer,
* and the html sandbox settings pin the registry's behavior. (Office
@@ -24,21 +24,24 @@ function setup(): { service: ReturnType<typeof createBetterSidebarService>; stor
}
describe('built-in tab registrations', () => {
it('registers the 7 built-in tabs', () => {
it('registers the 6 built-in tabs', () => {
const { service } = setup()
expect(service.getTabs().map(t => t.id).sort()).toEqual(
['browser', 'diff', 'editor', 'explorer', 'git', 'subagent', 'terminal'],
['browser', 'diff', 'editor', 'git', 'subagent', 'terminal'],
)
})
it('editor and diff are hidden from the + menu (opened by file-open / git view)', () => {
it('only diff is hidden from the + menu; editor is the visible files window (order 10)', () => {
const { service } = setup()
expect(service.getTabs().filter(t => t.hidden).map(t => t.id).sort()).toEqual(['diff', 'editor'])
expect(service.getTabs().filter(t => t.hidden).map(t => t.id)).toEqual(['diff'])
const editor = service.getTab('editor')
expect(editor?.hidden).toBe(false)
expect(editor?.order).toBe(10)
})
it('single-instance tabs use the single sugar', () => {
const { service } = setup()
for (const id of ['explorer', 'git', 'subagent']) {
for (const id of ['git', 'subagent']) {
expect(service.getTab(id)?.single).toBe(true)
}
})
@@ -49,6 +52,19 @@ describe('built-in tab registrations', () => {
expect(toggles.map(t => t.key)).toEqual(['autoOpenSubagent', 'autoOpenJobs'])
})
it('the editor tab declares its merged-mode (embedded file tree) setting', () => {
const { service } = setup()
const toggles = service.getTab('editor')?.settings?.toggles ?? []
expect(toggles.map(t => t.key)).toEqual(['editorExplorer'])
expect(toggles[0]?.title).toBeDefined()
expect(toggles[0]?.desc).toBeDefined()
// The merged mode is an iconed select (merged vs separate), not a switch.
expect(toggles[0]?.type).toBe('select')
const options = toggles[0]?.options ?? []
expect(options.map(o => o.value)).toEqual([true, false])
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', () => {
const { service } = setup()
const toggles = service.getTab('terminal')?.settings?.toggles ?? []
+64 -24
View File
@@ -83,28 +83,8 @@ interface FrameSample {
test('width drag tracks the shell 1:1 with transitions disabled (issue #92)', async ({ page }) => {
await page.goto(BASE_URL, { waitUntil: 'domcontentloaded' })
await expect(page.locator('#root > *')).not.toHaveCount(0, { timeout: 90_000 })
// The seeded session opens the right panel by default: the layout push
// variable becomes live once the panel mounts (session activation lags
// the shell render).
await expect
.poll(async () => (
await page.evaluate(() => document.documentElement.style.getPropertyValue('--dsh-sidebar-width'))
), { timeout: 90_000 })
.not.toBe('')
// The width drag strip is the panel's left-edge hit strip. There is no
// dedicated hook (the skinning contract is token-driven), so locate it
// semantically: the only `cursor: col-resize` element in the sidebar.
const stripBox = await page.evaluate(() => {
const host = document.querySelector('[data-dsh-better-sidebar]')
if (host === null) return null
const found = [...host.querySelectorAll<HTMLElement>('*')]
.find(el => getComputedStyle(el).cursor === 'col-resize')
if (found === undefined) return null
const r = found.getBoundingClientRect()
return { x: r.x, y: r.y, width: r.width, height: r.height }
})
expect(stripBox, 'the width drag strip must be present (cursor: col-resize)').not.toBeNull()
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 mount
// lane), so the pointer can reach the strip without a masking overlay.
@@ -131,12 +111,72 @@ test('width drag tracks the shell 1:1 with transitions disabled (issue #92)', as
if (!dismissed) break
}
// openByDefault defaults OFF: a fresh session's panel starts collapsed, and
// the collapsed layout push still writes `--dsh-sidebar-width: 0px` — so the
// geometry checks below are meaningless until the panel is expanded through
// the toggle cluster.
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()
// The layout push variable becomes live (non-zero) once the panel opens
// (session activation lags the shell render).
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)
// The width drag strip is the panel's left-edge hit strip. There is no
// dedicated hook (the skinning contract is token-driven), so locate it
// semantically among the sidebar's `cursor: col-resize` elements — the files
// window's tree-dock handle matches too, but the panel strip is always the
// LEFTMOST one (the dock sits at the panel's right edge).
const locateStrip = `(() => {
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,
}
})()`
type StripBox = { x: number; y: number; width: number; height: number; varWidth: number; innerWidth: number }
// The panel SLIDES IN from the right on expand: locating the strip before
// the open transition settles captures a mid-animation box at the viewport
// edge, and the drag lands off-panel. Wait until the strip sits at the
// pushed layout edge (its right edge ≈ innerWidth - the push variable).
await expect
.poll(async () => {
const box = await page.evaluate<StripBox | null>(locateStrip)
if (box === null) return false
return Math.abs((box.x + box.width) - (box.innerWidth - box.varWidth)) <= 8
}, { timeout: 30_000 })
.toBe(true)
const stripBox = await page.evaluate<StripBox | null>(locateStrip)
expect(stripBox, 'the width drag strip must be present (cursor: col-resize)').not.toBeNull()
// Instrument a per-frame sampler BEFORE the drag begins.
await page.evaluate(() => {
type Sample = FrameSample
const samples: Sample[] = []
const strip = [...document.querySelectorAll<HTMLElement>('*')]
.find(el => getComputedStyle(el).cursor === 'col-resize')
// Same rule as the strip locator above: the LEFTMOST col-resize element
// inside the sidebar host (the tree-dock handle is further right).
const host = document.querySelector('[data-dsh-better-sidebar]')
const strip = host === null
? null
: [...host.querySelectorAll<HTMLElement>('*')]
.filter(el => getComputedStyle(el).cursor === 'col-resize')
.sort((a, b) => a.getBoundingClientRect().x - b.getBoundingClientRect().x)[0]
// The conversation column: the grid item the layout push squeezes (the
// same nth-child(2) layout.css targets for the vertical push; its right
// edge is where the width push lands).
+54 -22
View File
@@ -13,10 +13,13 @@
* plugin's `[data-dsh-better-sidebar]` host mount;
* 3. asserts the plugin's crash markers never appear (no RenderBoundary /
* fail() strips, no `pageerror`, no plugin-prefixed console errors);
* 4. sweeps every built-in tab (Explorer / Source Control / Tasks /
* Terminal / Browser) — including the lazily-fetched terminal chunk —
* and then opens a seeded file through the Explorer to force the
* lazily-fetched editor chunk (client-editor.js) to load as well.
* 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 a seeded
* file through the Files window's tree (in-place mode: the seeded home
* tab itself switches to the file, no new tab), while a response wait
* armed before goto proves the lazily-fetched editor chunk
* (client-editor.js) 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
@@ -35,8 +38,8 @@ if (!BASE_URL) {
/** Workspace the sidebar renders against (created by the lane's seeding). */
const WORKSPACE_PATH = process.env.DSH_E2E_WORKSPACE ?? join(tmpdir(), 'dsh-e2e-workspace')
/** A file seeded into the workspace, opened through the Explorer to force the
* lazily-packed editor chunk (client-editor.js) to load. */
/** A file seeded into the workspace, opened through the Files window's tree to
* exercise the file-open path (editor chunk = client-editor.js). */
const SEEDED_FILE = 'hello.txt'
/**
@@ -47,7 +50,7 @@ const SEEDED_FILE = 'hello.txt'
const CRASH_STRIP_PATTERNS = [/^dsh-better-sidebar:/, /^\[dsh-better-sidebar\]/]
/** Built-in tab titles the sweep drives (en-US copy; follows DSH locale). */
const BUILTIN_TABS = ['Explorer', 'Source Control', 'Tasks', 'Terminal', 'Browser']
const BUILTIN_TABS = ['Files', 'Source Control', 'Tasks', 'Terminal', 'Browser']
let api: APIRequestContext
@@ -91,6 +94,15 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
// Load the shell. The app renders into #root; the plugin appends its own
// [data-dsh-better-sidebar] host once its client half activates.
//
// The editor chunk (client-editor.js) loads as soon as ANY files-window tab
// renders — the seeded home tab mounts the moment the panel expands, long
// before the tree click below — so the response wait must be armed BEFORE
// goto, or it misses the fetch and times out.
const editorChunk = page.waitForResponse(
(response) => response.url().includes('/sidebar/bundle/editor.js'),
{ timeout: 120_000 },
)
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]')
@@ -134,6 +146,12 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
const tabBar = sidebar.locator('[title]')
await expect(tabBar.first()).toBeAttached({ timeout: 90_000 })
// openByDefault defaults OFF: a fresh session's panel starts collapsed.
// Expand it through the toggle cluster before the layout push can apply.
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()
// The skinning contract is token-driven (AGENTS.md §8): the panels consume
// `--dsw-alias-bg-layer-1`, so switching a skin re-skins the sidebar with
// no per-skin code. The layout push variable must be live once the panel
@@ -179,22 +197,36 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
await assertNoCrash()
}
// The editor tab is hidden from the + menu — its CodeMirror chunk
// (client-editor.js) only loads when a file is opened. Exercise that path
// explicitly: reopen Explorer, open the seeded file, and require the chunk
// round-trip, so a missing/corrupt editor chunk fails the lane.
await newTabButton.click()
const explorerItem = page.getByRole('menuitem', { name: 'Explorer' }).first()
await expect(explorerItem, 'Explorer must be re-openable for the editor-chunk probe').toHaveCount(1)
await explorerItem.click()
const editorChunk = page.waitForResponse(
(response) => response.url().includes('/sidebar/bundle/editor.js'),
{ timeout: 30_000 },
)
const fileRow = sidebar.locator(`[role="button"][title$="${SEEDED_FILE}"]`)
await expect(fileRow, `the seeded "${SEEDED_FILE}" file must appear in the Explorer tree`).toHaveCount(1, { timeout: 30_000 })
await fileRow.click()
// The editor chunk (client-editor.js) only loads when a files-window tab
// renders. Exercise the file-open path explicitly through the Files window's
// own tree: the seeded home tab ("Files") is already open with its tree
// panel pinned — activate it from the tab strip, open the seeded file, and
// require the chunk round-trip (armed before goto), so a missing/corrupt
// editor chunk fails the lane.
// Tab-strip tabs carry `draggable="true"`; the always-mounted (hidden)
// bottom panel's empty-pane welcome cards repeat the + menu labels with
// `title="Files"`, so a bare `[title="Files"]` match is ambiguous.
const filesTab = sidebar.locator('[title="Files"][draggable="true"]').first()
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.
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
// the row's right end, and a center click on a narrow dock lands on it
// (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.
await expect(
sidebar.locator('[title="Files"][draggable="true"]'),
'in-place mode rewrites the activated home tab instead of opening a new one',
).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 page.waitForTimeout(1_500)
await assertNoCrash()
+286
View File
@@ -0,0 +1,286 @@
/**
* EditorHost (the files window): in merged (in-place) mode a path-less tab
* renders the empty-state hint with the tree dock open, and the header's
* tree toggle persists its flag through ctx.betterSidebar.updateTab
* (meta.treeOpen rides the tab's persisted layout). The editorExplorer pref
* controls FILE-OPEN behavior — in-place rewrites the current tab via
* updateTab, split opens a per-path dedupe tab via openSidebarFile — and in
* split mode a PATH-LESS window becomes the standalone explorer (tree panel
* only, no editor chrome); file tabs keep the full chrome in both modes.
*/
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest'
import { createElement, useEffect } from 'react'
import { createRoot } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import type { Context } from '../src/context-types.ts'
import { EditorHost } from '../src/client/EditorHost.tsx'
import { createBetterSidebarService } from '../src/client/service.ts'
import { allLeaves, createSidebarStore, type SidebarTab } from '../src/client/state.ts'
// 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). */
function setup(): {
store: ReturnType<typeof createSidebarStore>
ctx: Context
homeTab: () => SidebarTab
} {
const store = createSidebarStore()
const service = createBetterSidebarService(store)
// The openTab path needs a registered editor descriptor (dedupe by path).
service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null })
store.setSession('editor-home-session')
const homeTab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
.find(tab => tab.type === 'editor' && tab.path === undefined)!
// openSidebarFile reads the session cwd from ctx.sessions.
const sessionsSnapshot = { byId: { 'editor-home-session': { cwd: '/tmp' } }, current: 'editor-home-session' }
const ctx = {
betterSidebar: service,
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } },
} as unknown as Context
return { store, ctx, homeTab }
}
/** Mount the host for one tab; returns the container and an unmount helper. */
function mountHost(ctx: Context, store: ReturnType<typeof createSidebarStore>, tab: () => SidebarTab): {
container: HTMLDivElement
rerender: () => void
unmount: () => void
} {
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const render = (): void => {
root.render(createElement(EditorHost, {
ctx,
store,
scope: { sessionId: 'editor-home-session' },
tab: tab(),
expanded: [],
onToggleDir: () => {},
onReferenceFile: () => {},
}))
}
act(render)
return {
container,
// The real app re-renders the host with the fresh tab on every store
// change (Sidebar subscribes); mirror that after mutating the store.
rerender: () => { act(render) },
unmount: () => {
act(() => { root.unmount() })
container.remove()
},
}
}
/** Type into the controlled path input (native setter) and press Enter. */
function typeAndCommit(input: HTMLInputElement, value: string): void {
act(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)
input.dispatchEvent(new Event('input', { bubbles: true }))
})
act(() => {
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
})
}
describe('EditorHost (files window)', () => {
it('a path-less tab renders the empty-state hint with the tree panel open', () => {
const { store, ctx, homeTab } = setup()
const { container, unmount } = mountHost(ctx, store, homeTab)
try {
const html = container.innerHTML
// The empty-state hint renders instead of the viewer loading flow.
expect(html).toContain('Pick a file from the tree panel')
expect(html).not.toContain('Loading…')
// The header carries the path input and the pressed tree toggle; the
// docked panel (search box) is open by default for path-less tabs.
expect(container.querySelector('input')).not.toBeNull()
const toggle = container.querySelector('button[aria-pressed]')
expect(toggle?.getAttribute('aria-pressed')).toBe('true')
// No cwd: the embedded tree renders its no-session placeholder
// instead of touching the network.
expect(html).toContain('Select a conversation')
} finally {
unmount()
}
})
it('the tree toggle persists meta.treeOpen through updateTab', () => {
const { store, ctx, homeTab } = setup()
expect(homeTab().meta).toEqual({ treeOpen: true })
const { container, rerender, unmount } = mountHost(ctx, store, homeTab)
try {
act(() => {
container.querySelector('button[aria-pressed]')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }))
})
expect(homeTab().meta).toEqual({ treeOpen: false })
// The store change re-renders the host with the fresh tab (Sidebar's
// subscription in the real app); the second click flips it back.
rerender()
expect(container.querySelector('button[aria-pressed]')?.getAttribute('aria-pressed')).toBe('false')
act(() => {
container.querySelector('button[aria-pressed]')!
.dispatchEvent(new MouseEvent('click', { bubbles: true }))
})
expect(homeTab().meta).toEqual({ treeOpen: true })
} finally {
unmount()
}
})
it('in-place mode: the path input Enter switches the CURRENT tab (stable id, meta kept)', () => {
const { store, ctx, homeTab } = setup()
const { container, unmount } = mountHost(ctx, store, homeTab)
try {
const before = homeTab()
typeAndCommit(container.querySelector('input')!, '/tmp/a.ts')
// The same tab id now carries the file (homeTab's path-less finder no
// longer matches — look the tab up by id).
const after = allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
.find(tab => tab.id === before.id)!
expect(after.id).toBe(before.id)
expect(after.path).toBe('/tmp/a.ts')
expect(after.title).toBe('a.ts')
expect(after.meta).toEqual({ treeOpen: true })
// No new tab landed.
expect(allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)).toHaveLength(1)
} finally {
unmount()
}
})
it('split mode: a file tab\'s path input Enter opens a NEW per-path tab; the source tab keeps its path', () => {
const { store, ctx } = setup()
store.setPrefs({ ...store.getPrefs(), editorExplorer: false })
ctx.betterSidebar.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts' })
const fileTab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
.find(tab => tab.path === '/tmp/a.ts')!
const { container, unmount } = mountHost(ctx, store, fileTab)
try {
typeAndCommit(container.querySelector('input[placeholder^="File path"]')!, '/tmp/b.ts')
const tabs = allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
// home + a.ts + b.ts
expect(tabs).toHaveLength(3)
expect(fileTab().path).toBe('/tmp/a.ts')
const opened = tabs.find(tab => tab.path === '/tmp/b.ts')!
expect(opened.type).toBe('editor')
expect(opened.title).toBe('b.ts')
expect(opened.id).toBe('editor:/tmp/b.ts')
} finally {
unmount()
}
})
it('split mode: the path-less window is the standalone explorer (tree only, no chrome)', () => {
const { store, ctx, homeTab } = setup()
store.setPrefs({ ...store.getPrefs(), editorExplorer: false })
const { container, unmount } = mountHost(ctx, store, homeTab)
try {
// No editor chrome: no path input, no tree toggle, no resize handle.
expect(container.querySelector('input[placeholder^="File path"]')).toBeNull()
expect(container.querySelector('button[aria-pressed]')).toBeNull()
expect(container.querySelector('[role="separator"]')).toBeNull()
// The tree panel fills the whole window — its search box is the only
// input, and (no cwd) the tree shows its no-session placeholder.
expect(container.querySelector('input[placeholder^="Search files"]')).not.toBeNull()
expect(container.innerHTML).toContain('Select a conversation')
} finally {
unmount()
}
})
it('split mode: a file tab keeps the full chrome (path input + tree toggle + dock)', () => {
const { store, ctx } = setup()
store.setPrefs({ ...store.getPrefs(), editorExplorer: false })
ctx.betterSidebar.openTab({
type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts', meta: { treeOpen: true },
})
const fileTab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
.find(tab => tab.path === '/tmp/a.ts')!
const { container, unmount } = mountHost(ctx, store, fileTab)
try {
expect(container.querySelector('input[placeholder^="File path"]')).not.toBeNull()
expect(container.querySelector('button[aria-pressed]')?.getAttribute('aria-pressed')).toBe('true')
expect(container.querySelector('[role="separator"]')).not.toBeNull()
} finally {
unmount()
}
})
it('dragging the panel edge resizes the dock and persists meta.treeWidth on release', () => {
const { store, ctx, homeTab } = setup()
const { container, unmount } = mountHost(ctx, store, homeTab)
try {
const handle = container.querySelector('[role="separator"]')!
expect(handle).not.toBeNull()
// The dock starts at the default width.
const dock = handle.parentElement!
expect(dock.style.width).toBe('240px')
// Drag the left edge LEFT by 100px → the right-docked panel widens.
// Pointer capture keeps move/up on the handle (jsdom: MouseEvent with
// pointer* type names; setPointerCapture is absent and skipped).
act(() => {
handle.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, clientX: 300 }))
handle.dispatchEvent(new MouseEvent('pointermove', { bubbles: true, clientX: 200 }))
})
expect(dock.style.width).toBe('340px')
// Release: the drag state clears and the width persists on the tab.
act(() => { handle.dispatchEvent(new MouseEvent('pointerup', { bubbles: true, clientX: 200 })) })
expect(homeTab().meta).toEqual({ treeOpen: true, treeWidth: 340 })
} finally {
unmount()
}
})
it('the header hosts the viewer toolbar (mode toggle / dirty dot / save)', () => {
const { store, ctx } = setup()
const service = ctx.betterSidebar
const calls: string[] = []
// A viewer with a hoisted toolbar (the TextEditor contract): register
// commands and report the state once on mount.
service.registerFileViewer({
id: 'test:fake',
exts: ['fake'],
fetchStrategy: 'none',
component: (viewerProps) => {
useEffect(() => {
viewerProps.onToolbarControls?.({
setMode: (next) => { calls.push(`mode:${next}`) },
save: () => { calls.push('save') },
})
viewerProps.onToolbarState?.({ modes: true, mode: 'preview', dirty: true, editable: true, saveState: 'idle' })
return () => { viewerProps.onToolbarControls?.(null) }
}, [])
return null
},
})
service.openTab({ type: 'editor', title: 'x.fake', path: '/tmp/x.fake', id: 'editor:/tmp/x.fake' })
const fileTab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
.find(tab => tab.path === '/tmp/x.fake')!
const { container, unmount } = mountHost(ctx, store, fileTab)
try {
// Mode toggle + dirty dot + save button sit in the header row.
const header = container.querySelector('input')!.parentElement!
const buttons = [...header.querySelectorAll('button')]
expect(buttons.map(b => b.textContent)).toContain('Preview')
expect(buttons.map(b => b.textContent)).toContain('Edit')
expect(header.querySelector('button[aria-label="Save"]')).not.toBeNull()
expect(header.querySelector('[title="Unsaved"]')).not.toBeNull()
// The header commands reach the viewer's registered controls.
act(() => { buttons.find(b => b.textContent === 'Edit')!.click() })
act(() => { header.querySelector<HTMLButtonElement>('button[aria-label="Save"]')!.click() })
expect(calls).toEqual(['mode:edit', 'save'])
} finally {
unmount()
}
})
})
+151
View File
@@ -0,0 +1,151 @@
/**
* fs-search: the host's recursive file-name search behind the editor side
* panel's search box. Matches are case-insensitive name substrings, reported
* RELATIVE to the root ('/'-separated); `.git` directories are skipped,
* symlinked directories are never descended (cycle safety), and the
* maxMatches/maxVisited budgets stop a runaway walk with `truncated: true`.
*/
import { describe, expect, it } from 'vitest'
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { searchFiles } from '../src/fs-search.ts'
/**
* Symlink creation needs extra privileges on Windows; the symlink case skips
* there rather than fails (mirror of the fs-tree symlink spec).
*/
const canSymlink = (() => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-probe-'))
try {
symlinkSync('target', join(dir, 'link'))
return true
} catch {
return false
} finally {
rmSync(dir, { recursive: true, force: true })
}
})()
/** A scratch tree: nested matches, a .git dir, and unrelated noise. */
function makeFixture(): string {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-'))
mkdirSync(join(dir, 'src'))
mkdirSync(join(dir, 'docs'))
mkdirSync(join(dir, '.git'))
mkdirSync(join(dir, '.git', 'objects'))
writeFileSync(join(dir, 'README.md'), 'readme')
writeFileSync(join(dir, 'src', 'Index.TS'), 'code')
writeFileSync(join(dir, 'src', 'util.ts'), 'code')
writeFileSync(join(dir, 'docs', 'guide.md'), 'doc')
writeFileSync(join(dir, '.git', 'config'), 'git-internal')
writeFileSync(join(dir, '.git', 'objects', 'readme-pack'), 'git-internal')
return dir
}
describe('fs-search', () => {
it('matches name substrings and reports root-relative /-separated paths', async () => {
const dir = makeFixture()
try {
const result = await searchFiles(dir, 'util')
expect(result).toEqual({ matches: ['src/util.ts'], truncated: false })
// A multi-level match list is sorted and relative (never absolute).
const md = await searchFiles(dir, '.md')
expect(md.truncated).toBe(false)
expect(md.matches).toEqual(['README.md', 'docs/guide.md'])
for (const match of md.matches) {
expect(match.startsWith(dir)).toBe(false)
expect(match).not.toContain('\\')
}
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('matches case-insensitively on the entry name', async () => {
const dir = makeFixture()
try {
expect((await searchFiles(dir, 'index.ts')).matches).toEqual(['src/Index.TS'])
expect((await searchFiles(dir, 'INDEX.TS')).matches).toEqual(['src/Index.TS'])
// Directory names match too (the client can hint where matches live).
expect((await searchFiles(dir, 'SRC')).matches).toEqual(['src'])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('never descends into .git directories', async () => {
const dir = makeFixture()
try {
// 'readme' would hit .git/objects/readme-pack if the walk entered .git.
expect((await searchFiles(dir, 'readme')).matches).toEqual(['README.md'])
expect((await searchFiles(dir, 'config')).matches).toEqual([])
expect((await searchFiles(dir, '.git')).matches).toEqual([])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('an empty (or whitespace) query matches nothing without walking', async () => {
const dir = makeFixture()
try {
expect(await searchFiles(dir, '')).toEqual({ matches: [], truncated: false })
expect(await searchFiles(dir, ' ')).toEqual({ matches: [], truncated: false })
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it.skipIf(!canSymlink)('does not descend into symlinked directories (cycle safety)', async () => {
const dir = makeFixture()
try {
// A link back to the root would loop forever if descended; a link to
// src would duplicate its matches. Neither must be entered.
symlinkSync(dir, join(dir, 'loop'))
symlinkSync(join(dir, 'src'), join(dir, 'src-link'))
const result = await searchFiles(dir, 'util')
expect(result).toEqual({ matches: ['src/util.ts'], truncated: false })
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('stops with truncated: true when the match budget is exceeded', async () => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-cap-'))
try {
for (let index = 0; index < 5; index += 1) {
writeFileSync(join(dir, `match-${index}.txt`), 'x')
}
const result = await searchFiles(dir, 'match', { maxMatches: 2 })
expect(result.truncated).toBe(true)
expect(result.matches.length).toBe(2)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('stops with truncated: true when the visited budget is exceeded', async () => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-visited-'))
try {
for (let index = 0; index < 5; index += 1) {
writeFileSync(join(dir, `file-${index}.txt`), 'x')
}
// The walk visits more entries than the budget allows and gives up.
const result = await searchFiles(dir, 'nomatch', { maxVisited: 3 })
expect(result.truncated).toBe(true)
expect(result.matches).toEqual([])
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('an unreadable root yields no matches instead of throwing', async () => {
const dir = makeFixture()
try {
const missing = join(dir, 'does-not-exist')
expect(await searchFiles(missing, 'x')).toEqual({ matches: [], truncated: false })
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
})
+5 -3
View File
@@ -49,8 +49,8 @@ describe('dsh-better-sidebar plugin export shape', () => {
const resolved = (PrefsSchema as unknown as {
(input: Record<string, unknown> | undefined): Record<string, unknown>
})(undefined)
expect(resolved.openByDefault).toBe(true)
expect(resolved.defaultWidthPercent).toBe(30)
expect(resolved.openByDefault).toBe(false)
expect(resolved.defaultWidthPercent).toBe(35)
expect(resolved.autoOpenSubagent).toBe(true)
// A new background job auto-opens the Jobs page too.
expect(resolved.autoOpenJobs).toBe(true)
@@ -68,12 +68,14 @@ 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)
// 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, 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: true, titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
})
})
+49 -19
View File
@@ -36,6 +36,7 @@ describe('side card preferences', () => {
terminalFontFamily: '',
terminalFontSize: 13,
interceptOpenPath: true,
editorExplorer: true,
titleBarCompat: false,
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
@@ -53,7 +54,7 @@ describe('side card preferences', () => {
it('falls back per-field when a stored field is malformed', async () => {
expect(await loadPrefs(wire({ openByDefault: 'yes', defaultWidthPercent: 33, autoOpenSubagent: 'no', agentTerminalTools: 'yes' })))
.toEqual({
openByDefault: true,
openByDefault: false,
defaultWidthPercent: 33,
autoOpenSubagent: true,
autoOpenJobs: true,
@@ -62,6 +63,7 @@ describe('side card preferences', () => {
terminalFontFamily: '',
terminalFontSize: 13,
interceptOpenPath: true,
editorExplorer: true,
titleBarCompat: false,
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
@@ -88,6 +90,7 @@ describe('side card preferences', () => {
terminalFontFamily: '',
terminalFontSize: 13,
interceptOpenPath: true,
editorExplorer: true,
titleBarCompat: false,
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
@@ -126,6 +129,16 @@ 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)
// Explicit booleans survive verbatim.
expect((await loadPrefs(wire({ editorExplorer: false }))).editorExplorer).toBe(false)
expect((await loadPrefs(wire({ editorExplorer: true }))).editorExplorer).toBe(true)
})
it('defaults titleBarCompat to false; only an explicit true turns the position-compat mode on', async () => {
// Absent or malformed → off (the normal layout is the default).
expect((await loadPrefs(wire({}))).titleBarCompat).toBe(false)
@@ -198,17 +211,17 @@ 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, 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, 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, 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, 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)
expect(snapshot.state?.width).toBe(400)
// The default prefs keep the panel open.
// The default prefs keep the panel closed (openByDefault defaults off).
const openStore = createSidebarStore()
openStore.setSession('another-fresh')
expect(openStore.getSnapshot().state?.panelOpen).toBe(true)
expect(openStore.getSnapshot().state?.panelOpen).toBe(false)
})
it('seeds a brand-new session COLLAPSED on narrow viewports (the panel is a full-screen drawer there)', () => {
@@ -222,8 +235,8 @@ describe('side card preferences', () => {
}
try {
const store = createSidebarStore()
// Default prefs say openByDefault: true — the narrow viewport overrides
// it for the FIRST seeding only (a later user expansion persists).
// The narrow viewport keeps a fresh session collapsed for the FIRST
// seeding only (a later user expansion persists).
store.setSession('narrow-fresh')
expect(store.getSnapshot().state?.panelOpen).toBe(false)
// The width seeding still follows the window (clamped to the floor).
@@ -234,20 +247,37 @@ describe('side card preferences', () => {
}
})
it('skips the default explorer tab when the explorer type is disabled', () => {
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, titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: { explorer: false }, viewersEnabled: {}, pluginSettings: {} })
store.setSession('no-explorer')
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.setSession('no-editor')
const state = store.getSnapshot().state!
const tabs = allLeaves(state.splits).flatMap(leaf => leaf.tabs)
expect(tabs).toHaveLength(0)
expect(state.splits.kind).toBe('leaf')
// Re-enabling seeds the explorer tab again.
const openStore = createSidebarStore()
openStore.setPrefs({ openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, autoOpenJobs: true, agentTerminalTools: false, bottomPanelAutoTerminal: true, terminalFontFamily: '', terminalFontSize: 13, interceptOpenPath: true, titleBarCompat: false, titleBarStripPx: 40, htmlViewerNoSandbox: false, htmlViewerDefaultUnsafe: false, browserNoSandbox: false, browserInterceptLinks: true, browserInterceptHttp: true, browserInterceptHttps: false, tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {} })
openStore.setSession('with-explorer')
const openTabs = allLeaves(openStore.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
expect(openTabs.map(tab => tab.type)).toEqual(['explorer'])
// Re-enabling seeds the files window (editor home tab) again — in BOTH
// 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.setSession(`with-editor-${editorExplorer}`)
const openTabs = allLeaves(openStore.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
expect(openTabs.map(tab => tab.type)).toEqual(['editor'])
}
})
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.setSession(`fresh-${editorExplorer}`)
const tabs = allLeaves(store.getSnapshot().state!.splits).flatMap(leaf => leaf.tabs)
expect(tabs).toHaveLength(1)
expect(tabs[0]!.type).toBe('editor')
expect(tabs[0]!.title).toBe('Files')
expect(tabs[0]!.path).toBeUndefined()
expect(tabs[0]!.meta).toEqual({ treeOpen: true })
}
})
it('derives the default width from the window percent with clamps', () => {
@@ -260,8 +290,8 @@ describe('side card preferences', () => {
expect(makeDefaultState().panelOpen).toBe(true)
expect(makeDefaultState(400, false).panelOpen).toBe(false)
expect(makeDefaultState(400, false).width).toBe(400)
// The seedExplorer flag controls the default explorer tab.
expect(makeDefaultState(400, true, false).splits.kind).toBe('leaf')
expect((makeDefaultState(400, true, false).splits as { tabs: unknown[] }).tabs).toHaveLength(0)
// The 'none' seed starts with an empty pane (no default tab).
expect(makeDefaultState(400, true, 'none').splits.kind).toBe('leaf')
expect((makeDefaultState(400, true, 'none').splits as { tabs: unknown[] }).tabs).toHaveLength(0)
})
})
+13 -9
View File
@@ -21,7 +21,7 @@ if (g.localStorage === undefined) {
}
import { createBetterSidebarService, matchUrlTarget, SIDEBAR_FEATURES, SIDEBAR_SERVICE_VERSION } from '../src/client/service.ts'
import { createSidebarStore, allLeaves, makeDefaultState, openDiffTab, sanitizeState } from '../src/client/state.ts'
import { createSidebarStore, allLeaves, makeDefaultState, openDiffTab, openTabInActivePane, sanitizeState } from '../src/client/state.ts'
describe('BetterSidebar service', () => {
it('registerTab adds to the registry and dispose removes it', () => {
@@ -108,8 +108,9 @@ describe('enable switches (declarative settings)', () => {
store.setPrefs({ ...store.getPrefs(), tabsEnabled: { explorer: false } })
store.setSession('s1')
service.openTab({ type: 'explorer', title: 'Explorer' })
// The seeded files-window home tab stays; no EXPLORER tab landed.
const tabs = allLeaves(store.getSnapshot().state!.splits).flatMap(l => l.tabs)
expect(tabs).toHaveLength(0)
expect(tabs.filter(t => t.type === 'explorer')).toHaveLength(0)
})
it('matchFileViewer skips a disabled viewer (files fall through)', () => {
@@ -352,7 +353,8 @@ describe('service.openTab dedupe', () => {
store.setSession('s1')
service.openTab({ type: 'editor', title: 'main.ts', path: '/p/main.ts' })
const state = store.getSnapshot().state!
const tab = allLeaves(state.splits).flatMap(l => l.tabs).find(t => t.type === 'editor')
// Find by path: the seeded files-window home tab is an editor tab too.
const tab = allLeaves(state.splits).flatMap(l => l.tabs).find(t => t.type === 'editor' && t.path === '/p/main.ts')
expect(tab?.title).toBe('main.ts')
})
@@ -643,7 +645,7 @@ describe('service.openTab auto-expand for content opens', () => {
service.openTab({ type: 'editor', title: 'main.ts', path: '/p/main.ts' })
const state = store.getSnapshot().state!
expect(state.panelOpen).toBe(true)
expect(allLeaves(state.splits).flatMap(l => l.tabs).filter(t => t.type === 'editor')).toHaveLength(1)
expect(allLeaves(state.splits).flatMap(l => l.tabs).filter(t => t.type === 'editor' && t.path === '/p/main.ts')).toHaveLength(1)
})
})
@@ -671,7 +673,7 @@ describe('state subscription (v0.12.0)', () => {
const snapshot = service.getSnapshot()
expect(snapshot.sessionId).toBe('s1')
expect(snapshot.state).toBeDefined()
expect(snapshot.prefs.openByDefault).toBe(true)
expect(snapshot.prefs.openByDefault).toBe(false)
})
it('subscribeState fires on state changes but NOT on registry changes', () => {
@@ -739,7 +741,7 @@ describe('targeted openTab (v0.12.0)', () => {
service.registerTab({ id: 'notes', title: 'Notes', component: () => null })
store.setSession('s1')
service.openTab({ type: 'notes', title: 'Notes', id: 'notes:1' }, { sessionId: 's2' })
// The UI snapshot still shows s1, untouched (its default explorer tab
// The UI snapshot still shows s1, untouched (its default files-window tab
// is the only one — no notes tab landed there).
const snapshot = store.getSnapshot()
expect(snapshot.sessionId).toBe('s1')
@@ -783,7 +785,8 @@ describe('openFile (v0.12.0)', () => {
store.setSession('s1')
service.openFile({ sessionId: 's1', cwd: '/p' }, '/p/src/main.ts')
const state = store.getSnapshot().state!
const tab = allLeaves(state.splits).flatMap(l => l.tabs).find(t => t.type === 'editor')
// Find by path: the seeded files-window home tab is an editor tab too.
const tab = allLeaves(state.splits).flatMap(l => l.tabs).find(t => t.type === 'editor' && t.path !== undefined)
expect(tab?.title).toBe('main.ts')
expect(tab?.path).toBe('/p/src/main.ts')
// Windows separators are handled too.
@@ -892,8 +895,9 @@ describe('tab meta (v0.12.0)', () => {
})
it('older persisted tabs (no meta) sanitize unchanged', () => {
const state = makeDefaultState(400, true, true)
const sanitized = sanitizeState(JSON.parse(JSON.stringify(state)))
const state = makeDefaultState(400, true, 'none')
const withTab = openTabInActivePane(state, { id: 'tab:old', type: 'git', title: 'Git' })
const sanitized = sanitizeState(JSON.parse(JSON.stringify(withTab)))
const tabs = allLeaves(sanitized!.splits).flatMap(l => l.tabs)
expect(tabs[0]?.meta).toBeUndefined()
})
+103 -5
View File
@@ -1,9 +1,11 @@
/**
* Interactive tests for the settings popup's text/number rows: the draft is
* local state committed on blur through the parent's onCommit; the parent's
* canonical return is adopted (clamped numbers, stored value for invalid
* input), and the row remounts when the committed pref value changes (a
* failed commit reverts prefs → the stored value reappears).
* Interactive tests for the settings popup's text/number/select rows: the
* draft is local state committed on blur through the parent's onCommit; the
* parent's canonical return is adopted (clamped numbers, stored value for
* invalid input), and the row remounts when the committed pref value changes
* (a failed commit reverts prefs → the stored value reappears). Select rows
* commit the picked option's value (single) or the picked values in options
* order (multi) through onSelectValue.
*
* Rendered with createRoot + act() in jsdom (the SSR specs stay in
* side-card-section.spec.tsx; this file exercises the event paths).
@@ -173,3 +175,99 @@ describe('FeatureSettingsRows typed rows (interactive)', () => {
unmount()
})
})
/** Open one select row's dropdown: click the anchor, the Menu portals its
* list into document.body (role="menuitem" rows). */
function openSelect(container: HTMLDivElement): HTMLElement[] {
const anchor = container.querySelector<HTMLButtonElement>('button[aria-haspopup="listbox"]')!
act(() => { anchor.click() })
return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
}
describe('FeatureSettingsRows select rows (interactive)', () => {
const options: NonNullable<SidebarSettingToggle['options']> = [
{ value: true, icon: (size: number) => createElement('i', { 'data-size': size }), title: () => 'Merged', desc: () => 'Docked tree' },
{ value: false, icon: (size: number) => createElement('i', { 'data-size': size }), title: () => 'Split', desc: () => 'Two tabs' },
]
it('commits the picked option value and closes (iconed single select)', () => {
const commits: Array<[string, unknown]> = []
const toggle: SidebarSettingToggle = {
key: 'editorExplorer',
type: 'select',
title: () => 'Editor explorer',
options,
}
const { container, unmount } = mount(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs,
onToggle: () => {},
onSelectValue: (t, next) => { commits.push([t.key, next]) },
}))
// The closed anchor shows the selected option's title (icon variant).
expect(container.textContent).toContain('Merged')
const items = openSelect(container)
// Big-icon cards: title + desc per option.
expect(items.map(item => item.textContent)).toEqual(['MergedDocked tree', 'SplitTwo tabs'])
act(() => { items[1]!.click() })
expect(commits).toEqual([['editorExplorer', false]])
// Single-pick closes the dropdown.
expect(document.querySelectorAll('[role="menuitem"]')).toHaveLength(0)
unmount()
})
it('toggles membership and commits the picked values in options order (multi)', () => {
const commits: Array<[string, unknown]> = []
const plain: NonNullable<SidebarSettingToggle['options']> = [
{ value: 'a', title: () => 'Alpha' },
{ value: 'b', title: () => 'Beta' },
{ value: 'c', title: () => 'Gamma' },
]
const toggle: SidebarSettingToggle = {
key: 'pluginKey',
type: 'select',
multi: true,
title: () => 'Pick several',
options: plain,
}
const rows = (value: unknown) => createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs,
onToggle: () => {},
onSelectValue: (t, next) => { commits.push([t.key, next]) },
valueSource: () => value,
})
const { container, rerender, unmount } = mount(rows(['c', 'a']))
// The anchor shows the picked titles; options follow the declared order.
const items = openSelect(container)
expect(items.map(item => item.textContent)).toEqual(['Alpha', 'Beta', 'Gamma'])
// Deselect 'a' → ['c'] is normalized to options order… (['c'] here).
act(() => { items[0]!.click() })
expect(commits).toEqual([['pluginKey', ['c']]])
// The menu stays open under multi; re-render with the committed value.
rerender(rows(['c']))
const again = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
expect(again).toHaveLength(3)
// Select 'b' → committed in OPTIONS order, not pick order.
act(() => { again[1]!.click() })
expect(commits[1]).toEqual(['pluginKey', ['b', 'c']])
unmount()
})
it('shows an em dash when nothing is selected', () => {
const toggle: SidebarSettingToggle = {
key: 'editorExplorer',
type: 'select',
title: () => 'Editor explorer',
options,
}
const { container, unmount } = mount(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs,
onToggle: () => {},
valueSource: () => undefined,
}))
expect(container.querySelector('button[aria-haspopup="listbox"]')!.textContent).toContain('—')
unmount()
})
})
+12 -11
View File
@@ -80,13 +80,14 @@ describe('SideCardSection declarative inventory', () => {
expect(html).toContain('>explorer<')
expect(html).toContain('data-icon="subagent"')
expect(html).toContain('>Subagents<')
// Default prefs: openByDefault + interceptOpenPath switches checked, and
// both tabs + the image viewer cards pressed (3 aria-pressed cards).
// Default prefs: only the interceptOpenPath switch is checked (openByDefault
// now defaults off), and both tabs + the image viewer cards pressed
// (3 aria-pressed cards).
// The nested auto-open toggle is NOT an inline card (it lives in the popup).
expect(pressedCount(html, 'true')).toBe(3)
expect(pressedCount(html, 'false')).toBe(0)
// The general toggles are custom switches (real checkboxes, checked).
expect(html.match(/checked=""/g)?.length).toBe(2)
// The general toggles are custom switches (real checkboxes, one checked).
expect(html.match(/checked=""/g)?.length).toBe(1)
expect(html).not.toContain('Auto-open Subagents')
})
@@ -140,9 +141,9 @@ describe('SideCardSection declarative inventory', () => {
expect(html).toContain('>Subagents<')
expect(html).toContain('>Image<')
expect(pressedCount(html, 'false')).toBe(2)
// The explorer card stays pressed; the general switches stay checked.
// The explorer card stays pressed; the one default-on general switch stays checked.
expect(pressedCount(html, 'true')).toBe(1)
expect(html.match(/checked=""/g)?.length).toBe(2)
expect(html.match(/checked=""/g)?.length).toBe(1)
})
it('hides the gear of a disabled feature (its related settings are dormant)', () => {
@@ -158,11 +159,11 @@ describe('SideCardSection declarative inventory', () => {
// The general row renders its title and description.
expect(html).toContain('Position compatibility mode')
expect(html).toContain('Reserve space for the native Windows title bar')
// Three general rows now: openByDefault + interceptOpenPath checked,
// the new titleBarCompat row UNCHECKED (default off) — the checked
// checkbox count stays at 2 while the total checkbox count is 3.
// Three general rows now: only interceptOpenPath is checked by default
// (openByDefault defaults off, the titleBarCompat row starts UNCHECKED) —
// the checked checkbox count is 1 while the total checkbox count is 3.
expect(html.match(/type="checkbox"/g)?.length).toBe(3)
expect(html.match(/checked=""/g)?.length).toBe(2)
expect(html.match(/checked=""/g)?.length).toBe(1)
// The row's gear (customize the shift distance) is dormant while the
// mode is off — the feature-card convention.
expect(html).not.toContain('Position compatibility mode Feature settings')
@@ -170,7 +171,7 @@ describe('SideCardSection declarative inventory', () => {
// When the pref is on, the new switch is checked and the gear appears.
store.setPrefs({ ...store.getPrefs(), titleBarCompat: true })
html = renderSection(store, service)
expect(html.match(/checked=""/g)?.length).toBe(3)
expect(html.match(/checked=""/g)?.length).toBe(2)
expect(html).toContain('aria-label="Position compatibility mode Feature settings"')
})
})
+2 -1
View File
@@ -53,7 +53,8 @@ function mountSidebar(): MountedSidebar {
document.body.append(container)
const store = createSidebarStore()
const service = createBetterSidebarService(store)
// Fresh-session seed: the panel starts OPEN (openByDefault default true).
// Fresh-session seed: open the panel explicitly (openByDefault defaults off).
store.setPrefs({ ...store.getPrefs(), openByDefault: true })
store.setSession('s1')
// useSyncExternalStore requires STABLE snapshots across calls (the real DSH
// services return stable objects) — a fresh object per call loops forever.
+6 -5
View File
@@ -566,8 +566,8 @@ describe('side card settings routes', () => {
expect(read.ok).toBe(true)
expect(read.value).toEqual({
value: {
openByDefault: true,
defaultWidthPercent: 30,
openByDefault: false,
defaultWidthPercent: 35,
autoOpenSubagent: true,
autoOpenJobs: true,
agentTerminalTools: false,
@@ -575,6 +575,7 @@ describe('side card settings routes', () => {
terminalFontFamily: '',
terminalFontSize: 13,
interceptOpenPath: true,
editorExplorer: true,
titleBarCompat: false,
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
@@ -592,11 +593,11 @@ describe('side card settings routes', () => {
revision: 0,
})
const written = await invoke(route, 'settings.update', { patch: { openByDefault: false } })
const written = await invoke(route, 'settings.update', { patch: { openByDefault: true } })
expect(written.ok).toBe(true)
const view = written.value as { value: { openByDefault: boolean; defaultWidthPercent: number }; revision: number }
expect(view.value.openByDefault).toBe(false)
expect(view.value.defaultWidthPercent).toBe(30)
expect(view.value.openByDefault).toBe(true)
expect(view.value.defaultWidthPercent).toBe(35)
expect(view.revision).toBe(1)
})
+57 -4
View File
@@ -10,6 +10,59 @@ import {
describe('sidebar state', () => {
const state = (): SidebarState => makeDefaultState()
it('makeDefaultState seeds per the seed enum (editor-home / none)', () => {
// Default and explicit 'editor-home' seed an EMPTY editor tab (the files
// window) with the tree panel pinned open.
for (const s of [makeDefaultState(), makeDefaultState(400, true, 'editor-home')]) {
const leaf = s.splits as { tabs: SidebarTab[]; active: string | null }
expect(leaf.tabs).toHaveLength(1)
expect(leaf.tabs[0]!.type).toBe('editor')
expect(leaf.tabs[0]!.title).toBe('Files')
expect(leaf.tabs[0]!.path).toBeUndefined()
expect(leaf.tabs[0]!.meta).toEqual({ treeOpen: true })
expect(leaf.active).toBe(leaf.tabs[0]!.id)
}
// The seeded home tab survives the persist round-trip (meta intact).
const restored = sanitizeState(JSON.parse(JSON.stringify(makeDefaultState())))
const restoredLeaf = restored!.splits as { tabs: SidebarTab[] }
expect(restoredLeaf.tabs[0]!.meta).toEqual({ treeOpen: true })
// 'none' seeds an empty pane.
const bare = makeDefaultState(400, true, 'none')
const bareLeaf = bare.splits as { tabs: SidebarTab[]; active: string | null }
expect(bareLeaf.tabs).toHaveLength(0)
expect(bareLeaf.active).toBeNull()
})
it('sanitizeState migrates persisted explorer tabs to editor home tabs (both trees)', () => {
const valid = sanitizeState({
panelOpen: true,
width: 400,
nextTerminal: 1,
activePane: 'pane:1',
expanded: [],
splits: {
kind: 'leaf',
id: 'pane:1',
active: 'ex-right',
tabs: [{ id: 'ex-right', type: 'explorer', title: 'Explorer', meta: { treeWidth: 300 } }],
},
bottomSplits: {
kind: 'leaf',
id: 'pane:b',
active: 'ex-bottom',
tabs: [{ id: 'ex-bottom', type: 'explorer', title: 'Explorer' }],
},
})
const right = (valid?.splits as { tabs: SidebarTab[] }).tabs
expect(right).toHaveLength(1)
// Migrated: editor home tab (no path), tree pinned open, prior meta kept.
expect(right[0]).toMatchObject({ id: 'ex-right', type: 'editor', title: 'Files', meta: { treeOpen: true, treeWidth: 300 } })
expect(right[0]!.path).toBeUndefined()
const bottom = (valid?.bottomSplits as { tabs: SidebarTab[] }).tabs
expect(bottom).toHaveLength(1)
expect(bottom[0]).toMatchObject({ id: 'ex-bottom', type: 'editor', title: 'Files', meta: { treeOpen: true } })
})
it('opens tabs into the active pane and dedupes by id (safety net)', () => {
let s = state()
const gitTab = { id: 'git', type: 'git' as const, title: 'Git' }
@@ -411,8 +464,8 @@ describe('sidebar state', () => {
const tab = { id: 'git', type: 'git' as const, title: 'Git' }
s = openTabInActivePane(s, tab)
expect((s.bottomSplits as { tabs: SidebarTab[] }).tabs.map(t => t.id)).toContain('git')
// The right tree is untouched.
expect((s.splits as { tabs: SidebarTab[] }).tabs.map(t => t.type)).toEqual(['explorer'])
// The right tree is untouched (its seeded files-window home tab stays).
expect((s.splits as { tabs: SidebarTab[] }).tabs.map(t => t.type)).toEqual(['editor'])
expect(s.activePane).toBe(bottomPane)
// The id safety net works across trees: reopening the same id focuses it.
const after = openTabInActivePane(s, tab)
@@ -677,8 +730,8 @@ describe('persisted state sanitization', () => {
it('falls back from a stale active pane instead of dropping the open', () => {
let s = makeDefaultState()
const paneA = allLeaves(s.splits)[0]!.id
const explorerTab = allLeaves(s.splits)[0]!.tabs.find(tab => tab.type === 'explorer')!.id
s = closeTab(s, paneA, explorerTab)
const seededTab = allLeaves(s.splits)[0]!.tabs.find(tab => tab.type === 'editor')!.id
s = closeTab(s, paneA, seededTab)
s = openTabInActivePane(s, { id: 'editor:/a.ts', type: 'editor', title: 'a.ts', path: '/a.ts' })
const split = insertLeafAt(s.splits, paneA, 'col', { id: 'terminal:1', type: 'terminal', title: 'Terminal 1' }, false)
s = { ...s, splits: split.node, activePane: paneA }