feat: yield the terminal and browser to DSH 0.1.6's own sidebar types

DSH 0.1.6-alpha.2 ships a right-Sidebar terminal and a right-Sidebar browser
of its own. Both were things this plugin had built from scratch, so keeping
them meant two implementations of one surface plus a plugin that shadows a
host type the product is actively developing.

Terminal: the plugin's whole PTY stack goes — the UI-tab manager, the
agent-owned registry, the lazy node-pty loader, the eight model-facing
terminal_* tools, the xterm view and its font/link/scrollback helpers, and
the cross-session 'pinned terminal' rail that existed only to keep a terminal
alive across a session switch. The host's terminal kind becomes the only
provider, which also retires the node-pty dependency, its pnpm allowBuilds
entry, and the installer's -Repair mode (issue #140's whole class of
'node-pty failed to load' support).

Model-facing capability note: the plugin used to inject terminal_* tools
(off by default). Those are the model's only cross-call persistent terminal,
and DSH's own equivalent (@deepseek-ai/dsh-tool-terminal) is not mounted by
any shipped bundle, so removing them leaves the model with the one-shot
bash/pwsh tools only. That is the accepted cost of not maintaining a second
PTY surface; the README documents how to enable the upstream toolset.

Browser: the plugin's browser tab type is dropped, so the host's own browser
kind owns embedded pages. The DOM-level link takeover STAYS (it is the only
thing that can route an https link to the system browser by protocol, which
the host does not do) but now delegates to the host's browser tab via
ctx.sidebarRight.openTab('browser', …) with a window.open fallback, and the
two settings that only ever configured the plugin's own iframe (sandbox
escape hatch, loopback allowlist) go with it — along with the host-side
browser.probe route they fed.

Cards: the empty-pane welcome cards adopt the host's guide-capsule recipe
(0.5px l4 hairline, 24px radius, layer-1 fill, 56px floor, 14px/20px padding)
so the plugin's 'pick what opens here' surface reads as the same design as
DSH's own. A theme.spec guard pins the geometry and the token-only paint —
including that the upstream-only --dsw-alias-bg-l1/-l2 spellings (defined
nowhere, so their declarations are silently dropped upstream) never appear
here.

Also drops the dead state the removed features left behind (SidebarTab.pin,
nextTerminal, agentWaits, bottomOpenedOnce, the agent-tab helpers, the
pinned-tab memo key), re-points every test fixture that used them at
surviving equivalents, and prunes the specs of the deleted features.
This commit is contained in:
Menghuan1918 committed 2026-09-21 20:35:11 +08:00
1 parent d60899841d
commit 5912274e41
79 files changed
+381 -9464

No files matched your search

