chore: v0.8.0 — 任务管理页(子代理拓扑 + 后台命令底部输出 Dock、两击确认终止)
- tab 更名为任务管理:同页显示当前树全部后台命令(bash/pwsh 徽标、状态、时长、属主、退出码) - 点击任务行在侧边栏底部共享 Dock 显示输出(sticky 终端式、自动跟随、单一轮询实例) - 运行中任务两击确认强制终止;大量任务时列表保持紧凑、排序变动不跳动 - 新增 /sidebar/api tasks.output(非消费 peek,不偷模型 task_output 字节)与 tasks.kill 路由 - 修复任务镜像清空时的 React #300 hook 顺序崩溃(useCallback 移到提前 return 之前)+ 回归测试
This commit is contained in:
1 parent
27bc49830e
commit
8c521be26e
18 files changed
+1568
-72
No files matched your search
@@ -27,6 +27,8 @@ interface FakeContext {
|
||||
/** The settings service never appears in the smoke context: the inject
|
||||
* callback must never run (mirror of cordis' service-less inject). */
|
||||
inject: (deps: readonly string[], callback: (sctx: never) => void) => () => void
|
||||
/** Optional services (tasks/agents) are read lazily; absent → undefined. */
|
||||
get: (key: string) => undefined
|
||||
}
|
||||
|
||||
describe('host plugin smoke', () => {
|
||||
@@ -56,6 +58,8 @@ describe('host plugin smoke', () => {
|
||||
// No settings service in the smoke context: the registration callback
|
||||
// never runs (cordis' service-less inject behaves the same).
|
||||
inject: () => () => {},
|
||||
// No tasks/agents services: the tasks routes degrade to a 503.
|
||||
get: () => undefined,
|
||||
}
|
||||
apply(ctx as never)
|
||||
expect(routes.map(route => route.path)).toEqual(['/sidebar/api', '/sidebar/bundle', '/sidebar/file', '/sidebar/html'])
|
||||
@@ -315,6 +319,8 @@ describe('session cwd resolution over the API route', () => {
|
||||
effect: (fn: () => void | (() => void)) => { fn() },
|
||||
// No settings service: the namespace registration never runs.
|
||||
inject: () => () => {},
|
||||
// No tasks/agents services in the smoke context: the routes degrade.
|
||||
get: () => undefined,
|
||||
}
|
||||
apply(ctx as never)
|
||||
return routes.find(route => route.path === '/sidebar/api')!
|
||||
@@ -464,6 +470,8 @@ describe('side card settings routes', () => {
|
||||
if (deps.includes('settings') && settings !== undefined) callback({ settings })
|
||||
return () => {}
|
||||
},
|
||||
// No tasks/agents services: the tasks routes degrade to a 503.
|
||||
get: () => undefined,
|
||||
}
|
||||
apply(ctx as never)
|
||||
return routes.find(route => route.path === '/sidebar/api')!
|
||||
@@ -647,6 +655,8 @@ describe('agent terminal tool gating', () => {
|
||||
if (deps.includes('settings')) callback({ settings })
|
||||
return () => {}
|
||||
},
|
||||
// No tasks/agents services: the tasks routes degrade to a 503.
|
||||
get: () => undefined,
|
||||
}
|
||||
apply(ctx as never)
|
||||
// Default off: no tools are registered even though the settings service is mounted.
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Subagent page tests for the background-task section: rows render from the
|
||||
* `tasksBySession` mirror, clicking a row peeks its output through
|
||||
* `tasks.output` with the OWNER session scope, the kill button needs a
|
||||
* two-click confirm, settled rows offer no kill, and the output panel never
|
||||
* polls while the page is hidden.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement, type ReactNode } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { SubagentView } from '../src/client/SubagentView.tsx'
|
||||
import type { Context, SidebarSessionList } from '../src/context-types.ts'
|
||||
|
||||
/** A subscribable sessions-list snapshot (mirror of the runtime list feed). */
|
||||
function makeStore(initial: SidebarSessionList) {
|
||||
let snapshot = initial
|
||||
const listeners = new Set<() => void>()
|
||||
return {
|
||||
getSnapshot: () => snapshot,
|
||||
subscribe: (fn: () => void) => {
|
||||
listeners.add(fn)
|
||||
return () => { listeners.delete(fn) }
|
||||
},
|
||||
set(next: SidebarSessionList) {
|
||||
snapshot = next
|
||||
for (const fn of [...listeners]) fn()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type Store = ReturnType<typeof makeStore>
|
||||
|
||||
/** The client context face SubagentView touches (history stub; everything else inert). */
|
||||
function makeCtx(store: Store): Context {
|
||||
return {
|
||||
sessions: {
|
||||
list: store,
|
||||
setSubagentCatalogOpen: () => {},
|
||||
openSubagent: () => {},
|
||||
open: () => {},
|
||||
refreshSubagents: async () => {},
|
||||
},
|
||||
connection: {
|
||||
api: {
|
||||
subagents: {
|
||||
history: async () => ({ result: { ok: true, value: { events: [], hasMore: false } } }),
|
||||
},
|
||||
},
|
||||
},
|
||||
} as unknown as Context
|
||||
}
|
||||
|
||||
/** Render `node` into a detached body container under React's act(). */
|
||||
function mount(node: ReactNode): { container: HTMLDivElement; unmount: () => void } {
|
||||
const container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
const root: Root = createRoot(container)
|
||||
act(() => { root.render(node) })
|
||||
const unmount = (): void => {
|
||||
act(() => { root.unmount() })
|
||||
container.remove()
|
||||
}
|
||||
return { container, unmount }
|
||||
}
|
||||
|
||||
const outputCalls: Array<{ sessionId: string; id: string }> = []
|
||||
const killCalls: Array<{ sessionId: string; id: string }> = []
|
||||
|
||||
function jsonResponse(value: unknown): Response {
|
||||
return { ok: true, status: 200, json: async () => value } as unknown as Response
|
||||
}
|
||||
|
||||
function baseSnapshot(): SidebarSessionList {
|
||||
return {
|
||||
current: 'root',
|
||||
byId: {
|
||||
root: { id: 'root', displayTitle: '主会话', running: true },
|
||||
child: { id: 'child', displayTitle: '子代理', origin: 'subagent', parentId: 'root', running: true },
|
||||
},
|
||||
subagentsByParent: {},
|
||||
tasksBySession: {
|
||||
root: [
|
||||
{ id: 'bash-1', kind: 'bash', label: 'sleep 300', status: 'running', startedAt: 1_000 },
|
||||
],
|
||||
child: [
|
||||
{ id: 'bash-2', kind: 'bash', label: 'echo hi', status: 'completed', startedAt: 2_000, finishedAt: 3_000 },
|
||||
],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
outputCalls.length = 0
|
||||
killCalls.length = 0
|
||||
vi.stubGlobal('fetch', async (url: string | URL | Request, init?: RequestInit) => {
|
||||
const method = String(url).split('/').pop()
|
||||
const body = JSON.parse(String(init?.body)) as { sessionId: string; id: string }
|
||||
if (method === 'tasks.output') {
|
||||
outputCalls.push({ sessionId: body.sessionId, id: body.id })
|
||||
return jsonResponse({ ok: true, value: { text: `output-of-${body.id}`, truncated: false, status: 'running' } })
|
||||
}
|
||||
if (method === 'tasks.kill') {
|
||||
killCalls.push({ sessionId: body.sessionId, id: body.id })
|
||||
return jsonResponse({ ok: true, value: { ok: true, outcome: 'requested' } })
|
||||
}
|
||||
throw new Error(`unexpected fetch ${String(url)}`)
|
||||
})
|
||||
Object.defineProperty(globalThis.navigator, 'language', { value: 'zh-CN', configurable: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
for (const el of document.querySelectorAll('body > div')) el.remove()
|
||||
})
|
||||
|
||||
describe('SubagentView background tasks', () => {
|
||||
it('renders the tree tasks with status, durations, and owner labels', () => {
|
||||
const store = makeStore(baseSnapshot())
|
||||
const { container, unmount } = mount(
|
||||
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
|
||||
)
|
||||
const text = container.textContent ?? ''
|
||||
expect(text).toContain('后台命令')
|
||||
expect(text).toContain('2 个后台命令 · 1 运行中')
|
||||
// Both rows of the whole tree, owner-labeled (the tree spans two sessions).
|
||||
expect(text).toContain('sleep 300')
|
||||
expect(text).toContain('echo hi')
|
||||
expect(text).toContain('主会话')
|
||||
expect(text).toContain('子代理')
|
||||
// Only the running row offers a kill button.
|
||||
expect(container.querySelectorAll('button[aria-label="终止"]')).toHaveLength(1)
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('renders nothing task-related when the mirror is empty', () => {
|
||||
const store = makeStore({ current: 'root', byId: { root: { id: 'root', displayTitle: '主会话' } }, subagentsByParent: {}, tasksBySession: {} })
|
||||
const { container, unmount } = mount(
|
||||
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
|
||||
)
|
||||
expect(container.textContent).not.toContain('后台命令')
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('survives the mirror emptying while mounted (hook-order regression #300)', async () => {
|
||||
const store = makeStore(baseSnapshot())
|
||||
const { container, unmount } = mount(
|
||||
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
|
||||
)
|
||||
expect(container.textContent).toContain('sleep 300')
|
||||
// The mirror empties (all tasks settled and dropped): the section must
|
||||
// vanish WITHOUT reordering hooks — a hook below the empty-state return
|
||||
// would crash React with "Rendered fewer hooks than expected" (the
|
||||
// minified #300 the sidebar boundary surfaces with a retry button).
|
||||
await act(async () => { store.set({ ...baseSnapshot(), tasksBySession: {} }) })
|
||||
expect(container.textContent).not.toContain('后台命令')
|
||||
// And returning tasks must work too, with the same hook order.
|
||||
await act(async () => { store.set(baseSnapshot()) })
|
||||
expect(container.textContent).toContain('sleep 300')
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('shows the selected task output in the bottom dock, closeable', async () => {
|
||||
const store = makeStore(baseSnapshot())
|
||||
const { container, unmount } = mount(
|
||||
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
|
||||
)
|
||||
const row = container.querySelector('button[aria-label*="sleep 300"]') as HTMLButtonElement
|
||||
await act(async () => { row.click() })
|
||||
// The peek request carries the OWNER session (the fence compares it).
|
||||
expect(outputCalls).toEqual([{ sessionId: 'root', id: 'bash-1' }])
|
||||
expect(container.textContent).toContain('output-of-bash-1')
|
||||
// Exactly one dock region exists (never one per row).
|
||||
expect(container.querySelectorAll('[role="region"]')).toHaveLength(1)
|
||||
// The selected row is marked, and the close button dismisses the dock.
|
||||
expect(row.getAttribute('aria-pressed')).toBe('true')
|
||||
const close = container.querySelector('button[aria-label="关闭"]') as HTMLButtonElement
|
||||
await act(async () => { close.click() })
|
||||
expect(container.textContent).not.toContain('output-of-bash-1')
|
||||
expect(container.querySelectorAll('[role="region"]')).toHaveLength(0)
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('switches the single dock between selected rows', async () => {
|
||||
const store = makeStore(baseSnapshot())
|
||||
const { container, unmount } = mount(
|
||||
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
|
||||
)
|
||||
const first = container.querySelector('button[aria-label*="sleep 300"]') as HTMLButtonElement
|
||||
await act(async () => { first.click() })
|
||||
expect(container.textContent).toContain('output-of-bash-1')
|
||||
const second = container.querySelector('button[aria-label*="echo hi"]') as HTMLButtonElement
|
||||
await act(async () => { second.click() })
|
||||
// One dock, now fed by the second task (its owner session scopes the peek).
|
||||
expect(outputCalls).toEqual([
|
||||
{ sessionId: 'root', id: 'bash-1' },
|
||||
{ sessionId: 'child', id: 'bash-2' },
|
||||
])
|
||||
expect(container.querySelectorAll('[role="region"]')).toHaveLength(1)
|
||||
expect(container.textContent).not.toContain('output-of-bash-1')
|
||||
expect(container.textContent).toContain('output-of-bash-2')
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('stays compact and functional with many tasks', async () => {
|
||||
const many = Array.from({ length: 60 }, (_, index) => ({
|
||||
id: `bash-${index + 10}`,
|
||||
kind: 'bash' as const,
|
||||
label: `bulk cmd ${index}`,
|
||||
status: index % 2 === 0 ? ('running' as const) : ('completed' as const),
|
||||
startedAt: 1_000 + index,
|
||||
...(index % 2 === 0 ? {} : { finishedAt: 2_000 + index, detail: 'exit code: 1' }),
|
||||
}))
|
||||
const store = makeStore({
|
||||
current: 'root',
|
||||
byId: { root: { id: 'root', displayTitle: '主会话' } },
|
||||
subagentsByParent: {},
|
||||
tasksBySession: { root: many },
|
||||
})
|
||||
const { container, unmount } = mount(
|
||||
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
|
||||
)
|
||||
expect(container.textContent).toContain('60 个后台命令 · 30 运行中')
|
||||
expect(container.querySelectorAll('button[aria-label*="bulk cmd"]')).toHaveLength(60)
|
||||
// Clicking a row anywhere in the long list still feeds the single dock.
|
||||
const row = container.querySelector('button[aria-label*="bulk cmd 59"]') as HTMLButtonElement
|
||||
await act(async () => { row.click() })
|
||||
expect(outputCalls).toEqual([{ sessionId: 'root', id: 'bash-69' }])
|
||||
expect(container.textContent).toContain('output-of-bash-69')
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('kills a live task only after the two-click confirm', async () => {
|
||||
const store = makeStore(baseSnapshot())
|
||||
const { container, unmount } = mount(
|
||||
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
|
||||
)
|
||||
const kill = container.querySelector('button[aria-label="终止"]') as HTMLButtonElement
|
||||
await act(async () => { kill.click() })
|
||||
// First click only arms the confirm — no request leaves the page.
|
||||
expect(killCalls).toEqual([])
|
||||
const confirm = container.querySelector('button[aria-label="再次点击确认终止"]')
|
||||
expect(confirm).not.toBeNull()
|
||||
await act(async () => { (confirm as HTMLButtonElement).click() })
|
||||
expect(killCalls).toEqual([{ sessionId: 'root', id: 'bash-1' }])
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('does not poll the output while the page is hidden', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const store = makeStore(baseSnapshot())
|
||||
const { container, unmount } = mount(
|
||||
createElement(SubagentView, { sessionId: 'root', active: false, ctx: makeCtx(store) }),
|
||||
)
|
||||
const row = container.querySelector('button[aria-label*="sleep 300"]') as HTMLButtonElement
|
||||
await act(async () => { row.click() })
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
|
||||
// One peek for the initial load; the 2s poll never ran while inactive.
|
||||
expect(outputCalls).toHaveLength(1)
|
||||
unmount()
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Pure-helper tests for the Subagent page's background-task section:
|
||||
* tree-membership collection, ordering, and status presentation mapping.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
collectTreeTasks,
|
||||
formatTaskDuration,
|
||||
isTaskLive,
|
||||
orderTasks,
|
||||
taskDotState,
|
||||
taskStatusLabel,
|
||||
treeSessionIds,
|
||||
} from '../src/client/subagent-tasks.ts'
|
||||
import type { SidebarSessionSummary, SidebarTaskStatus, SidebarTaskView } from '../src/context-types.ts'
|
||||
|
||||
/** The translator stub: renders duration templates like the real locale copy. */
|
||||
const templates: Record<string, string> = {
|
||||
taskDurationSeconds: '{seconds}秒',
|
||||
taskDurationMinutes: '{minutes}分{seconds}秒',
|
||||
taskDurationHours: '{hours}小时{minutes}分',
|
||||
}
|
||||
const t = (key: string, params?: Record<string, string | number>): string => {
|
||||
let text = templates[key] ?? key
|
||||
if (params !== undefined) {
|
||||
for (const [name, value] of Object.entries(params)) text = text.replaceAll(`{${name}}`, String(value))
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
function summary(id: string, over: Partial<SidebarSessionSummary> = {}): SidebarSessionSummary {
|
||||
return { id, displayTitle: `title-${id}`, ...over }
|
||||
}
|
||||
|
||||
function task(id: string, over: Partial<SidebarTaskView> = {}): SidebarTaskView {
|
||||
return { id, kind: 'bash', label: `cmd ${id}`, status: 'running', startedAt: 1_000, ...over }
|
||||
}
|
||||
|
||||
describe('treeSessionIds', () => {
|
||||
it('includes the root and every subagent-origin session whose chain reaches it', () => {
|
||||
const byId = {
|
||||
root: summary('root'),
|
||||
child: summary('child', { origin: 'subagent', parentId: 'root' }),
|
||||
grand: summary('grand', { origin: 'subagent', parentId: 'child' }),
|
||||
orphan: summary('orphan', { origin: 'subagent', parentId: 'gone' }),
|
||||
other: summary('other', { origin: 'subagent', parentId: 'other-root' }),
|
||||
}
|
||||
const ids = treeSessionIds(byId, 'root')
|
||||
expect([...ids].sort()).toEqual(['child', 'grand', 'root'])
|
||||
})
|
||||
|
||||
it('fails soft on parent cycles and yields nothing without a root', () => {
|
||||
const byId = {
|
||||
root: summary('root'),
|
||||
a: summary('a', { origin: 'subagent', parentId: 'b' }),
|
||||
b: summary('b', { origin: 'subagent', parentId: 'a' }),
|
||||
}
|
||||
expect(treeSessionIds(byId, 'root').size).toBe(1)
|
||||
expect(treeSessionIds(byId, undefined).size).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('collectTreeTasks', () => {
|
||||
it('collects tasks of the whole tree with owner titles, ignoring outside sessions', () => {
|
||||
const byId = {
|
||||
root: summary('root'),
|
||||
child: summary('child', { origin: 'subagent', parentId: 'root' }),
|
||||
}
|
||||
const tasksBySession = {
|
||||
root: [task('bash-1')],
|
||||
child: [task('bash-2', { status: 'completed', finishedAt: 2_000 })],
|
||||
stranger: [task('bash-9')],
|
||||
}
|
||||
const rows = collectTreeTasks(byId, tasksBySession, 'root')
|
||||
expect(rows.map(row => [row.ownerSessionId, row.ownerTitle, row.task.id]))
|
||||
.toEqual([['root', 'title-root', 'bash-1'], ['child', 'title-child', 'bash-2']])
|
||||
})
|
||||
|
||||
it('returns an empty list for an absent mirror or empty sets', () => {
|
||||
const byId = { root: summary('root') }
|
||||
expect(collectTreeTasks(byId, undefined, 'root')).toEqual([])
|
||||
expect(collectTreeTasks(byId, {}, 'root')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('orderTasks', () => {
|
||||
it('puts live rows first in start order, then settled rows newest-first', () => {
|
||||
const row = (id: string, status: SidebarTaskStatus, startedAt: number, finishedAt?: number) => ({
|
||||
ownerSessionId: 'root',
|
||||
ownerTitle: 'root',
|
||||
task: task(id, { status, startedAt, ...(finishedAt !== undefined ? { finishedAt } : {}) }),
|
||||
})
|
||||
const rows = [
|
||||
row('old-settled', 'completed', 1_000, 2_000),
|
||||
row('live-2', 'running', 4_000),
|
||||
row('new-settled', 'killed', 1_500, 1_800),
|
||||
row('live-1', 'stopping', 3_000),
|
||||
]
|
||||
expect(orderTasks(rows).map(r => r.task.id)).toEqual(['live-1', 'live-2', 'old-settled', 'new-settled'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('status presentation helpers', () => {
|
||||
it('treats running and stopping as live', () => {
|
||||
expect(isTaskLive(task('a', { status: 'running' }))).toBe(true)
|
||||
expect(isTaskLive(task('b', { status: 'stopping' }))).toBe(true)
|
||||
expect(isTaskLive(task('c', { status: 'completed' }))).toBe(false)
|
||||
expect(isTaskLive(task('d', { status: 'killed' }))).toBe(false)
|
||||
expect(isTaskLive(task('e', { status: 'failed' }))).toBe(false)
|
||||
})
|
||||
|
||||
it('maps the five wire statuses to dot states and localized labels', () => {
|
||||
expect(taskDotState('running')).toBe('ongoing')
|
||||
expect(taskDotState('stopping')).toBe('warning')
|
||||
expect(taskDotState('completed')).toBe('done')
|
||||
expect(taskDotState('killed')).toBe('warning')
|
||||
expect(taskDotState('failed')).toBe('error')
|
||||
expect(taskStatusLabel('running', t)).toBe('taskStatusRunning')
|
||||
expect(taskStatusLabel('stopping', t)).toBe('taskStatusStopping')
|
||||
expect(taskStatusLabel('completed', t)).toBe('taskStatusCompleted')
|
||||
expect(taskStatusLabel('killed', t)).toBe('taskStatusKilled')
|
||||
expect(taskStatusLabel('failed', t)).toBe('taskStatusFailed')
|
||||
})
|
||||
|
||||
it('formats durations in at most two adjacent units', () => {
|
||||
expect(formatTaskDuration(0, t)).toBe('0秒')
|
||||
expect(formatTaskDuration(45_000, t)).toBe('45秒')
|
||||
expect(formatTaskDuration(90_000, t)).toBe('1分30秒')
|
||||
expect(formatTaskDuration(3_661_000, t)).toBe('1小时1分')
|
||||
// Negative or fractional input clamps to zero seconds.
|
||||
expect(formatTaskDuration(-5, t)).toBe('0秒')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Host route tests for the background-task API ('tasks.output' / 'tasks.kill'):
|
||||
* caller resolution from the requested session, the non-consuming peek
|
||||
* contract (capped, never reported), kill semantics, and the optional-service
|
||||
* downgrade when the deployment lacks the tasks registry.
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { buildTasksApi } from '../src/tasks-routes.ts'
|
||||
import { SidebarError } from '../src/wire.ts'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
|
||||
/** A context whose `get` serves only the tasks/agents faces. */
|
||||
function ctxWith(tasks: unknown, agents: unknown): Context {
|
||||
return {
|
||||
get: (key: string) => (key === 'tasks' ? tasks : key === 'agents' ? agents : undefined),
|
||||
} as unknown as Context
|
||||
}
|
||||
|
||||
/** A stub live agent (the fence compares `id` only). */
|
||||
const agent = (id: string) => ({ id, session: { header: { cwd: '/p' } } })
|
||||
|
||||
describe('tasks.output route', () => {
|
||||
it('peeks the full output with the live caller of the requested session', () => {
|
||||
const tasks = {
|
||||
peek: vi.fn(() => ({ text: 'line1\nline2\n', snapshot: { status: 'running' } })),
|
||||
}
|
||||
const agents = { get: vi.fn((id: string) => agent(id)) }
|
||||
const api = buildTasksApi(ctxWith(tasks, agents), 512 * 1024)!
|
||||
const value = api.output({ sessionId: 's1', id: 'bash-1' })
|
||||
|
||||
expect(value).toEqual({ text: 'line1\nline2\n', truncated: false, status: 'running' })
|
||||
// The caller is the live agent of the OWNING session, and the registry
|
||||
// call is a peek (non-consuming by construction of the seam contract).
|
||||
expect(agents.get).toHaveBeenCalledWith('s1')
|
||||
expect(tasks.peek).toHaveBeenCalledWith('bash-1', agent('s1'))
|
||||
})
|
||||
|
||||
it('carries the terminal detail and caps oversized output with the truncated flag', () => {
|
||||
const tasks = {
|
||||
peek: vi.fn(() => ({
|
||||
text: 'x'.repeat(10_000),
|
||||
snapshot: { status: 'completed', detail: 'exit code: 0' },
|
||||
})),
|
||||
}
|
||||
const api = buildTasksApi(ctxWith(tasks, undefined), 100)!
|
||||
const value = api.output({ sessionId: 's1', id: 'bash-1' })
|
||||
|
||||
expect(value.text).toBe('x'.repeat(100))
|
||||
expect(value.truncated).toBe(true)
|
||||
expect(value.status).toBe('completed')
|
||||
expect(value.detail).toBe('exit code: 0')
|
||||
})
|
||||
|
||||
it('maps registry refusals to a 404 task-error (unknown/foreign ids stay indistinguishable)', () => {
|
||||
const tasks = { peek: vi.fn(() => { throw new Error('task bash-9 belongs to another session') }) }
|
||||
const api = buildTasksApi(ctxWith(tasks, {}), 100)!
|
||||
expect(() => api.output({ sessionId: 's1', id: 'bash-9' })).toThrowError(
|
||||
expect.objectContaining<Partial<SidebarError>>({ code: 'task-error', status: 404 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a missing sessionId or id as bad-request', () => {
|
||||
const tasks = { peek: vi.fn() }
|
||||
const api = buildTasksApi(ctxWith(tasks, {}), 100)!
|
||||
expect(() => api.output({ id: 'bash-1' })).toThrowError(expect.objectContaining<Partial<SidebarError>>({ code: 'bad-request' }))
|
||||
expect(() => api.output({ sessionId: 's1' })).toThrowError(expect.objectContaining<Partial<SidebarError>>({ code: 'bad-request' }))
|
||||
})
|
||||
})
|
||||
|
||||
describe('tasks.kill route', () => {
|
||||
it('kills with the forwarded reason and the live caller', () => {
|
||||
const tasks = { kill: vi.fn(() => 'requested' as const) }
|
||||
const agents = { get: vi.fn((id: string) => agent(id)) }
|
||||
const api = buildTasksApi(ctxWith(tasks, agents), 100)!
|
||||
expect(api.kill({ sessionId: 's1', id: 'bash-1', reason: 'user pressed stop' }))
|
||||
.toEqual({ ok: true, outcome: 'requested' })
|
||||
expect(tasks.kill).toHaveBeenCalledWith('bash-1', agent('s1'), 'user pressed stop')
|
||||
})
|
||||
|
||||
it('defaults the reason when none is supplied', () => {
|
||||
const tasks = { kill: vi.fn(() => 'already-finished' as const) }
|
||||
const api = buildTasksApi(ctxWith(tasks, undefined), 100)!
|
||||
expect(api.kill({ sessionId: 's1', id: 'bash-1' })).toEqual({ ok: true, outcome: 'already-finished' })
|
||||
expect(tasks.kill).toHaveBeenCalledWith('bash-1', undefined, 'user requested via sidebar')
|
||||
})
|
||||
|
||||
it('maps registry refusals to a 404 task-error', () => {
|
||||
const tasks = { kill: vi.fn(() => { throw new Error('unknown task bash-9') }) }
|
||||
const api = buildTasksApi(ctxWith(tasks, {}), 100)!
|
||||
expect(() => api.kill({ sessionId: 's1', id: 'bash-9' })).toThrowError(
|
||||
expect.objectContaining<Partial<SidebarError>>({ code: 'task-error', status: 404 }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('optional-service downgrade', () => {
|
||||
it('returns undefined (the caller maps to a 503) when ctx.tasks is absent', () => {
|
||||
expect(buildTasksApi(ctxWith(undefined, {}), 100)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('resolves the caller as undefined when the agents registry is absent', () => {
|
||||
const tasks = { peek: vi.fn(() => ({ text: '', snapshot: { status: 'running' } })), kill: vi.fn(() => 'requested' as const) }
|
||||
const api = buildTasksApi(ctxWith(tasks, undefined), 100)!
|
||||
api.output({ sessionId: 's1', id: 'bash-1' })
|
||||
expect(tasks.peek).toHaveBeenCalledWith('bash-1', undefined)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user