import type { LoopEvent } from '../types.js'; export interface WorkflowPresentation { branches?: Record; milestones?: string[]; outcome?: string; pluginId: string; runId?: string; current?: number; max?: number; message?: string; action?: string; summary?: string; nextAction?: string; completed?: boolean; } export function isWorkflowMilestone(e: Extract): boolean { return !['model', 'agent-tool', 'tool', 'process'].includes(e.phase) || !!e.summary || !!e.nextAction; } export function projectWorkflowProgress(previous: WorkflowPresentation | null, e: Extract): WorkflowPresentation { const message = e.message ?? e.phase; const nested = e.runId !== e.rootRunId; const restarting = !nested && e.phase === 'workflow' && e.status === 'start'; const sameRun = previous?.runId === e.rootRunId && !restarting; // Late heartbeats must not reopen a terminal run or branch. if (sameRun && previous?.completed) return previous; if (nested && sameRun && previous?.branches?.[e.runId]?.outcome && !(e.phase === 'workflow' && e.status === 'start')) return previous; const branch = { name: e.workflow, parentRunId: e.parentRunId, message, outcome: e.outcome ?? (e.phase === 'workflow' && e.status === 'complete' ? 'succeeded' : undefined) }; if (nested) return { ...(sameRun ? previous : { pluginId: e.workflow, runId: e.rootRunId }), action: `${e.workflow}:${message}`, branches: { ...(sameRun ? previous?.branches : {}), [e.runId]: branch }, }; const milestone = isWorkflowMilestone(e); return { ...(sameRun && !(e.phase === 'workflow' && e.status === 'start') ? previous : {}), pluginId: e.workflow, runId: e.runId, ...(milestone ? { message, current: e.current, max: e.total, summary: e.summary, nextAction: e.nextAction, action: undefined } : { action: message }), milestones: milestone ? [...(sameRun ? previous?.milestones ?? [] : []), message].filter((value, index, list) => index === 0 || value !== list[index - 1]).slice(-50) : (sameRun ? previous?.milestones : undefined), outcome: e.outcome ?? (e.phase === 'workflow' && e.status === 'complete' ? 'succeeded' : undefined), completed: !!e.outcome || (e.phase === 'workflow' && e.status === 'complete'), }; } /** Legacy plugin messages may be emitted inside a structured workflow. Keep its * identity and branches; an unstructured message is only the latest action. */ export function projectPluginProgress(previous: WorkflowPresentation | null, e: Extract): WorkflowPresentation { if (previous?.runId) return previous.completed ? previous : { ...previous, action: e.message ?? previous.action }; return { pluginId: e.pluginId, current: e.current, max: e.max, message: e.message }; } export const workflowOutcomeLabel = (outcome?: string): string => ({ succeeded: '执行完成', failed: '执行失败', stopped: '已停止', budget_limited: '预算已用尽', usage_limited: '用量受限' }[outcome ?? ''] ?? '执行中');