fix: 修复 agent 终端工具审查问题(terminal_list 输出契约、跨会话归属、UTF-8 截断边界等),工具注入改为设置面板开关(默认关闭)

This commit is contained in:
Menghuan1918
2026-08-10 21:43:58 +08:00
parent 6f62d19905
commit 8edfbfde44
17 changed files with 581 additions and 130 deletions
+36 -1
View File
@@ -95,7 +95,6 @@ describe('AgentPtyRegistry', () => {
expect(page.totalLines).toBeGreaterThan(0)
expect(page.text).toContain('line1')
expect(page.text).toContain('line3')
expect(page.truncated).toBe(false)
// Negative offset reads from the end.
const tail = registry.read(uuid, -2)
expect(tail.lineBegin).toBeGreaterThanOrEqual(0)
@@ -115,6 +114,38 @@ describe('AgentPtyRegistry', () => {
}
})
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 {
@@ -182,6 +213,10 @@ describe('AgentPtyRegistry', () => {
// 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()
}
+4 -1
View File
@@ -45,12 +45,15 @@ describe('dsh-better-sidebar plugin export shape', () => {
expect(resolved.openByDefault).toBe(true)
expect(resolved.defaultWidthPercent).toBe(30)
expect(resolved.autoOpenSubagent).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)
// A stored overridden value resolves through (the range contract is
// enforced by the settings service on write); the new pref keeps its
// default when the stored document predates it.
const overridden = (PrefsSchema as unknown as {
(input: Record<string, unknown> | undefined): Record<string, unknown>
})({ openByDefault: false, defaultWidthPercent: 45 })
expect(overridden).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true })
expect(overridden).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, agentTerminalTools: false })
})
})
+61 -3
View File
@@ -255,8 +255,7 @@ describe('session cwd resolution over the API route', () => {
describe('side card settings routes', () => {
/** A minimal settings seam: register/describe/update with the revision guard. */
const createFakeSettings = () => {
const namespaces = new Map<string, {
const createFakeSettings = () => { const namespaces = new Map<string, {
schema: unknown
value: Record<string, unknown> | undefined
revision: number
@@ -343,7 +342,7 @@ describe('side card settings routes', () => {
const read = await invoke(route, 'settings.get', {})
expect(read.ok).toBe(true)
expect(read.value).toEqual({
value: { openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true },
value: { openByDefault: true, defaultWidthPercent: 30, autoOpenSubagent: true, agentTerminalTools: false },
revision: 0,
})
@@ -375,3 +374,62 @@ describe('side card settings routes', () => {
expect(result.error?.message).toMatch(/plain object/)
})
})
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 = {
loader: { entries: () => [] },
httpServer: {
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 () => {}
},
}
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)
})
})
+223
View File
@@ -0,0 +1,223 @@
/**
* 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 }>()
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; elapsedMs: number }> {
// 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'))
return Promise.resolve({ kind: 'found', needle, line: 0, column: 0, 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, () => '/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, elapsedMs: 1 })
expect(validateJsonSchemaValue(tool.output.schema, value, 'value')).toEqual([])
})
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)
}
})
})
+15 -8
View File
@@ -602,29 +602,36 @@ describe('side card preferences', () => {
})
it('parses a valid value and clamps the percent into the contract range', async () => {
expect(await loadPrefs(wire({ openByDefault: false, defaultWidthPercent: 80, autoOpenSubagent: false })))
.toEqual({ openByDefault: false, defaultWidthPercent: 60, autoOpenSubagent: false })
expect(await loadPrefs(wire({ openByDefault: false, defaultWidthPercent: 80, autoOpenSubagent: false, agentTerminalTools: true })))
.toEqual({ openByDefault: false, defaultWidthPercent: 60, autoOpenSubagent: false, agentTerminalTools: true })
})
it('falls back per-field when a stored field is malformed', async () => {
expect(await loadPrefs(wire({ openByDefault: 'yes', defaultWidthPercent: 33, autoOpenSubagent: 'no' })))
.toEqual({ openByDefault: true, defaultWidthPercent: 33, autoOpenSubagent: true })
expect(await loadPrefs(wire({ openByDefault: 'yes', defaultWidthPercent: 33, autoOpenSubagent: 'no', agentTerminalTools: 'yes' })))
.toEqual({ openByDefault: true, defaultWidthPercent: 33, autoOpenSubagent: true, agentTerminalTools: false })
})
it('defaults autoOpenSubagent to true when the stored value is absent or malformed', async () => {
it('defaults autoOpenSubagent to true and agentTerminalTools to false when the stored value is absent or malformed', async () => {
expect(await loadPrefs(wire({ openByDefault: false, defaultWidthPercent: 40 })))
.toEqual({ openByDefault: false, defaultWidthPercent: 40, autoOpenSubagent: true })
.toEqual({ openByDefault: false, defaultWidthPercent: 40, autoOpenSubagent: true, agentTerminalTools: false })
expect((await loadPrefs(wire({ openByDefault: true, defaultWidthPercent: 40, autoOpenSubagent: 1 }))).autoOpenSubagent)
.toBe(true)
// The terminal-tools feature is OFF by default; only an explicit true turns it on.
expect((await loadPrefs(wire({ openByDefault: true, defaultWidthPercent: 40 }))).agentTerminalTools)
.toBe(false)
expect((await loadPrefs(wire({ openByDefault: true, defaultWidthPercent: 40, agentTerminalTools: 1 }))).agentTerminalTools)
.toBe(false)
expect((await loadPrefs(wire({ openByDefault: true, defaultWidthPercent: 40, agentTerminalTools: true }))).agentTerminalTools)
.toBe(true)
})
it('seeds new-session defaults from the store prefs (open flag + width)', () => {
const store = createSidebarStore()
// Node environment: no window → the width falls back to PANEL_DEFAULT,
// while the open flag still follows the preference.
store.setPrefs({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true })
store.setPrefs({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, agentTerminalTools: false })
store.setSession('fresh-session')
expect(store.getPrefs()).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true })
expect(store.getPrefs()).toEqual({ openByDefault: false, defaultWidthPercent: 45, autoOpenSubagent: true, agentTerminalTools: false })
const snapshot = store.getSnapshot()
expect(snapshot.sessionId).toBe('fresh-session')
expect(snapshot.state?.panelOpen).toBe(false)