feat(host): add workflows.list and teams.* sidebar routes

- workflows.list folds tool-workflow/* session events (the same four types
  the official workflow-run panel folds) across the whole session tree,
  merging the stored log with a live session/event mirror deduped by seq;
  absence of events yields an empty list, never an error.
- teams.view / teams.taskCreate / teams.taskUpdate ride the experimental
  agentTeams service's Remote vocabulary with structural degradation:
  layer absent -> {available:false}; root leads no team -> {team:null};
  CAS conflicts pass through the service's own result union.
- wire gains the team-error code; context-types gains structural mirrors
  of the team view/request vocabulary (no experimental package import).
- 29 unit tests across fold, route merging/degradation, and CAS shaping.
This commit is contained in:
Menghuan1918 committed 2026-09-27 22:18:14 +08:00
1 parent ad6b0b1486
commit c445495f8b
9 files changed
+1016

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
/**
* Host route tests for the Agent Teams API ('teams.view' / 'teams.taskCreate'
* / 'teams.taskUpdate'): structural degradation (layer absent → available:
* false; root leads no team → team: null), passthrough of the service's own
* Remote vocabulary, CAS conflict unions returned untouched, and payload
* validation. The plugin never imports the experimental package — the fake
* service here is a structural double.
*/
import { describe, expect, it, vi } from 'vitest'
import { buildTeamsApi } from '../src/team-routes.ts'
import type {
Context,
SidebarTeamMemberView,
SidebarTeamTaskView,
} from '../src/context-types.ts'
/** One member row. */
function member(over: Partial<SidebarTeamMemberView> = {}): SidebarTeamMemberView {
return {
id: 'root', name: 'lead', role: 'lead', status: 'running', diagnostics: [], ...over,
}
}
/** One task row. */
function task(over: Partial<SidebarTeamTaskView> = {}): SidebarTeamTaskView {
return {
id: 'task-1', revision: 1, subject: 's', description: 'd', status: 'pending',
blockedBy: [], writeScopes: [], ready: true, writeScopeWarnings: [], ...over,
}
}
/** A context serving the given agentTeams/agents faces. */
function ctxWith(teams: unknown, agents: unknown): Context {
return {
get: (key: string) => (key === 'agentTeams' ? teams : key === 'agents' ? agents : undefined),
} as unknown as Context
}
/** An agents face resolving one live root agent. */
function agentsWithRoot(): { get(id: string): { id: string } | undefined } {
return { get: (id: string) => (id === 'root' ? { id: 'root' } : undefined) }
}
describe('teams.view route', () => {
it('reports available:false when the experimental layer is absent', async () => {
const api = buildTeamsApi(ctxWith(undefined, agentsWithRoot()))
await expect(api.view({ rootSessionId: 'root' })).resolves.toEqual({ available: false })
})
it('reports team:null when the root agent is not live', async () => {
const teams = { tryMembership: vi.fn(), remoteView: vi.fn() }
const api = buildTeamsApi(ctxWith(teams, { get: () => undefined }))
await expect(api.view({ rootSessionId: 'root' })).resolves.toEqual({ available: true, team: null })
expect(teams.remoteView).not.toHaveBeenCalled()
})
it('reports team:null when tryMembership misses', async () => {
const teams = { tryMembership: vi.fn(async () => undefined), remoteView: vi.fn() }
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
await expect(api.view({ rootSessionId: 'root' })).resolves.toEqual({ available: true, team: null })
expect(teams.remoteView).not.toHaveBeenCalled()
})
it('reports team:null when tryMembership throws (stale member)', async () => {
const teams = { tryMembership: vi.fn(async () => { throw new Error('stale') }), remoteView: vi.fn() }
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
await expect(api.view({ rootSessionId: 'root' })).resolves.toEqual({ available: true, team: null })
})
it('returns the service view on a membership hit', async () => {
const view = { members: [member()], tasks: [task()] }
const teams = {
tryMembership: vi.fn(async () => ({ role: 'lead' })),
remoteView: vi.fn(async () => view),
}
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
await expect(api.view({ rootSessionId: 'root' })).resolves.toEqual({ available: true, team: view })
})
it('maps a remoteView rejection to a 400 team-error', async () => {
const teams = {
tryMembership: vi.fn(async () => ({ role: 'lead' })),
remoteView: vi.fn(async () => { throw new Error('replay failed') }),
}
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
await expect(api.view({ rootSessionId: 'root' })).rejects.toThrowError(
expect.objectContaining({ code: 'team-error', status: 400 }),
)
})
})
describe('teams.taskCreate route', () => {
it('passes the shaped request through and returns the union', async () => {
const created = task({ id: 'task-9', subject: '新任务' })
const teams = {
tryMembership: vi.fn(async () => ({ role: 'lead' })),
remoteCreateTask: vi.fn(async () => ({ ok: true, value: created })),
}
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
const result = await api.taskCreate({
rootSessionId: 'root', subject: '新任务', description: '详', blockedBy: ['task-1'],
})
expect(result).toEqual({ ok: true, value: created })
expect(teams.remoteCreateTask).toHaveBeenCalledWith(
{ id: 'root' },
{ subject: '新任务', description: '详', blockedBy: ['task-1'] },
)
})
it('degrades to 503 on a mutation when the layer is absent', async () => {
const api = buildTeamsApi(ctxWith(undefined, agentsWithRoot()))
await expect(api.taskCreate({ rootSessionId: 'root', subject: 's' })).rejects.toThrowError(
expect.objectContaining({ code: 'team-error', status: 503 }),
)
})
it('degrades to 404 when the root leads no team', async () => {
const teams = { tryMembership: vi.fn(async () => undefined) }
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
await expect(api.taskCreate({ rootSessionId: 'root', subject: 's' })).rejects.toThrowError(
expect.objectContaining({ code: 'team-error', status: 404 }),
)
})
it('rejects a missing subject as bad-request', async () => {
const teams = { tryMembership: vi.fn(async () => ({ role: 'lead' })) }
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
await expect(api.taskCreate({ rootSessionId: 'root' })).rejects.toThrowError(
expect.objectContaining({ code: 'bad-request' }),
)
})
})
describe('teams.taskUpdate route', () => {
it('passes the CAS request through, conflict union untouched', async () => {
const conflict = { ok: false, error: { code: 'team-task-conflict', message: 'stale revision' } }
const teams = {
tryMembership: vi.fn(async () => ({ role: 'lead' })),
remoteUpdateTask: vi.fn(async () => conflict),
}
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
const result = await api.taskUpdate({
rootSessionId: 'root', taskId: 'task-1', expectedRevision: 3, action: 'complete',
})
expect(result).toEqual(conflict)
expect(teams.remoteUpdateTask).toHaveBeenCalledWith(
{ id: 'root' },
{ taskId: 'task-1', expectedRevision: 3, action: 'complete' },
)
})
it('validates taskId / expectedRevision / action', async () => {
const teams = { tryMembership: vi.fn(async () => ({ role: 'lead' })), remoteUpdateTask: vi.fn() }
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
await expect(api.taskUpdate({ rootSessionId: 'root', expectedRevision: 1, action: 'complete' }))
.rejects.toThrowError(expect.objectContaining({ code: 'bad-request' }))
await expect(api.taskUpdate({ rootSessionId: 'root', taskId: 't', action: 'complete' }))
.rejects.toThrowError(expect.objectContaining({ code: 'bad-request' }))
await expect(api.taskUpdate({ rootSessionId: 'root', taskId: 't', expectedRevision: -1, action: 'complete' }))
.rejects.toThrowError(expect.objectContaining({ code: 'bad-request' }))
await expect(api.taskUpdate({ rootSessionId: 'root', taskId: 't', expectedRevision: 1, action: 'nuke' }))
.rejects.toThrowError(expect.objectContaining({ code: 'bad-request' }))
expect(teams.remoteUpdateTask).not.toHaveBeenCalled()
})
it('forwards optional edit fields when present', async () => {
const teams = {
tryMembership: vi.fn(async () => ({ role: 'lead' })),
remoteUpdateTask: vi.fn(async () => ({ ok: true, value: task() })),
}
const api = buildTeamsApi(ctxWith(teams, agentsWithRoot()))
await api.taskUpdate({
rootSessionId: 'root', taskId: 'task-1', expectedRevision: 2, action: 'reassign', owner: 'writer',
})
expect(teams.remoteUpdateTask).toHaveBeenCalledWith(
{ id: 'root' },
{ taskId: 'task-1', expectedRevision: 2, action: 'reassign', owner: 'writer' },
)
})
})
+141
View File
@@ -0,0 +1,141 @@
/**
* Host route tests for the workflow-runs API ('workflows.list'): the route
* must enumerate the tree (root + catalog descendants), merge each session's
* stored log with the live `session/event` mirror (deduped by seq), skip
* unreadable sessions, and degrade to a root-only fold when the subagent
* runtime is absent. Absence of workflow events is an empty list, never an
* error.
*/
import { describe, expect, it, vi } from 'vitest'
import { buildWorkflowsApi } from '../src/workflow-routes.ts'
import type {
Context,
SidebarSessionEvent,
SidebarSubagentDescendantEntry,
} from '../src/context-types.ts'
/** One child descendant row. */
function child(id: string): SidebarSubagentDescendantEntry {
return { kind: 'child', id, activity: 'running', hasChildren: false, mode: 'one-shot', parentId: 'root', depth: 1 }
}
/** A session with the given raw events. */
function session(events: SidebarSessionEvent[]) {
return { header: { cwd: '/p' }, snapshotEvents: () => events }
}
/** One workflow event row. */
function ev(seq: number, type: string, data: Record<string, unknown>): SidebarSessionEvent {
return { type, seq, time: 0, data }
}
/** A context with sessions + optional subagents service + optional event feed. */
function ctxWith(options: {
sessions: Map<string, SidebarSessionEvent[]>
subagents?: unknown
on?: (event: string, listener: (session: unknown, event: SidebarSessionEvent) => void) => () => void
}): Context {
return {
sessions: { get: (id: string) => { const e = options.sessions.get(id); return e === undefined ? undefined : session(e) } },
get: (key: string) => (key === 'subagents' ? options.subagents : undefined),
...(options.on === undefined ? {} : { on: options.on }),
effect: () => () => {},
} as unknown as Context
}
describe('workflows.list route', () => {
it('folds the runs of every tree session, oldest first', async () => {
const subagents = { listDescendants: vi.fn(async () => [child('child-a')]) }
const sessions = new Map<string, SidebarSessionEvent[]>([
['child-a', [
ev(1, 'tool-workflow/run-start', { runId: 'r1', name: 'child-run' }),
ev(2, 'tool-workflow/run-end', { runId: 'r1', stopReason: 'completed' }),
]],
['root', [
ev(5, 'tool-workflow/run-start', { runId: 'r2', name: 'root-run' }),
]],
])
const api = buildWorkflowsApi(ctxWith({ sessions, subagents }))
const { runs } = await api.list({ rootSessionId: 'root' })
expect(runs.map(run => [run.runId, run.originSessionId, run.status])).toEqual([
['r1', 'child-a', 'completed'],
['r2', 'root', 'running'],
])
expect(subagents.listDescendants).toHaveBeenCalledWith('root')
})
it('returns an empty list when the tree never ran a workflow', async () => {
const subagents = { listDescendants: vi.fn(async () => [child('child-a')]) }
const sessions = new Map<string, SidebarSessionEvent[]>([
['root', [ev(1, 'assistant/message', { message: { content: [] } })]],
['child-a', []],
])
const api = buildWorkflowsApi(ctxWith({ sessions, subagents }))
await expect(api.list({ rootSessionId: 'root' })).resolves.toEqual({ runs: [] })
})
it('folds the root alone when the subagent runtime is absent', async () => {
const sessions = new Map<string, SidebarSessionEvent[]>([
['root', [ev(1, 'tool-workflow/run-start', { runId: 'r', name: 'solo' })]],
])
const api = buildWorkflowsApi(ctxWith({ sessions }))
const { runs } = await api.list({ rootSessionId: 'root' })
expect(runs.map(run => run.runId)).toEqual(['r'])
})
it('folds the root alone when listDescendants fails', async () => {
const subagents = { listDescendants: vi.fn(async () => { throw new Error('stale') }) }
const sessions = new Map<string, SidebarSessionEvent[]>([
['root', [ev(1, 'tool-workflow/run-start', { runId: 'r', name: 'solo' })]],
])
const api = buildWorkflowsApi(ctxWith({ sessions, subagents }))
const { runs } = await api.list({ rootSessionId: 'root' })
expect(runs.map(run => run.runId)).toEqual(['r'])
})
it('merges the live mirror with the stored log, deduped by seq', async () => {
type Listener = (session: unknown, event: SidebarSessionEvent) => void
let listener: Listener | undefined
const on = (_event: string, bound: Listener) => { listener = bound; return () => {} }
// The stored log ends at the run-start (a rehydrated store session); the
// live mirror carries the rest, re-sending the stored start row too.
const sessions = new Map<string, SidebarSessionEvent[]>([
['root', [ev(1, 'tool-workflow/run-start', { runId: 'r', name: 'live' })]],
])
const api = buildWorkflowsApi(ctxWith({ sessions, on }))
listener?.({ id: 'root' }, ev(1, 'tool-workflow/run-start', { runId: 'r', name: 'live' }))
listener?.({ id: 'root' }, ev(2, 'tool-workflow/agent-start', { runId: 'r', seq: 1, label: 'a', childId: 'c' }))
listener?.({ id: 'root' }, ev(3, 'tool-workflow/run-end', { runId: 'r', stopReason: 'completed' }))
listener?.({ id: 'other' }, ev(1, 'tool-workflow/run-start', { runId: 'stray', name: 'stray' }))
const { runs } = await api.list({ rootSessionId: 'root' })
expect(runs).toHaveLength(1)
expect(runs[0]).toMatchObject({ runId: 'r', status: 'completed' })
expect(runs[0]?.phases[0]?.members).toHaveLength(1)
})
it('skips a session whose log read throws without failing the batch', async () => {
const subagents = { listDescendants: vi.fn(async () => [child('bad'), child('good')]) }
const sessions = {
get: (id: string) => {
if (id === 'good') return session([ev(1, 'tool-workflow/run-start', { runId: 'g', name: 'good' })])
if (id === 'root') return session([])
throw new Error('missing')
},
}
const ctx = {
sessions,
get: (key: string) => (key === 'subagents' ? subagents : undefined),
effect: () => () => {},
} as unknown as Context
const api = buildWorkflowsApi(ctx)
const { runs } = await api.list({ rootSessionId: 'root' })
expect(runs.map(run => run.runId)).toEqual(['g'])
})
it('rejects a missing rootSessionId as bad-request', async () => {
const api = buildWorkflowsApi(ctxWith({ sessions: new Map() }))
await expect(api.list({})).rejects.toThrowError(
expect.objectContaining({ code: 'bad-request' }),
)
})
})
+133
View File
@@ -0,0 +1,133 @@
/**
* Unit tests for the workflow-run fold (`foldWorkflowRuns`): the pure
* derivation that turns one session's `tool-workflow/*` events into the run
* views the Tasks page renders (the same four event types the official
* `dsh-client-ui-workflow-run` panel folds).
*/
import { describe, expect, it } from 'vitest'
import { foldWorkflowRuns, type WorkflowRunView } from '../src/workflow-runs.ts'
import type { SidebarSessionEvent } from '../src/context-types.ts'
/** One event row. */
function ev(seq: number, type: string, data: Record<string, unknown>, time = 0): SidebarSessionEvent {
return { type, seq, time, data }
}
/** The full lifecycle of one run with two phases. */
function lifecycle(seq = 1): SidebarSessionEvent[] {
return [
ev(seq, 'tool-workflow/run-start', { runId: 'run-1', name: 'repo-audit' }, 1000),
ev(seq + 1, 'tool-workflow/agent-start', { runId: 'run-1', seq: 1, label: '扫描 src', phase: '侦察', childId: 'child-a' }),
ev(seq + 2, 'tool-workflow/agent-start', { runId: 'run-1', seq: 2, label: '扫描 tests', phase: '侦察', childId: 'child-b' }),
ev(seq + 3, 'tool-workflow/agent-end', { runId: 'run-1', seq: 1, outcome: 'completed' }),
ev(seq + 4, 'tool-workflow/agent-start', { runId: 'run-1', seq: 3, label: '生成报告', phase: '汇总', childId: 'child-c' }),
ev(seq + 5, 'tool-workflow/agent-end', { runId: 'run-1', seq: 2, outcome: 'failed' }),
ev(seq + 6, 'tool-workflow/run-end', { runId: 'run-1', stopReason: 'completed' }, 5000),
]
}
describe('foldWorkflowRuns', () => {
it('folds a full lifecycle into phases with outcomes', () => {
const runs = foldWorkflowRuns(lifecycle(), 'origin')
expect(runs).toHaveLength(1)
const run = runs[0] as WorkflowRunView
expect(run).toMatchObject({
runId: 'run-1',
name: 'repo-audit',
originSessionId: 'origin',
status: 'completed',
stopReason: 'completed',
startedSeq: 1,
startedAt: 1000,
finishedAt: 5000,
})
expect(run.phases.map(phase => phase.title)).toEqual(['侦察', '汇总'])
const [scout, report] = run.phases
expect(scout?.members.map(member => [member.seq, member.label, member.outcome])).toEqual([
[1, '扫描 src', 'completed'],
[2, '扫描 tests', 'failed'],
])
expect(report?.members).toHaveLength(1)
expect(report?.members[0]).toMatchObject({ seq: 3, label: '生成报告', childId: 'child-c' })
expect(report?.members[0]?.outcome).toBeUndefined()
})
it('keeps a run without run-end running', () => {
const runs = foldWorkflowRuns(lifecycle().slice(0, 3), 'origin')
expect(runs[0]?.status).toBe('running')
expect(runs[0]?.stopReason).toBeUndefined()
expect(runs[0]?.finishedAt).toBeUndefined()
})
it('maps stopReason error to the failed display status', () => {
const runs = foldWorkflowRuns([
ev(1, 'tool-workflow/run-start', { runId: 'r', name: 'n' }),
ev(2, 'tool-workflow/run-end', { runId: 'r', stopReason: 'error' }, 42),
], 'origin')
expect(runs[0]).toMatchObject({ status: 'failed', stopReason: 'error', finishedAt: 42 })
})
it('groups unphased members into one untitled phase in first-seen order', () => {
const runs = foldWorkflowRuns([
ev(1, 'tool-workflow/run-start', { runId: 'r', name: 'n' }),
ev(2, 'tool-workflow/agent-start', { runId: 'r', seq: 1, label: 'a', childId: 'c1' }),
ev(3, 'tool-workflow/agent-start', { runId: 'r', seq: 2, label: 'b', phase: 'p', childId: 'c2' }),
ev(4, 'tool-workflow/agent-start', { runId: 'r', seq: 3, label: 'c', childId: 'c3' }),
], 'origin')
const run = runs[0] as WorkflowRunView
expect(run.phases.map(phase => phase.title)).toEqual([undefined, 'p'])
expect(run.phases[0]?.members.map(member => member.seq)).toEqual([1, 3])
})
it('skips orphan rows that reference an unknown run', () => {
const runs = foldWorkflowRuns([
ev(1, 'tool-workflow/agent-start', { runId: 'ghost', seq: 1, label: 'a', childId: 'c' }),
ev(2, 'tool-workflow/agent-end', { runId: 'ghost', seq: 1, outcome: 'completed' }),
ev(3, 'tool-workflow/run-end', { runId: 'ghost', stopReason: 'completed' }),
], 'origin')
expect(runs).toEqual([])
})
it('ignores a duplicated run-start and non-run events', () => {
const runs = foldWorkflowRuns([
ev(1, 'tool-workflow/run-start', { runId: 'r', name: 'first' }),
ev(2, 'assistant/message', { message: { content: [{ type: 'text', text: 'hi' }] } }),
ev(3, 'tool-workflow/run-start', { runId: 'r', name: 'second' }),
], 'origin')
expect(runs).toHaveLength(1)
expect(runs[0]?.name).toBe('first')
})
it('keeps multiple runs in run-start order with their own member books', () => {
const runs = foldWorkflowRuns([
ev(1, 'tool-workflow/run-start', { runId: 'a', name: 'A' }),
ev(2, 'tool-workflow/agent-start', { runId: 'a', seq: 1, label: 'a1', childId: 'ca' }),
ev(3, 'tool-workflow/run-start', { runId: 'b', name: 'B' }),
ev(4, 'tool-workflow/agent-start', { runId: 'b', seq: 1, label: 'b1', childId: 'cb' }),
ev(5, 'tool-workflow/agent-end', { runId: 'a', seq: 1, outcome: 'completed' }),
], 'origin')
expect(runs.map(run => run.runId)).toEqual(['a', 'b'])
expect(runs[0]?.phases[0]?.members[0]).toMatchObject({ label: 'a1', outcome: 'completed' })
expect(runs[1]?.phases[0]?.members[0]?.label).toBe('b1')
expect(runs[1]?.phases[0]?.members[0]?.outcome).toBeUndefined()
})
it('validates agent-end outcomes and ignores malformed rows', () => {
const runs = foldWorkflowRuns([
ev(1, 'tool-workflow/run-start', { runId: 'r', name: 'n' }),
ev(2, 'tool-workflow/agent-start', { runId: 'r', seq: 1, label: 'a', childId: 'c' }),
ev(3, 'tool-workflow/agent-end', { runId: 'r', seq: 1, outcome: 'bogus' }),
ev(4, 'tool-workflow/agent-end', { runId: 'r', seq: 'not-a-number', outcome: 'completed' }),
], 'origin')
expect(runs[0]?.phases[0]?.members[0]?.outcome).toBeUndefined()
})
it('falls back to runId/#seq labels when name/label are empty', () => {
const runs = foldWorkflowRuns([
ev(1, 'tool-workflow/run-start', { runId: 'r', name: '' }),
ev(2, 'tool-workflow/agent-start', { runId: 'r', seq: 7, label: '', childId: 'c' }),
], 'origin')
expect(runs[0]?.name).toBe('r')
expect(runs[0]?.phases[0]?.members[0]?.label).toBe('#7')
})
})