-566
View File
@@ -1,566 +0,0 @@
/**
* AgentPtyRegistry unit tests: spawn real ptys (mirroring the pty-manager
* smoke tests) and verify uuid-keyed CRUD, transcript bounding, exit
* tracking, and change-event subscription. The "AttachConsole failed"
* console noise from node-pty's ConPTY module on Windows is expected and
* does not affect the assertions.
*/
import { describe, expect, it, vi } from 'vitest'
import {
AgentPtyRegistry,
ALLOWED_SIGNALS,
snapshotOf,
tryResizePty,
} from '../src/agent-pty.ts'
import { SidebarError } from '../src/wire.ts'
/**
* Resolve a shell binary for tests: on Windows use PowerShell (available on
* every modern Windows host), on POSIX use /bin/sh (universally available).
*/
function testShell(): string {
return process.platform === 'win32' ? 'powershell.exe' : '/bin/sh'
}
/**
* Wait for a freshly spawned shell to have produced ANY output.
*
* The alternative — waiting for a string the prepared command prints — ties
* the test to shell wording, and waiting for a string the command CONTAINS is
* worse: an interactive shell echoes what is written to it (PowerShell does,
* POSIX /bin/sh does not), so the needle would already be in the transcript
* before the point the test means to exercise. The suites that only need "the
* shell is up" therefore wait for output of any kind.
* @param registry - the registry under test.
* @param uuid - the terminal to watch.
* @returns nothing; the caller asserts straight after.
*/
async function waitForShellReady(registry: AgentPtyRegistry, uuid: string): Promise<void> {
await waitForTranscript(registry, uuid, '', 0, true)
}
/** Wait for a terminal's transcript to contain a substring (or timeout). */
async function waitForTranscript(
registry: AgentPtyRegistry,
uuid: string,
needle: string,
timeoutMs = 15_000,
anyOutput = false,
): Promise<string> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
const handle = registry.get(uuid)
if (handle !== undefined) {
if (anyOutput ? handle.transcript.length > 0 : handle.transcript.includes(needle)) return handle.transcript
}
await new Promise(resolve => setTimeout(resolve, 50))
}
const handle = registry.get(uuid)
return handle?.transcript ?? ''
}
describe('tryResizePty', () => {
it('clamps valid dimensions before resizing', () => {
const resize = vi.fn()
expect(tryResizePty({ resize }, 5000, 80.9)).toBe(true)
expect(resize).toHaveBeenCalledWith(1024, 80)
})
it('contains a node-pty resize failure', () => {
const resize = vi.fn(() => {
throw new Error('Usage: pty.resize(fd, cols, rows, xPixel, yPixel)')
})
expect(tryResizePty({ resize }, 80, 24)).toBe(false)
expect(resize).toHaveBeenCalledWith(80, 24)
})
it.each([
[Number.NaN, 24],
[Number.POSITIVE_INFINITY, 24],
[80, Number.NEGATIVE_INFINITY],
])('rejects non-finite dimensions without calling node-pty (%s, %s)', (cols, rows) => {
const resize = vi.fn()
expect(tryResizePty({ resize }, cols, rows)).toBe(false)
expect(resize).not.toHaveBeenCalled()
})
})
/**
* The registry suite really starts a shell per terminal — a PowerShell +
* ConPTY pair on Windows, /bin/sh elsewhere. vitest's 5000 ms default is
* below a cold PowerShell start on a loaded 2-core CI runner (a sibling spec
* measured 12.1 s on 2026-09-10), which is what turned six ci-windows runs
* red in the 2026-09-09/10 window. Generous, but still finite: a genuinely
* hung spawn fails the case.
*/
describe('AgentPtyRegistry', { timeout: 30_000 }, () => {
it('creates a terminal with a uuid, writes the command to stdin, and lists it', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'echo test', 'echo hello-agent-pty', process.cwd(), 80, 24)
expect(uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i)
const list = registry.list('s1')
expect(list).toHaveLength(1)
expect(list[0]!.uuid).toBe(uuid)
expect(list[0]!.title).toBe('echo test')
expect(list[0]!.command).toBe('echo hello-agent-pty')
expect(list[0]!.exited).toBe(false)
// The command was written to stdin; wait for the output.
const transcript = await waitForTranscript(registry, uuid, 'hello-agent-pty')
expect(transcript).toContain('hello-agent-pty')
} finally {
registry.disposeAll()
}
})
it('spawns a bare shell when command is empty', () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'bare', '', process.cwd(), 80, 24)
const handle = registry.get(uuid)
expect(handle).toBeDefined()
expect(handle!.command).toBe('')
expect(handle!.exited).toBe(false)
// The pty process exists; its transcript may take a moment to
// accumulate on Windows ConPTY. The handle is alive and listed.
expect(registry.list('s1')).toHaveLength(1)
} finally {
registry.disposeAll()
}
})
it('sends raw text to stdin (send-keys semantics)', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'sender', '', process.cwd(), 80, 24)
// Wait for the shell prompt, then send a command.
await waitForTranscript(registry, uuid, '', 1000)
// The registry's send() writes verbatim; the caller (tool layer) is
// responsible for appending \r when submit=true. Here we test the
// registry directly: send text + \r to submit.
registry.send(uuid, 'echo sent-via-send\r')
const transcript = await waitForTranscript(registry, uuid, 'sent-via-send')
expect(transcript).toContain('sent-via-send')
} finally {
registry.disposeAll()
}
})
it('reads a bounded page of the transcript', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'reader', 'echo line1\necho line2\necho line3', process.cwd(), 80, 24)
await waitForTranscript(registry, uuid, 'line3')
const page = registry.read(uuid)
expect(page.totalLines).toBeGreaterThan(0)
expect(page.text).toContain('line1')
expect(page.text).toContain('line3')
// Negative offset reads from the end.
const tail = registry.read(uuid, -2)
expect(tail.lineBegin).toBeGreaterThanOrEqual(0)
expect(tail.lineEnd).toBe(tail.lineBegin + tail.text.split('\n').length)
} finally {
registry.disposeAll()
}
})
it('resizes without throwing', () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'resizer', '', process.cwd(), 80, 24)
expect(() => registry.resize(uuid, 120, 40)).not.toThrow()
} finally {
registry.disposeAll()
}
})
it('resize clamps to the 2..1024 range and returns the applied dimensions', () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'clamp', '', process.cwd(), 80, 24)
// Oversized / undersized requests report the clamped values, so the
// echoed result always matches the pty (the tool contract).
expect(registry.resize(uuid, 5000, 1)).toEqual({ cols: 1024, rows: 2 })
expect(registry.resize(uuid, -3, 80.9)).toEqual({ cols: 2, rows: 80 })
expect(registry.resize(uuid, 120, 40)).toEqual({ cols: 120, rows: 40 })
// create clamps through the same helper.
const other = registry.create('s1', 'clamped-create', '', process.cwd(), 1, 9999)
expect(registry.get(other)!.pty.cols).toBe(2)
expect(registry.get(other)!.pty.rows).toBe(1024)
} finally {
registry.disposeAll()
}
})
it('assertOwned rejects a uuid owned by another session', () => {
const registry = new AgentPtyRegistry(testShell())
try {
const mine = registry.create('s1', 'mine', '', process.cwd(), 80, 24)
const theirs = registry.create('s2', 'theirs', '', process.cwd(), 80, 24)
expect(() => registry.assertOwned(mine, 's1')).not.toThrow()
// A foreign uuid is indistinguishable from an unknown one.
expect(() => registry.assertOwned(theirs, 's1')).toThrow(/not found/)
expect(() => registry.assertOwned('nope', 's1')).toThrow(/not found/)
} finally {
registry.disposeAll()
}
})
it('closes a terminal and removes it from the list', () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'closer', '', process.cwd(), 80, 24)
expect(registry.list('s1')).toHaveLength(1)
const closed = registry.close(uuid)
expect(closed).toBe(true)
expect(registry.list('s1')).toHaveLength(0)
// Closing again is a no-op.
const closedAgain = registry.close(uuid)
expect(closedAgain).toBe(false)
} finally {
registry.disposeAll()
}
})
it('scopes list by session id', () => {
const registry = new AgentPtyRegistry(testShell())
try {
registry.create('s1', 'a', '', process.cwd(), 80, 24)
registry.create('s1', 'b', '', process.cwd(), 80, 24)
registry.create('s2', 'c', '', process.cwd(), 80, 24)
expect(registry.list('s1')).toHaveLength(2)
expect(registry.list('s2')).toHaveLength(1)
expect(registry.list('s3')).toHaveLength(0)
} finally {
registry.disposeAll()
}
})
it('fires change listeners on create, close, and exit', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
let changeCount = 0
registry.subscribe(() => { changeCount += 1 })
const uuid = registry.create('s1', 'watched', '', process.cwd(), 80, 24)
// create fires one change.
expect(changeCount).toBeGreaterThanOrEqual(1)
registry.close(uuid)
// close fires another change.
expect(changeCount).toBeGreaterThanOrEqual(2)
} finally {
registry.disposeAll()
}
})
it('disposeAll closes every terminal', () => {
const registry = new AgentPtyRegistry(testShell())
registry.create('s1', 'a', '', process.cwd(), 80, 24)
registry.create('s2', 'b', '', process.cwd(), 80, 24)
registry.disposeAll()
expect(registry.list('s1')).toHaveLength(0)
expect(registry.list('s2')).toHaveLength(0)
})
it('snapshotOf drops the pty reference and transcript', () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'snap', '', process.cwd(), 80, 24)
const handle = registry.get(uuid)!
const snap = snapshotOf(handle)
expect(snap.uuid).toBe(uuid)
expect(snap.title).toBe('snap')
expect(snap.exited).toBe(false)
// No pty or transcript fields on the snapshot.
expect('pty' in snap).toBe(false)
expect('transcript' in snap).toBe(false)
// sessionId is registry-internal ownership, never serialized (it would
// violate the terminal_list output schema's additionalProperties:false).
expect('sessionId' in snap).toBe(false)
expect('sessionId' in registry.list('s1')[0]!).toBe(false)
} finally {
registry.disposeAll()
}
})
it('ALLOWED_SIGNALS includes SIGINT, SIGTERM, SIGKILL, SIGHUP, SIGTSTP', () => {
expect(ALLOWED_SIGNALS).toContain('SIGINT')
expect(ALLOWED_SIGNALS).toContain('SIGTERM')
expect(ALLOWED_SIGNALS).toContain('SIGKILL')
expect(ALLOWED_SIGNALS).toContain('SIGHUP')
expect(ALLOWED_SIGNALS).toContain('SIGTSTP')
})
it('waitFor returns found when the needle is already in the transcript', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'echo-test', 'echo wait-for-fast', process.cwd(), 80, 24)
await waitForTranscript(registry, uuid, 'wait-for-fast')
// The needle is already present; waitFor should return immediately.
const result = await registry.waitFor(uuid, 'wait-for-fast', 2000)
expect(result.kind).toBe('found')
if (result.kind === 'found') {
expect(result.needle).toBe('wait-for-fast')
expect(result.elapsedMs).toBeLessThan(500)
}
} finally {
registry.disposeAll()
}
})
it('waitFor supports regex alternation and reports which alternative matched', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
// Multi-outcome pattern (build success/failure): the terminal prints
// only the FAILURE marker; the alternation must match immediately and
// the `match` field must tell WHICH alternative hit.
const uuid = registry.create('s1', 'multi-outcome', 'echo BUILD_FAIL', process.cwd(), 80, 24)
await waitForTranscript(registry, uuid, 'BUILD_FAIL')
const result = await registry.waitFor(uuid, 'BUILD_(OK|FAIL)', 2000)
expect(result.kind).toBe('found')
if (result.kind === 'found') {
expect(result.needle).toBe('BUILD_(OK|FAIL)')
expect(result.match).toBe('BUILD_FAIL')
}
} finally {
registry.disposeAll()
}
})
it('waitFor falls back to verbatim matching when the pattern is not a valid regex', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
// `BUILD_(OK` does not compile as a regex (unbalanced group); the wait
// must degrade to literal substring matching and still find it.
const uuid = registry.create('s1', 'bad-regex', 'echo "BUILD_(OK literal"', process.cwd(), 80, 24)
await waitForTranscript(registry, uuid, 'BUILD_(OK')
const result = await registry.waitFor(uuid, 'BUILD_(OK', 2000)
expect(result.kind).toBe('found')
if (result.kind === 'found') {
expect(result.match).toBe('BUILD_(OK')
}
} finally {
registry.disposeAll()
}
})
it('waitFor regex matches text a plain substring could not express', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'regex-version', 'echo version v1.2.3 ready', process.cwd(), 80, 24)
await waitForTranscript(registry, uuid, 'v1.2.3')
const result = await registry.waitFor(uuid, String.raw`v\d+\.\d+\.\d+`, 2000)
expect(result.kind).toBe('found')
if (result.kind === 'found') {
expect(result.match).toBe('v1.2.3')
}
} finally {
registry.disposeAll()
}
})
it('waitFor returns found after the needle appears (async output)', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
// Spawn a shell WITH a command (so output is guaranteed), but start
// the wait for a DIFFERENT needle that only appears after we send
// a follow-up command. This exercises the subscribe/poll path: the
// wait must notice output arriving AFTER it started, not just find
// pre-existing content.
const uuid = registry.create('s1', 'async-echo', 'echo shell-ready', process.cwd(), 80, 24)
// Wait for the initial command's output so we know the shell is live.
await waitForTranscript(registry, uuid, 'shell-ready', 10_000)
// Start the wait BEFORE sending the follow-up command. The needle is
// NOT in the transcript yet. ConPTY under test concurrency can be slow,
// so the timeout is generous.
const waitPromise = registry.waitFor(uuid, 'UNIQUE_NEEDLE_42', 30_000)
// Give the wait a moment to subscribe, then send the command.
await new Promise(resolve => setTimeout(resolve, 200))
registry.send(uuid, 'echo UNIQUE_NEEDLE_42\r')
const result = await waitPromise
expect(result.kind).toBe('found')
if (result.kind === 'found') {
expect(result.needle).toBe('UNIQUE_NEEDLE_42')
}
} finally {
registry.disposeAll()
}
}, 40_000)
it('waitFor returns timeout when the needle never appears', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'silent', '', process.cwd(), 80, 24)
await waitForTranscript(registry, uuid, '', 1000)
// Wait for a needle that will never appear; use a short timeout to
// keep the test fast.
const result = await registry.waitFor(uuid, 'this-needle-will-never-appear', 500)
expect(result.kind).toBe('timeout')
if (result.kind === 'timeout') {
expect(result.timeoutMs).toBe(500)
expect(result.totalLines).toBeGreaterThan(0)
}
} finally {
registry.disposeAll()
}
})
it('waitFor throws on an empty needle', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'empty-needle', '', process.cwd(), 80, 24)
await expect(registry.waitFor(uuid, '', 500)).rejects.toThrow()
} finally {
registry.disposeAll()
}
})
it('waitFor throws on an unknown uuid', async () => {
const registry = new AgentPtyRegistry(testShell())
await expect(registry.waitFor('nonexistent-uuid', 'foo', 500)).rejects.toThrow()
})
it('waitFor returns skipped when the user skips from the sidebar', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
// A BARE shell, and the wait needle appears nowhere in its preparation:
// an interactive shell echoes what is written to it, so a command that
// spelled the needle would already have put it in the transcript before
// this point — waitFor's fast path would resolve the wait and there
// would be nothing left to skip. POSIX /bin/sh does not echo a command
// written to a non-tty and hid this for a long time; PowerShell does,
// which is why it only ever failed on Windows.
const uuid = registry.create('s1', 'skip-test', '', process.cwd(), 80, 24)
await waitForShellReady(registry, uuid)
// waitFor registers its record synchronously (before the first poll
// await), so the skip can fire immediately after the call.
const waitPromise = registry.waitFor(uuid, 'NEVER_APPEARS_XYZ', 30_000)
expect(await registry.skipWait(uuid)).toBe(1)
const result = await waitPromise
expect(result.kind).toBe('skipped')
if (result.kind === 'skipped') expect(result.needle).toBe('NEVER_APPEARS_XYZ')
// Idempotent: nothing left to skip once the wait resolved.
expect(registry.skipWait(uuid)).toBe(0)
} finally {
registry.disposeAll()
}
})
it('snapshot exposes waiting while a wait is active and clears after it ends', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
// Same echo hazard as the skip case above: a bare shell puts no needle
// in the transcript on its own.
const uuid = registry.create('s1', 'wait-snap', '', process.cwd(), 80, 24)
await waitForShellReady(registry, uuid)
const waitPromise = registry.waitFor(uuid, 'LATER_MARK_9', 30_000)
// Registration happens synchronously before waitFor's first await.
expect(registry.list('s1')[0]?.waiting?.needle).toBe('LATER_MARK_9')
expect(typeof registry.list('s1')[0]?.waiting?.since).toBe('number')
expect(registry.skipWait(uuid)).toBe(1)
const result = await waitPromise
expect(result.kind).toBe('skipped')
expect(registry.list('s1')[0]?.waiting).toBeUndefined()
} finally {
registry.disposeAll()
}
})
it('concurrent waits on one uuid: snapshot shows the latest needle, skipWait skips all', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'concurrent', '', process.cwd(), 80, 24)
// The bare shell never emits either needle → both waits miss the fast
// paths and register their records (synchronously, before waitFor's
// first poll await — the documented concurrent-wait contract).
const first = registry.waitFor(uuid, 'NEVER_A_XYZ', 60_000)
const second = registry.waitFor(uuid, 'NEVER_B_XYZ', 60_000)
// The banner mirrors the LATEST wait (waits.at(-1)).
expect(registry.list('s1')[0]?.waiting?.needle).toBe('NEVER_B_XYZ')
expect(typeof registry.list('s1')[0]?.waiting?.since).toBe('number')
// One skip transitions EVERY active wait on the terminal.
expect(registry.skipWait(uuid)).toBe(2)
expect(await first).toEqual({ kind: 'skipped', needle: 'NEVER_A_XYZ' })
expect(await second).toEqual({ kind: 'skipped', needle: 'NEVER_B_XYZ' })
// Both resolved → the wait state cleared from the snapshot.
expect(registry.list('s1')[0]?.waiting).toBeUndefined()
// Idempotent: nothing left to skip.
expect(registry.skipWait(uuid)).toBe(0)
} finally {
registry.disposeAll()
}
})
it('fires change listeners when a wait starts and ends', async () => {
const registry = new AgentPtyRegistry(testShell())
try {
// Same echo hazard as the skip case above: a bare shell puts no needle
// in the transcript on its own.
const uuid = registry.create('s1', 'watched-wait', '', process.cwd(), 80, 24)
await waitForShellReady(registry, uuid)
let changes = 0
const unsubscribe = registry.subscribe(() => { changes += 1 })
const waitPromise = registry.waitFor(uuid, 'NEVER_NOTIFY_1', 30_000)
const afterStart = changes
expect(afterStart).toBeGreaterThanOrEqual(1)
expect(await registry.skipWait(uuid)).toBe(1)
expect(await waitPromise).toEqual({ kind: 'skipped', needle: 'NEVER_NOTIFY_1' })
expect(changes).toBeGreaterThan(afterStart)
unsubscribe()
} finally {
registry.disposeAll()
}
})
it('skipWait rejects an unknown uuid with not-found', () => {
const registry = new AgentPtyRegistry(testShell())
try {
expect(() => registry.skipWait('missing-uuid')).toThrow(/not found/)
// The HTTP layer maps `status` straight onto the response, so the 404
// contract rides this field — assert it, not just the message.
let thrown: unknown
try {
registry.skipWait('missing-uuid')
} catch (error) {
thrown = error
}
expect(thrown).toBeInstanceOf(SidebarError)
expect((thrown as SidebarError).status).toBe(404)
expect((thrown as SidebarError).code).toBe('not-found')
} finally {
registry.disposeAll()
}
})
it('delivers SIGINT and SIGTSTP by writing control characters (cross-platform)', () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'signal-test', '', process.cwd(), 80, 24)
// SIGINT and SIGTSTP are delivered by writing \x03 / \x1a to the pty
// stdin — the cross-platform way terminals send Ctrl+C / Ctrl+Z.
// These must NOT throw (the old kill(SIGINT) path threw on Windows).
expect(() => registry.signal(uuid, 'SIGINT')).not.toThrow()
expect(() => registry.signal(uuid, 'SIGTSTP')).not.toThrow()
// The control byte was written to the pty; the shell received it.
// On POSIX the line discipline generates the signal; on Windows
// ConPTY translates it. Either way the write path is exercised.
} finally {
registry.disposeAll()
}
})
it('delivers SIGKILL via the process-termination path', () => {
const registry = new AgentPtyRegistry(testShell())
try {
const uuid = registry.create('s1', 'kill-test', '', process.cwd(), 80, 24)
// SIGKILL uses pty.kill() (TerminateProcess on Windows). Must not
// throw even when the pty's kill() rejects named signals — the
// fallback to the default kill ensures the signal takes effect.
expect(() => registry.signal(uuid, 'SIGKILL')).not.toThrow()
} finally {
registry.disposeAll()
}
})
})
-148
View File
@@ -1,148 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
allLeaves, makeDefaultState, openTabInBottomPane, reconcileAgentTerminals,
setTabPin, tabOpenIn, toggleBottomPanel,
} from '../src/client/state.ts'
describe('agent terminal reconciliation', () => {
it('adds tabs for new agent terminals', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [
{ uuid: 'aaa-111', title: 'dev server' },
{ uuid: 'bbb-222', title: 'python repl' },
])
expect(tabOpenIn(s, 'agent:aaa-111')).toBe(true)
expect(tabOpenIn(s, 'agent:bbb-222')).toBe(true)
// The titles are preserved.
const tabs = allLeaves(s.bottomSplits).flatMap(leaf => leaf.tabs)
const agentTab = tabs.find(t => t.id === 'agent:aaa-111')
expect(agentTab?.title).toBe('dev server')
expect(agentTab?.type).toBe('terminal')
})
it('removes tabs for agent terminals that vanished from the server list', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [
{ uuid: 'aaa-111', title: 'keep' },
{ uuid: 'bbb-222', title: 'remove' },
])
expect(tabOpenIn(s, 'agent:bbb-222')).toBe(true)
// Next push drops bbb-222.
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'keep' }])
expect(tabOpenIn(s, 'agent:aaa-111')).toBe(true)
expect(tabOpenIn(s, 'agent:bbb-222')).toBe(false)
})
it('is a no-op (same reference) when the lists already match', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'stable' }])
const next = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'stable' }])
expect(next).toBe(s)
})
it('does not touch non-agent terminal tabs', () => {
let s = makeDefaultState()
s = openTabInBottomPane(s, { id: 'terminal:1', type: 'terminal', title: 'UI Tab' })
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'agent' }])
expect(tabOpenIn(s, 'terminal:1')).toBe(true)
expect(tabOpenIn(s, 'agent:aaa-111')).toBe(true)
})
it('handles an empty server list (removes all agent tabs)', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [
{ uuid: 'aaa-111', title: 'a' },
{ uuid: 'bbb-222', title: 'b' },
])
s = reconcileAgentTerminals(s, [])
expect(tabOpenIn(s, 'agent:aaa-111')).toBe(false)
expect(tabOpenIn(s, 'agent:bbb-222')).toBe(false)
})
it('lands new agent terminals in the workbench pane', () => {
let s = makeDefaultState()
s = toggleBottomPanel(s)
const pane = (s.bottomSplits as { id: string }).id
s = { ...s, activePane: pane }
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'dev server' }])
expect(tabOpenIn(s, 'agent:aaa-111')).toBe(true)
expect(allLeaves(s.bottomSplits).flatMap(l => l.tabs).some(t => t.id === 'agent:aaa-111')).toBe(true)
})
describe('pinned agent terminal exemption (v0.17.0)', () => {
it('keeps a pinned agent tab when its uuid vanishes from the server list', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [
{ uuid: 'aaa-111', title: 'keep' },
{ uuid: 'bbb-222', title: 'pinned' },
])
// Pin bbb-222, then drop it from the server list.
s = setTabPin(s, 'agent:bbb-222', { scope: 'global' })
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'keep' }])
// aaa-111 (unpinned) survived; bbb-222 (pinned) survived too.
expect(tabOpenIn(s, 'agent:aaa-111')).toBe(true)
expect(tabOpenIn(s, 'agent:bbb-222')).toBe(true)
// The pin marker is intact.
const tabs = allLeaves(s.bottomSplits).flatMap(l => l.tabs)
const pinned = tabs.find(t => t.id === 'agent:bbb-222')!
expect(pinned.pin).toEqual({ scope: 'global' })
})
it('still removes an unpinned agent tab when the uuid vanishes', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [
{ uuid: 'aaa-111', title: 'pinned' },
{ uuid: 'bbb-222', title: 'unpinned' },
])
s = setTabPin(s, 'agent:aaa-111', { scope: 'workspace', homeCwd: '/p' })
s = reconcileAgentTerminals(s, []) // both vanish
// Pinned stays, unpinned goes.
expect(tabOpenIn(s, 'agent:aaa-111')).toBe(true)
expect(tabOpenIn(s, 'agent:bbb-222')).toBe(false)
})
it('a pinned tab whose uuid RETURNS in a later push is a no-op (already exists)', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'gone' }])
s = setTabPin(s, 'agent:aaa-111', { scope: 'global' })
// First push without it: exempted, stays.
s = reconcileAgentTerminals(s, [])
expect(tabOpenIn(s, 'agent:aaa-111')).toBe(true)
// Later push brings it back: reconcile sees the uuid already exists,
// does not re-add, does not touch the pin.
const before = s
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'gone' }])
expect(s).toBe(before)
})
it('exemption does not block the toAdd path (new uuids still land)', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'first' }])
s = setTabPin(s, 'agent:aaa-111', { scope: 'global' })
// aaa-111 vanishes (exempted), bbb-222 is brand-new.
s = reconcileAgentTerminals(s, [{ uuid: 'bbb-222', title: 'second' }])
expect(tabOpenIn(s, 'agent:aaa-111')).toBe(true) // pinned, kept
expect(tabOpenIn(s, 'agent:bbb-222')).toBe(true) // new, added
})
})
it('mirrors the pushed waiting state into agentWaits and clears it when it ends', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'busy', waiting: { needle: 'READY_1', since: 42 } }])
expect(s.agentWaits['aaa-111']).toEqual({ needle: 'READY_1', since: 42 })
// The next push without waiting drops the entry (the push is authoritative).
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'stable' }])
expect(s.agentWaits['aaa-111']).toBeUndefined()
})
it('produces a new state when ONLY the wait state changes (no tab add/remove)', () => {
let s = makeDefaultState()
s = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'stable' }])
const before = s
const next = reconcileAgentTerminals(s, [{ uuid: 'aaa-111', title: 'stable', waiting: { needle: 'N', since: 1 } }])
expect(next).not.toBe(before)
expect(next.agentWaits['aaa-111']).toBeDefined()
// Idempotent: the same push again returns the same reference.
expect(reconcileAgentTerminals(next, [{ uuid: 'aaa-111', title: 'stable', waiting: { needle: 'N', since: 1 } }])).toBe(next)
})
})
-138
View File
@@ -1,138 +0,0 @@
/**
* The agent-terminal wait badge chain, end to end in jsdom: the host's
* agent-terminals push (mirroring the real /sidebar/ws/agent-terminals
* frames) reconciles tabs AND the wait map; the shell's tabBadgeOf renders
* the hourglass pill on the agent tab while a wait is live and drops it
* when the push clears. Harness mirrors tests/bottom-auto-terminal.spec.tsx
* (real Sidebar shell + fake context + stubbed WebSocket).
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
import { Sidebar } from '../src/client/Sidebar.tsx'
import { createSidebarStore, openTabInBottomPane } from '../src/client/state.ts'
import { createBetterSidebarService, type BetterSidebarService } from '../src/client/service.ts'
/** jsdom has no WebSocket; the agent-terminals push effect constructs one on mount. */
class FakeWebSocket {
static instances: FakeWebSocket[] = []
onmessage: ((event: { data: unknown }) => void) | null = null
onclose: (() => void) | null = null
onerror: (() => void) | null = null
close = (): void => {}
constructor(readonly url: string) {
FakeWebSocket.instances.push(this)
}
}
/** Unique per-test session ids (see the comment inside mountSidebar). */
let sessionSeq = 0
/** Roots mounted by the current test; afterEach unmounts them (reverse
* order) so React effect cleanup (store subscription, host-feed sockets,
* debounced persistence) actually runs between tests. */
const mounted: Array<() => void> = []
function mountSidebar(): { container: HTMLDivElement; store: ReturnType<typeof createSidebarStore>; service: BetterSidebarService; unmount: () => void } {
vi.stubGlobal('WebSocket', FakeWebSocket)
FakeWebSocket.instances = []
const container = document.createElement('div')
document.body.append(container)
const store = createSidebarStore()
const service = createBetterSidebarService(store)
// Replace the terminal descriptor with a stub: the real one lazy-loads the
// xterm chunk, which jsdom cannot fetch — the badge under test renders in
// the TAB STRIP, independent of the view component.
service.registerTab({
id: 'terminal',
title: () => 'Terminal',
component: () => null,
})
// 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)
const localeSnapshot = { active: 'en' }
const sessionsSnapshot = {
current: sessionId,
byId: { [sessionId]: { cwd: '/tmp' } },
}
const ctx = {
locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot },
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } },
betterSidebar: service,
get: (name: string) => name === 'betterSidebar' ? service : undefined,
}
const root: Root = createRoot(container)
act(() => { root.render(createElement(Sidebar, { ctx: ctx as never, store })) })
const unmount = (): void => {
act(() => { root.unmount() })
container.remove()
}
mounted.push(unmount)
return { container, store, service, unmount }
}
afterEach(() => {
// Unmount BEFORE wiping the DOM: root.unmount() must run the shell's
// effect cleanups (store subscription, WS close, persistence debounce);
// document.body.innerHTML = '' alone leaves them alive into later tests.
for (const unmount of mounted.splice(0).reverse()) unmount()
document.body.innerHTML = ''
// Belt and braces (same as bottom-auto-terminal): drop any persisted layout
// a pending 200ms debounce write left behind between tests. Fully guarded —
// some node/jsdom combos expose no working localStorage, and an opaque
// origin can define it as a THROWING accessor, so even `typeof` can throw;
// the try/catch keeps the cleanup hook itself failure-proof.
try {
if (typeof localStorage !== 'undefined') localStorage.clear()
} catch {
// Opaque origin / no storage: nothing persisted to clear.
}
vi.unstubAllGlobals()
})
/** The agent-terminals push socket the shell opened for the current session. */
function feedsSocket(): FakeWebSocket {
const socket = FakeWebSocket.instances.find(candidate => candidate.url.includes('/sidebar/ws/agent-terminals'))
if (socket === undefined) throw new Error('agent-terminals socket not connected')
return socket
}
describe('agent terminal wait badge (push → state → tab pill)', () => {
it('shows ⏳ on the agent tab while a wait is active and drops it when it ends', () => {
const { container } = mountSidebar()
const terminal = { uuid: 'u1', title: 'dev server', command: '', exited: false }
// First push: the agent tab lands in the active pane.
act(() => { feedsSocket().onmessage?.({ data: JSON.stringify([terminal]) }) })
expect(container.textContent).toContain('dev server')
expect(container.textContent).not.toContain('⏳')
// Second push carries a live wait → the hourglass pill appears.
act(() => { feedsSocket().onmessage?.({ data: JSON.stringify([{ ...terminal, waiting: { needle: 'READY_1', since: 1 } }]) }) })
expect(container.textContent).toContain('⏳')
// The wait resolved (skip/exit/abort all converge to a waiting-less push).
act(() => { feedsSocket().onmessage?.({ data: JSON.stringify([terminal]) }) })
expect(container.textContent).not.toContain('⏳')
})
it('shows ⏳ only on agent tabs, never on UI-owned terminal tabs', () => {
const { container, store } = mountSidebar()
// A UI-owned terminal tab (id NOT agent:) lives in the strip too; the
// badge lookup keys on the agent uuid, so it never badges.
act(() => { store.reduce(s => openTabInBottomPane(s, { id: 'terminal:manual-1', type: 'terminal', title: 'UI terminal' })) })
const terminal = { uuid: 'u1', title: 'dev server', command: '', exited: false }
act(() => { feedsSocket().onmessage?.({ data: JSON.stringify([{ ...terminal, waiting: { needle: 'READY_1', since: 1 } }]) }) })
// Exactly ONE hourglass: the agent tab. (Counted from textContent — CSS
// module class names are not stable under the test transform.)
expect((container.textContent?.match(/⏳/g) ?? []).length).toBe(1)
// The wait resolved → the pill disappears entirely.
act(() => { feedsSocket().onmessage?.({ data: JSON.stringify([terminal]) }) })
expect(container.textContent).not.toContain('⏳')
})
})
-180
View File
@@ -1,180 +0,0 @@
/**
* Bottom-panel first-expand auto-terminal tests — the TRIGGER CHAIN behind
* issue #42 (bottom panel first expand + auto terminal → whole panel blank).
*
* #42's crash itself was the zero-size xterm open (the same root cause as
* #25, fixed by openWhenSized — see tests/open-when-sized.spec.ts), and the
* "whole panel blank" amplification is covered by the per-tab containment
* tests (tests/sidebar-crash.spec.tsx). What no test pinned was the trigger:
* the Sidebar effect that opens a terminal tab the FIRST time the bottom
* panel expands (`bottomOpenedOnce`), its pref / enable-switch gates, and
* the once-per-session semantics. These tests render the REAL Sidebar shell
* against a minimal fake context (the repo's jsdom pattern) and drive the
* bottom panel through the store, asserting the tab lands in the bottom
* workbench, renders, and the panel itself survives.
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
// The act() environment flag (React 18.2 reads it before flushing effects).
import { setupReactAct } from './test-utils.ts'
setupReactAct()
import { Sidebar } from '../src/client/Sidebar.tsx'
import { allLeaves, createSidebarStore, toggleBottomPanel, type SidebarStore } from '../src/client/state.ts'
import { createBetterSidebarService, type BetterSidebarService } from '../src/client/service.ts'
import { t } from '../src/client/locales.ts'
/** jsdom has no WebSocket; the agent-terminals push effect constructs one on mount. */
class FakeWebSocket {
onmessage: ((event: { data: unknown }) => void) | null = null
onclose: (() => void) | null = null
onerror: (() => void) | null = null
close = (): void => {}
constructor(_url: string) {}
}
interface MountedSidebar {
container: HTMLDivElement
store: SidebarStore
service: BetterSidebarService
unmount: () => void
}
/** 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')
document.body.append(container)
const store = createSidebarStore()
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).
// 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: sessionId,
// cwd present → api.sessionCwd is never called in these tests.
byId: { [sessionId]: { cwd: '/tmp' } },
}
const ctx = {
locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot },
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } },
betterSidebar: service,
get: (name: string) => name === 'betterSidebar' ? service : undefined,
}
const root: Root = createRoot(container)
act(() => { root.render(createElement(Sidebar, { ctx: ctx as never, store })) })
return {
container,
store,
service,
unmount: () => {
act(() => { root.unmount() })
container.remove()
},
}
}
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()
})
/** Every tab currently living in the bottom workbench. */
function bottomTabs(store: SidebarStore): Array<{ type: string; title: string }> {
const state = store.getSnapshot().state
if (state === undefined) return []
return allLeaves(state.bottomSplits).flatMap(leaf => leaf.tabs)
}
/** The stub terminal tab: counts renders so the test can see it actually mount. */
function registerStubTerminal(service: BetterSidebarService, renders: { count: number }): void {
service.registerTab({
id: 'terminal',
title: () => 'Terminal',
component: () => {
renders.count += 1
return createElement('div', null, 'terminal-stub-content')
},
})
}
describe('bottom-panel first-expand auto terminal (issue #42 trigger chain)', () => {
it('auto-opens exactly one terminal tab in the bottom workbench on the FIRST expansion', () => {
const { container, store, service } = mountSidebar()
const renders = { count: 0 }
registerStubTerminal(service, renders)
act(() => { store.reduce(toggleBottomPanel) })
const state = store.getSnapshot().state!
expect(state.bottomOpen).toBe(true)
// The once-flag is set atomically with the first fire.
expect(state.bottomOpenedOnce).toBe(true)
// The terminal tab landed in the BOTTOM workbench (the effect pins the
// active pane to the bottom tree's first leaf before opening).
expect(bottomTabs(store).map(tab => tab.type)).toEqual(['terminal'])
// The tab actually mounted and rendered — the chain is live end to end.
expect(renders.count).toBeGreaterThanOrEqual(1)
expect(container.textContent).toContain('terminal-stub-content')
// The panel itself survived (the #42 symptom was a WHOLE blank panel):
// the close control is present and the layout push for the bottom panel
// height is live.
expect(container.querySelector(`[aria-label="${t('collapseBottomPanel')}"]`)).not.toBeNull()
expect(document.documentElement.style.getPropertyValue('--dsh-sidebar-height')).toBe(
`${state.bottomHeight}px`,
)
})
it('never repeats the auto-open on later expansions (once per session)', () => {
const { store, service } = mountSidebar()
registerStubTerminal(service, { count: 0 })
act(() => { store.reduce(toggleBottomPanel) })
expect(bottomTabs(store)).toHaveLength(1)
// Collapse → expand again: the once-flag suppresses any second terminal.
act(() => { store.reduce(toggleBottomPanel) })
expect(store.getSnapshot().state!.bottomOpen).toBe(false)
act(() => { store.reduce(toggleBottomPanel) })
expect(bottomTabs(store)).toHaveLength(1)
})
it('does not auto-open when the bottomPanelAutoTerminal pref is off', () => {
const { store, service } = mountSidebar()
registerStubTerminal(service, { count: 0 })
// setPrefs REPLACES the prefs record — spread the current one so only
// the toggle moves.
act(() => { store.setPrefs({ ...store.getPrefs(), bottomPanelAutoTerminal: false }) })
act(() => { store.reduce(toggleBottomPanel) })
expect(store.getSnapshot().state!.bottomOpen).toBe(true)
expect(bottomTabs(store)).toHaveLength(0)
})
it('does not auto-open when the terminal tab type is disabled in settings', () => {
const { store, service } = mountSidebar()
registerStubTerminal(service, { count: 0 })
act(() => { store.setPrefs({ ...store.getPrefs(), tabsEnabled: { terminal: false } }) })
act(() => { store.reduce(toggleBottomPanel) })
expect(store.getSnapshot().state!.bottomOpen).toBe(true)
expect(bottomTabs(store)).toHaveLength(0)
})
})
-50
View File
@@ -1,50 +0,0 @@
/**
* browser.probe helpers: the CSP frame-ancestors parser (host side) and the
* embeddability verdict (client side). Together they turn the target's
* response headers into the "refused to be embedded" explanation the
* sidebar browser shows instead of the browser's cryptic blank frame.
*/
import { describe, expect, it } from 'vitest'
import { extractFrameAncestors } from '../src/browser-probe.ts'
import { embeddabilityOf } from '../src/client/browser.ts'
describe('extractFrameAncestors', () => {
it('extracts a frame-ancestors source list from a CSP header', () => {
expect(extractFrameAncestors("default-src 'self'; frame-ancestors 'none'"))
.toEqual(["'none'"])
expect(extractFrameAncestors("frame-ancestors 'self' https://example.com"))
.toEqual(["'self'", 'https://example.com'])
expect(extractFrameAncestors('frame-ancestors *')).toEqual(['*'])
})
it('is undefined when the directive is absent or empty', () => {
expect(extractFrameAncestors(null)).toBeUndefined()
expect(extractFrameAncestors("default-src 'self'")).toBeUndefined()
expect(extractFrameAncestors('frame-ancestors')).toBeUndefined()
expect(extractFrameAncestors('frame-ancestors ; default-src *')).toBeUndefined()
})
})
describe('embeddabilityOf', () => {
it('blocks X-Frame-Options DENY / SAMEORIGIN', () => {
expect(embeddabilityOf({ reachable: true, status: 200, xFrameOptions: 'DENY' })).toBe('blocked')
expect(embeddabilityOf({ reachable: true, status: 200, xFrameOptions: 'SAMEORIGIN' })).toBe('blocked')
expect(embeddabilityOf({ reachable: true, status: 200, xFrameOptions: 'sameorigin' })).toBe('blocked')
})
it('blocks a frame-ancestors list that does not allow * ("self" means the SITE origin, never ours)', () => {
expect(embeddabilityOf({ reachable: true, frameAncestors: ["'none'"] })).toBe('blocked')
expect(embeddabilityOf({ reachable: true, frameAncestors: ["'self'"] })).toBe('blocked')
expect(embeddabilityOf({ reachable: true, frameAncestors: ["'self'", 'https://x.dev'] })).toBe('blocked')
})
it('allows a wildcard frame-ancestors and absent anti-framing headers', () => {
expect(embeddabilityOf({ reachable: true, status: 200, frameAncestors: ['*'] })).toBe('embeddable')
expect(embeddabilityOf({ reachable: true, status: 200 })).toBe('embeddable')
expect(embeddabilityOf({ reachable: true, status: 200, xFrameOptions: 'ALLOW-FROM https://x' })).toBe('embeddable')
})
it('is unknown when the target is unreachable (plain iframe stays)', () => {
expect(embeddabilityOf({ reachable: false })).toBe('unknown')
})
})
-79
View File
@@ -1,79 +0,0 @@
/**
* Browser address-bar policy tests: only http(s) URLs may be navigated,
* loopback addresses and the GUI's own origin are refused outright. The
* iframe sandbox (opaque origin) is the primary security boundary; this
* policy is the address-bar gate on top of it.
*/
import { describe, expect, it } from 'vitest'
import { isLoopbackHostname, normalizeBrowserUrl } from '../src/client/browser.ts'
const SELF = 'http://127.0.0.1:3080'
describe('normalizeBrowserUrl', () => {
it('normalizes a bare domain to https', () => {
expect(normalizeBrowserUrl('example.com', SELF)).toEqual({ kind: 'ok', url: 'https://example.com/' })
})
it('normalizes a host with a port to https', () => {
expect(normalizeBrowserUrl('example.com:8080/path', SELF)).toEqual({ kind: 'ok', url: 'https://example.com:8080/path' })
})
it('keeps an explicit http:// scheme', () => {
expect(normalizeBrowserUrl('http://example.com/a?b=1', SELF)).toEqual({ kind: 'ok', url: 'http://example.com/a?b=1' })
})
it('accepts a non-loopback IP literal', () => {
expect(normalizeBrowserUrl('https://8.8.8.8/dns', SELF)?.kind).toBe('ok')
})
it('refuses non-http(s) schemes', () => {
expect(normalizeBrowserUrl('javascript:alert(1)', SELF)).toEqual({ kind: 'blocked', reason: 'scheme' })
expect(normalizeBrowserUrl('data:text/html,<b>x</b>', SELF)).toEqual({ kind: 'blocked', reason: 'scheme' })
expect(normalizeBrowserUrl('file:///etc/passwd', SELF)).toEqual({ kind: 'blocked', reason: 'scheme' })
expect(normalizeBrowserUrl('about:blank', SELF)).toEqual({ kind: 'blocked', reason: 'scheme' })
})
it('refuses loopback hostnames in every spelling', () => {
for (const input of [
'http://localhost/', 'https://localhost:3080/', 'http://LOCALHOST/',
'http://127.0.0.1/', 'http://127.255.255.255/',
'http://[::1]/', 'http://0.0.0.0/',
]) {
expect(normalizeBrowserUrl(input, SELF), input).toEqual({ kind: 'blocked', reason: 'loopback' })
}
})
it('allows the GUI\'s own origin (the sandbox keeps it opaque like any site)', () => {
// The user may browse the GUI itself in the sidebar; its host is
// loopback, so the self check must win BEFORE the loopback gate.
expect(normalizeBrowserUrl('http://127.0.0.1:3080/sidebar', SELF)).toEqual({
kind: 'ok', url: 'http://127.0.0.1:3080/sidebar',
})
expect(normalizeBrowserUrl('http://127.0.0.1:3080/', SELF)).toEqual({
kind: 'ok', url: 'http://127.0.0.1:3080/',
})
// A different port of the same loopback host is NOT the GUI origin and
// stays blocked.
expect(normalizeBrowserUrl('http://127.0.0.1:9999/', SELF)).toEqual({ kind: 'blocked', reason: 'loopback' })
})
it('reports invalid input', () => {
expect(normalizeBrowserUrl('', SELF)).toEqual({ kind: 'invalid' })
expect(normalizeBrowserUrl(' ', SELF)).toEqual({ kind: 'invalid' })
expect(normalizeBrowserUrl('ht tp://x', SELF)).toEqual({ kind: 'invalid' })
})
})
describe('isLoopbackHostname', () => {
it('flags localhost, IPv6 loopback, and the 127/8 block', () => {
expect(isLoopbackHostname('localhost')).toBe(true)
expect(isLoopbackHostname('::1')).toBe(true)
expect(isLoopbackHostname('[::1]')).toBe(true)
expect(isLoopbackHostname('127.0.0.1')).toBe(true)
expect(isLoopbackHostname('127.8.9.10')).toBe(true)
expect(isLoopbackHostname('0.0.0.0')).toBe(true)
expect(isLoopbackHostname('example.com')).toBe(false)
expect(isLoopbackHostname('128.0.0.1')).toBe(false)
expect(isLoopbackHostname('192.168.1.1')).toBe(false)
})
})
+7 -96
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 5 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
@@ -9,31 +9,28 @@
*/
import { describe, expect, it } from 'vitest'
import type { ReactElement } from 'react'
import { VscCommentDiscussion, VscGitCommit, VscGlobe, VscLayers, VscTerminal } from 'react-icons/vsc'
import { VscCommentDiscussion, VscGitCommit, VscLayers } from 'react-icons/vsc'
// First import: browser globals before the xterm-carrying builtin graph loads.
import './browser-globals.ts'
import type { Context } from '../src/context-types.ts'
import { createBetterSidebarService } from '../src/client/service.ts'
import { createSidebarStore } from '../src/client/state.ts'
import { allLeaves } from '../src/client/state.ts'
import { registerBuiltins } from '../src/client/builtins/index.ts'
import type { BuiltinTabOptions } from '../src/client/builtins/tabs.tsx'
import { parkSidechatReopen } from '../src/client/SideChatView.tsx'
import { t } from '../src/client/locales.ts'
function setup(options: BuiltinTabOptions = {}): { service: ReturnType<typeof createBetterSidebarService>; store: ReturnType<typeof createSidebarStore>; dispose: () => void } {
function setup(): { service: ReturnType<typeof createBetterSidebarService>; store: ReturnType<typeof createSidebarStore>; dispose: () => void } {
const store = createSidebarStore()
const service = createBetterSidebarService(store)
const dispose = registerBuiltins({} as Context, service, options)
const dispose = registerBuiltins({} as Context, service)
return { service, store, dispose }
}
describe('built-in tab registrations', () => {
it('registers the 7 built-in tabs', () => {
it('registers the 5 built-in tabs (the host owns terminal and browser)', () => {
const { service } = setup()
expect(service.getTabs().map(t => t.id).sort()).toEqual(
['browser', 'diff', 'editor', 'git', 'sidechat', 'subagent', 'terminal'],
['diff', 'editor', 'git', 'sidechat', 'subagent'],
)
})
@@ -101,7 +98,7 @@ describe('built-in tab registrations', () => {
}
})
it('the side chat tab sits between tasks and terminal in the + menu', () => {
it('the side chat tab sits between tasks and the removed terminal slot in the + menu', () => {
const { service } = setup()
const sidechat = service.getTab('sidechat')
expect(sidechat?.order).toBe(35)
@@ -154,83 +151,6 @@ describe('built-in tab registrations', () => {
expect(service.getTab('editor')?.settings?.render).toBeDefined()
})
it('the terminal tab declares the model terminal-tools, auto-terminal, shell and custom-font settings', () => {
const { service } = setup()
const toggles = service.getTab('terminal')?.settings?.toggles ?? []
expect(toggles.map(t => t.key)).toEqual(['agentTerminalTools', 'bottomPanelAutoTerminal', 'terminalShell', 'terminalShellArgs', 'terminalFontFamily', 'terminalFontSize'])
// The shell rows are text inputs (empty = yaml/auto resolution), the
// font rows text/number inputs (not switches), with the size row bounded
// by the shared 9–32 contract.
expect(toggles[2]?.type).toBe('text')
expect(toggles[2]?.title).toBeDefined()
expect(toggles[2]?.placeholder).toBeDefined()
expect(toggles[3]?.type).toBe('text')
expect(toggles[3]?.title).toBeDefined()
expect(toggles[4]?.type).toBe('text')
expect(toggles[4]?.title).toBeDefined()
expect(toggles[4]?.placeholder).toBeDefined()
expect(toggles[5]?.type).toBe('number')
expect(toggles[5]?.min).toBe(9)
expect(toggles[5]?.max).toBe(32)
expect(toggles[5]?.unit).toBe('px')
// The first two rows stay plain boolean switches.
expect(toggles[0]?.type ?? 'switch').toBe('switch')
expect(toggles[1]?.type ?? 'switch').toBe('switch')
})
it('the browser tab declares its sandbox, link-takeover master and per-protocol settings', () => {
const { service } = setup()
const toggles = service.getTab('browser')?.settings?.toggles ?? []
expect(toggles.map(t => t.key)).toEqual([
'browserNoSandbox',
'browserInterceptLinks',
'browserInterceptHttp',
'browserInterceptHttps',
'browserAllowedLoopback',
])
for (const toggle of toggles) {
expect(toggle.title).toBeDefined()
expect(toggle.desc).toBeDefined()
}
})
it('the browser createTab mints browser:<n> ids and bumps nextBrowser', () => {
const { service, store } = setup()
store.setSession('s1')
service.openTab({ type: 'browser' })
service.openTab({ type: 'browser' })
const state = store.getSnapshot().state!
const tabs = allLeaves(state.bottomSplits).flatMap(leaf => leaf.tabs).filter(t => t.type === 'browser')
expect(tabs).toHaveLength(2)
expect(tabs[0]!.id).toBe('browser:1')
expect(tabs[1]!.id).toBe('browser:2')
expect(state.nextBrowser).toBe(3)
})
it('the terminal createTab uses shell-name titles and hidden uuid ids, allowing duplicates', () => {
const { service, store } = setup({ terminalTitle: () => 'bash' })
store.setSession('s1')
service.openTab({ type: 'terminal' })
service.openTab({ type: 'terminal' })
const state = store.getSnapshot().state!
const tabs = allLeaves(state.bottomSplits).flatMap(leaf => leaf.tabs).filter(t => t.type === 'terminal')
expect(tabs).toHaveLength(2)
expect(tabs[0]!.title).toBe('bash')
expect(tabs[1]!.title).toBe('bash')
expect(tabs[0]!.id).toMatch(/^terminal:[0-9a-f-]{36}$/)
expect(tabs[1]!.id).toMatch(/^terminal:[0-9a-f-]{36}$/)
expect(tabs[0]!.id).not.toBe(tabs[1]!.id)
})
it('the terminal createTab falls back to the localized terminal label before shell info resolves', () => {
const { service, store } = setup()
store.setSession('s1')
service.openTab({ type: 'terminal' })
const state = store.getSnapshot().state!
const tab = allLeaves(state.bottomSplits).flatMap(leaf => leaf.tabs).find(t => t.type === 'terminal')
expect(tab?.title).toBe(t('terminal'))
})
it('every built-in tab carries the settings-surface icon', () => {
const { service } = setup()
for (const tab of service.getTabs()) {
@@ -256,15 +176,6 @@ describe('built-in tab registrations', () => {
expect(glyphOf('subagent')).toBe(VscLayers)
expect(glyphOf('git')).toBe(VscGitCommit)
expect(glyphOf('sidechat')).toBe(VscCommentDiscussion)
expect(glyphOf('browser')).toBe(VscGlobe)
// The terminal glyph is the widest in the set, so it renders a step down
// from the strip's size. No outline: the glyphs stay exactly as the icon
// set draws them, only tinted through the wrapper's token.
const wrapper = iconOf('terminal') as ReactElement<{ children?: ReactElement }>
const terminal = wrapper.props.children as ReactElement<{ size?: number; style?: Record<string, unknown> }>
expect(terminal.type).toBe(VscTerminal)
expect(terminal.props.size).toBeLessThan(14)
expect(terminal.props.style).toBeUndefined()
})
})
+3 -3
View File
@@ -117,9 +117,9 @@ describe('/sidebar/bundle route', () => {
const { handler, cleanup } = setup()
try {
const res = fakeRes()
// 'terminal' is allowlisted but the scratch fixture only ships
// 'locale' is allowlisted but the scratch fixture only ships
// client-editor.js — the built file is missing → 404.
await handler(req('GET', '/sidebar/bundle/terminal.js'), res as unknown as ServerResponse)
await handler(req('GET', '/sidebar/bundle/locale.js'), res as unknown as ServerResponse)
expect(res.status).toBe(404)
} finally {
cleanup()
@@ -150,6 +150,6 @@ describe('/sidebar/bundle route', () => {
})
it('exports the chunk allowlist (mirror of src/client/chunk-loader.ts)', () => {
expect([...CHUNK_NAMES]).toEqual(['terminal', 'editor', 'mermaid', 'locale'])
expect([...CHUNK_NAMES]).toEqual(['editor', 'mermaid', 'locale'])
})
})
+2 -2
View File
@@ -11,13 +11,13 @@
import { existsSync, readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
// Browser globals first: chunk bodies probe `self`/`document` at evaluation
// (xterm's UMD wrapper, CodeMirror's UA probe).
// (CodeMirror's UA probe).
import './browser-globals.ts'
import { CHUNK_EXTERNALS } from '../src/client/chunk-loader.ts'
const g = globalThis as Record<string, unknown>
const CHUNKS = ['terminal', 'editor', 'mermaid']
const CHUNKS = ['editor', 'mermaid']
/** All chunk artifacts present (tsdown emits the whole lib/ in one run). */
const chunksBuilt = CHUNKS.every(name => existsSync(`lib/client-${name}.js`))
+14 -14
View File
@@ -71,13 +71,13 @@ describe('test-registry path (vitest / jsdom-less environments)', () => {
it('a failed load clears the cache so the next call retries', async () => {
let calls = 0
registerChunkForTests('terminal', async () => {
registerChunkForTests('locale', async () => {
calls += 1
if (calls === 1) throw new Error('boom')
return { TerminalView: 'terminal-view' }
return { localeDicts: 'locale-dicts' }
})
await expect(loadChunk('terminal')).rejects.toThrow('boom')
await expect(loadChunk('terminal')).resolves.toEqual({ TerminalView: 'terminal-view' })
await expect(loadChunk('locale')).rejects.toThrow('boom')
await expect(loadChunk('locale')).resolves.toEqual({ localeDicts: 'locale-dicts' })
expect(calls).toBe(2)
})
})
@@ -131,11 +131,11 @@ describe('production path (script injection + global registry + externals requir
const seen: string[] = []
setChunkScriptLoaderForTests(async (src) => {
seen.push(src)
simulateScript(src.endsWith('editor.js') ? 'editor' : 'terminal', () => ({}))
simulateScript(src.endsWith('editor.js') ? 'editor' : 'locale', () => ({}))
})
await loadChunk('terminal')
await loadChunk('locale')
await loadChunk('editor')
expect(seen).toEqual(['/sidebar/bundle/terminal.js', '/sidebar/bundle/editor.js'])
expect(seen).toEqual(['/sidebar/bundle/locale.js', '/sidebar/bundle/editor.js'])
expect(modules.import).toHaveBeenCalledTimes(CHUNK_EXTERNALS.length)
})
@@ -150,11 +150,11 @@ describe('production path (script injection + global registry + externals requir
it('a script load failure rejects without materializing', async () => {
const modules = installModuleSystem()
setChunkScriptLoaderForTests(async () => { throw new Error('script 404') })
await expect(loadChunk('terminal')).rejects.toThrow('script 404')
await expect(loadChunk('locale')).rejects.toThrow('script 404')
expect(modules.import).not.toHaveBeenCalled()
// Cache cleared: the retry re-attempts the script load.
setChunkScriptLoaderForTests(async () => { simulateScript('terminal', () => ({ TerminalView: 'ok' })) })
await expect(loadChunk('terminal')).resolves.toEqual({ TerminalView: 'ok' })
setChunkScriptLoaderForTests(async () => { simulateScript('locale', () => ({ localeDicts: 'ok' })) })
await expect(loadChunk('locale')).resolves.toEqual({ localeDicts: 'ok' })
})
it('a script that ran but registered no factory fails with a clear error', async () => {
@@ -216,7 +216,7 @@ describe('revalidateChunksOnReactivate (HMR re-activation keeps unchanged chunks
function stubBundleHead(etagFor: (name: string) => string | null | Error): void {
vi.stubGlobal('fetch', vi.fn(async (input: unknown) => {
const url = String(input)
const name = url.endsWith('terminal.js') ? 'terminal' : 'editor'
const name = url.endsWith('locale.js') ? 'locale' : 'editor'
const etag = etagFor(name)
if (etag instanceof Error) throw etag
return {
@@ -268,13 +268,13 @@ describe('revalidateChunksOnReactivate (HMR re-activation keeps unchanged chunks
let scriptCalls = 0
setChunkScriptLoaderForTests(async () => {
scriptCalls += 1
simulateScript('terminal', () => ({ TerminalView: 'tv' }))
simulateScript('locale', () => ({ localeDicts: 'ld' }))
})
stubBundleHead(() => new Error('HEAD unreachable'))
await loadChunk('terminal')
await loadChunk('locale')
await settleEtag()
await revalidateChunksOnReactivate()
await loadChunk('terminal')
await loadChunk('locale')
expect(scriptCalls).toBe(2)
})
+2 -2
View File
@@ -53,8 +53,8 @@ const tab: TabDescriptor = {
single: false,
dedupeKey: (t: SidebarTab) => t.id,
createTab: (state: SidebarState) => ({
tab: { id: `my-plugin:db:${state.nextTerminal}`, type: 'my-plugin:db', title: 'DB', meta: { n: state.nextTerminal } },
patch: { nextTerminal: state.nextTerminal + 1 },
tab: { id: `my-plugin:db:${state.nextBrowser}`, type: 'my-plugin:db', title: 'DB', meta: { n: state.nextBrowser } },
patch: { nextBrowser: state.nextBrowser + 1 },
}),
badge: (ctx, scope, state) => (state.expanded.length > 0 ? state.expanded.length : null),
onOpen: (tab: SidebarTab, scope: SessionScope) => { void tab; void scope },
+20 -9
View File
@@ -13,11 +13,12 @@
* 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. expands DSH's native right Sidebar, sweeps every built-in tab type
* through its guide page (Files / Changes / Tasks / Terminal / Browser) —
* including the lazily-fetched terminal chunk — and then opens seeded
* files through the Files window's tree (separate mode: each file opens
* its own new tab, the seeded home "Files" tab stays the explorer),
* 4. expands DSH's native right Sidebar, sweeps every tab type the COMPOSED
* guide offers (the plugin's own Files / Changes / Tasks / Side chat, plus
* whatever the host contributes — its own terminal and browser tab types
* when those packages are mounted) through its guide page, and then opens
* seeded files through the Files window's tree (separate mode: each file
* opens its own new tab, the seeded home "Files" tab stays the explorer),
* while response waits armed before goto prove the lazily-fetched editor
* chunk (client-editor.js) and the mermaid chunk (client-mermaid.js,
* rendered SVG diagram + zoom modal) loaded.
@@ -56,8 +57,18 @@ const SEEDED_README_FILE = 'readme-style.md'
*/
const CRASH_STRIP_PATTERNS = [/^dsh-better-sidebar:/, /^\[dsh-better-sidebar\]/]
/** Built-in tab titles the sweep drives (en-US copy; follows DSH locale). */
const NATIVE_TABS = ['files', 'git', 'subagent', 'sidechat', 'terminal', 'browser']
/**
* The tab types the plugin itself contributes, plus the host-owned kinds the
* guide is asserted to still offer.
*
* `terminal` and `browser` are DSH 0.1.6's own right-Sidebar types: this
* plugin deliberately ships neither (it used to own both), so the guide must
* show exactly ONE entry for each when the host mounts those packages — a
* second entry would mean the plugin is shadowing the host again.
*/
const PLUGIN_TABS = ['files', 'git', 'subagent', 'sidechat'] as const
const HOST_OWNED_TABS = ['terminal', 'browser'] as const
const NATIVE_TABS: readonly string[] = [...PLUGIN_TABS, ...HOST_OWNED_TABS]
let api: APIRequestContext
/** The seeded session id (captured by seedSession; the Side Chat smoke's parent). */
@@ -288,7 +299,7 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
}
// Sweep every type through the guide. Each open mounts a real viewer (the
// terminal fetches its lazy chunk); a failure anywhere surfaces as a
// editor and mermaid chunks arrive lazily); a failure anywhere surfaces as a
// pageerror or a crash strip, both of which the next assertion sees. A pane
// holds one guide tab, so re-seed it through the strip's add control before
// every pick.
@@ -361,7 +372,7 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
const settingsGetBody = (await settingsGet.json()) as { value?: { tabsEnabled?: Record<string, boolean> } }
const originalTabsEnabled = settingsGetBody.value?.tabsEnabled ?? {}
/** The types this check switches off (leaving three entries, i.e. ≤4). */
const shrunken = ['git', 'subagent', 'terminal'] as const
const shrunken = ['git', 'subagent'] as const
try {
// Send the FULL map back (the route's patch is key-wise merged, so a
// full map is correct whether the host merges or replaces).
+7 -2
View File
@@ -33,8 +33,13 @@ import { PAGE_URL, createHostApi, hostRpc, sendFirstMessage } from './host'
* share seed paths with mount/drag). */
const WORKSPACE_PATH = process.env.DSH_E2E_PERF_WORKSPACE ?? join(tmpdir(), 'dsh-e2e-perf-workspace')
/** Built-in tab titles the sweep drives (en-US copy; follows DSH locale). */
const NATIVE_TABS = ['files', 'git', 'subagent', 'sidechat', 'terminal', 'browser']
/**
* Every tab type the composed guide must offer: the plugin's own four plus
* DSH 0.1.6's host-owned terminal and browser. This plugin deliberately ships
* neither of those, so exactly one entry each proves it is not shadowing the
* host. The ids are the guides' `data-sidebar-right-guide-entry` keys.
*/
const NATIVE_TABS = ['files', 'git', 'subagent', 'sidechat', 'terminal', 'browser'] as const
let api: APIRequestContext
+23 -42
View File
@@ -17,7 +17,6 @@ import { builtinTabs } from '../src/client/builtins/tabs.tsx'
import { builtinViewers } from '../src/client/builtins/viewers.tsx'
import { registerChunkForTests, resetChunks } from '../src/client/chunk-loader.ts'
import { lazyChunkComponent } from '../src/client/lazy-chunk.tsx'
import type { Context } from '../src/context-types.ts'
import type { FileViewerProps, TabComponentProps } from '../src/client/service.ts'
import css from '../src/client/sidebar.module.css'
@@ -72,8 +71,8 @@ describe('lazyChunkComponent', () => {
it('props flow through to the chunk component', async () => {
const Recorder = (props: { label: string }): ReactNode => createElement('div', { 'data-testid': 'rec', 'data-label': props.label })
registerChunkForTests('terminal', async () => ({ TerminalView: Recorder }))
const Wrapper = lazyChunkComponent<{ label: string }>('terminal', (mod) => mod.TerminalView as ComponentType<{ label: string }> | undefined)
registerChunkForTests('mermaid', async () => ({ MermaidMarkdown: Recorder }))
const Wrapper = lazyChunkComponent<{ label: string }>('mermaid', (mod) => mod.MermaidMarkdown as ComponentType<{ label: string }> | undefined)
const { container, unmount } = renderRoot(createElement(Wrapper, { label: 'hello' }))
await act(async () => {})
expect(container.querySelector('[data-testid="rec"]')?.getAttribute('data-label')).toBe('hello')
@@ -93,14 +92,14 @@ describe('built-in descriptor contract (render-prop functions)', () => {
}
})
it('the terminal tab component keeps the same contract', () => {
const tabs = builtinTabs({} as Context)
const terminal = tabs.find(tab => tab.id === 'terminal')
expect(terminal).toBeDefined()
// The descriptor reads tab.id (the tabId mapping); a real tab is part of
// the contract — Sidebar always provides one.
const props = { tab: { id: 'terminal:1', type: 'terminal', title: '终端 1' } } as unknown as TabComponentProps
expect(() => terminal!.component(props)).not.toThrow()
it('a built-in tab component keeps the same contract', () => {
const tabs = builtinTabs()
const editor = tabs.find(tab => tab.id === 'editor')
expect(editor).toBeDefined()
// The descriptor renders from props; a real tab is part of the contract —
// Sidebar always provides one.
const props = { tab: { id: 'editor:1', type: 'editor', title: '文件' } } as unknown as TabComponentProps
expect(() => editor!.component(props)).not.toThrow()
})
it('a built-in viewer mounted without a chunk available degrades to the error + retry affordance (no crash)', async () => {
@@ -133,44 +132,26 @@ describe('built-in descriptor contract (render-prop functions)', () => {
unmount()
})
it('the terminal descriptor maps tab.id → tabId (TerminalView props are not TabComponentProps)', async () => {
let received: unknown
registerChunkForTests('terminal', async () => ({
TerminalView: ((props: { tabId: string }) => {
received = props.tabId
return createElement('div', { 'data-testid': 'terminal-tabid' }, props.tabId)
}) as unknown as ComponentType<Record<string, never>>,
}))
const tabs = builtinTabs({} as Context)
const terminal = tabs.find(tab => tab.id === 'terminal')!
it('the loader cache survives across descriptor mounts (chunk fetched once)', async () => {
let calls = 0
registerChunkForTests('editor', async () => {
calls += 1
return { TextEditor: Marker }
})
const markdown = builtinViewers().find(viewer => viewer.id === 'markdown')!
const props = {
ctx: {},
store: undefined,
scope: { sessionId: 's1', cwd: '/p' },
tab: { id: 'terminal:2', type: 'terminal', title: '终端 2' },
visible: true,
} as unknown as TabComponentProps
const { container, unmount } = renderRoot(createElement(terminal.component, props))
await act(async () => {})
expect(container.querySelector('[data-testid="terminal-tabid"]')?.textContent).toBe('terminal:2')
expect(received).toBe('terminal:2')
unmount()
})
it('the loader cache survives across descriptor mounts (chunk fetched once)', async () => {
let calls = 0
registerChunkForTests('terminal', async () => {
calls += 1
return { TerminalView: Marker }
})
const tabs = builtinTabs({} as Context)
const terminal = tabs.find(tab => tab.id === 'terminal')!
const props = { tab: { id: 'terminal:1', type: 'terminal', title: '终端 1' } } as unknown as TabComponentProps
const { container: first, unmount: unmountFirst } = renderRoot(createElement(terminal.component, props))
path: '/p/a.md',
title: 'a.md',
viewerId: 'markdown',
} as unknown as FileViewerProps
const { container: first, unmount: unmountFirst } = renderRoot(createElement(markdown.component, props))
await act(async () => {})
expect(first.querySelector('[data-testid="chunk-rendered"]')).not.toBeNull()
unmountFirst()
const { container: second, unmount: unmountSecond } = renderRoot(createElement(terminal.component, props))
const { container: second, unmount: unmountSecond } = renderRoot(createElement(markdown.component, props))
await act(async () => {})
expect(second.querySelector('[data-testid="chunk-rendered"]')).not.toBeNull()
unmountSecond()
+12 -2
View File
@@ -48,7 +48,17 @@ interface PackageJson {
const manifest = JSON.parse(readFileSync(resolve(ROOT, 'dsh.plugin.json'), 'utf8')) as PluginManifest
const pkg = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf8')) as PackageJson
/** The registry's strict id validation (manifest.ts / client-modules registerExternal): exactly two lowercase slash-separated segments. */
/**
* The THIRD-PARTY registry channel's id rule (the community market validates
* `dsh.plugin.json`'s id itself): exactly two lowercase slash-separated
* segments.
*
* `dsh.plugin.json` is NOT a DSH contract — no DSH version reads it, and the
* official channel is `package.json`'s `dsh.bundle.patch` + `dsh.client` +
* `exports["./client"]` (asserted in tests/plugin-shape.spec.ts). This spec
* guards the registry channel's own shape so publishing there cannot break
* silently.
*/
const ID_PATTERN = /^(?!node_modules\/)(?:@[a-z0-9][a-z0-9-.]*\/[a-z0-9][a-z0-9-.]*|[a-z0-9][a-z0-9-.]*\/[a-z0-9][a-z0-9-.]*)$/
/** Literal require() specifiers the frozen browser module table can answer. */
@@ -71,7 +81,7 @@ function bundleId(file: string): string {
}
/** The lazy chunk bundle names (mirror of src/bundle-route.ts CHUNK_NAMES). */
const CHUNK_FILES = ['terminal', 'editor', 'mermaid'].map(name => `lib/client-${name}.js`)
const CHUNK_FILES = ['editor', 'mermaid'].map(name => `lib/client-${name}.js`)
/** The global registry slot a built chunk script assigns (its factory key). */
function chunkSlot(file: string): string {
+16 -5
View File
@@ -89,7 +89,18 @@ describe('service routing into the native surface', () => {
store.setSession('s1')
const service = createBetterSidebarService(store)
service.setSurface(surface)
service.registerTab({ id: 'terminal', title: 'Terminal', component: () => null, createTab: state => ({ tab: { id: `terminal:${state.nextTerminal}`, type: 'terminal', title: 'Terminal', meta: { n: state.nextTerminal } } }) })
service.registerTab({
id: 'my-plugin:term',
title: 'Terminal',
component: () => null,
createTab: state => ({
// A `terminal`-shaped tab id (the plugin no longer ships that type,
// but the service treats the descriptor id as an open string) keeps
// this fixture's native routing identical.
tab: { id: `terminal:${state.nextBrowser}`, type: 'terminal', title: 'Terminal', meta: { n: state.nextBrowser } },
patch: { nextBrowser: state.nextBrowser + 1 },
}),
})
service.registerTab({ id: 'git', title: 'Changes', component: () => null })
service.registerTab({ id: 'editor', title: 'Files', component: () => null, icon: () => null })
return { surface, calls, service }
@@ -97,11 +108,11 @@ describe('service routing into the native surface', () => {
it('opens a page type natively, carrying the descriptor factory seed', () => {
const { service, calls } = mount()
service.openTab({ type: 'terminal' }, scope)
service.openTab({ type: 'my-plugin:term' }, scope)
expect(calls).toEqual([{
op: 'openTab',
sessionId: 's1',
kind: 'terminal',
kind: 'my-plugin:term',
params: { title: 'Terminal', meta: { n: 1 } },
revealIfOpened: false,
}])
@@ -141,8 +152,8 @@ describe('service routing into the native surface', () => {
id: 'my-plugin:console',
title: 'Console',
createTab: (state) => ({
tab: { id: `console:${state.nextTerminal}`, type: 'my-plugin:console', title: 'Console' },
patch: { nextTerminal: state.nextTerminal + 1 },
tab: { id: `console:${state.nextBrowser}`, type: 'my-plugin:console', title: 'Console' },
patch: { nextBrowser: state.nextBrowser + 1 },
}),
component: () => null,
})
-138
View File
@@ -1,138 +0,0 @@
/**
* openWhenSized tests: the deferred one-shot open guard for hosts that may
* not have a real size yet (xterm crashes when opened in a zero-size
* container — the WKWebView bottom-panel blank-terminal bug, issue #25).
* The polling must open exactly once, only once the host reports a real
* size, stop when the host leaves the document, and cancel cleanly.
*/
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest'
import { openWhenSized } from '../src/client/open-when-sized.ts'
/** A manually-stepped raf/caf pair so the polling is deterministic. */
function makeScheduler(): {
raf: (cb: FrameRequestCallback) => number
caf: (id: number) => void
tick: () => void
pending: () => number
} {
let nextId = 0
const frames = new Map<number, FrameRequestCallback>()
return {
raf: (cb) => { const id = ++nextId; frames.set(id, cb); return id },
caf: (id) => { frames.delete(id) },
tick: () => {
const cbs = [...frames.values()]
frames.clear()
for (const cb of cbs) cb(0)
},
pending: () => frames.size,
}
}
/** A host whose reported size can be changed between ticks. */
function makeHost(width: number, height: number): {
el: HTMLElement
setSize: (w: number, h: number) => void
} {
const el = document.createElement('div')
document.body.appendChild(el)
const setSize = (w: number, h: number): void => {
Object.defineProperty(el, 'clientWidth', { value: w, configurable: true })
Object.defineProperty(el, 'clientHeight', { value: h, configurable: true })
}
setSize(width, height)
return { el, setSize }
}
describe('openWhenSized', () => {
it('opens on the first tick when the host already has a size, then stops', () => {
const { raf, caf, tick, pending } = makeScheduler()
const host = makeHost(320, 200)
let opened = 0
const cancel = openWhenSized(host.el, () => { opened += 1 }, raf, caf)
tick()
expect(opened).toBe(1)
expect(pending()).toBe(0)
tick()
expect(opened).toBe(1)
cancel()
})
it('defers while the host is zero-sized and opens exactly once once sized', () => {
const { raf, caf, tick, pending } = makeScheduler()
const host = makeHost(0, 0)
let opened = 0
const cancel = openWhenSized(host.el, () => { opened += 1 }, raf, caf)
tick()
tick()
tick()
expect(opened).toBe(0)
expect(pending()).toBe(1)
host.setSize(320, 200)
tick()
expect(opened).toBe(1)
expect(pending()).toBe(0)
tick()
expect(opened).toBe(1)
cancel()
})
it('opens when only one dimension was missing', () => {
const { raf, caf, tick } = makeScheduler()
const host = makeHost(320, 0)
let opened = 0
const cancel = openWhenSized(host.el, () => { opened += 1 }, raf, caf)
tick()
expect(opened).toBe(0)
host.setSize(320, 120)
tick()
expect(opened).toBe(1)
cancel()
})
it('cancels a pending open and leaves no scheduled frames', () => {
const { raf, caf, tick, pending } = makeScheduler()
const host = makeHost(0, 0)
let opened = 0
const cancel = openWhenSized(host.el, () => { opened += 1 }, raf, caf)
tick()
cancel()
expect(pending()).toBe(0)
host.setSize(320, 200)
tick()
expect(opened).toBe(0)
// Idempotent: cancelling again is a no-op.
cancel()
})
it('stops polling when the host leaves the document', () => {
const { raf, caf, tick, pending } = makeScheduler()
const host = makeHost(0, 0)
let opened = 0
const cancel = openWhenSized(host.el, () => { opened += 1 }, raf, caf)
tick()
host.el.remove()
tick()
expect(opened).toBe(0)
expect(pending()).toBe(0)
// Even if the host somehow got a size after detaching, nothing opens.
host.setSize(320, 200)
tick()
expect(opened).toBe(0)
cancel()
})
it('does not swallow exceptions from open (the caller owns error handling)', () => {
const { raf, caf, tick } = makeScheduler()
const host = makeHost(320, 200)
let calls = 0
const cancel = openWhenSized(host.el, () => {
calls += 1
throw new Error('boom')
}, raf, caf)
expect(() => tick()).toThrow('boom')
expect(calls).toBe(1)
cancel()
})
})
+2 -2
View File
@@ -23,7 +23,7 @@ function typesOf(node: unknown): string[] {
describe('sanitize keeps unregistered tab types', () => {
it('preserves a persisted tab of an unknown type with its title/path', () => {
const raw = {
nextTerminal: 1,
nextBrowser: 1,
activePane: null,
expanded: [],
bottomSplits: {
@@ -47,7 +47,7 @@ describe('sanitize keeps unregistered tab types', () => {
it('an unknown type alone in a pane still sanitizes cleanly', () => {
const raw = {
nextTerminal: 1,
nextBrowser: 1,
activePane: null,
expanded: [],
bottomSplits: {
-261
View File
@@ -1,261 +0,0 @@
/**
* Pinned-terminal resolver (v0.17.0) — pure functions over cached session
* states. Covers the visibility matrix (global / workspace × cwd match /
* mismatch / both undefined / viewer-only undefined) and the cross-session
* collection (multi-session, exclusion of the viewer's own session, stable
* tree order).
*/
import { describe, expect, it } from 'vitest'
import {
makeDefaultState, openTabInBottomPane, setTabPin, splitPane,
type SidebarState,
} from '../src/client/state.ts'
import { collectPinnedTabs, pinnedVisibleTo, type PinnedViewer,
isPinnedVirtualId, parsePinnedVirtualId, isPinnedVirtualTab, getPinnedHomeScope,
createPinnedVirtualTab, injectPinnedIntoTree,
} from '../src/client/pinned.ts'
/** A pinned terminal tab in a fresh state, opened and pinned in one go. */
function stateWithPinnedTerminal(
id: string,
pin: { scope: 'workspace' | 'global'; homeCwd?: string },
): SidebarState {
let s = makeDefaultState()
s = openTabInBottomPane(s, { id, type: 'terminal', title: id })
return setTabPin(s, id, pin)
}
const viewer = (sessionId: string, cwd?: string): PinnedViewer => ({ sessionId, cwd })
describe('pinnedVisibleTo', () => {
it('returns false for an unpinned tab', () => {
const tab = { id: 't', type: 'terminal', title: 'T' }
expect(pinnedVisibleTo(tab, viewer('s', '/p'))).toBe(false)
})
it('global pin is visible to any session regardless of cwd', () => {
const tab = { id: 't', type: 'terminal', title: 'T', pin: { scope: 'global' as const } }
expect(pinnedVisibleTo(tab, viewer('s', '/other'))).toBe(true)
expect(pinnedVisibleTo(tab, viewer('s', undefined))).toBe(true)
})
it('workspace pin matches when cwds are equal', () => {
const tab = { id: 't', type: 'terminal', title: 'T', pin: { scope: 'workspace' as const, homeCwd: '/p' } }
expect(pinnedVisibleTo(tab, viewer('s', '/p'))).toBe(true)
expect(pinnedVisibleTo(tab, viewer('s', '/q'))).toBe(false)
})
it('workspace pin without homeCwd is visible everywhere (pin set before cwd resolved)', () => {
const tab = { id: 't', type: 'terminal', title: 'T', pin: { scope: 'workspace' as const } }
expect(pinnedVisibleTo(tab, viewer('s', '/anywhere'))).toBe(true)
expect(pinnedVisibleTo(tab, viewer('s', undefined))).toBe(true)
})
it('workspace pin is conservatively visible when viewer.cwd is unknown (no hydration flash)', () => {
const tab = { id: 't', type: 'terminal', title: 'T', pin: { scope: 'workspace' as const, homeCwd: '/p' } }
expect(pinnedVisibleTo(tab, viewer('s', undefined))).toBe(true)
})
it('both undefined cwds match (legacy pin + unhydrated viewer)', () => {
const tab = { id: 't', type: 'terminal', title: 'T', pin: { scope: 'workspace' as const, homeCwd: undefined } }
expect(pinnedVisibleTo(tab, viewer('s', undefined))).toBe(true)
})
})
describe('collectPinnedTabs', () => {
it('returns an empty array when no other session has pinned terminals', () => {
const bySession = new Map<string, SidebarState>([
['s1', stateWithPinnedTerminal('terminal:1', { scope: 'global' })],
])
expect(collectPinnedTabs(bySession, viewer('s1', '/p'))).toEqual([])
})
it('returns an empty array for an empty session cache', () => {
expect(collectPinnedTabs(new Map(), viewer('s1', '/p'))).toEqual([])
})
it('collects a global pin from another session', () => {
const bySession = new Map<string, SidebarState>([
['home', stateWithPinnedTerminal('terminal:1', { scope: 'global' })],
])
const entries = collectPinnedTabs(bySession, viewer('viewer', '/anywhere'))
expect(entries).toHaveLength(1)
expect(entries[0]!.tab.id).toBe('terminal:1')
expect(entries[0]!.homeSessionId).toBe('home')
})
it('collects a workspace pin only when the viewer cwd matches homeCwd', () => {
const home = stateWithPinnedTerminal('terminal:1', { scope: 'workspace', homeCwd: '/proj' })
const bySession = new Map<string, SidebarState>([['home', home]])
expect(collectPinnedTabs(bySession, viewer('viewer', '/proj'))).toHaveLength(1)
expect(collectPinnedTabs(bySession, viewer('viewer', '/elsewhere'))).toHaveLength(0)
})
it('excludes the viewer\'s own session (its pinned tabs are on its own strip)', () => {
const bySession = new Map<string, SidebarState>([
['viewer', stateWithPinnedTerminal('terminal:1', { scope: 'global' })],
['home', stateWithPinnedTerminal('terminal:2', { scope: 'global' })],
])
const entries = collectPinnedTabs(bySession, viewer('viewer', '/p'))
expect(entries.map(e => e.tab.id)).toEqual(['terminal:2'])
})
it('collects in stable tree order (the workbench split tree, depth-first)', () => {
let home = makeDefaultState()
home = openTabInBottomPane(home, { id: 'terminal:first', type: 'terminal', title: 'A' })
home = setTabPin(home, 'terminal:first', { scope: 'global' })
// A second leaf to the right of the first one: its tabs collect after.
const firstPane = (home.bottomSplits as { id: string }).id
home = splitPane(home, 'row')
home = openTabInBottomPane(home, { id: 'terminal:second', type: 'terminal', title: 'B' })
home = setTabPin(home, 'terminal:second', { scope: 'global' })
expect(firstPane).not.toBe('')
const bySession = new Map<string, SidebarState>([['home', home]])
const entries = collectPinnedTabs(bySession, viewer('viewer', '/p'))
expect(entries.map(e => e.tab.id)).toEqual(['terminal:first', 'terminal:second'])
})
it('keeps stable insertion order across multiple home sessions', () => {
const bySession = new Map<string, SidebarState>([
['homeA', stateWithPinnedTerminal('terminal:a', { scope: 'global' })],
['homeB', stateWithPinnedTerminal('terminal:b', { scope: 'global' })],
])
const entries = collectPinnedTabs(bySession, viewer('viewer', '/p'))
expect(entries.map(e => e.tab.id)).toEqual(['terminal:a', 'terminal:b'])
expect(entries.map(e => e.homeSessionId)).toEqual(['homeA', 'homeB'])
})
it('ignores unpinned terminals and non-terminal tabs in other sessions', () => {
let home = makeDefaultState()
home = openTabInBottomPane(home, { id: 'terminal:unpinned', type: 'terminal', title: 'U' })
home = openTabInBottomPane(home, { id: 'editor:1', type: 'editor', title: 'E', path: '/e' })
home = setTabPin(home, 'editor:1', { scope: 'global' }) // defensive: pin only targets terminals
home = openTabInBottomPane(home, { id: 'terminal:pinned', type: 'terminal', title: 'P' })
home = setTabPin(home, 'terminal:pinned', { scope: 'global' })
const bySession = new Map<string, SidebarState>([['home', home]])
const entries = collectPinnedTabs(bySession, viewer('viewer', '/p'))
expect(entries.map(e => e.tab.id)).toEqual(['terminal:pinned'])
})
})
describe('isPinnedVirtualId / parsePinnedVirtualId', () => {
it('detects a pinned virtual id by prefix', () => {
expect(isPinnedVirtualId('pinned:home:terminal:3')).toBe(true)
expect(isPinnedVirtualId('pinned:abc-123:agent:def-456')).toBe(true)
expect(isPinnedVirtualId('terminal:3')).toBe(false)
expect(isPinnedVirtualId('agent:uuid')).toBe(false)
})
it('parses home session id and original tab id (terminal)', () => {
const { homeSessionId, tabId } = parsePinnedVirtualId('pinned:home-sess:terminal:3')
expect(homeSessionId).toBe('home-sess')
expect(tabId).toBe('terminal:3')
})
it('parses home session id and original tab id (agent)', () => {
const { homeSessionId, tabId } = parsePinnedVirtualId('pinned:abc-123:agent:def-456')
expect(homeSessionId).toBe('abc-123')
expect(tabId).toBe('agent:def-456')
})
})
describe('createPinnedVirtualTab', () => {
it('creates a virtual tab with a prefixed id and home scope in meta', () => {
const tab = { id: 'terminal:3', type: 'terminal' as const, title: 'T3', pin: { scope: 'global' as const, homeCwd: '/p' } }
const vtab = createPinnedVirtualTab({ tab, homeSessionId: 'home' })
expect(vtab.id).toBe('pinned:home:terminal:3')
expect(vtab.type).toBe('terminal')
expect(vtab.title).toBe('T3')
expect(vtab.pin).toEqual({ scope: 'global', homeCwd: '/p' })
})
it('stores the home scope (sessionId, cwd, original tabId) in meta', () => {
const tab = { id: 'terminal:3', type: 'terminal' as const, title: 'T3', pin: { scope: 'workspace' as const, homeCwd: '/proj' } }
const vtab = createPinnedVirtualTab({ tab, homeSessionId: 'home-sess' })
const home = getPinnedHomeScope(vtab)
expect(home).toBeDefined()
expect(home!.sessionId).toBe('home-sess')
expect(home!.cwd).toBe('/proj')
expect(home!.tabId).toBe('terminal:3')
})
it('preserves existing meta fields alongside the pinned home scope', () => {
const tab = { id: 'terminal:3', type: 'terminal' as const, title: 'T3', pin: { scope: 'global' as const }, meta: { custom: 42 } }
const vtab = createPinnedVirtualTab({ tab, homeSessionId: 'home' })
expect((vtab.meta as Record<string, unknown>).custom).toBe(42)
expect(isPinnedVirtualTab(vtab)).toBe(true)
})
it('cwd is undefined for a global pin without homeCwd', () => {
const tab = { id: 'terminal:3', type: 'terminal' as const, title: 'T3', pin: { scope: 'global' as const } }
const vtab = createPinnedVirtualTab({ tab, homeSessionId: 'home' })
expect(getPinnedHomeScope(vtab)!.cwd).toBeUndefined()
})
it('isPinnedVirtualTab returns false for a regular tab', () => {
const tab = { id: 'terminal:3', type: 'terminal' as const, title: 'T3' }
expect(isPinnedVirtualTab(tab)).toBe(false)
})
})
describe('injectPinnedIntoTree', () => {
it('returns the original tree when no pinned tabs and no active override', () => {
const tree = makeDefaultState().bottomSplits
expect(injectPinnedIntoTree(tree, [], null)).toBe(tree)
})
it('appends pinned virtual tabs to the first leaf', () => {
const s = makeDefaultState()
const vtab = createPinnedVirtualTab({
tab: { id: 'terminal:3', type: 'terminal', title: 'T3', pin: { scope: 'global' } },
homeSessionId: 'home',
})
const result = injectPinnedIntoTree(s.bottomSplits, [vtab], null)
expect(result.kind).toBe('leaf')
if (result.kind === 'leaf') {
expect(result.tabs[result.tabs.length - 1]!.id).toBe('pinned:home:terminal:3')
}
})
it('overrides the first leaf active when activePinnedId is set', () => {
const s = openTabInBottomPane(makeDefaultState(), { id: 'terminal:1', type: 'terminal', title: 'T1' })
const vtab = createPinnedVirtualTab({
tab: { id: 'terminal:2', type: 'terminal', title: 'T2', pin: { scope: 'global' } },
homeSessionId: 'home',
})
const result = injectPinnedIntoTree(s.bottomSplits, [vtab], vtab.id)
if (result.kind === 'leaf') {
expect(result.active).toBe(vtab.id)
expect(result.tabs.map(t => t.id)).toContain(vtab.id)
expect(result.tabs.map(t => t.id)).toContain('terminal:1')
}
})
it('injects into the first child of a split tree', () => {
let s = makeDefaultState()
s = openTabInBottomPane(s, { id: 'terminal:1', type: 'terminal', title: 'T1' })
// Create a split (splits the active pane into two)
const leafId = s.bottomSplits.kind === 'leaf' ? s.bottomSplits.id : ''
s = { ...s, bottomSplits: { kind: 'split', id: 'split:1', dir: 'row', sizes: [0.5, 0.5], children: [
{ kind: 'leaf', id: leafId, tabs: s.bottomSplits.kind === 'leaf' ? s.bottomSplits.tabs : [], active: 'terminal:1' },
{ kind: 'leaf', id: 'pane:2', tabs: [], active: null },
] } }
const vtab = createPinnedVirtualTab({
tab: { id: 'terminal:2', type: 'terminal', title: 'T2', pin: { scope: 'global' } },
homeSessionId: 'home',
})
const result = injectPinnedIntoTree(s.bottomSplits, [vtab], null)
expect(result.kind).toBe('split')
if (result.kind === 'split') {
const first = result.children[0]!
if (first.kind === 'leaf') {
expect(first.tabs.map(t => t.id)).toContain(vtab.id)
}
const second = result.children[1]!
if (second.kind === 'leaf') {
expect(second.tabs.map(t => t.id)).not.toContain(vtab.id)
}
}
})
})
+4 -23
View File
@@ -32,23 +32,10 @@ describe('dsh-better-sidebar plugin export shape', () => {
expect(resolved.readLimit).toBe(512 * 1024)
expect(resolved.mediaLimit).toBe(20 * 1024 * 1024)
expect(resolved.listLimit).toBe(1000)
expect(resolved.terminalsPerSession).toBe(3)
expect(resolved.reconnectGraceMs).toBe(30_000)
// The terminal shell config defaults to auto-resolution (empty shell =
// the platform chain in defaultShell()).
expect(resolved.shell).toBe('')
// Shell args default to an empty list; non-empty values replace the
// automatic platform login flag.
expect(resolved.shellArgs).toEqual([])
const configured = (schema as unknown as {
(input: Record<string, unknown> | undefined): Record<string, unknown>
})({ shell: 'pwsh.exe' })
expect(configured.shell).toBe('pwsh.exe')
const configuredWithArgs = (schema as unknown as {
(input: Record<string, unknown> | undefined): Record<string, unknown>
})({ shell: '/bin/zsh', shellArgs: ['--noprofile', '--no-rc'] })
expect(configuredWithArgs.shell).toBe('/bin/zsh')
expect(configuredWithArgs.shellArgs).toEqual(['--noprofile', '--no-rc'])
})({ readLimit: 1024 })
expect(configured.readLimit).toBe(1024)
})
it('registers the side card preferences schema with the documented defaults', async () => {
@@ -63,15 +50,9 @@ describe('dsh-better-sidebar plugin export shape', () => {
expect(resolved.autoOpenSubagent).toBe(true)
// A new background job auto-opens the Jobs page too.
expect(resolved.autoOpenJobs).toBe(true)
// 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).
// The sidebar-open tool defaults OFF (dormant until the user enables it
// in the side card settings).
expect(resolved.agentOpenTools).toBe(false)
// The terminal font customizations default to the theme (empty family)
// and 13px.
expect(resolved.terminalFontFamily).toBe('')
expect(resolved.terminalFontSize).toBe(13)
// The position-compat scheme is declared WITHOUT a schema default so a
// stored document that predates it resolves without the field — the
// CLIENT parsePrefs then applies the conservative `auto` default (or
+9 -53
View File
@@ -30,18 +30,13 @@ describe('side card preferences', () => {
})
it('parses a valid value', async () => {
expect(await loadPrefs(wire({ autoOpenSubagent: false, agentTerminalTools: true })))
expect(await loadPrefs(wire({ autoOpenSubagent: false, agentOpenTools: true })))
.toEqual({
autoOpenSubagent: false,
autoOpenJobs: true,
agentTerminalTools: true, agentOpenTools: false,
bottomPanelAutoTerminal: true,
terminalFontFamily: '',
terminalFontSize: 13,
agentOpenTools: true,
editorExplorer: false,
workspaceFence: true,
terminalShell: '',
terminalShellArgs: '',
titleBarScheme: 'auto',
titleBarPresetId: '',
customCss: '',
@@ -49,11 +44,9 @@ describe('side card preferences', () => {
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
htmlViewerDefaultUnsafe: false,
browserNoSandbox: false,
browserInterceptLinks: true,
browserInterceptHttp: true,
browserInterceptHttps: false,
browserAllowedLoopback: '',
tabsEnabled: {},
viewersEnabled: {},
pluginSettings: {},
@@ -61,18 +54,13 @@ describe('side card preferences', () => {
})
it('falls back per-field when a stored field is malformed', async () => {
expect(await loadPrefs(wire({ autoOpenSubagent: 'no', agentTerminalTools: 'yes' })))
expect(await loadPrefs(wire({ autoOpenSubagent: 'no', agentOpenTools: 'yes' })))
.toEqual({
autoOpenSubagent: true,
autoOpenJobs: true,
agentTerminalTools: false, agentOpenTools: false,
bottomPanelAutoTerminal: true,
terminalFontFamily: '',
terminalFontSize: 13,
agentOpenTools: false,
editorExplorer: false,
workspaceFence: true,
terminalShell: '',
terminalShellArgs: '',
titleBarScheme: 'auto',
titleBarPresetId: '',
customCss: '',
@@ -80,30 +68,23 @@ describe('side card preferences', () => {
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
htmlViewerDefaultUnsafe: false,
browserNoSandbox: false,
browserInterceptLinks: true,
browserInterceptHttp: true,
browserInterceptHttps: false,
browserAllowedLoopback: '',
tabsEnabled: {},
viewersEnabled: {},
pluginSettings: {},
})
})
it('defaults autoOpenSubagent to true and agentTerminalTools to false when the stored value is absent or malformed', async () => {
it('defaults autoOpenSubagent to true and the agent toggles to false when the stored value is absent or malformed', async () => {
expect(await loadPrefs(wire({})))
.toEqual({
autoOpenSubagent: true,
autoOpenJobs: true,
agentTerminalTools: false, agentOpenTools: false,
bottomPanelAutoTerminal: true,
terminalFontFamily: '',
terminalFontSize: 13,
agentOpenTools: false,
editorExplorer: false,
workspaceFence: true,
terminalShell: '',
terminalShellArgs: '',
titleBarScheme: 'auto',
titleBarPresetId: '',
customCss: '',
@@ -111,25 +92,16 @@ describe('side card preferences', () => {
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
htmlViewerDefaultUnsafe: false,
browserNoSandbox: false,
browserInterceptLinks: true,
browserInterceptHttp: true,
browserInterceptHttps: false,
browserAllowedLoopback: '',
tabsEnabled: {},
viewersEnabled: {},
pluginSettings: {},
})
expect((await loadPrefs(wire({ autoOpenSubagent: 1 }))).autoOpenSubagent)
.toBe(true)
// The terminal-tools feature is OFF by default; only an explicit true turns it on.
expect((await loadPrefs(wire({}))).agentTerminalTools)
.toBe(false)
expect((await loadPrefs(wire({ agentTerminalTools: 1 }))).agentTerminalTools)
.toBe(false)
expect((await loadPrefs(wire({ agentTerminalTools: true }))).agentTerminalTools)
.toBe(true)
// The sidebar-open tool is OFF by default too; only an explicit true turns it on.
// The sidebar-open tool is OFF by default; only an explicit true turns it on.
expect((await loadPrefs(wire({}))).agentOpenTools)
.toBe(false)
expect((await loadPrefs(wire({ agentOpenTools: 1 }))).agentOpenTools)
@@ -229,22 +201,6 @@ describe('side card preferences', () => {
.toMatchObject({ browserInterceptLinks: false, browserInterceptHttp: true, browserInterceptHttps: true })
})
it('resolves the terminal font prefs (family passthrough, size clamp)', async () => {
// Absent → theme default (empty family) + default size.
expect((await loadPrefs(wire({}))).terminalFontFamily).toBe('')
expect((await loadPrefs(wire({}))).terminalFontSize).toBe(13)
// A custom family survives verbatim; a malformed one falls back.
expect((await loadPrefs(wire({ terminalFontFamily: '"JetBrains Mono", monospace' }))).terminalFontFamily)
.toBe('"JetBrains Mono", monospace')
expect((await loadPrefs(wire({ terminalFontFamily: 42 }))).terminalFontFamily).toBe('')
// The size clamps into 9–32 (rounded); non-numbers fall back.
expect((await loadPrefs(wire({ terminalFontSize: 5 }))).terminalFontSize).toBe(9)
expect((await loadPrefs(wire({ terminalFontSize: 40 }))).terminalFontSize).toBe(32)
expect((await loadPrefs(wire({ terminalFontSize: 15.6 }))).terminalFontSize).toBe(16)
expect((await loadPrefs(wire({ terminalFontSize: 'big' }))).terminalFontSize).toBe(13)
expect((await loadPrefs(wire({ terminalFontSize: 18 }))).terminalFontSize).toBe(18)
})
it('validates the per-tab / per-viewer enable maps (absent keys mean enabled)', async () => {
// A non-object map falls back to {} (everything enabled).
expect((await loadPrefs(wire({ tabsEnabled: 'nope' }))).tabsEnabled).toEqual({})
@@ -294,8 +250,8 @@ describe('boot decision (one fetch for prefs + external disable)', () => {
})
it('reads suspended false when the flag is absent', async () => {
const decision = await loadBootDecision(wire({ terminalFontSize: 20 }))
const decision = await loadBootDecision(wire({ titleBarStripPx: 60 }))
expect(decision.suspended).toBe(false)
expect(decision.prefs.terminalFontSize).toBe(20)
expect(decision.prefs.titleBarStripPx).toBe(60)
})
})
-209
View File
@@ -1,209 +0,0 @@
/**
* pty-deps unit tests (issue #140, plugin side): lazy node-pty loading,
* profile/plugin-root discovery, and the pasteable repair command — the
* degraded mode the terminal tab enters when node-pty cannot load, instead
* of the whole plugin (and `dsh web`) failing to boot.
*/
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, dirname } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
buildRepairCommand,
depsStatus,
DSH_NODE_PTY_RANGE,
findPluginRoot,
findProfileDir,
loadNodePty,
loadRequiredNodePty,
nodePtyLoadCause,
resetNodePtyCache,
} from '../src/pty-deps.ts'
import { SidebarError } from '../src/wire.ts'
/** A throw-only require: node-pty missing or its native binding broken. */
const failingRequire = (): never => { throw new Error('Cannot find package node-pty') }
describe('loadNodePty', () => {
beforeEach(() => { resetNodePtyCache() })
it('loads the real node-pty module in this repository', () => {
const mod = loadNodePty()
expect(mod).not.toBeNull()
expect(typeof mod?.spawn).toBe('function')
})
it('returns null and records the cause when the require throws', () => {
expect(loadNodePty(failingRequire)).toBeNull()
expect((nodePtyLoadCause() as Error).message).toBe('Cannot find package node-pty')
})
it('caches the first outcome (a later working require does not override)', () => {
expect(loadNodePty(failingRequire)).toBeNull()
expect(loadNodePty(() => ({ spawn: () => undefined }))).toBeNull()
resetNodePtyCache()
expect(loadNodePty(() => ({ spawn: () => undefined }))).not.toBeNull()
})
it('loadRequiredNodePty throws the canonical degraded-mode error', () => {
loadNodePty(failingRequire)
let thrown: unknown
try {
loadRequiredNodePty()
} catch (error) {
thrown = error
}
expect(thrown).toBeInstanceOf(SidebarError)
expect((thrown as SidebarError).code).toBe('pty-deps-missing')
expect((thrown as SidebarError).status).toBe(503)
})
})
describe('buildRepairCommand', () => {
let root: string
let pluginRoot: string
let profileDir: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'pty-deps-'))
pluginRoot = join(root, 'plugin')
profileDir = join(root, 'profiles', 'web')
mkdirSync(join(pluginRoot, 'scripts'), { recursive: true })
mkdirSync(profileDir, { recursive: true })
writeFileSync(join(pluginRoot, 'scripts', 'install.sh'), '#!/usr/bin/env bash\n')
writeFileSync(join(pluginRoot, 'scripts', 'install.ps1'), '# ps1\n')
})
afterEach(() => { rmSync(root, { recursive: true, force: true }) })
it('posix: bash installer with --repair and the detected profile', () => {
const { command, note } = buildRepairCommand({ pluginRoot, profileDir, platform: 'darwin' })
expect(command).toBe(`bash "${join(pluginRoot, 'scripts', 'install.sh')}" --repair --profile "web"`)
expect(note).toBeUndefined()
})
it('posix: omits --profile when the profile could not be detected', () => {
const { command } = buildRepairCommand({ pluginRoot, profileDir: null, platform: 'linux' })
expect(command).toBe(`bash "${join(pluginRoot, 'scripts', 'install.sh')}" --repair`)
})
it('win32: powershell -ExecutionPolicy Bypass with -Repair and -Profile', () => {
const { command } = buildRepairCommand({ pluginRoot, profileDir, platform: 'win32' })
const expected = join(pluginRoot, 'scripts', 'install.ps1')
expect(command).toBe(`powershell -ExecutionPolicy Bypass -File "${expected}" -Repair -Profile "web"`)
})
it('falls back to the dsh plugin command when the plugin scripts are unavailable', () => {
const bareRoot = join(root, 'bare')
mkdirSync(bareRoot)
const { command, note } = buildRepairCommand({ pluginRoot: bareRoot, profileDir, platform: 'darwin' })
expect(command).toBe('dsh plugin --profile "web" install')
expect(note).toContain('allowBuilds')
})
it('falls back to the dsh plugin command (default web) when nothing is detectable', () => {
const { command } = buildRepairCommand({ pluginRoot: null, profileDir: null, platform: 'darwin' })
expect(command).toBe('dsh plugin --profile "web" install')
})
})
describe('findProfileDir / findPluginRoot', () => {
let root: string
let moduleFile: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'pty-deps-'))
// A fake plugin module deep inside the profile's pnpm node_modules.
const pkgRoot = join(root, 'profiles', 'web', 'node_modules', '.pnpm', 'dsh-better-sidebar@0.0.0', 'node_modules', 'dsh-better-sidebar')
const libDir = join(pkgRoot, 'lib')
mkdirSync(libDir, { recursive: true })
writeFileSync(join(root, 'profiles', 'web', 'package.json'), JSON.stringify({ name: 'dsh-profile-web' }))
writeFileSync(join(root, 'profiles', 'web', 'pnpm-workspace.yaml'), '')
writeFileSync(join(pkgRoot, 'package.json'), JSON.stringify({ name: 'dsh-better-sidebar' }))
moduleFile = join(libDir, 'index.js')
writeFileSync(moduleFile, '')
})
afterEach(() => { rmSync(root, { recursive: true, force: true }) })
it('walks up from the plugin module to the profile root (pnpm-workspace.yaml)', () => {
expect(findProfileDir(moduleFile)).toBe(realpathSync(join(root, 'profiles', 'web')))
})
it('walks up to the plugin package root by package.json name', () => {
expect(findPluginRoot(moduleFile)).toBe(realpathSync(join(root, 'profiles', 'web', 'node_modules', '.pnpm', 'dsh-better-sidebar@0.0.0', 'node_modules', 'dsh-better-sidebar')))
})
it('falls back to $DSH_HOME/profiles/web when no ancestor looks like a profile', () => {
const home = join(root, 'home')
const web = join(home, 'profiles', 'web')
mkdirSync(web, { recursive: true })
writeFileSync(join(web, 'package.json'), JSON.stringify({ name: 'dsh-profile-web' }))
writeFileSync(join(web, 'pnpm-workspace.yaml'), '')
// A bare module path with no profile-like ancestor (the walk-up must miss).
const bareModule = join(root, 'elsewhere', 'lib', 'index.js')
mkdirSync(dirname(bareModule), { recursive: true })
writeFileSync(bareModule, '')
const previous = process.env.DSH_HOME
process.env.DSH_HOME = home
try {
expect(findProfileDir(bareModule)).toBe(realpathSync(web))
} finally {
if (previous === undefined) delete process.env.DSH_HOME
else process.env.DSH_HOME = previous
}
})
})
describe('depsStatus', () => {
let root: string
let moduleFile: string
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'pty-deps-'))
const pkgRoot = join(root, 'profiles', 'web', 'node_modules', '.pnpm', 'dsh-better-sidebar@0.0.0', 'node_modules', 'dsh-better-sidebar')
mkdirSync(join(pkgRoot, 'scripts'), { recursive: true })
mkdirSync(join(pkgRoot, 'lib'), { recursive: true })
writeFileSync(join(root, 'profiles', 'web', 'package.json'), JSON.stringify({ name: 'dsh-profile-web' }))
writeFileSync(join(root, 'profiles', 'web', 'pnpm-workspace.yaml'), '')
writeFileSync(join(pkgRoot, 'package.json'), JSON.stringify({ name: 'dsh-better-sidebar' }))
writeFileSync(join(pkgRoot, 'scripts', 'install.sh'), '#!/usr/bin/env bash\n')
writeFileSync(join(pkgRoot, 'scripts', 'install.ps1'), '# repair fixture\n')
moduleFile = join(pkgRoot, 'lib', 'index.js')
writeFileSync(moduleFile, '')
resetNodePtyCache()
})
afterEach(() => {
rmSync(root, { recursive: true, force: true })
resetNodePtyCache()
})
it('reports ok:true when node-pty loads', () => {
expect(depsStatus({ fromFile: moduleFile })).toEqual({ ok: true })
})
it('reports the cause, the repair command and the profile when the load fails', () => {
loadNodePty(failingRequire)
const status = depsStatus({ fromFile: moduleFile })
expect(status.ok).toBe(false)
if (status.ok) throw new Error('unreachable')
expect(status.cause).toBe('Cannot find package node-pty')
const scriptName = process.platform === 'win32' ? 'install.ps1' : 'install.sh'
const script = realpathSync(join(root, 'profiles', 'web', 'node_modules', '.pnpm', 'dsh-better-sidebar@0.0.0', 'node_modules', 'dsh-better-sidebar', 'scripts', scriptName))
expect(status.command).toBe(process.platform === 'win32'
? `powershell -ExecutionPolicy Bypass -File "${script}" -Repair -Profile "web"`
: `bash "${script}" --repair --profile "web"`)
expect(status.profile).toBe('web')
})
})
describe('DSH sync contract', () => {
it('the declared node-pty range stays identical to DSH core (dsh-subprocess-local ^1.1.0)', () => {
expect(DSH_NODE_PTY_RANGE).toBe('^1.1.0')
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {
dependencies: Record<string, string>
}
expect(pkg.dependencies['node-pty']).toBe(DSH_NODE_PTY_RANGE)
})
})
-225
View File
@@ -1,225 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
// Pin the passwd login shell to a non-bash value for the pty helpers tests:
// the CI runner's own login shell is /bin/bash, which the old hardcoded
// fallback would have satisfied by coincidence, so the fallback chain needs
// a mock passwd to be genuinely discriminating. No other test reads os.userInfo.
vi.mock('node:os', async (importOriginal) => {
const os = await importOriginal<typeof import('node:os')>()
return {
...os,
userInfo: () => ({ ...os.userInfo(), shell: '/usr/bin/zsh' }),
}
})
import { existsSync, statSync } from 'node:fs'
import { createRequire } from 'node:module'
import { dirname, join } from 'node:path'
import { resolveSidebarConfig } from '../src/config.ts'
import {
defaultShell,
ensureSpawnHelper,
resolveShellExecutable,
shellDisplayName,
shellSpawnArgs,
splitShellArgs,
unquotePath,
} from '../src/pty-manager.ts'
import { SidebarError } from '../src/wire.ts'
describe('pty helpers', () => {
it('prefers an explicit shell, then SHELL, then the account login shell on POSIX', () => {
// The platform is injected so this chain also runs (and is asserted) on
// non-POSIX developer machines. The userInfo mock at the top of the file
// pins the passwd login shell to /usr/bin/zsh.
expect(defaultShell({ platform: 'linux', env: { SHELL: '/explicit/zsh' } })).toBe('/explicit/zsh')
// Surrounding whitespace must not leak into the spawned executable path.
expect(defaultShell({ platform: 'linux', env: { SHELL: ' /explicit/zsh ' } })).toBe('/explicit/zsh')
expect(defaultShell({ platform: 'linux', env: { SHELL: ' ' } })).toBe('/usr/bin/zsh')
expect(defaultShell({ platform: 'linux', env: {} })).toBe('/usr/bin/zsh')
})
it('Windows: explicit shell wins, then DSH_SIDEBAR_SHELL, then a probed pwsh.exe, then powershell.exe 5.1', () => {
// The explicit shell (the `shell` config field) beats every automatic
// source, and whitespace-only values count as unset.
expect(defaultShell({ platform: 'win32', explicit: 'C:\\Tools\\pwsh.exe', env: { DSH_SIDEBAR_SHELL: 'pwsh.exe' } }))
.toBe('C:\\Tools\\pwsh.exe')
expect(defaultShell({ platform: 'win32', explicit: ' ', env: { DSH_SIDEBAR_SHELL: 'pwsh.exe' } }))
.toBe('pwsh.exe')
// PATH is probed entry by entry; the first directory containing pwsh.exe
// wins and the returned value is the full resolved path. The candidate is
// normalized to forward slashes before comparing so the assertion holds
// under BOTH join() implementations: on the ubuntu runners node:path is
// POSIX and joins 'C:\\other' + 'pwsh.exe' as 'C:\\other/pwsh.exe'.
const fromPath = defaultShell({
platform: 'win32',
env: { PATH: 'C:\\tools;C:\\other' },
exists: path => path.replaceAll('\\', '/') === 'C:/other/pwsh.exe',
})
expect(fromPath.replaceAll('\\', '/')).toBe('C:/other/pwsh.exe')
// PATH misses fall through to the known install directories. On 32-bit
// Node, ProgramW6432 is the real 64-bit Program Files and is preferred.
const fromProgramW6432 = defaultShell({
platform: 'win32',
env: { ProgramW6432: 'C:\\PF64' },
exists: path => path.replaceAll('\\', '/') === 'C:/PF64/PowerShell/7/pwsh.exe',
})
expect(fromProgramW6432.replaceAll('\\', '/')).toBe('C:/PF64/PowerShell/7/pwsh.exe')
const fromProgramFiles = defaultShell({
platform: 'win32',
env: { ProgramFiles: 'C:\\PF', LOCALAPPDATA: 'C:\\Users\\x\\AppData\\Local' },
exists: path => path.replaceAll('\\', '/') === 'C:/PF/PowerShell/7/pwsh.exe',
})
expect(fromProgramFiles.replaceAll('\\', '/')).toBe('C:/PF/PowerShell/7/pwsh.exe')
// Nothing installed: keep the inbox 5.1 fallback instead of breaking.
expect(defaultShell({ platform: 'win32', env: {}, exists: () => false })).toBe('powershell.exe')
})
it('Windows: resolves bare custom shells through PATH/PATHEXT before node-pty spawn', () => {
const files = new Set([
'C:/Tools/PowerShell/pwsh.exe',
'C:/Windows/System32/cmd.exe',
])
const options = {
platform: 'win32' as const,
// Mixed-case Path/PATHEXT pins the case-insensitive environment lookup
// that real Windows process.env provides but plain test objects do not.
env: {
Path: 'C:\\Tools\\PowerShell',
PathExt: '.COM;.EXE;.BAT;.CMD',
SystemRoot: 'C:\\Windows',
},
exists: (path: string) => files.has(path.replaceAll('\\', '/')),
}
expect(resolveShellExecutable('pwsh', options).replaceAll('\\', '/'))
.toBe('C:/Tools/PowerShell/pwsh.exe')
expect(resolveShellExecutable('cmd', options).replaceAll('\\', '/'))
.toBe('C:/Windows/System32/cmd.exe')
})
it('Windows: accepts .exe names and absolute paths, and names a missing configured shell', () => {
const options = {
platform: 'win32' as const,
env: { PATH: 'C:\\Tools' },
exists: (path: string) => path.replaceAll('\\', '/') === 'C:/Tools/pwsh.exe'
|| path.replaceAll('\\', '/') === 'D:/Portable Shell/custom.exe',
}
expect(resolveShellExecutable('pwsh.exe', options).replaceAll('\\', '/'))
.toBe('C:/Tools/pwsh.exe')
expect(resolveShellExecutable('D:\\Portable Shell\\custom.exe', options).replaceAll('\\', '/'))
.toBe('D:/Portable Shell/custom.exe')
expect(() => resolveShellExecutable('missing-shell', options))
.toThrow('shell executable not found: "missing-shell"')
})
it('POSIX: resolves bare names along PATH and names a missing configured shell', () => {
const options = {
platform: 'linux' as const,
env: { PATH: '/usr/local/bin:/usr/bin' },
exists: (path: string) => path === join('/usr/bin', 'zsh'),
}
expect(resolveShellExecutable('zsh', options)).toBe(join('/usr/bin', 'zsh'))
const thrown = (() => {
try {
resolveShellExecutable('nope', options)
return undefined
} catch (error) {
return error
}
})()
expect(thrown).toBeInstanceOf(SidebarError)
expect((thrown as SidebarError).code).toBe('shell-not-found')
expect((thrown as SidebarError).message).toBe('shell executable not found: "nope"')
expect((thrown as SidebarError).meta?.shell).toBe('nope')
})
it('POSIX: checks an absolute path exists and passes it through verbatim', () => {
expect(resolveShellExecutable('/explicit/zsh', { platform: 'linux', env: {}, exists: () => true }))
.toBe('/explicit/zsh')
expect(() => resolveShellExecutable('/missing/zsh', { platform: 'linux', env: {}, exists: () => false }))
.toThrow('shell executable not found: "/missing/zsh"')
})
it('unquotes the configured shell before resolving (Windows probe included)', () => {
const options = {
platform: 'win32' as const,
env: { PATH: 'C:\\Tools' },
exists: (path: string) => path.replaceAll('\\', '/') === 'C:/Tools/pwsh.exe',
}
expect(resolveShellExecutable('"pwsh.exe"', options).replaceAll('\\', '/')).toBe('C:/Tools/pwsh.exe')
})
it('trims the configured shell and defaults it to auto for old documents', () => {
expect(resolveSidebarConfig(undefined).shell).toBe('')
expect(resolveSidebarConfig({ shell: ' pwsh.exe ' }).shell).toBe('pwsh.exe')
expect(resolveSidebarConfig({ shell: '/bin/zsh', shellArgs: ['--noprofile'] }).shellArgs).toEqual(['--noprofile'])
expect(resolveSidebarConfig(undefined).shellArgs).toEqual([])
})
it('derives a short display name for terminal tab titles', () => {
expect(shellDisplayName('/bin/zsh')).toBe('zsh')
expect(shellDisplayName('/usr/bin/bash')).toBe('bash')
expect(shellDisplayName('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe')).toBe('powershell')
expect(shellDisplayName('pwsh.exe')).toBe('pwsh')
expect(shellDisplayName('/weird')).toBe('weird')
expect(shellDisplayName('/')).toBe('/')
})
it('uses explicit shell args verbatim and keeps platform defaults when none are configured', () => {
expect(shellSpawnArgs(['--noprofile', '--no-rc'])).toEqual(['--noprofile', '--no-rc'])
expect(shellSpawnArgs([])).toEqual(process.platform === 'win32' ? [] : ['-l'])
})
it('restores the spawn-helper executable bit idempotently', () => {
// node-pty's spawn-helper is a macOS-only artifact: binding.gyp builds
// the executable only for OS=="mac", and no other platform ships one to
// restore (linux uses forkpty directly). Skip elsewhere.
if (process.platform !== 'darwin') return
ensureSpawnHelper()
ensureSpawnHelper()
const entry = createRequire(import.meta.url).resolve('node-pty')
const root = dirname(dirname(entry))
// Prebuilt (tarball) or node-gyp-compiled (build/Release): mirror
// ensureSpawnHelper's candidate list — either location is acceptable.
const candidates = [
join(root, 'prebuilds', `${process.platform}-${process.arch}`, 'spawn-helper'),
join(root, 'build', 'Release', 'spawn-helper'),
]
const helper = candidates.find(existsSync)
expect(helper).toBeTruthy()
expect((statSync(helper!).mode & 0o111) !== 0).toBe(true)
})
it('unquotes a paired surrounding quote from a configured shell path', () => {
expect(unquotePath('"C:\\Program Files\\PowerShell\\7\\pwsh.exe"'))
.toBe('C:\\Program Files\\PowerShell\\7\\pwsh.exe')
expect(unquotePath("'/usr/bin/my shell'")).toBe('/usr/bin/my shell')
// Unpaired or single characters stay verbatim.
expect(unquotePath('"mismatched')).toBe('"mismatched')
expect(unquotePath('pwsh.exe')).toBe('pwsh.exe')
expect(unquotePath('"')).toBe('"')
expect(unquotePath('')).toBe('')
})
it('splits shell args with quote-aware grouping', () => {
expect(splitShellArgs('-NoLogo -File "C:\\my init\\init.ps1"'))
.toEqual(['-NoLogo', '-File', 'C:\\my init\\init.ps1'])
// Single quotes group too, and preserve inner double quotes verbatim.
expect(splitShellArgs("-c 'echo \"hi\"'")).toEqual(['-c', 'echo "hi"'])
expect(splitShellArgs(' -l ')).toEqual(['-l'])
expect(splitShellArgs('')).toEqual([])
expect(splitShellArgs(' ')).toEqual([])
})
it('keeps backslashes literal inside quotes and tolerates an unclosed quote', () => {
// Backslash is NOT an escape (Windows paths): "C:\a\" ends with a slash.
expect(splitShellArgs('"C:\\a\\"')).toEqual(['C:\\a\\'])
// An unclosed quote folds the remainder into one token instead of erroring.
expect(splitShellArgs('"unclosed quote')).toEqual(['unclosed quote'])
// Empty quote pairs produce no empty-string argument.
expect(splitShellArgs('"" x')).toEqual(['x'])
})
})
-95
View File
@@ -15,7 +15,6 @@ import type { Context } from '../src/context-types.ts'
import { TextEditor } from '../src/client/TextEditor.tsx'
import { HTML_IFRAME_SANDBOX } from '../src/client/html-preview.ts'
import { DiffPane, HtmlRenderPreview } from '../src/client/changes/DiffPane.tsx'
import { BrowserView, BrowserEmbedBlocked, BROWSER_IFRAME_SANDBOX, iframeSandboxFor } from '../src/client/BrowserView.tsx'
import { createSidebarStore } from '../src/client/state.ts'
import type { FileViewerProps } from '../src/client/service.ts'
@@ -157,97 +156,3 @@ describe('changes tab HTML render preview sandbox', () => {
expect(html).not.toContain('渲染')
})
})
describe('browser tab iframe sandbox', () => {
function tabProps(store: ReturnType<typeof createSidebarStore>, path?: string) {
return {
ctx: CTX,
store,
scope: { sessionId: 's1', cwd: '/p' },
tab: { id: 'browser:1', type: 'browser', title: 'Browser', ...(path !== undefined ? { path } : {}) },
visible: true,
}
}
it('renders the start page before any navigation (no iframe, no auto-load)', () => {
const store = createSidebarStore()
const html = renderToString(createElement(BrowserView, tabProps(store)))
expect(html).not.toContain('<iframe')
expect(html).toContain('输入网址开始浏览')
})
it('sandboxes the iframe without same-origin / top-navigation', () => {
const store = createSidebarStore()
const html = renderToString(createElement(BrowserView, tabProps(store, 'https://example.com/')))
const iframe = /<iframe[^>]*>/.exec(html)?.[0]
expect(iframe).toBeDefined()
expect(iframe).toContain(`sandbox="${BROWSER_IFRAME_SANDBOX}"`)
expect(BROWSER_IFRAME_SANDBOX).not.toContain('allow-same-origin')
expect(BROWSER_IFRAME_SANDBOX).not.toContain('allow-top-navigation')
expect(iframe).toContain('src="https://example.com/"')
expect(iframe).toContain('referrerPolicy="no-referrer"')
expect(iframe).toContain('allow=""')
})
it('never grants allow-same-origin to the GUI\'s own origin, even when allowlisted', () => {
// A bare-host allowlist entry covers every port, so an allowlisted GUI
// host also matches the GUI's exact origin — but a page at the GUI's
// origin must keep the opaque-origin sandbox: allow-same-origin there
// would make it same-origin with its parent and hand it GUI storage/API.
const allowlist = 'localhost'
const guiOrigin = 'http://localhost:5173'
expect(iframeSandboxFor('http://localhost:5173/', allowlist, guiOrigin)).toBe(BROWSER_IFRAME_SANDBOX)
expect(iframeSandboxFor('http://localhost:5173/', allowlist, guiOrigin)).not.toContain('allow-same-origin')
// Other allowlisted loopback origins still get the same-origin token.
const sandbox = iframeSandboxFor('http://localhost:4000/', allowlist, guiOrigin)
expect(sandbox).not.toBe(BROWSER_IFRAME_SANDBOX)
expect(sandbox).toContain('allow-same-origin')
// A different (non-GUI) origin with no allowlist stays opaque.
expect(iframeSandboxFor('https://example.com/', '', guiOrigin)).toBe(BROWSER_IFRAME_SANDBOX)
})
it('renders the live sandbox status row with the temporary unlock action', () => {
const store = createSidebarStore()
const html = renderToString(createElement(BrowserView, tabProps(store, 'https://example.com/')))
expect(html).toContain('沙箱模式:已启用')
expect(html).toContain('临时解锁(不安全)')
})
it('offers the open-in-browser action once a URL is loaded (disabled before navigation)', () => {
const store = createSidebarStore()
// No URL yet: the external-open action is disabled.
const start = renderToString(createElement(BrowserView, tabProps(store)))
expect(start).toContain('aria-label="在浏览器中打开"')
expect(start).toContain('title="在浏览器中打开" disabled=""')
// With a URL: enabled.
const loaded = renderToString(createElement(BrowserView, tabProps(store, 'https://example.com/')))
expect(loaded).toContain('aria-label="在浏览器中打开"')
expect(loaded).not.toContain('title="在浏览器中打开" disabled=""')
})
it('drops the sandbox attribute with the red warning when the setting is on (no restore action — the global setting owns it)', () => {
const store = createSidebarStore()
store.setPrefs({ ...store.getPrefs(), browserNoSandbox: true })
const html = renderToString(createElement(BrowserView, tabProps(store, 'https://example.com/')))
const iframe = /<iframe[^>]*>/.exec(html)?.[0]
expect(iframe).toBeDefined()
expect(iframe).not.toContain('sandbox=')
expect(html).toContain('沙箱已关闭')
expect(html).not.toContain('临时解锁(不安全)')
expect(html).not.toContain('恢复沙箱')
})
})
describe('browser embed-refusal panel', () => {
it('explains the refusal with the host, the reason, and both actions', () => {
const html = renderToString(createElement(BrowserEmbedBlocked, {
url: 'https://arxiv.org/abs/2401.10001',
onOpenInBrowser: () => {},
onLoadAnyway: () => {},
}))
expect(html).toContain('arxiv.org 拒绝了嵌入请求')
expect(html).toContain('X-Frame-Options / frame-ancestors')
expect(html).toContain('在浏览器中打开')
expect(html).toContain('仍然加载')
})
})
+4 -4
View File
@@ -330,8 +330,8 @@ describe('service.openTab dedupe', () => {
id: 'counter',
title: 'Counter',
createTab: (state) => ({
tab: { id: `counter:${state.nextTerminal}`, type: 'counter', title: `C${state.nextTerminal}` },
patch: { nextTerminal: state.nextTerminal + 1 },
tab: { id: `counter:${state.nextBrowser}`, type: 'counter', title: `C${state.nextBrowser}` },
patch: { nextBrowser: state.nextBrowser + 1 },
}),
component: () => null,
})
@@ -343,7 +343,7 @@ describe('service.openTab dedupe', () => {
expect(tabs).toHaveLength(2)
expect(tabs[0]!.id).toBe('counter:1')
expect(tabs[1]!.id).toBe('counter:2')
expect(state.nextTerminal).toBe(3)
expect(state.nextBrowser).toBe(3)
})
it('a caller-provided title wins over the descriptor title (editor shows the file name)', () => {
@@ -557,7 +557,7 @@ describe('state subscription (v0.12.0)', () => {
const snapshot = service.getSnapshot()
expect(snapshot.sessionId).toBe('s1')
expect(snapshot.state).toBeDefined()
expect(snapshot.prefs.agentTerminalTools).toBe(false)
expect(snapshot.prefs.agentOpenTools).toBe(false)
})
it('subscribeState fires on state changes but NOT on registry changes', () => {
+21 -20
View File
@@ -40,9 +40,9 @@ describe('FeatureSettingsRows typed rows (interactive)', () => {
it('commits the raw text on blur and adopts the canonical return', () => {
const commits: Array<[string, string]> = []
const toggle: SidebarSettingToggle = {
key: 'terminalFontFamily',
key: 'titleBarPresetId',
type: 'text',
title: () => 'Font family',
title: () => 'Preset id',
}
const { container, unmount } = renderRoot(createElement(FeatureSettingsRows, {
toggles: [toggle],
@@ -55,7 +55,7 @@ describe('FeatureSettingsRows typed rows (interactive)', () => {
}))
const input = container.querySelector('input')!
typeAndBlur(input, 'Monaco')
expect(commits).toEqual([['terminalFontFamily', 'Monaco']])
expect(commits).toEqual([['titleBarPresetId', 'Monaco']])
// The canonical return is adopted into the draft.
expect(input.value).toBe('Monaco')
unmount()
@@ -64,56 +64,57 @@ describe('FeatureSettingsRows typed rows (interactive)', () => {
it('clamps numbers into the declared bounds on commit', () => {
const commits: Array<[string, number]> = []
const toggle: SidebarSettingToggle = {
key: 'terminalFontSize',
key: 'titleBarStripPx',
type: 'number',
title: () => 'Font size',
min: 9,
max: 32,
title: () => 'Shift distance',
min: 0,
max: 120,
}
const { container, unmount } = renderRoot(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs: { ...prefs, terminalFontSize: 13 },
prefs: { ...prefs, titleBarStripPx: 40 },
onToggle: () => {},
onCommit: (t, raw) => {
const parsed = Number(raw)
const clamped = Math.min(32, Math.max(9, Math.round(parsed)))
const clamped = Math.min(120, Math.max(0, Math.round(parsed)))
commits.push([t.key, clamped])
return String(clamped)
},
}))
const input = container.querySelector('input')!
typeAndBlur(input, '40')
expect(commits).toEqual([['terminalFontSize', 32]])
expect(input.value).toBe('32')
// Above the declared max: the commit clamps to 120.
typeAndBlur(input, '130')
expect(commits).toEqual([['titleBarStripPx', 120]])
expect(input.value).toBe('120')
unmount()
})
it('clamps an emptied number input to the lower bound on commit (width-row precedent)', () => {
const commits: Array<[string, number]> = []
const toggle: SidebarSettingToggle = {
key: 'terminalFontSize',
key: 'titleBarStripPx',
type: 'number',
title: () => 'Font size',
min: 9,
max: 32,
title: () => 'Shift distance',
min: 0,
max: 120,
}
const { container, unmount } = renderRoot(createElement(FeatureSettingsRows, {
toggles: [toggle],
prefs: { ...prefs, terminalFontSize: 13 },
prefs: { ...prefs, titleBarStripPx: 40 },
onToggle: () => {},
// The parent mirrors the real handler: an emptied number parses to 0
// and clamps into the bounds (a browser number input never holds a
// non-numeric string — the draft can only be empty or numeric).
onCommit: (t, raw) => {
const clamped = Math.min(32, Math.max(9, Math.round(Number(raw))))
const clamped = Math.min(120, Math.max(0, Math.round(Number(raw))))
commits.push([t.key, clamped])
return String(clamped)
},
}))
const input = container.querySelector('input')!
typeAndBlur(input, '')
expect(commits).toEqual([['terminalFontSize', 9]])
expect(input.value).toBe('9')
expect(commits).toEqual([['titleBarStripPx', 0]])
expect(input.value).toBe('0')
unmount()
})
+11 -11
View File
@@ -228,41 +228,41 @@ describe('FeatureSettingsRows (the secondary settings popup body)', () => {
expect(html).toContain('checked=""')
})
it('renders a text row as an input seeded with the pref value (empty = theme default)', () => {
it('renders a text row as an input seeded with the pref value', () => {
const html = renderToString(createElement(FeatureSettingsRows, {
toggles: [{
key: 'terminalFontFamily',
key: 'titleBarPresetId',
type: 'text',
title: () => 'Font family',
desc: () => 'CSS stack',
title: () => 'Preset id',
desc: () => 'Named shell preset',
placeholder: '"JetBrains Mono", monospace',
}],
prefs: { ...prefs, terminalFontFamily: '"JetBrains Mono", monospace' },
prefs: { ...prefs, titleBarPresetId: '"JetBrains Mono", monospace' },
onToggle: () => {},
onCommit: () => '',
}))
expect(html).toContain('Font family')
expect(html).toContain('Preset id')
expect(html).toContain('placeholder="&quot;JetBrains Mono&quot;, monospace"')
// The input carries the pref value (no switch for text rows).
expect(html).toContain('value="&quot;JetBrains Mono&quot;, monospace"')
expect(html).not.toContain('type="checkbox"')
})
it('renders a number row with the pref value, the declared bounds and a unit suffix', () => {
it('renders a number row with the pref value, the declared bounds and a unit suffix (non-default bounds)', () => {
const html = renderToString(createElement(FeatureSettingsRows, {
toggles: [{
key: 'terminalFontSize',
key: 'titleBarStripPx',
type: 'number',
title: () => 'Font size',
title: () => 'Shift distance',
min: 9,
max: 32,
unit: 'px',
}],
prefs: { ...prefs, terminalFontSize: 18 },
prefs: { ...prefs, titleBarStripPx: 18 },
onToggle: () => {},
onCommit: () => '18',
}))
expect(html).toContain('Font size')
expect(html).toContain('Shift distance')
expect(html).toContain('type="number"')
expect(html).toContain('value="18"')
expect(html).toContain('min="9"')
+12 -391
View File
@@ -3,18 +3,16 @@
* exercises the real integrations — route registration, git against the
* actual repository, and a real directory listing. Runs with `pnpm test`.
*/
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve as resolvePath } from 'node:path'
import { SettingsConflictError, type SettingsNamespace } from '@deepseek-ai/dsh-settings'
import { apply, mediaTypeForPath, wsCloseReasonOf } from '../src/index.ts'
import { SidebarError } from '../src/wire.ts'
import { apply, mediaTypeForPath } from '../src/index.ts'
import { encodeHtmlUrl } from '../src/html-route.ts'
import * as git from '../src/git.ts'
import { listDirectory } from '../src/fs-tree.ts'
import { defaultShell, PtyManager, type SidebarPty } from '../src/pty-manager.ts'
import type { SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
/** Symlink creation may require elevated privileges on Windows. */
@@ -49,32 +47,6 @@ interface FakeContext {
get: (key: string) => undefined
}
/**
* The login-shell test spawns a real pty whose bash may still be writing to
* the temp HOME (history files, etc.) when `disposeAll()` returns — `close()`
* only requests the kill and the process exit lands asynchronously in
* `onExit`. Deleting the directory immediately then races the shell and
* fails with ENOTEMPTY on CI. Wait for the spawned handle to report `exited`
* (bounded), then remove with a short retry loop as a belt-and-braces
* fallback for any straggler fd.
*/
async function rmTempDirAfterPtyExit(handle: { exited: boolean }, dir: string): Promise<void> {
const deadline = Date.now() + 2000
while (Date.now() < deadline && !handle.exited) {
await new Promise((resolve) => setTimeout(resolve, 50))
}
for (let attempt = 0; ; attempt++) {
try {
rmSync(dir, { recursive: true, force: true })
return
} catch (error) {
const busy = (error as NodeJS.ErrnoException).code === 'ENOTEMPTY' || (error as NodeJS.ErrnoException).code === 'EBUSY'
if (!busy || attempt >= 4) throw error
await new Promise((resolve) => setTimeout(resolve, 100 * (attempt + 1)))
}
}
}
describe('host plugin smoke', () => {
it('serves PDF with the browser-native content type', () => {
expect(mediaTypeForPath('/work/report.PDF')).toBe('application/pdf')
@@ -114,8 +86,8 @@ describe('host plugin smoke', () => {
'/sidebar/file',
'/sidebar/html',
])
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).
expect(upgrades.map(route => route.path)).toEqual(['/sidebar/ws/agent-opens'])
// Teardown runs without throwing.
for (const cleanup of effects) cleanup()
})
@@ -210,171 +182,6 @@ describe('host plugin smoke', () => {
expect(await git.log(cwd, 5, 10_000)).toEqual([])
})
it('pty manager releases the quota on close and respawns after exit', async () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const first = manager.open('s1', 't1', process.cwd(), 80, 24)
expect(manager.keysOf('s1')).toHaveLength(1)
// Tab-close semantics (close frame): quota released immediately.
manager.scheduleClose(first.key, 0)
await new Promise(resolve => setTimeout(resolve, 50))
expect(manager.keysOf('s1')).toHaveLength(0)
// Reopen spawns a fresh process.
const second = manager.open('s1', 't1', process.cwd(), 80, 24)
expect(second).not.toBe(first)
expect(manager.keysOf('s1')).toHaveLength(1)
// After the shell exits, a reconnect respawns instead of reusing the dead handle.
second.pty.write('exit\r')
const deadline = Date.now() + 5000
while (!second.exited && Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 100))
}
expect(second.exited).toBe(true)
const third = manager.open('s1', 't1', process.cwd(), 80, 24)
expect(third.exited).toBe(false)
expect(third).not.toBe(second)
} finally {
manager.disposeAll()
}
})
it('pty manager: exited zombie handles do not consume the quota', async () => {
const manager = new PtyManager(defaultShell(), 1)
try {
const first = manager.open('s3', 't1', process.cwd(), 80, 24)
first.pty.write('exit\r')
const deadline = Date.now() + 5000
while (!first.exited && Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 100))
}
expect(first.exited).toBe(true)
// Quota is 1; the exited handle is swept, so a NEW tab can still spawn.
const second = manager.open('s3', 't2', process.cwd(), 80, 24)
expect(second.exited).toBe(false)
expect(manager.keysOf('s3')).toHaveLength(1)
} finally {
manager.disposeAll()
}
})
it('pty manager: a reconnect within the grace period cancels the pending close', async () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const handle = manager.open('s2', 't1', process.cwd(), 80, 24)
manager.scheduleClose(handle.key, 200)
manager.open('s2', 't1', process.cwd(), 80, 24)
await new Promise(resolve => setTimeout(resolve, 400))
expect(manager.get(handle.key)).toBeDefined()
} finally {
manager.disposeAll()
}
})
it('pty manager: a parked pty survives past the reconnect grace (session switch)', async () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const handle = manager.open('s2', 't1', process.cwd(), 80, 24)
manager.park(handle.key)
expect(manager.isParked(handle.key)).toBe(true)
// A parked pty does NOT enter the grace countdown — it stays alive
// well past any realistic reconnectGraceMs.
await new Promise(resolve => setTimeout(resolve, 300))
expect(manager.get(handle.key)).toBeDefined()
expect(manager.isParked(handle.key)).toBe(true)
} finally {
manager.disposeAll()
}
})
it('pty manager: a reconnecting view clears the parked state (switch back)', () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const handle = manager.open('s2', 't1', process.cwd(), 80, 24)
manager.park(handle.key)
expect(manager.isParked(handle.key)).toBe(true)
// open() calls cancelClose(), which clears the parked state — the
// user switched back to the session and the view reattached.
manager.open('s2', 't1', process.cwd(), 80, 24)
expect(manager.isParked(handle.key)).toBe(false)
expect(manager.get(handle.key)).toBeDefined()
} finally {
manager.disposeAll()
}
})
it('pty manager: an explicit close frame on a parked pty still kills it', async () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const handle = manager.open('s2', 't1', process.cwd(), 80, 24)
manager.park(handle.key)
// The user switched back and closed the tab — scheduleClose (the
// close-frame handler) clears the parked state and kills the pty.
manager.scheduleClose(handle.key, 0)
expect(manager.isParked(handle.key)).toBe(false)
await new Promise(resolve => setTimeout(resolve, 50))
expect(manager.get(handle.key)).toBeUndefined()
} finally {
manager.disposeAll()
}
})
it('pty manager: park on an unknown key is a no-op', () => {
const manager = new PtyManager(defaultShell(), 3)
expect(() => manager.park('s2:nonexistent')).not.toThrow()
expect(manager.isParked('s2:nonexistent')).toBe(false)
})
it('pty manager: reopening with a different cwd respawns in the new directory', async () => {
const manager = new PtyManager(defaultShell(), 3)
// A real second directory: os.tmpdir() exists on every platform ('/tmp'
// does not exist on Windows).
const other = tmpdir()
try {
const first = manager.open('s4', 't1', process.cwd(), 80, 24)
// The hydrate race: the first connect fell back to the process cwd,
// the reconnect carries the session's real cwd — the shell must move.
const second = manager.open('s4', 't1', other, 80, 24)
expect(second).not.toBe(first)
expect(second.cwd).toBe(other)
expect(manager.keysOf('s4')).toHaveLength(1)
// A same-cwd reconnect reattaches without respawning.
const third = manager.open('s4', 't1', other, 80, 24)
expect(third).toBe(second)
expect(manager.keysOf('s4')).toHaveLength(1)
} finally {
manager.disposeAll()
}
})
it.skipIf(process.platform === 'win32')('spawns the shell as a login shell (loads ~/.profile)', async () => {
const home = mkdtempSync(join(tmpdir(), 'dsh-sidebar-login-'))
const previousHome = process.env.HOME
let handle: SidebarPty | undefined
try {
// A login bash reads ~/.profile (a non-login interactive bash reads
// ~/.bashrc instead), so this marker proves the spawn used a login
// argv — the terminal-emulator behavior the tab should match.
writeFileSync(join(home, '.profile'), 'export DSH_LOGIN_MARKER=loaded-from-profile\n')
process.env.HOME = home
const manager = new PtyManager('/bin/bash', 3)
try {
handle = manager.open('s5', 't1', process.cwd(), 80, 24)
handle.pty.write('echo $DSH_LOGIN_MARKER\r')
const deadline = Date.now() + 5000
while (!handle.transcript.includes('loaded-from-profile') && Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 50))
}
expect(handle.transcript).toContain('loaded-from-profile')
} finally {
manager.disposeAll()
}
} finally {
if (previousHome === undefined) delete process.env.HOME
else process.env.HOME = previousHome
await rmTempDirAfterPtyExit(handle ?? { exited: true }, home)
}
})
it('lists the repository root level', async () => {
const listing = await listDirectory(process.cwd(), 1000)
expect(listing.entries.some(entry => entry.name === 'src' && entry.isDir)).toBe(true)
@@ -637,14 +444,6 @@ describe('session cwd resolution over the API route', () => {
expect(result.error?.message).toMatch(/invalid working directory/)
})
it('pty.close releases a terminal key (and rejects a missing tab)', async () => {
const route = mount()
const result = await invoke(route, 'pty.close', { sessionId: 's-pty', tab: 't1' })
expect(result.ok).toBe(true)
const missing = await invoke(route, 'pty.close', { sessionId: 's-pty' })
expect(missing.ok).toBe(false)
})
it('git.diff resolves repo-relative paths (session in a subdirectory)', async () => {
// The plugin repo's status paths are relative to the repo top level
// (e.g. `src/git.ts`); a session whose cwd sits inside the repo must
@@ -936,56 +735,6 @@ describe('side card settings routes', () => {
expect((result.value as { externalDisable?: boolean }).externalDisable).toBe(true)
})
it('serves the effective terminal shell and its display name', async () => {
const route = mountWithSettings(undefined)
const result = await invoke(route, 'shell.get', {})
expect(result.ok).toBe(true)
expect(result.value).toMatchObject({
shell: expect.any(String),
name: expect.any(String),
})
expect(String((result.value as { name: unknown }).name).length).toBeGreaterThan(0)
})
it('shell.get reflects the settings-page override with the quotes stripped', async () => {
const route = mountWithSettings(createFakeSettings({
'dsh-better-sidebar': {
terminalShell: '"C:\\Program Files\\PowerShell\\7\\pwsh.exe"',
terminalShellArgs: '-NoLogo',
},
}))
const result = await invoke(route, 'shell.get', {})
expect(result.ok).toBe(true)
expect(result.value).toMatchObject({
shell: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',
name: 'pwsh',
})
})
it('maps a shell-not-found failure to the machine-readable close reason', async () => {
expect(wsCloseReasonOf(new SidebarError(
'shell-not-found',
'shell executable not found: "C:\\Program Files\\PowerShell\\7\\pwsh.exe"',
400,
{ shell: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe' },
))).toBe('shell-not-found:pwsh')
expect(wsCloseReasonOf(new Error('boom'))).toBe('boom')
expect(wsCloseReasonOf('plain')).toBe('plain')
})
it('caps the close reason by UTF-8 bytes so the ws 123-byte limit holds', () => {
// 200 CJK characters are ~600 bytes: a character-count slice would still
// overflow the cap `ws` enforces with Buffer.byteLength.
const reason = wsCloseReasonOf(new SidebarError(
'shell-not-found',
'shell executable not found',
400,
{ shell: `/bin/${'终'.repeat(200)}` },
))
expect(reason.startsWith('shell-not-found:')).toBe(true)
expect(Buffer.byteLength(reason)).toBeLessThanOrEqual(123)
})
it('reads the resolved prefs and writes a patch through the seam', async () => {
const route = mountWithSettings(createFakeSettings())
const read = await invoke(route, 'settings.get', {})
@@ -994,23 +743,20 @@ describe('side card settings routes', () => {
value: {
autoOpenSubagent: true,
autoOpenJobs: true,
agentTerminalTools: false, agentOpenTools: false,
bottomPanelAutoTerminal: true,
terminalFontFamily: '',
terminalFontSize: 13,
agentOpenTools: false,
editorExplorer: false,
workspaceFence: true,
terminalShell: '',
terminalShellArgs: '',
// The route serves the SCHEMA-resolved document, and these three
// title-bar fields are declared without a schema default on purpose
// (the client's parsePrefs supplies `auto` / '' instead, which is
// what lets a document predating them migrate rather than flip).
titleBarCompat: false,
titleBarStripPx: 40,
htmlViewerNoSandbox: false,
htmlViewerDefaultUnsafe: false,
browserNoSandbox: false,
browserInterceptLinks: true,
browserInterceptHttp: true,
browserInterceptHttps: false,
browserAllowedLoopback: '',
// The enable-switch maps default to {} (everything on).
tabsEnabled: {},
viewersEnabled: {},
@@ -1023,9 +769,9 @@ describe('side card settings routes', () => {
const written = await invoke(route, 'settings.update', { patch: { agentOpenTools: true } })
expect(written.ok).toBe(true)
const view = written.value as { value: { agentOpenTools: boolean; terminalFontSize: number }; revision: number }
const view = written.value as { value: { agentOpenTools: boolean; titleBarStripPx: number }; revision: number }
expect(view.value.agentOpenTools).toBe(true)
expect(view.value.terminalFontSize).toBe(13)
expect(view.value.titleBarStripPx).toBe(40)
expect(view.revision).toBe(1)
})
@@ -1062,7 +808,7 @@ describe('side card settings routes', () => {
await invoke(route, 'settings.update', { patch: { agentOpenTools: false } })
// The second write carries the pre-write revision: the seam refuses it.
const stale = await invoke(route, 'settings.update', {
patch: { terminalFontSize: 15 },
patch: { titleBarStripPx: 15 },
expectedRevision: 0,
})
expect(stale.ok).toBe(false)
@@ -1076,131 +822,6 @@ describe('side card settings routes', () => {
expect(result.ok).toBe(false)
expect(result.error?.message).toMatch(/plain object/)
})
/** Fake fetch responses shaped like what the route consumes. */
const respond = (status: number, headers: Record<string, string>): Response =>
({ status, url: 'https://site.example/', headers: new Headers(headers) }) as unknown as Response
it('reports X-Frame-Options and frame-ancestors from the target headers', async () => {
const route = mountWithSettings(undefined)
vi.stubGlobal('fetch', vi.fn(async () => respond(200, {
'x-frame-options': 'SAMEORIGIN',
'content-security-policy': "default-src 'self'; frame-ancestors 'none'",
})))
try {
const result = await invoke(route, 'browser.probe', { url: 'https://arxiv.org/' })
expect(result.ok).toBe(true)
expect(result.value).toEqual({
reachable: true,
url: 'https://site.example/',
status: 200,
xFrameOptions: 'SAMEORIGIN',
frameAncestors: ["'none'"],
})
} finally {
vi.unstubAllGlobals()
}
})
it('retries a 405 HEAD as GET', async () => {
const route = mountWithSettings(undefined)
const fetchMock = vi.fn()
.mockResolvedValueOnce(respond(405, {}))
.mockResolvedValueOnce(respond(200, {}))
vi.stubGlobal('fetch', fetchMock)
try {
const result = await invoke(route, 'browser.probe', { url: 'https://example.com/' })
expect(result.ok).toBe(true)
expect(fetchMock).toHaveBeenCalledTimes(2)
expect(result.value).toMatchObject({ reachable: true, status: 200 })
} finally {
vi.unstubAllGlobals()
}
})
it('reports an unreachable target as reachable:false', async () => {
const route = mountWithSettings(undefined)
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ENOTFOUND') }))
try {
const result = await invoke(route, 'browser.probe', { url: 'https://example.com/' })
expect(result.ok).toBe(true)
expect(result.value).toEqual({ reachable: false })
} finally {
vi.unstubAllGlobals()
}
})
it('refuses non-http(s) and loopback URLs', async () => {
const route = mountWithSettings(undefined)
for (const url of ['javascript:alert(1)', 'file:///etc/passwd', 'http://127.0.0.1:8080/', 'http://localhost/']) {
const result = await invoke(route, 'browser.probe', { url })
expect(result.ok, url).toBe(false)
expect(result.error?.code, url).toBe('bad-request')
}
})
})
describe('agent terminal tool gating', () => {
it('injects the eight tools only when the side-card setting is enabled (default off)', () => {
let registered = 0
let disposed = 0
// The tools currently registered (registered minus disposed).
const live = (): number => registered - disposed
// A ref container: the watch callback is only assigned inside a closure,
// which TypeScript's control-flow analysis ignores (the bare variable
// would narrow to null and refuse the optional call).
const watcherRef: { current: (() => void) | null } = { current: null }
let enabled = false
const settings = {
register() {
return {
get: () => ({ agentTerminalTools: enabled }),
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 () => {}
},
// The session/agent event feeds: nothing emits in these tests.
on: () => () => {},
// No jobs/agents services: the jobs routes degrade to a 503.
get: () => undefined,
}
apply(ctx as never)
// Default off: no tools are registered even though the settings service is mounted.
expect(live()).toBe(0)
// Flipping the setting on registers all eight tools.
enabled = true
watcherRef.current?.()
expect(live()).toBe(8)
expect(disposed).toBe(0)
// Flipping it back off unregisters them (and releases any agent terminals).
enabled = false
watcherRef.current?.()
expect(live()).toBe(0)
expect(disposed).toBe(8)
// And a redundant toggle registers them fresh (no double-registration per
// flip: the guard only skips when the tools are already live).
enabled = true
watcherRef.current?.()
expect(live()).toBe(8)
expect(registered).toBe(16)
})
})
describe('agent sidebar-open tool gating', () => {
+8 -108
View File
@@ -3,7 +3,7 @@ import {
activateTab, allLeaves, BOTTOM_DEFAULT, BOTTOM_MIN, closeTab, CONVERSATION_MIN, createSidebarStore,
insertLeafAt, makeDefaultState, moveTab, moveTabToEdge, openDiffTab,
openTabInBottomPane, patchTab, resizeSplit,
resizeSplitIn, revealPaths, sanitizeState, setBottomHeight, setTabPin,
resizeSplitIn, revealPaths, sanitizeState, setBottomHeight,
splitPane, tabOpenIn, toggleBottomPanel, toggleExpanded,
type SidebarState, type SidebarTab, type SplitNode,
} from '../src/client/state.ts'
@@ -13,7 +13,7 @@ describe('sidebar state', () => {
it('sanitizeState migrates persisted explorer tabs to editor home tabs', () => {
const valid = sanitizeState({
nextTerminal: 1,
nextBrowser: 1,
activePane: 'pane:1',
expanded: [],
bottomSplits: {
@@ -117,7 +117,7 @@ describe('sidebar state', () => {
it('sanitize drops diff tabs (ephemeral, like VSCode diff editors)', () => {
const valid = sanitizeState({
nextTerminal: 1,
nextBrowser: 1,
activePane: 'pane:1',
expanded: [],
bottomSplits: {
@@ -138,7 +138,7 @@ describe('sidebar state', () => {
expect((valid?.bottomSplits as { active: string | null }).active).toBeNull()
// A leaf of ONLY diff tabs survives as an empty pane (welcome cards).
const onlyDiff = sanitizeState({
nextTerminal: 1,
nextBrowser: 1,
activePane: 'pane:1',
expanded: [],
bottomSplits: {
@@ -154,7 +154,7 @@ describe('sidebar state', () => {
it('sanitize removes a pane emptied by ephemeral diff tabs', () => {
const valid = sanitizeState({
nextTerminal: 1,
nextBrowser: 1,
activePane: 'pane:diff',
expanded: [],
bottomSplits: {
@@ -314,7 +314,7 @@ describe('sidebar state', () => {
it('sanitize accepts nextBrowser (defaulting a missing/malformed one to 1)', () => {
const base = {
nextTerminal: 1,
nextBrowser: 1,
activePane: 'pane:1',
expanded: [],
bottomSplits: {
@@ -391,7 +391,7 @@ describe('sidebar state', () => {
it('sanitize defaults the bottom fields for older persisted states and repairs a broken bottom tree', () => {
const base = {
nextTerminal: 1,
nextBrowser: 1,
activePane: 'pane:1',
expanded: [],
}
@@ -726,106 +726,6 @@ describe('revealPaths (show in folder)', () => {
})
})
describe('pinned terminals (v0.17.0)', () => {
// setTabPin reads neither window nor localStorage directly, but the
// pinnedTab-aware sanitize round-trip below uses JSON.parse/stringify
// only — keep this block window-less for parity with the main describe.
const state = (): SidebarState => makeDefaultState()
it('setTabPin marks a terminal in the workbench', () => {
let s = state()
s = openTabInBottomPane(s, { id: 'terminal:1', type: 'terminal', title: 'T' })
s = setTabPin(s, 'terminal:1', { scope: 'workspace', homeCwd: '/proj' })
const tab = allLeaves(s.bottomSplits).flatMap(l => l.tabs).find(t => t.id === 'terminal:1')!
expect(tab.pin).toEqual({ scope: 'workspace', homeCwd: '/proj' })
})
it('setTabPin with null clears the pin marker but keeps the tab', () => {
let s = state()
s = openTabInBottomPane(s, { id: 'terminal:1', type: 'terminal', title: 'T' })
s = setTabPin(s, 'terminal:1', { scope: 'global' })
s = setTabPin(s, 'terminal:1', null)
const tab = allLeaves(s.bottomSplits).flatMap(l => l.tabs).find(t => t.id === 'terminal:1')!
expect(tab.pin).toBeUndefined()
expect(tabOpenIn(s, 'terminal:1')).toBe(true)
})
it('setTabPin on an unknown tab id is a strict same-reference no-op', () => {
const s = state()
expect(setTabPin(s, 'ghost', { scope: 'global' })).toBe(s)
expect(setTabPin(s, 'ghost', null)).toBe(s)
})
it('setTabPin is idempotent: setting the same pin twice returns the same reference', () => {
let s = state()
s = openTabInBottomPane(s, { id: 'terminal:1', type: 'terminal', title: 'T' })
s = setTabPin(s, 'terminal:1', { scope: 'workspace', homeCwd: '/p' })
const once = s
s = setTabPin(s, 'terminal:1', { scope: 'workspace', homeCwd: '/p' })
expect(s).toBe(once)
})
it('sanitizeState preserves a legal pin and strips an illegal scope (keeps the tab)', () => {
const g = globalThis as Record<string, unknown>
g.window = { clearTimeout: () => {}, setTimeout: () => 0, innerWidth: 1024, innerHeight: 768 }
g.localStorage = { getItem: () => null, setItem: () => {} }
try {
const legal = JSON.parse(JSON.stringify(makeDefaultState())) as {
bottomSplits: { kind: 'leaf'; id: string; tabs: SidebarTab[]; active: string | null }
}
legal.bottomSplits.tabs.push({
id: 'terminal:1', type: 'terminal', title: 'T',
pin: { scope: 'workspace', homeCwd: '/proj' },
} as SidebarTab)
legal.bottomSplits.active = 'terminal:1'
const restored = sanitizeState(legal)!
const tab = (restored.bottomSplits as { tabs: SidebarTab[] }).tabs.find(t => t.id === 'terminal:1')!
expect(tab.pin).toEqual({ scope: 'workspace', homeCwd: '/proj' })
// Illegal scope drops the pin, keeps the tab.
const illegal = JSON.parse(JSON.stringify(makeDefaultState())) as {
bottomSplits: { kind: 'leaf'; id: string; tabs: SidebarTab[]; active: string | null }
}
illegal.bottomSplits.tabs.push({
id: 'terminal:2', type: 'terminal', title: 'T2',
pin: { scope: 'bogus', homeCwd: '/x' },
} as unknown as SidebarTab)
illegal.bottomSplits.active = 'terminal:2'
const cleaned = sanitizeState(illegal)!
const tab2 = (cleaned.bottomSplits as { tabs: SidebarTab[] }).tabs.find(t => t.id === 'terminal:2')!
expect(tab2.pin).toBeUndefined()
expect(tab2.id).toBe('terminal:2')
// Non-string homeCwd drops homeCwd but keeps a global pin.
const weirdHome = JSON.parse(JSON.stringify(makeDefaultState())) as {
bottomSplits: { kind: 'leaf'; id: string; tabs: SidebarTab[]; active: string | null }
}
weirdHome.bottomSplits.tabs.push({
id: 'terminal:3', type: 'terminal', title: 'T3',
pin: { scope: 'global', homeCwd: 42 },
} as unknown as SidebarTab)
weirdHome.bottomSplits.active = 'terminal:3'
const weird = sanitizeState(weirdHome)!
const tab3 = (weird.bottomSplits as { tabs: SidebarTab[] }).tabs.find(t => t.id === 'terminal:3')!
expect(tab3.pin).toEqual({ scope: 'global' })
// Older state without pin loads unchanged.
const legacy = JSON.parse(JSON.stringify(makeDefaultState())) as {
bottomSplits: { kind: 'leaf'; id: string; tabs: SidebarTab[]; active: string | null }
}
legacy.bottomSplits.tabs.push({ id: 'terminal:4', type: 'terminal', title: 'T4' } as SidebarTab)
legacy.bottomSplits.active = 'terminal:4'
const legacyRestored = sanitizeState(legacy)!
const tab4 = (legacyRestored.bottomSplits as { tabs: SidebarTab[] }).tabs.find(t => t.id === 'terminal:4')!
expect(tab4.pin).toBeUndefined()
} finally {
delete g.window
delete g.localStorage
}
})
})
describe('URL reset escape hatch (issue #369)', () => {
// Same browser-global stubs as the v0.12.0 block above; loadState reads
// window.location.search (reset param) and localStorage (persisted state).
@@ -842,7 +742,7 @@ describe('URL reset escape hatch (issue #369)', () => {
/** A persisted layout whose restored git tab would re-hang the page. */
const frozenState = JSON.stringify({
nextTerminal: 1,
nextBrowser: 1,
activePane: 'pane:1',
expanded: [],
bottomSplits: { kind: 'leaf', id: 'pane:1', active: 'g1', tabs: [{ id: 'g1', type: 'git', title: 'Git' }] },
-153
View File
@@ -208,156 +208,3 @@ describe('TabBar right-click context menu', () => {
}
})
})
describe('TabBar pin submenu (v0.17.0)', () => {
/** The portaled submenu rows (aria-expanded parent + nested menuitem rows). */
function submenuItems(): HTMLElement[] {
return [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"], [role="menuitem"]')]
}
it('hides the pin entry when onPinTab is not provided (legacy callers)', () => {
stubZh()
const { tabEls, unmount } = mountBar(fourTabs())
try {
act(() => { rightClick(tabEls[2]!) }) // t3 = terminal
// Exactly the legacy close-only menu, no pin row.
expect(menuItems().map(item => item.textContent)).toEqual(MENU_LABELS)
} finally {
unmount()
}
})
it('adds a "Pin Terminal ▸" submenu for an unpinned UI terminal', () => {
stubZh()
const onPinTab = vi.fn<(tabId: string, scope: 'workspace' | 'global' | null) => void>()
const { tabEls, unmount } = mountBar(fourTabs(), { onPinTab })
try {
act(() => { rightClick(tabEls[2]!) }) // t3 = UI terminal
const labels = menuItems().map(item => item.textContent)
// pin (with submenu indicator) | close | closeOthers | closeLeft | closeRight
expect(labels[0]).toBe('固定终端')
expect(labels[1]).toBe('关闭')
// Hovering the pin row reveals the submenu items. React synthesizes
// onMouseEnter from the bubbling mouseover event, so dispatch that.
act(() => { menuItems()[0]!.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })) })
const sub = submenuItems().map(item => item.textContent)
expect(sub).toContain('固定到工作区')
expect(sub).toContain('固定到全局')
// Clicking "pin to workspace" fires the callback.
const wsItem = submenuItems().find(item => item.textContent === '固定到工作区')!
act(() => { wsItem.click() })
expect(onPinTab).toHaveBeenCalledWith('t3', 'workspace')
} finally {
unmount()
}
})
it('uses the "Pin Agent Terminal" label for an agent terminal tab', () => {
stubZh()
const onPinTab = vi.fn<(tabId: string, scope: 'workspace' | 'global' | null) => void>()
const tabs: SidebarTab[] = [
{ id: 'agent:abc-123', type: 'terminal', title: 'Agent T' },
]
const { tabEls, unmount } = mountBar(tabs, { onPinTab })
try {
act(() => { rightClick(tabEls[0]!) })
const labels = menuItems().map(item => item.textContent)
expect(labels[0]).toBe('固定 Agent 终端')
} finally {
unmount()
}
})
it('shows "Unpin" instead of the submenu for an already-pinned terminal', () => {
stubZh()
const onPinTab = vi.fn<(tabId: string, scope: 'workspace' | 'global' | null) => void>()
const tabs: SidebarTab[] = [
{ id: 'terminal:1', type: 'terminal', title: 'T', pin: { scope: 'global' } },
]
const { tabEls, unmount } = mountBar(tabs, { onPinTab })
try {
act(() => { rightClick(tabEls[0]!) })
const labels = menuItems().map(item => item.textContent)
expect(labels).toContain('取消固定')
expect(labels).not.toContain('固定终端')
const unpinItem = menuItems().find(item => item.textContent === '取消固定')!
act(() => { unpinItem.click() })
expect(onPinTab).toHaveBeenCalledWith('terminal:1', null)
} finally {
unmount()
}
})
it('does not add a pin entry for non-terminal tabs even with onPinTab provided', () => {
stubZh()
const onPinTab = vi.fn<(tabId: string, scope: 'workspace' | 'global' | null) => void>()
const { tabEls, unmount } = mountBar(fourTabs(), { onPinTab })
try {
act(() => { rightClick(tabEls[0]!) }) // t1 = editor
expect(menuItems().map(item => item.textContent)).toEqual(MENU_LABELS)
act(() => { rightClick(tabEls[1]!) }) // t2 = git
expect(menuItems().map(item => item.textContent)).toEqual(MENU_LABELS)
expect(onPinTab).not.toHaveBeenCalled()
} finally {
unmount()
}
})
})
describe('TabBar context menu flip geometry (submenu clamping)', () => {
const ATTR = 'data-dsh-sidebar-submenu'
/** jsdom's default viewport (what the hook reads via window.innerWidth/Height). */
const VW = window.innerWidth
const VH = window.innerHeight
it('publishes "down" while the menu is open and clears it on selection', () => {
stubZh()
const { tabEls, onClose, unmount } = mountBar(fourTabs())
try {
// rightClick() dispatches at clientY 40 — the top strip, upper half.
act(() => { rightClick(tabEls[1]!) })
expect(document.body.getAttribute(ATTR)).toBe('down')
act(() => { menuItems()[0]!.click() })
expect(onClose).toHaveBeenCalledWith('t2')
expect(document.body.hasAttribute(ATTR)).toBe(false)
} finally {
unmount()
}
})
it('flips left when the cursor sits within the right-hand submenu room', () => {
stubZh()
const { tabEls, unmount } = mountBar(fourTabs())
try {
const nearRight = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: VW - 10, clientY: 40 })
act(() => { tabEls[1]!.dispatchEvent(nearRight) })
expect(document.body.getAttribute(ATTR)).toBe('down left')
} finally {
unmount()
}
})
it('keeps the primitive defaults (empty tokens) for a lower-half opening', () => {
stubZh()
const { tabEls, unmount } = mountBar(fourTabs())
try {
const lowLeft = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: VH - 40 })
act(() => { tabEls[1]!.dispatchEvent(lowLeft) })
// Attribute present but empty: layout.css matches no token, so the
// host primitive's own up/right geometry applies.
expect(document.body.getAttribute(ATTR)).toBe('')
} finally {
unmount()
}
})
it('clears the attribute on unmount with the menu still open', () => {
stubZh()
const { tabEls, unmount } = mountBar(fourTabs())
act(() => { rightClick(tabEls[1]!) })
expect(document.body.getAttribute(ATTR)).toBe('down')
unmount()
expect(document.body.hasAttribute(ATTR)).toBe(false)
})
})
-1
View File
@@ -21,7 +21,6 @@ function makeKey(overrides: Partial<TabContentMemoKey> = {}): TabContentMemoKey
revealed: [],
localeRevision: 'en-US',
tabsVersion: 0,
effectiveTabId: undefined,
...overrides,
}
}
-83
View File
@@ -1,83 +0,0 @@
/**
* TerminalDepsBanner tests (issue #140): the degraded-mode banner the
* terminal tab shows when node-pty fails to load. It must render the
* failure title, the PASTEABLE repair command (bash / cmd / PowerShell),
* a copy button that writes the command to the clipboard with a transient
* "Copied" feedback, and a retry button.
*
* The banner is tested directly (like PluginListBody): it is a pure
* presentational component, so server-side renderToString covers the
* static content and createRoot + act() covers the copy click.
*/
// @vitest-environment jsdom
import { describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { renderToString } from 'react-dom/server'
import { createRoot } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import * as primitives from '@deepseek-ai/dsh-client-ui-primitives'
import { TerminalDepsBanner } from '../src/client/TerminalView.tsx'
// The act() environment flag (React 18.2 reads it before flushing effects).
import { setupReactAct } from './test-utils.ts'
setupReactAct()
const deps = {
ok: false as const,
cause: 'Cannot find package node-pty',
command: 'bash "/Users/u/.dsh/profiles/web/node_modules/.pnpm/dsh-better-sidebar@0.0.0/node_modules/dsh-better-sidebar/scripts/install.sh" --repair --profile "web"',
profile: 'web',
}
describe('TerminalDepsBanner (render)', () => {
it('renders the failure title, the pasteable command and the actions', () => {
const html = renderToString(createElement(TerminalDepsBanner, { deps, onRetry: () => {} }))
// The jsdom locale is en-US, so the en dictionary applies.
expect(html).toContain('Terminal dependency node-pty failed to load')
// renderToString HTML-escapes the quotes inside the command block.
expect(html).toContain(deps.command.replaceAll('"', '&quot;'))
expect(html).toContain('Copy')
expect(html).toContain('Retry')
// The profile the command targets is shown next to the hint.
expect(html).toContain('detected profile: web')
})
})
describe('TerminalDepsBanner copy click (interactive)', () => {
it('clicking Copy writes the repair command and flashes "Copied"', async () => {
vi.spyOn(primitives, 'writeClipboard').mockResolvedValue(true)
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const onRetry = vi.fn()
act(() => {
root.render(createElement(TerminalDepsBanner, { deps, onRetry }))
})
const copyButton = container.querySelector('button[aria-label="Copy"]') as HTMLButtonElement
expect(copyButton).not.toBeNull()
expect(copyButton.textContent).toBe('Copy')
await act(async () => { copyButton.click() })
expect(primitives.writeClipboard).toHaveBeenCalledWith(deps.command)
expect(copyButton.textContent).toBe('Copied')
act(() => { root.unmount() })
container.remove()
vi.restoreAllMocks()
})
it('clicking Retry fires the callback (the view reconnects)', async () => {
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const onRetry = vi.fn()
act(() => {
root.render(createElement(TerminalDepsBanner, { deps, onRetry }))
})
const buttons = [...container.querySelectorAll('button')] as HTMLButtonElement[]
const retry = buttons.find(button => button.textContent === 'Retry')
expect(retry).toBeDefined()
await act(async () => { retry!.click() })
expect(onRetry).toHaveBeenCalledTimes(1)
act(() => { root.unmount() })
container.remove()
})
})
-248
View File
@@ -1,248 +0,0 @@
/**
* Terminal font resolution tests: the custom font prefs (side card settings,
* terminal card) resolve into xterm options with a strict fallback chain —
* user family > theme code font > the built-in monospace stack, and the size
* clamped into the 9–32 contract.
*
* On top of the base family, icon fonts (Nerd Font + color emoji) are
* appended so shell prompts drawing from the Private Use Areas render real
* glyphs instead of the missing-glyph box, and the stack is terminated with
* a generic family so an unresolvable name degrades to a monospace instead
* of the proportional standard font.
*/
import { describe, expect, it } from 'vitest'
import { SIDEBAR_PREFS_DEFAULTS, clampTerminalFontSize, TERMINAL_FONT_SIZE_MAX, TERMINAL_FONT_SIZE_MIN } from '../src/prefs-shared.ts'
import {
DEFAULT_TERMINAL_FONT_FAMILY,
ICON_FONT_FALLBACKS,
resolveTerminalFont,
withIconFontFallbacks,
withMonospaceFallback,
} from '../src/client/terminal-font.ts'
describe('clampTerminalFontSize', () => {
it('rounds and clamps into the 9–32 contract', () => {
expect(clampTerminalFontSize(13)).toBe(13)
expect(clampTerminalFontSize(15.6)).toBe(16)
expect(clampTerminalFontSize(5)).toBe(TERMINAL_FONT_SIZE_MIN)
expect(clampTerminalFontSize(40)).toBe(TERMINAL_FONT_SIZE_MAX)
})
})
describe('withIconFontFallbacks', () => {
/** Index of a family in a resolved stack, -1 when absent. */
function indexOfFamily(stack: string, family: string): number {
return stack.split(',').map(part => part.trim()).indexOf(family)
}
it('keeps the base font first so xterm measures cells against it', () => {
const stack = withIconFontFallbacks('"JetBrains Mono", monospace')
expect(stack.startsWith('"JetBrains Mono"')).toBe(true)
})
it('splices icon fonts ahead of a trailing generic family (a generic always resolves)', () => {
const stack = withIconFontFallbacks('"JetBrains Mono", monospace')
const parts = stack.split(',').map(part => part.trim())
expect(parts[parts.length - 1]).toBe('monospace')
expect(parts.indexOf('"Symbols Nerd Font Mono"')).toBeGreaterThan(0)
expect(parts.indexOf('"Symbols Nerd Font Mono"')).toBeLessThan(parts.length - 1)
})
it('splices ahead of a generic sitting MID-stack, not just a trailing one', () => {
// Regression guard: a generic anywhere is a catch-all, so appending
// after it silently defeats the whole fix (the icon fonts would never
// be consulted). Stacks of this shape come from theme tokens.
const stack = withIconFontFallbacks('ui-monospace, Menlo, monospace, "Apple Color Emoji"')
expect(indexOfFamily(stack, '"Symbols Nerd Font Mono"'))
.toBeLessThan(indexOfFamily(stack, 'ui-monospace'))
})
it('keeps fully-patched fonts BEHIND a leading generic (they carry Latin and would become the base)', () => {
// A leading generic resolves, so prepending a fully-patched Nerd Font
// (which ships Latin glyphs) would make it xterm's measuring/base font
// and override the user/theme family precedence. Only the symbols-only
// patches (no Latin) may precede it.
const stack = withIconFontFallbacks('monospace')
expect(indexOfFamily(stack, '"Symbols Nerd Font Mono"')).toBeLessThan(indexOfFamily(stack, 'monospace'))
expect(indexOfFamily(stack, '"Hack Nerd Font Mono"')).toBeGreaterThan(indexOfFamily(stack, 'monospace'))
expect(indexOfFamily(stack, '"JetBrainsMono Nerd Font Mono"')).toBeGreaterThan(indexOfFamily(stack, 'monospace'))
})
it('splices ahead of the FIRST generic when several are present', () => {
const stack = withIconFontFallbacks('Menlo, monospace, sans-serif')
const nerd = indexOfFamily(stack, '"Symbols Nerd Font Mono"')
expect(nerd).toBeGreaterThan(indexOfFamily(stack, 'Menlo'))
expect(nerd).toBeLessThan(indexOfFamily(stack, 'monospace'))
expect(indexOfFamily(stack, 'sans-serif')).toBe(stack.split(',').length - 1)
})
it('appends at the end when the stack has no generic family', () => {
const stack = withIconFontFallbacks('"JetBrains Mono"')
expect(stack.startsWith('"JetBrains Mono", "Symbols Nerd Font Mono"')).toBe(true)
})
it('orders symbols-only patches ahead of fully-patched distributions', () => {
// Order IS the priority contract: the symbols-only families carry no
// Latin glyphs, so they can never hijack ASCII cell metrics.
const stack = withIconFontFallbacks('Menlo, monospace')
expect(indexOfFamily(stack, '"Symbols Nerd Font Mono"'))
.toBeLessThan(indexOfFamily(stack, '"Hack Nerd Font Mono"'))
})
it('names Nerd Font families explicitly to cover both PUA planes', () => {
const stack = withIconFontFallbacks('Menlo, monospace')
expect(stack).toContain('"Symbols Nerd Font Mono"')
expect(stack).toContain('"Hack Nerd Font Mono"')
})
it('omits color-emoji families (Chromium routes emoji through its own fallback)', () => {
// Listing a color font ahead of the generic would let it capture BMP
// symbols the prompt expects in monospace and break the cell grid.
const stack = withIconFontFallbacks('Menlo, monospace')
expect(stack).not.toContain('Apple Color Emoji')
expect(stack).not.toContain('Segoe UI Emoji')
expect(stack).not.toContain('Noto Color Emoji')
})
it('does not duplicate a family the caller already listed, preserving its priority', () => {
const stack = withIconFontFallbacks("'hack nerd font mono', monospace")
expect(stack.toLowerCase().split('hack nerd font mono').length - 1).toBe(1)
// The caller's entry keeps pole position.
expect(stack.startsWith("'hack nerd font mono'")).toBe(true)
})
it('treats quote, case and whitespace differences as the same family', () => {
const stack = withIconFontFallbacks('"Symbols Nerd Font Mono", monospace')
expect(stack.toLowerCase().split('symbols').length - 1).toBe(2) // Mono + proportional
})
it('is idempotent so TerminalView\'s option diff does not thrash', () => {
const once = withIconFontFallbacks('Menlo, monospace')
expect(withIconFontFallbacks(once)).toBe(once)
})
it('splits on top-level commas only, keeping quoted and function values whole', () => {
expect(withIconFontFallbacks('"Foo,Bar", monospace')).toContain('"Foo,Bar"')
expect(withIconFontFallbacks('var(--code, monospace)')).toContain('var(--code, monospace)')
})
it('falls back to the icon list alone for an empty stack (defensive)', () => {
expect(withIconFontFallbacks('')).toBe(ICON_FONT_FALLBACKS.join(', '))
expect(withIconFontFallbacks(' , ')).toBe(ICON_FONT_FALLBACKS.join(', '))
})
})
describe('resolveTerminalFont', () => {
it('falls back to the theme code font when the family pref is empty', () => {
const { fontFamily, fontSize } = resolveTerminalFont(SIDEBAR_PREFS_DEFAULTS, 'var-theme-font')
// The theme font stays the base (first) entry; the monospace tail keeps
// the grid alive, and icon fonts top it up.
expect(fontFamily).toBe(withIconFontFallbacks(withMonospaceFallback('var-theme-font')))
expect(fontFamily.startsWith('var-theme-font')).toBe(true)
expect(fontFamily.endsWith('monospace')).toBe(true)
expect(fontSize).toBe(13)
})
it('terminates a custom family that names no generic, keeping the grid monospaced', () => {
// The reported failure: a family installed only on the machine running the
// shell resolves to nothing in the browser, and without a generic tail the
// fallback is the proportional standard font (PingFang SC on macOS), whose
// advance xterm then measures the cell from.
const { fontFamily } = resolveTerminalFont(
{ ...SIDEBAR_PREFS_DEFAULTS, terminalFontFamily: 'Maple Mono NF CN' },
undefined,
)
expect(fontFamily.startsWith('Maple Mono NF CN')).toBe(true)
expect(fontFamily.endsWith('monospace')).toBe(true)
})
it('falls back to the built-in monospace stack when neither the pref nor the theme provides one', () => {
expect(resolveTerminalFont(SIDEBAR_PREFS_DEFAULTS, undefined).fontFamily)
.toBe(withIconFontFallbacks(DEFAULT_TERMINAL_FONT_FAMILY))
// A whitespace-only pref counts as empty (theme default).
expect(resolveTerminalFont({ ...SIDEBAR_PREFS_DEFAULTS, terminalFontFamily: ' ' }, undefined).fontFamily)
.toBe(withIconFontFallbacks(DEFAULT_TERMINAL_FONT_FAMILY))
})
it('skips a CSS-wide keyword instead of building an invalid declaration', () => {
// Skins do set tokens to these; appending to one yields an invalid
// font-family that the CSSOM discards, losing every font at once.
for (const keyword of ['inherit', 'initial', 'unset', 'revert', 'REVERT-LAYER']) {
const { fontFamily } = resolveTerminalFont(SIDEBAR_PREFS_DEFAULTS, keyword)
expect(fontFamily).toBe(withIconFontFallbacks(DEFAULT_TERMINAL_FONT_FAMILY))
expect(fontFamily.toLowerCase()).not.toContain(keyword.toLowerCase())
}
// Same guard on the user pref, which then defers to the theme font.
expect(resolveTerminalFont({ ...SIDEBAR_PREFS_DEFAULTS, terminalFontFamily: 'inherit' }, 'var-theme-font').fontFamily)
.toBe(withIconFontFallbacks(withMonospaceFallback('var-theme-font')))
})
it('prefers the custom family as the base and clamps the size', () => {
const { fontFamily, fontSize } = resolveTerminalFont(
{ ...SIDEBAR_PREFS_DEFAULTS, terminalFontFamily: '"JetBrains Mono", monospace', terminalFontSize: 40 },
'var-theme-font',
)
expect(fontFamily).toBe(withIconFontFallbacks('"JetBrains Mono", monospace'))
expect(fontFamily.startsWith('"JetBrains Mono"')).toBe(true)
expect(fontFamily).not.toContain('var-theme-font')
expect(fontSize).toBe(TERMINAL_FONT_SIZE_MAX)
})
it('applies icon fallbacks no matter which base family wins', () => {
for (const resolved of [
resolveTerminalFont(SIDEBAR_PREFS_DEFAULTS, 'var-theme-font'),
resolveTerminalFont(SIDEBAR_PREFS_DEFAULTS, undefined),
resolveTerminalFont({ ...SIDEBAR_PREFS_DEFAULTS, terminalFontFamily: 'Menlo' }, undefined),
]) {
expect(resolved.fontFamily).toContain('"Symbols Nerd Font Mono"')
expect(resolved.fontFamily.endsWith('monospace')).toBe(true)
}
})
})
describe('withMonospaceFallback', () => {
it('appends a monospace tail when the stack names no generic family', () => {
expect(withMonospaceFallback('"Maple Mono NF CN"')).toBe('"Maple Mono NF CN", monospace')
expect(withMonospaceFallback('Menlo, Consolas')).toBe('Menlo, Consolas, monospace')
})
it('leaves a stack that already names a generic family untouched', () => {
expect(withMonospaceFallback('"JetBrains Mono", monospace')).toBe('"JetBrains Mono", monospace')
expect(withMonospaceFallback('ui-monospace, "SF Mono"')).toBe('ui-monospace, "SF Mono"')
// A deliberate non-monospace generic is the user's call, not ours to override.
expect(withMonospaceFallback('"Foo", sans-serif')).toBe('"Foo", sans-serif')
})
it('matches generic families case-insensitively and only when unquoted', () => {
expect(withMonospaceFallback('"Foo", MONOSPACE')).toBe('"Foo", MONOSPACE')
// A quoted name merely containing the word is a family, not a generic.
expect(withMonospaceFallback('"My monospace Font"')).toBe('"My monospace Font", monospace')
})
it('splits on top-level commas only, keeping quoted names and var() intact', () => {
expect(withMonospaceFallback('"Foo, Bar"')).toBe('"Foo, Bar", monospace')
expect(withMonospaceFallback('var(--code, Menlo)')).toBe('var(--code, Menlo), monospace')
expect(withMonospaceFallback("'Esc\\'aped, Name'")).toBe("'Esc\\'aped, Name', monospace")
})
it('drops the empty entries a stray comma produces', () => {
expect(withMonospaceFallback('"Foo",')).toBe('"Foo", monospace')
expect(withMonospaceFallback(' "Foo" ,, Menlo ')).toBe('"Foo", Menlo, monospace')
})
it('is idempotent', () => {
const once = withMonospaceFallback('"Maple Mono NF CN"')
expect(withMonospaceFallback(once)).toBe(once)
expect(withMonospaceFallback(DEFAULT_TERMINAL_FONT_FAMILY)).toBe(DEFAULT_TERMINAL_FONT_FAMILY)
})
it('falls back to the built-in stack for an empty value or a CSS-wide keyword', () => {
// Appending to a CSS-wide keyword yields invalid CSS the CSSOM drops
// wholesale, which would leave xterm with no font at all.
expect(withMonospaceFallback('')).toBe(DEFAULT_TERMINAL_FONT_FAMILY)
expect(withMonospaceFallback(' , ')).toBe(DEFAULT_TERMINAL_FONT_FAMILY)
expect(withMonospaceFallback('inherit')).toBe(DEFAULT_TERMINAL_FONT_FAMILY)
expect(withMonospaceFallback('REVERT-LAYER')).toBe(DEFAULT_TERMINAL_FONT_FAMILY)
// Only a lone keyword is one; as part of a stack it is just a family name.
expect(withMonospaceFallback('inherit, Menlo')).toBe('inherit, Menlo, monospace')
})
})
-287
View File
@@ -1,287 +0,0 @@
// @vitest-environment jsdom
/**
* Terminal URL hyperlink helpers: the regex that scopes xterm's
* `registerLinkProvider`, the per-line scanner that turns matches into
* buffer ranges, the modifier gate that keeps a plain click a
* text-selection gesture, and the scheme guard that routes only http(s)
* to `window.open`. Pure-module unit tests — no xterm mount.
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
TERMINAL_URL_REGEX,
findTerminalUrlsInLine,
buildTerminalLinks,
shouldActivateTerminalLink,
openTerminalUrl,
} from '../src/client/terminal-links.ts'
/** Reset the regex's lastIndex between tests (it carries the `g` flag). */
function reset(): void {
TERMINAL_URL_REGEX.lastIndex = 0
}
afterEach(() => {
reset()
vi.restoreAllMocks()
})
/** Build a fake MouseEvent with only the modifier fields the gate reads. */
function fakeEvent(mods: { ctrlKey?: boolean; metaKey?: boolean } = {}): MouseEvent {
return {
ctrlKey: mods.ctrlKey ?? false,
metaKey: mods.metaKey ?? false,
} as MouseEvent
}
describe('TERMINAL_URL_REGEX', () => {
it('matches a bare http(s) URL', () => {
expect('https://example.com/path?x=1#frag'.match(TERMINAL_URL_REGEX))
.toEqual(['https://example.com/path?x=1#frag'])
expect('http://localhost:3000/'.match(TERMINAL_URL_REGEX))
.toEqual(['http://localhost:3000/'])
})
it('does not match a scheme that is not http(s)', () => {
expect('file:///etc/passwd'.match(TERMINAL_URL_REGEX)).toBeNull()
expect('mailto:foo@bar.com'.match(TERMINAL_URL_REGEX)).toBeNull()
expect('ssh://host/path'.match(TERMINAL_URL_REGEX)).toBeNull()
expect('javascript:alert(1)'.match(TERMINAL_URL_REGEX)).toBeNull()
})
it('does not match a scheme glued to a word character (word-boundary guard)', () => {
// Regression guard: a tool printing `nothttps://example.com` should not
// surface a clickable link — the word boundary rejects the embedded scheme.
expect('nothttps://example.com'.match(TERMINAL_URL_REGEX)).toBeNull()
expect('xhttps://example.com'.match(TERMINAL_URL_REGEX)).toBeNull()
})
it('matches when preceded by a non-word character (quote, bracket, whitespace)', () => {
expect('"https://example.com"'.match(TERMINAL_URL_REGEX))
.toEqual(['https://example.com'])
expect('<https://example.com>'.match(TERMINAL_URL_REGEX))
.toEqual(['https://example.com'])
expect('[see https://example.com for more]'.match(TERMINAL_URL_REGEX))
.toEqual(['https://example.com'])
})
it('excludes trailing wrapping punctuation from the matched URL', () => {
// Shells commonly wrap URLs in quotes / angle brackets / parentheses;
// the closing wrapper must not become part of the link target. The
// character class itself rejects quotes, angle brackets, square and
// curly braces; round parens are kept (Wikipedia URLs carry real
// parens) and trimmed by `findTerminalUrlsInLine` instead (covered
// in its own describe block below).
expect('"https://example.com"'.match(TERMINAL_URL_REGEX)?.[0]).toBe('https://example.com')
expect('<https://example.com>'.match(TERMINAL_URL_REGEX)?.[0]).toBe('https://example.com')
expect('[https://example.com]'.match(TERMINAL_URL_REGEX)?.[0]).toBe('https://example.com')
expect('{https://example.com}'.match(TERMINAL_URL_REGEX)?.[0]).toBe('https://example.com')
expect('`https://example.com`'.match(TERMINAL_URL_REGEX)?.[0]).toBe('https://example.com')
})
it('stops at whitespace (a URL never contains a space)', () => {
expect('run https://example.com now'.match(TERMINAL_URL_REGEX))
.toEqual(['https://example.com'])
})
it('finds multiple URLs on the same line (global flag)', () => {
const matches = 'see https://a.com and http://b.com/path'.match(TERMINAL_URL_REGEX)
expect(matches).toEqual(['https://a.com', 'http://b.com/path'])
})
it('keeps the path, query and fragment intact', () => {
const url = 'https://example.com/a/b/c?d=1&e=2#section-3'
expect(url.match(TERMINAL_URL_REGEX)?.[0]).toBe(url)
})
it('does not match plain text without a scheme', () => {
expect('example.com'.match(TERMINAL_URL_REGEX)).toBeNull()
expect('see the docs at example.com/path'.match(TERMINAL_URL_REGEX)).toBeNull()
})
})
describe('findTerminalUrlsInLine', () => {
it('returns an empty array when the line has no URL', () => {
expect(findTerminalUrlsInLine('just some text')).toEqual([])
expect(findTerminalUrlsInLine('')).toEqual([])
expect(findTerminalUrlsInLine('file:///etc/passwd')).toEqual([])
})
it('returns the URL text and its 0-based start offset', () => {
expect(findTerminalUrlsInLine('see https://example.com now'))
.toEqual([{ start: 4, text: 'https://example.com' }])
expect(findTerminalUrlsInLine('https://example.com'))
.toEqual([{ start: 0, text: 'https://example.com' }])
})
it('returns every URL on the line in source order', () => {
expect(findTerminalUrlsInLine('https://a.com and http://b.com/path')).toEqual([
{ start: 0, text: 'https://a.com' },
{ start: 18, text: 'http://b.com/path' },
])
})
it('trims wrapping punctuation from the matched text', () => {
expect(findTerminalUrlsInLine('"https://example.com"')).toEqual([
{ start: 1, text: 'https://example.com' },
])
expect(findTerminalUrlsInLine('<https://example.com>')).toEqual([
{ start: 1, text: 'https://example.com' },
])
})
it('strips trailing closing parens not balanced by an opening paren', () => {
// Shell-wrapped URLs: `(https://example.com)` — the regex captures the
// trailing `)` (round parens are kept so Wikipedia-style URLs work),
// and findTerminalUrlsInLine trims the unmatched excess.
expect(findTerminalUrlsInLine('(https://example.com)')).toEqual([
{ start: 1, text: 'https://example.com' },
])
expect(findTerminalUrlsInLine('see (https://example.com) here')).toEqual([
{ start: 5, text: 'https://example.com' },
])
})
it('keeps balanced parens inside Wikipedia-style URLs intact', () => {
const url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
expect(findTerminalUrlsInLine(`see ${url}`)).toEqual([{ start: 4, text: url }])
// Trailing balanced closer is part of the URL, not a wrapper.
expect(findTerminalUrlsInLine(url)).toEqual([{ start: 0, text: url }])
})
it('strips only the unmatched excess when the URL has both its own parens and a wrapper closer', () => {
// URL has 1 opening and 1 closing paren of its own, plus a wrapper
// closing paren: `https://en.wikipedia.org/wiki/Foo_(bar))`
// → opens=1, closers=2, excess=1 → strip one trailing `)`.
expect(findTerminalUrlsInLine('https://en.wikipedia.org/wiki/Foo_(bar))')).toEqual([
{ start: 0, text: 'https://en.wikipedia.org/wiki/Foo_(bar)' },
])
})
it('does not carry lastIndex state across calls (the g flag is module-shared)', () => {
// First call leaves lastIndex set; a second call on a different line
// must still scan from the start.
findTerminalUrlsInLine('https://a.com')
expect(findTerminalUrlsInLine('https://b.com')).toEqual([
{ start: 0, text: 'https://b.com' },
])
// And a third call after a partial match must also reset cleanly.
TERMINAL_URL_REGEX.exec('https://c.com') // leaves lastIndex past the match
expect(findTerminalUrlsInLine('https://d.com')).toEqual([
{ start: 0, text: 'https://d.com' },
])
})
})
describe('buildTerminalLinks', () => {
it('returns an empty array when the line has no URL', () => {
expect(buildTerminalLinks('plain text', 5)).toEqual([])
expect(buildTerminalLinks('', 0)).toEqual([])
})
it('builds a descriptor with xterm 1-based x coords and inclusive end', () => {
// Line: "see https://example.com now"
// 0123456789...
// URL starts at 0-based index 4, length 19 ('https://example.com').
// xterm x is 1-based: start cell = 4+1 = 5, last cell = 4+19 = 23.
expect(buildTerminalLinks('see https://example.com now', 7)).toEqual([
{
range: { start: { x: 5, y: 7 }, end: { x: 23, y: 7 } },
text: 'https://example.com',
},
])
})
it('places a URL at the start of the line at x=1', () => {
expect(buildTerminalLinks('https://example.com', 3)).toEqual([
{
range: { start: { x: 1, y: 3 }, end: { x: 19, y: 3 } },
text: 'https://example.com',
},
])
})
it('uses the buffer line number passed in as the range y', () => {
const links = buildTerminalLinks('https://example.com', 42)
expect(links[0]?.range.start.y).toBe(42)
expect(links[0]?.range.end.y).toBe(42)
})
it('builds one descriptor per URL on a multi-URL line, in source order', () => {
const links = buildTerminalLinks('https://a.com http://b.com', 1)
expect(links).toHaveLength(2)
expect(links[0]?.text).toBe('https://a.com')
expect(links[1]?.text).toBe('http://b.com')
// Non-overlapping ranges, in order.
expect(links[0]!.range.end.x).toBeLessThan(links[1]!.range.start.x)
})
})
describe('shouldActivateTerminalLink', () => {
it('returns false for a plain click (no modifier)', () => {
expect(shouldActivateTerminalLink(fakeEvent())).toBe(false)
})
it('returns true when Ctrl is held (Win/Linux convention)', () => {
expect(shouldActivateTerminalLink(fakeEvent({ ctrlKey: true }))).toBe(true)
})
it('returns true when Cmd is held (mac convention)', () => {
expect(shouldActivateTerminalLink(fakeEvent({ metaKey: true }))).toBe(true)
})
it('returns true when both modifiers are held (defensive — some remotes send both)', () => {
expect(shouldActivateTerminalLink(fakeEvent({ ctrlKey: true, metaKey: true }))).toBe(true)
})
it('returns false when only Shift / Alt are held (those are not open modifiers)', () => {
expect(shouldActivateTerminalLink(fakeEvent())).toBe(false)
// Construct with shiftKey/altKey only; the gate ignores them.
const event = { ctrlKey: false, metaKey: false, shiftKey: true, altKey: true } as MouseEvent
expect(shouldActivateTerminalLink(event)).toBe(false)
})
})
describe('openTerminalUrl', () => {
it('opens an http URL in a new tab with noopener,noreferrer', () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null)
expect(openTerminalUrl('http://example.com')).toBe(true)
expect(open).toHaveBeenCalledWith('http://example.com/', '_blank', 'noopener,noreferrer')
})
it('opens an https URL', () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null)
expect(openTerminalUrl('https://example.com/path?x=1')).toBe(true)
expect(open).toHaveBeenCalledWith(
'https://example.com/path?x=1',
'_blank',
'noopener,noreferrer',
)
})
it('rejects file:// (printed by tools, never handed to window.open)', () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null)
expect(openTerminalUrl('file:///etc/passwd')).toBe(false)
expect(open).not.toHaveBeenCalled()
})
it('rejects mailto:', () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null)
expect(openTerminalUrl('mailto:foo@bar.com')).toBe(false)
expect(open).not.toHaveBeenCalled()
})
it('rejects javascript: (defense-in-depth even though the regex skips it)', () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null)
expect(openTerminalUrl('javascript:alert(1)')).toBe(false)
expect(open).not.toHaveBeenCalled()
})
it('rejects a malformed URL string without throwing', () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null)
expect(openTerminalUrl('https://')).toBe(false)
expect(openTerminalUrl('not a url at all')).toBe(false)
expect(openTerminalUrl('')).toBe(false)
expect(open).not.toHaveBeenCalled()
})
})
-60
View File
@@ -1,60 +0,0 @@
/**
* TerminalWaitBanner unit tests: localized text with the needle, the skip
* button wiring, and the long-needle display cap (full text stays on the
* title attribute). The component imports no xterm — renderable in plain
* jsdom (the repo's jsdom pattern, see bottom-auto-terminal.spec.tsx head).
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
import { TerminalWaitBanner } from '../src/client/TerminalWaitBanner.tsx'
describe('TerminalWaitBanner', () => {
const mounted: Array<{ root: Root; container: HTMLDivElement }> = []
function mount(needle: string, onSkip: () => void): HTMLDivElement {
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
act(() => { root.render(createElement(TerminalWaitBanner, { needle, onSkip })) })
mounted.push({ root, container })
return container
}
afterEach(() => {
for (const { root, container } of mounted.splice(0)) {
act(() => { root.unmount() })
container.remove()
}
})
it('shows the localized waiting text with the needle and a working skip button', () => {
let skipped = 0
const container = mount('BUILD_OK', () => { skipped += 1 })
// jsdom navigator.language is en-US → the en dictionary applies.
expect(container.textContent).toContain('Agent is waiting for')
expect(container.textContent).toContain('BUILD_OK')
expect(container.textContent).toContain('Skip wait')
const button = container.querySelector('button')
expect(button).not.toBeNull()
act(() => { button!.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(skipped).toBe(1)
})
it('truncates a long needle for display but keeps the full text on the title', () => {
const long = 'X'.repeat(200)
const container = mount(long, () => {})
const span = container.querySelector('span[title]')
expect(span).not.toBeNull()
expect(span!.getAttribute('title')).toBe(long)
// The needle's inline contribution is capped (NEEDLE_DISPLAY_CAP): at
// most 80 X's are rendered — the full 200-char run only rides the title
// tooltip. The localized sentence around the needle is not measured;
// its length varies per language, so counting the needle's own chars is
// the language-agnostic form of the display-cap assertion.
expect((span!.textContent?.match(/X/g) ?? []).length).toBeLessThanOrEqual(80)
})
})
+23
View File
@@ -121,6 +121,29 @@ describe('skin contract: the plugin owns no color of its own', () => {
}
})
it('the empty-pane welcome capsule follows the host guide recipe', () => {
// The card is the same surface as DSH's own guide capsule ("pick what
// opens here"), so this pins the shared geometry and the token-only
// paint. A literal here would drift away from the host under every skin.
const styles = readFileSync(resolve(ROOT, 'src/client/sidebar.module.css'), 'utf8')
const block = /\.paneCard \{([\s\S]*?)\n\}/.exec(styles)?.[1]
expect(block, 'the .paneCard rule must exist').toBeDefined()
expect(block!).toContain('border: 0.5px solid var(--dsw-alias-border-l4)')
expect(block!).toContain('border-radius: 24px')
expect(block!).toContain('background: var(--dsw-alias-bg-layer-1)')
expect(block!).toContain('min-height: 56px')
expect(block!).toContain('padding: 14px 20px')
// No paint of its own: every color-ish declaration resolves to a token,
// and the upstream-only spellings this repo must not copy are absent.
for (const declaration of block!.matchAll(/(?:^|\n)\s*(?:background|border|color|font):\s*([^;]+);/g)) {
const value = declaration[1]
if (!/var\(--dsw-/.test(value)) continue
expect(value, declaration[0]).toContain('var(--dsw-')
}
expect(block!).not.toContain('--dsw-alias-bg-l1')
expect(block!).not.toContain('--dsw-alias-bg-l2')
})
it('no icon dataset is shipped as a lazy chunk', () => {
const chunkDir = resolve(ROOT, 'src/client/chunks')
const chunks = readdirSync(chunkDir).filter(name => /\.tsx?$/.test(name))
-250
View File
@@ -1,250 +0,0 @@
/**
* Tool-layer tests for the eight agent-terminal tools: registration shape,
* the combined disposer, canonical-output contract (validated against each
* tool's declared output schema exactly like the registry's
* `createSuccessResult` does), per-session ownership, and the UTF-8
* truncation boundary. The pty registry is stubbed (no real spawn): the
* wiring of the tools themselves is the subject here — pty behavior is
* covered by agent-pty.spec.ts.
*/
import { describe, expect, it } from 'vitest'
import { validateJsonSchemaValue, type ToolDefinition, type ToolRunContext } from '@deepseek-ai/dsh-tools'
import { boundBytes, registerTools } from '../src/tools.ts'
import type { AgentPtyRegistry } from '../src/agent-pty.ts'
import type { Context } from '../src/context-types.ts'
/** One registration captured by the fake tools service. */
interface CapturedTool {
definition: ToolDefinition
}
/** Stub registry: uuid-keyed rows without a real pty. */
class FakeRegistry {
readonly terminals = new Map<string, { sessionId: string; title: string; command: string; exited: boolean }>()
/** When set, waitFor resolves with the skipped shape instead of the found default. */
nextWaitResult: { kind: 'skipped' } | undefined = undefined
create(sessionId: string, title: string, command: string): string {
const uuid = `uuid-${this.terminals.size + 1}`
this.terminals.set(uuid, { sessionId, title, command, exited: false })
return uuid
}
list(sessionId: string): Array<{ uuid: string; title: string; command: string; exited: boolean }> {
return [...this.terminals.entries()]
.filter(([, row]) => row.sessionId === sessionId)
.map(([uuid, row]) => ({ uuid, title: row.title, command: row.command, exited: row.exited }))
}
assertOwned(uuid: string, sessionId: string): void {
const row = this.terminals.get(uuid)
if (row === undefined || row.sessionId !== sessionId) {
throw new Error(`agent terminal "${uuid}" not found`)
}
}
send(): void {}
read(): { text: string; totalLines: number; lineBegin: number; lineEnd: number } {
// A page larger than the tool's 256 KiB read cap, to exercise boundBytes.
return { text: 'x'.repeat(300 * 1024), totalLines: 1, lineBegin: 0, lineEnd: 1 }
}
resize(_uuid: string, cols: number, rows: number): { cols: number; rows: number } {
return { cols, rows }
}
signal(): void {}
close(): boolean {
return true
}
waitFor(_uuid: string, needle: string): Promise<
{ kind: 'found'; needle: string; line: number; column: number; match: string; elapsedMs: number }
| { kind: 'skipped'; needle: string }
> {
// Mirrors the registry's empty-needle rejection (the tool layer no
// longer duplicates this check).
if (needle === '') return Promise.reject(new Error('needle must be a non-empty string'))
if (this.nextWaitResult !== undefined) return Promise.resolve({ kind: 'skipped', needle })
return Promise.resolve({ kind: 'found', needle, line: 0, column: 0, match: needle, elapsedMs: 1 })
}
}
/** A minimal ToolRunContext for one calling session (only the slices the tools touch). */
function exec(sessionId: string): ToolRunContext {
return {
signal: { throwIfAborted: () => {}, aborted: false },
agent: { session: { id: sessionId } },
} as unknown as ToolRunContext
}
/** Register the eight tools against a fake service; the tools bind to `registry`. */
function mount(): { captured: CapturedTool[]; registry: FakeRegistry; dispose: () => number } {
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 FakeRegistry()
const dispose = registerTools(ctx, registry as unknown as AgentPtyRegistry, async () => '/cwd', () => ({}))
return { captured, registry, 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('agent terminal tools', () => {
it('registers all eight tools and the combined disposer unregisters them all', () => {
const { captured, dispose } = mount()
expect(captured.map(candidate => candidate.definition.name)).toEqual([
'terminal_create',
'terminal_list',
'terminal_send',
'terminal_read',
'terminal_wait_for',
'terminal_resize',
'terminal_signal',
'terminal_close',
])
expect(dispose()).toBe(8)
// Disposing twice must not throw (each registry disposer is idempotent).
expect(() => mount().dispose()).not.toThrow()
})
it('terminal_create returns the uuid and echoed title (schema-valid)', async () => {
const { captured, registry } = mount()
const tool = toolOf(captured, 'terminal_create')
const value = await tool.execute({ title: 'dev server', command: 'npm run dev' }, exec('s1'))
expect(value).toMatchObject({ title: 'dev server' })
expect(typeof (value as { uuid: unknown }).uuid).toBe('string')
expect(registry.terminals.size).toBe(1)
expect(validateJsonSchemaValue(tool.output.schema, value, 'value')).toEqual([])
})
it('terminal_list output matches the declared schema — no sessionId leaks', async () => {
const { captured, registry } = mount()
const tool = toolOf(captured, 'terminal_list')
const uuid = registry.create('s1', 'dev server', 'npm run dev')
registry.create('s2', 'other session', 'top secret')
const value = await tool.execute({}, exec('s1'))
const list = value as Array<Record<string, unknown>>
expect(list).toHaveLength(1)
expect(list[0]!.uuid).toBe(uuid)
// The session id is registry-internal ownership, never serialized.
expect('sessionId' in list[0]!).toBe(false)
// And the whole value validates against the declared output schema —
// this is the contract the registry enforces at runtime (additionalProperties: false).
expect(validateJsonSchemaValue(tool.output.schema, value, 'value')).toEqual([])
})
it('rejects a uuid owned by another session (send/read/resize/signal/close/wait_for)', async () => {
const { captured, registry } = mount()
const mine = registry.create('s1', 'mine', '')
const foreign = registry.create('s2', 'theirs', '')
for (const name of ['terminal_send', 'terminal_read', 'terminal_resize', 'terminal_signal', 'terminal_close', 'terminal_wait_for']) {
const tool = toolOf(captured, name)
const args = name === 'terminal_send' ? { uuid: foreign, text: 'ls' }
: name === 'terminal_read' ? { uuid: foreign }
: name === 'terminal_resize' ? { uuid: foreign, cols: 80, rows: 24 }
: name === 'terminal_signal' ? { uuid: foreign, signal: 'SIGINT' }
: name === 'terminal_close' ? { uuid: foreign }
: { uuid: foreign, needle: 'x', timeout_ms: 100 }
// A foreign uuid is indistinguishable from an unknown one.
await expect(tool.execute(args, exec('s1'))).rejects.toThrow(/not found/)
}
// Own-session uuids still work.
const sendTool = toolOf(captured, 'terminal_send')
await expect(sendTool.execute({ uuid: mine, text: 'ls' }, exec('s1'))).resolves.toBeDefined()
const closeTool = toolOf(captured, 'terminal_close')
await expect(closeTool.execute({ uuid: mine }, exec('s1'))).resolves.toMatchObject({ closed: true })
})
it('terminal_read truncates at the byte cap and reports it (schema-valid)', async () => {
const { captured, registry } = mount()
const tool = toolOf(captured, 'terminal_read')
const uuid = registry.create('s1', 'reader', '')
const value = await tool.execute({ uuid }, exec('s1'))
const result = value as { text: string; truncated: boolean }
expect(result.truncated).toBe(true)
expect(Buffer.byteLength(result.text, 'utf8')).toBeLessThanOrEqual(256 * 1024)
expect(validateJsonSchemaValue(tool.output.schema, value, 'value')).toEqual([])
})
it('terminal_resize echoes the registry-applied dimensions (schema-valid)', async () => {
const { captured, registry } = mount()
const tool = toolOf(captured, 'terminal_resize')
const uuid = registry.create('s1', 'resizer', '')
const value = await tool.execute({ uuid, cols: 120, rows: 40 }, exec('s1'))
expect(value).toEqual({ uuid, cols: 120, rows: 40 })
expect(validateJsonSchemaValue(tool.output.schema, value, 'value')).toEqual([])
})
it('terminal_wait_for returns the registry result in camelCase (schema-valid, no projection)', async () => {
const { captured, registry } = mount()
const tool = toolOf(captured, 'terminal_wait_for')
const uuid = registry.create('s1', 'waiter', '')
const value = await tool.execute({ uuid, needle: 'done' }, exec('s1'))
expect(value).toEqual({ kind: 'found', needle: 'done', line: 0, column: 0, match: 'done', elapsedMs: 1 })
expect(validateJsonSchemaValue(tool.output.schema, value, 'value')).toEqual([])
})
it('terminal_wait_for returns skipped (schema-valid) when the registry reports a user skip', async () => {
const { captured, registry } = mount()
const tool = toolOf(captured, 'terminal_wait_for')
// Use the uuid the registry actually minted — no coupling to its id scheme.
const uuid = registry.create('s1', 'skipper', '')
registry.nextWaitResult = { kind: 'skipped' }
const value = await tool.execute({ uuid, needle: 'BUILD_OK', timeout_ms: 1000 }, exec('s1'))
expect(value).toEqual({ kind: 'skipped', needle: 'BUILD_OK' })
expect(validateJsonSchemaValue(tool.output.schema, value, 'value')).toEqual([])
})
it('terminal_wait_for render describes the user skip and the needle', () => {
const { captured } = mount()
const tool = toolOf(captured, 'terminal_wait_for')
const blocks = tool.output.render({}, { kind: 'skipped', needle: 'BUILD_OK' }) as Array<{ type: string; text: string }>
expect(blocks[0]!.type).toBe('text')
expect(blocks[0]!.text).toContain('Skipped by user')
expect(blocks[0]!.text).toContain('BUILD_OK')
})
it('terminal_wait_for rejects an empty needle through the registry (no duplicate check)', async () => {
const { captured, registry } = mount()
const tool = toolOf(captured, 'terminal_wait_for')
const uuid = registry.create('s1', 'waiter', '')
await expect(tool.execute({ uuid, needle: '' }, exec('s1'))).rejects.toThrow(/non-empty/)
})
})
describe('boundBytes', () => {
it('never splits a multi-byte UTF-8 sequence at the cap', () => {
// '€' is 3 bytes (E2 82 AC); the cap must retreat to a sequence boundary.
expect(boundBytes('a€b', 2)).toEqual({ text: 'a', truncated: true })
expect(boundBytes('a€b', 3)).toEqual({ text: 'a', truncated: true })
expect(boundBytes('a€b', 4)).toEqual({ text: 'a€', truncated: true })
expect(boundBytes('a€b', 5)).toEqual({ text: 'a€b', truncated: false })
expect(boundBytes('€', 1)).toEqual({ text: '', truncated: true })
// ASCII pages truncate at the byte cap directly.
expect(boundBytes('hello', 3)).toEqual({ text: 'hel', truncated: true })
})
it('every retained prefix decodes without U+FFFD', () => {
for (let n = 1; n <= 18; n += 1) {
const { text } = boundBytes('中文字符串测试 123', n)
expect(text.includes('\uFFFD')).toBe(false)
expect(Buffer.byteLength(text, 'utf8')).toBeLessThanOrEqual(n)
}
})
})