fix(workflow): close review and snapshot gaps

This commit is contained in:
pku-xht
2026-08-10 19:25:21 +08:00
parent 8de6df19d9
commit 4eb0a52840
20 changed files with 300 additions and 350 deletions

View File

@@ -29,6 +29,7 @@
height: 16px;
align-items: center;
justify-content: center;
margin-right: 0;
color: var(--dsw-alias-label-tertiary);
}
@@ -93,14 +94,19 @@
height: 16px;
align-items: center;
justify-content: center;
margin-right: 0;
color: var(--dsw-alias-label-tertiary);
}
.phaseTitle {
flex: none;
overflow: hidden;
flex: 0 1 auto;
min-width: 0;
max-width: 42%;
color: var(--dsw-alias-label-secondary);
font-size: 14px;
line-height: 24px;
text-overflow: ellipsis;
white-space: nowrap;
}

View File

@@ -1,6 +1,6 @@
import { useMemo, useState, type KeyboardEvent } from 'react'
import { useMemo, useState } from 'react'
import {
IconChevronDownOutline14, IconChevronRightOutline14, StateDot, type StateDotState,
DisclosureRow, IconChevronRightOutline14, StateDot, type StateDotState,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
@@ -71,12 +71,6 @@ function phaseStatusSummary(members: readonly WorkflowRunMemberData[], t: Workfl
return visible.map(status => statusCount(status, count(status), t)).join(' · ')
}
function handleDisclosureKey(event: KeyboardEvent<HTMLDivElement>, onToggle: () => void): void {
if (event.key !== 'Enter' && event.key !== ' ') return
event.preventDefault()
onToggle()
}
function RunHeader({ count, name, onToggle, open, status, t }: {
readonly count: number
readonly name: string
@@ -86,27 +80,29 @@ function RunHeader({ count, name, onToggle, open, status, t }: {
readonly t: WorkflowRunPanelProps['t']
}) {
return (
<div
className={css.runHeader}
data-run-header
data-status={status}
role="button"
tabIndex={0}
aria-expanded={open}
onClick={onToggle}
onKeyDown={(event) => { handleDisclosureKey(event, onToggle) }}
>
<span className={css.runLeading}>
{open ? <IconChevronDownOutline14 /> : <IconChevronRightOutline14 />}
</span>
<span className={css.runTitle}>{t('run.title', { name })}</span>
<span className={css.separator} aria-hidden />
<span className={css.runSummary}>{t('run.members', { count })}</span>
<span className={css.statusTail} data-run-status-tail data-status={status}>
<StateDot state={dotState(status)} />
<span>{t(STATUS_KEYS[status])}</span>
</span>
</div>
<DisclosureRow
icon={<IconChevronRightOutline14 />}
title={t('run.title', { name })}
open={open}
expandable
onToggle={onToggle}
expandOnRowClick
previewChevron={false}
keepContentWhenOpen
rowClassName={css.runHeader}
leadingClassName={css.runLeading}
titleClassName={css.runTitle}
collapsedContent={(
<>
<span className={css.separator} aria-hidden />
<span className={css.runSummary}>{t('run.members', { count })}</span>
<span className={css.statusTail} data-status={status}>
<StateDot state={dotState(status)} />
<span>{t(STATUS_KEYS[status])}</span>
</span>
</>
)}
/>
)
}
@@ -149,38 +145,39 @@ function PhaseSection({ phase, navigable, openSession, t }: {
const [open, setOpen] = useState(false)
const toggle = (): void => { setOpen(value => !value) }
return (
<div className={css.phase} data-phase-key={phase.key} data-phase-status={phase.status}>
<div
className={css.phaseHeader}
data-phase-header
role="button"
tabIndex={0}
aria-expanded={open}
onClick={toggle}
onKeyDown={(event) => { handleDisclosureKey(event, toggle) }}
>
<span className={css.phaseLeading}>
{open ? <IconChevronDownOutline14 /> : <IconChevronRightOutline14 />}
</span>
<span className={css.phaseTitle}>{readablePhase(phase.phase, t)}</span>
<span className={css.separator} aria-hidden />
<span className={css.phaseCount} data-phase-count>{t('run.members', { count: phase.members.length })}</span>
<span className={css.phaseStatus} data-phase-status-text>{phaseStatusSummary(phase.members, t)}</span>
</div>
{open && (
<div className={css.members}>
{phase.members.map(member => (
<MemberRow
key={member.seq}
member={member}
navigable={navigable.has(member.childId)}
openSession={openSession}
t={t}
/>
))}
</div>
<DisclosureRow
icon={<IconChevronRightOutline14 />}
title={readablePhase(phase.phase, t)}
open={open}
expandable
onToggle={toggle}
expandOnRowClick
previewChevron={false}
keepContentWhenOpen
className={css.phase}
rowClassName={css.phaseHeader}
leadingClassName={css.phaseLeading}
titleClassName={css.phaseTitle}
collapsedContent={(
<>
<span className={css.separator} aria-hidden />
<span className={css.phaseCount} data-phase-count>{t('run.members', { count: phase.members.length })}</span>
<span className={css.phaseStatus} data-phase-status-text>{phaseStatusSummary(phase.members, t)}</span>
</>
)}
</div>
>
<div className={css.members}>
{phase.members.map(member => (
<MemberRow
key={member.seq}
member={member}
navigable={navigable.has(member.childId)}
openSession={openSession}
t={t}
/>
))}
</div>
</DisclosureRow>
)
}
@@ -188,6 +185,7 @@ function PhaseSection({ phase, navigable, openSession, t }: {
export function WorkflowRunPanel({ node, sessionId, useSessions, openSession, t }: WorkflowRunPanelProps) {
const [open, setOpen] = useState(() => node.data.status === 'running')
const sessions = useSessions(value => value)
const memberCount = node.data.phases.reduce((count, phase) => count + phase.members.length, 0)
const navigable = useMemo(() => {
const ordinary = new Set(sessions.ids)
const result = new Set<SessionId>()
@@ -208,7 +206,7 @@ export function WorkflowRunPanel({ node, sessionId, useSessions, openSession, t
return (
<section className={css.root} data-workflow-run data-run-status={node.data.status}>
<RunHeader
count={node.data.memberCount}
count={memberCount}
name={node.data.name}
open={open}
status={node.data.status}

View File

@@ -7,12 +7,6 @@ import { WorkflowRunPanel, type WorkflowRunInjected } from './WorkflowRunPanel.t
import { en, NS, type WorkflowRunKey, zh } from './locales.ts'
import { workflowRunDefinition } from './workflow-definition.ts'
export type { WorkflowRunInjected, WorkflowRunPanelProps } from './WorkflowRunPanel.tsx'
export type {
WorkflowRunChatData, WorkflowRunMemberData, WorkflowRunPhaseData, WorkflowRunStatus,
} from './workflow-definition.ts'
export type { WorkflowRunKey } from './locales.ts'
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface LocaleNamespaceMap {
/** Durable workflow-run node copy. */

View File

@@ -24,7 +24,6 @@ export interface WorkflowRunPhaseData {
readonly key: string
/** `null` is the absent field; the empty string remains a distinct identity. */
readonly phase: string | null
readonly status: WorkflowRunStatus
readonly members: readonly WorkflowRunMemberData[]
}
@@ -32,7 +31,6 @@ export interface WorkflowRunPhaseData {
export interface WorkflowRunChatData {
readonly name: string
readonly status: WorkflowRunStatus
readonly memberCount: number
readonly phases: readonly WorkflowRunPhaseData[]
}
@@ -43,7 +41,7 @@ declare module '@deepseek-ai/dsh-client-ui-conversation/client' {
}
}
interface WorkflowMemberState extends ToolWorkflowAgentStartData {
interface WorkflowMemberState extends Omit<ToolWorkflowAgentStartData, 'runId'> {
readonly outcome?: WorkflowAgentOutcome
}
@@ -90,14 +88,6 @@ function locationClosed(location: ConversationLocation | undefined): boolean {
return location.kind === 'turn' && location.turn.status === 'closed'
}
function aggregateStatus(members: readonly WorkflowRunMemberData[]): WorkflowRunStatus {
if (members.some(member => member.status === 'running')) return 'running'
if (members.some(member => member.status === 'failed')) return 'failed'
if (members.some(member => member.status === 'cancelled')) return 'cancelled'
if (members.some(member => member.status === 'interrupted')) return 'interrupted'
return 'completed'
}
function projectWorkflow(
context: ConversationNodeContext<WorkflowState>,
): WorkflowRunChatData | undefined {
@@ -126,7 +116,6 @@ function projectWorkflow(
const projectedPhases = [...phases].map(([key, phase]) => ({
key,
phase: phase.phase,
status: aggregateStatus(phase.members),
members: phase.members,
}))
return {
@@ -134,13 +123,18 @@ function projectWorkflow(
status: state.stopReason === undefined
? interrupted ? 'interrupted' : 'running'
: statusFromStopReason(state.stopReason),
memberCount: state.members.length,
phases: projectedPhases,
}
}
function updateAgentStart(state: WorkflowState, data: ToolWorkflowAgentStartData): WorkflowState {
return { ...state, members: [...state.members, data] }
const member: WorkflowMemberState = {
seq: data.seq,
label: data.label,
...data.phase === undefined ? {} : { phase: data.phase },
childId: data.childId,
}
return { ...state, members: [...state.members, member] }
}
function updateAgentEnd(state: WorkflowState, data: ToolWorkflowAgentEndData): WorkflowState {

View File

@@ -107,14 +107,13 @@ describe('workflow-run Conversation Definition', () => {
expect(data).toEqual({
name: 'audit',
status: 'failed',
memberCount: 2,
phases: [
{
key: 'value:0:', phase: '', status: 'completed',
key: 'value:0:', phase: '',
members: [{ seq: 1, label: 'first', childId: 'child-1', status: 'completed' }],
},
{
key: 'missing', phase: null, status: 'failed',
key: 'missing', phase: null,
members: [{ seq: 2, label: 'second', childId: 'child-2', status: 'failed' }],
},
],
@@ -167,7 +166,7 @@ describe('workflow-run Conversation Definition', () => {
at(4, 'tool-workflow/run-end', { runId: 'empty', stopReason: 'completed' }),
])
expect(workflowData(value)).toEqual({
name: 'empty', status: 'completed', memberCount: 0, phases: [],
name: 'empty', status: 'completed', phases: [],
})
})
@@ -187,7 +186,7 @@ describe('workflow-run Conversation Definition', () => {
])
expect(workflowData(cancelled)).toMatchObject({
status: 'cancelled',
phases: [{ phase: 'Research', status: 'cancelled', members: [{ status: 'cancelled' }, { status: 'completed' }] }],
phases: [{ phase: 'Research', members: [{ status: 'cancelled' }, { status: 'completed' }] }],
})
const interruptedTurn = assembler([
@@ -254,7 +253,6 @@ function node(data: WorkflowRunChatData): WorkflowRunPanelProps['node'] {
const phase = (overrides: Partial<WorkflowRunChatData['phases'][number]> = {}): WorkflowRunChatData['phases'][number] => ({
key: 'missing',
phase: null,
status: 'running',
members: [{ seq: 1, label: 'worker', childId: 'child-1' as SessionId, status: 'running' }],
...overrides,
})
@@ -303,7 +301,7 @@ function panelProps(data: WorkflowRunChatData, sessions = listState(), openSessi
describe('WorkflowRunPanel', () => {
it('defaults running runs open, terminal history closed, and keeps the current choice across data updates', () => {
const running: WorkflowRunChatData = {
name: 'audit', status: 'running', memberCount: 1, phases: [phase()],
name: 'audit', status: 'running', phases: [phase()],
}
const view = render(<WorkflowRunPanel {...panelProps(running)} />)
expect(screen.getByText('未分阶段')).toBeTruthy()
@@ -321,7 +319,7 @@ describe('WorkflowRunPanel', () => {
it('supports root keyboard disclosure and renders a zero-member running state', () => {
render(<WorkflowRunPanel {...panelProps({
name: 'keyboard', status: 'running', memberCount: 1,
name: 'keyboard', status: 'running',
phases: [phase({ key: 'research', phase: 'Research' })],
})} />)
const header = screen.getByRole('button', { name: /^keyboard/ })
@@ -344,14 +342,14 @@ describe('WorkflowRunPanel', () => {
cleanup()
render(<WorkflowRunPanel {...panelProps({
name: 'empty', status: 'running', memberCount: 0, phases: [],
name: 'empty', status: 'running', phases: [],
})} />)
expect(screen.getByText('没有启动成员')).toBeTruthy()
})
it('keeps phase disclosure independent and preserves empty versus absent names', () => {
render(<WorkflowRunPanel {...panelProps({
name: 'audit', status: 'running', memberCount: 2,
name: 'audit', status: 'running',
phases: [
phase({ key: 'value:0:', phase: '', members: [{
seq: 1, label: '', childId: 'child-1' as SessionId, status: 'running',
@@ -373,9 +371,8 @@ describe('WorkflowRunPanel', () => {
it('covers the Figma completed, failed/cancelled, and interrupted state boards', () => {
const completed: WorkflowRunChatData = {
name: 'repo-audit', status: 'completed', memberCount: 1,
name: 'repo-audit', status: 'completed',
phases: [phase({
status: 'completed',
members: [{ seq: 1, label: 'done', childId: 'child-1' as SessionId, status: 'completed' }],
})],
}
@@ -387,9 +384,8 @@ describe('WorkflowRunPanel', () => {
completedView.unmount()
const mixed: WorkflowRunChatData = {
name: 'repo-audit', status: 'failed', memberCount: 2,
name: 'repo-audit', status: 'failed',
phases: [phase({
status: 'failed',
members: [
{ seq: 1, label: 'failed', childId: 'child-1' as SessionId, status: 'failed' },
{ seq: 2, label: 'cancelled', childId: 'child-2' as SessionId, status: 'cancelled' },
@@ -407,17 +403,16 @@ describe('WorkflowRunPanel', () => {
mixedView.unmount()
const interrupted: WorkflowRunChatData = {
name: 'repo-audit', status: 'interrupted', memberCount: 2,
name: 'repo-audit', status: 'interrupted',
phases: [
phase({
status: 'interrupted',
members: [
{ seq: 1, label: 'done', childId: 'child-1' as SessionId, status: 'completed' },
{ seq: 2, label: 'interrupted', childId: 'child-2' as SessionId, status: 'interrupted' },
],
}),
phase({
key: 'interrupted-only', phase: 'Interrupted only', status: 'interrupted',
key: 'interrupted-only', phase: 'Interrupted only',
members: [{
seq: 3, label: 'interrupted', childId: 'child-3' as SessionId, status: 'interrupted',
}],
@@ -433,7 +428,7 @@ describe('WorkflowRunPanel', () => {
it('opens only a running ordinary-list subagent proven to have this parent', () => {
const data: WorkflowRunChatData = {
name: 'audit', status: 'running', memberCount: 1, phases: [phase()],
name: 'audit', status: 'running', phases: [phase()],
}
const openSession = vi.fn()
render(<WorkflowRunPanel {...panelProps(data, listState(), openSession)} />)
@@ -459,9 +454,8 @@ describe('WorkflowRunPanel', () => {
['member terminal', listState(), 'completed'],
] as const)('does not navigate when %s', (_name, sessions, memberStatus) => {
const data: WorkflowRunChatData = {
name: 'audit', status: 'running', memberCount: 1,
name: 'audit', status: 'running',
phases: [phase({
status: memberStatus === 'running' ? 'running' : 'completed',
members: [{
seq: 1, label: 'worker', childId: 'child-1' as SessionId, status: memberStatus,
}],

View File

@@ -17,8 +17,7 @@ import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import type { JsonValue, Session, SessionEventMap } from '@deepseek-ai/dsh-session'
import type {
WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowResult, WorkflowRun,
WorkflowRunId, WorkflowRunInfo, WorkflowStopReason,
WorkflowResult, WorkflowRun, WorkflowRunId, WorkflowStopReason,
} from '@deepseek-ai/dsh-workflow'
import type {
ToolWorkflowAgentEndData, ToolWorkflowAgentStartData,
@@ -45,14 +44,10 @@ export const Config: z<Config> = z.object({
type ResolvedConfig = Required<Config>
type BufferedWorkflowEvent =
| { readonly kind: 'agent-start'; readonly info: WorkflowRunInfo; readonly agent: WorkflowAgentInfo }
| { readonly kind: 'agent-end'; readonly info: WorkflowRunInfo; readonly agent: WorkflowAgentEndInfo }
interface WorkflowRecorder {
bind(run: WorkflowRun): void
finish(stopReason: WorkflowStopReason): void
dispose(): void
start(session: Session, run: WorkflowRun): void
finish(runId: WorkflowRunId, stopReason: WorkflowStopReason): void
abandon(runId: WorkflowRunId): void
}
interface ToolWorkflowRecordEventMap {
@@ -72,84 +67,66 @@ function renderRecordingError(error: unknown): string {
}
/**
* Project one top-level workflow run into its parent Session without letting
* recording failure affect tool execution. Listeners are installed before
* `start()` so even a synchronous provider cannot outrun the recorder.
* Project active top-level workflow runs into their parent Sessions without
* letting recording failure affect tool execution.
*/
function createWorkflowRecorder(ctx: Context, session: Session): WorkflowRecorder {
let runId: WorkflowRunId | undefined
let enabled = true
const buffered: BufferedWorkflowEvent[] = []
// These four package-owned events are all log-only. Narrowing the generic
// append face here lets TypeScript discharge Session.append's conditional
// surface-options tuple once for the complete closed event set.
const appendRecord = session.append.bind(session) as <Type extends keyof ToolWorkflowRecordEventMap>(
type: Type,
data: SessionEventMap[Type],
) => void
function createWorkflowRecorder(ctx: Context): WorkflowRecorder {
const active = new Map<WorkflowRunId, Session>()
const append = <Type extends keyof ToolWorkflowRecordEventMap>(
session: Session,
type: Type,
data: SessionEventMap[Type],
): void => {
if (!enabled) return
): boolean => {
// These four package-owned events are all log-only. Narrowing the generic
// append face here discharges Session.append's conditional options tuple.
const appendRecord = session.append.bind(session) as <Event extends keyof ToolWorkflowRecordEventMap>(
event: Event,
value: SessionEventMap[Event],
) => void
try {
appendRecord(type, data)
return true
} catch (error: unknown) {
enabled = false
ctx.logger.warn(`tool-workflow: disabled durable record after ${type} append failed: ${renderRecordingError(error)}`)
return false
}
}
const record = (event: BufferedWorkflowEvent): void => {
if (runId === undefined) {
buffered.push(event)
return
ctx.on('workflow/agent-start', (info, agent) => {
const session = active.get(info.id)
if (session === undefined) return
const data: ToolWorkflowAgentStartData = {
runId: info.id,
seq: agent.seq,
label: agent.label,
...agent.phase === undefined ? {} : { phase: agent.phase },
childId: agent.childId,
}
if (event.info.id !== runId) return
if (event.kind === 'agent-start') {
const data: ToolWorkflowAgentStartData = {
runId,
seq: event.agent.seq,
label: event.agent.label,
...event.agent.phase === undefined ? {} : { phase: event.agent.phase },
childId: event.agent.childId,
}
append('tool-workflow/agent-start', data)
return
}
const data: ToolWorkflowAgentEndData = {
runId,
seq: event.agent.seq,
outcome: event.agent.outcome,
}
append('tool-workflow/agent-end', data)
}
const disposeStart = ctx.on('workflow/agent-start', (info, agent) => {
record({ kind: 'agent-start', info, agent })
if (!append(session, 'tool-workflow/agent-start', data)) active.delete(info.id)
})
const disposeEnd = ctx.on('workflow/agent-end', (info, agent) => {
record({ kind: 'agent-end', info, agent })
ctx.on('workflow/agent-end', (info, agent) => {
const session = active.get(info.id)
if (session === undefined) return
const data: ToolWorkflowAgentEndData = {
runId: info.id,
seq: agent.seq,
outcome: agent.outcome,
}
if (!append(session, 'tool-workflow/agent-end', data)) active.delete(info.id)
})
return {
bind(run) {
runId = run.id
append('tool-workflow/run-start', { runId, name: run.meta.name })
for (const event of buffered) record(event)
buffered.length = 0
start(session, run) {
if (append(session, 'tool-workflow/run-start', { runId: run.id, name: run.meta.name })) {
active.set(run.id, session)
}
},
finish(stopReason) {
/* v8 ignore next -- execute binds every returned run before result settlement can call finish. */
if (runId === undefined) return
append('tool-workflow/run-end', { runId, stopReason })
},
dispose() {
disposeStart()
disposeEnd()
buffered.length = 0
finish(runId, stopReason) {
const session = active.get(runId)
if (session !== undefined) append(session, 'tool-workflow/run-end', { runId, stopReason })
active.delete(runId)
},
abandon: (runId) => { active.delete(runId) },
}
}
@@ -229,6 +206,7 @@ export function apply(ctx: Context, config: Config): void {
// schemastery (the exported Config schema) has already filled the defaulted
// fields; the assertion records that resolution, not a hidden fallback.
const { toolName, maxResultChars } = config as ResolvedConfig
const recorder = createWorkflowRecorder(ctx)
// Usage policy ships with the tool (the master convention: tool guidance
// lives in tool plugins as prompt sections, not in the deployment persona).
ctx.systemPrompt.section({
@@ -303,23 +281,15 @@ export function apply(ctx: Context, config: Config): void {
// Meta/body validation failures (META_INVALID/SCRIPT_PARSE) throw
// synchronously here and become isError results via the registry — the
// model sees the violation list and can correct the call.
const recorder = exec.parent === undefined
? createWorkflowRecorder(ctx, parent.session)
: undefined
let run: WorkflowRun
try {
run = ctx.workflows.start({
script: args.script,
meta: args.meta,
...args.args !== undefined ? { args: args.args } : {},
parent,
signal: exec.signal,
})
} catch (error: unknown) {
recorder?.dispose()
throw error
}
recorder?.bind(run)
const run = ctx.workflows.start({
script: args.script,
meta: args.meta,
...args.args !== undefined ? { args: args.args } : {},
parent,
signal: exec.signal,
})
const recordsRun = exec.parent === undefined
if (recordsRun) recorder.start(parent.session, run)
// Bridge the tool's abort signal to the run: if the parent step is aborted while the
// script is in flight, cancel the whole run. The signal also enters the engine directly, but
@@ -348,9 +318,9 @@ export function apply(ctx: Context, config: Config): void {
// synthesize cancelled member endings while reaching quiescence.
await run.dispose()
/* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */
if (result !== undefined) recorder?.finish(result.stopReason)
if (recordsRun && result !== undefined) recorder.finish(run.id, result.stopReason)
} finally {
recorder?.dispose()
if (recordsRun) recorder.abandon(run.id)
}
}
},

View File

@@ -19,12 +19,9 @@ interface RunTrace {
type WorkflowTrace = Map<string, RunTrace>
/** Clone the independent fold before validating one candidate append. */
function cloneTrace(source: WorkflowTrace): WorkflowTrace {
return new Map([...source].map(([runId, run]) => [runId, {
ended: run.ended,
members: new Map(run.members),
}]))
/** Whether this package owns the candidate Session event. */
function isWorkflowRecordEvent(event: SessionEvent): boolean {
return event.type.startsWith('tool-workflow/')
}
/** Require a durable opaque identity to be a non-empty string. */
@@ -50,6 +47,23 @@ function recordOf(event: SessionEvent, fail: InvariantFailure): Record<string, u
return data as Record<string, unknown>
}
/** Copy only the run one candidate can mutate; other committed states stay shared. */
function cloneTraceForEvent(
source: WorkflowTrace,
event: SessionEvent,
fail: InvariantFailure,
): WorkflowTrace {
const trace = new Map(source)
if (event.type === 'tool-workflow/run-start') return trace
const data = recordOf(event, fail)
const runId = stringId(data.runId, `${event.type} runId`, fail)
const run = source.get(runId)
if (run !== undefined) {
trace.set(runId, { ended: run.ended, members: new Map(run.members) })
}
return trace
}
/** Require the named run to exist and remain open. */
function openRun(trace: WorkflowTrace, runId: string, eventType: string, fail: InvariantFailure): RunTrace {
const run = trace.get(runId)
@@ -60,7 +74,6 @@ function openRun(trace: WorkflowTrace, runId: string, eventType: string, fail: I
/** Advance the workflow-record fold with one relevant Session event. */
function applyEvent(trace: WorkflowTrace, event: SessionEvent, fail: InvariantFailure): void {
if (!event.type.startsWith('tool-workflow/')) return
const data = recordOf(event, fail)
const runId = stringId(data.runId, `${event.type} runId`, fail)
@@ -107,6 +120,7 @@ function applyEvent(trace: WorkflowTrace, event: SessionEvent, fail: InvariantFa
fail(`tool-workflow/run-end leaves member seq ${openMembers.join(', ')} open in run ${runId}`)
}
run.ended = true
run.members.clear()
return
}
default:
@@ -126,23 +140,23 @@ const install: InvariantInstaller = Object.assign((ctx: Context, fail: Invariant
const seed = (session: Session): WorkflowTrace => {
const trace: WorkflowTrace = new Map()
for (const event of session.events) applyChecked(trace, event, fail)
for (const event of session.events.filter(isWorkflowRecordEvent)) applyChecked(trace, event, fail)
traces.set(session, trace)
return trace
}
/* v8 ignore next -- session/event always follows list() or session/created seeding. */
const traceFor = (session: Session): WorkflowTrace => traces.get(session) ?? seed(session)
for (const session of ctx.sessions.list()) seed(session)
ctx.sessions.list().forEach(seed)
ctx.on('session/created', (session) => { seed(session) }, { global: true })
ctx.on('internal/dispatch', (_mode, eventName, args) => {
if (eventName !== 'session/event') return
const [session, event] = args as [Session, SessionEvent]
const trace = cloneTrace(traceFor(session))
if (!isWorkflowRecordEvent(event)) return
// session/event dispatch follows list() or session/created seeding.
const trace = cloneTraceForEvent(traces.get(session) as WorkflowTrace, event, fail)
applyChecked(trace, event, fail)
staged.set(event, { session, trace })
}, { global: true })
ctx.on('session/event', (session, event) => {
if (!isWorkflowRecordEvent(event)) return
const candidate = staged.get(event)
/* v8 ignore next 2 -- internal/dispatch stages the exact session/event callback arguments. */
if (candidate === undefined || candidate.session !== session) {

View File

@@ -27,7 +27,6 @@ class StubEngine extends WorkflowService {
settle!: (result: WorkflowResult) => void
readonly settlements = new Map<WorkflowRunIdType, (result: WorkflowResult) => void>()
startError: Error | undefined
emitMemberDuringStart = false
start(request: WorkflowStartRequest): WorkflowRun {
if (this.startError) throw this.startError
@@ -35,12 +34,6 @@ class StubEngine extends WorkflowService {
const id = WorkflowRunId(`run-${this.requests.length}`)
const result = new Promise<WorkflowResult>((resolve) => { this.settle = resolve })
this.settlements.set(id, this.settle)
if (this.emitMemberDuringStart) {
const info = { id, meta: request.meta }
const member = { seq: 1, label: 'synchronous', childId: SessionId('sync-child') }
this.emitWorkflowEvent('workflow/agent-start', info, member)
this.emitWorkflowEvent('workflow/agent-end', info, { ...member, outcome: 'completed' })
}
request.signal?.addEventListener('abort', () => {
this.settle({ value: null, stopReason: 'cancelled', error: 'signal', agentsStarted: 0 })
}, { once: true })
@@ -205,23 +198,6 @@ describe('dsh-tool-workflow', () => {
])
})
it('buffers synchronous member events until start returns the run identity', async () => {
const { ctx, engine, parent, session } = await setup()
engine.emitMemberDuringStart = true
const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
engine.settleRun(WorkflowRunId('run-1'), {
value: null, stopReason: 'completed', agentsStarted: 1,
})
expect((await pending).isError).toBe(false)
expect(session.events.map(event => event.type)).toEqual([
'tool-workflow/run-start',
'tool-workflow/agent-start',
'tool-workflow/agent-end',
'tool-workflow/run-end',
])
})
it('does not record nested transport executions', async () => {
const { ctx, engine, parent, session } = await setup()
const pending = execute(ctx, { script: SCRIPT, meta: META }, {