diff --git a/docs/screenshots/pr-425/after-cancelled-run.png b/docs/screenshots/pr-425/after-cancelled-run.png new file mode 100644 index 00000000..2ce153a9 Binary files /dev/null and b/docs/screenshots/pr-425/after-cancelled-run.png differ diff --git a/docs/screenshots/pr-425/before-cancelled-run.png b/docs/screenshots/pr-425/before-cancelled-run.png new file mode 100644 index 00000000..12b64e3f Binary files /dev/null and b/docs/screenshots/pr-425/before-cancelled-run.png differ diff --git a/packages/i18n/src/locales/en-US/trace.ts b/packages/i18n/src/locales/en-US/trace.ts index 8481eb90..6d03f5a6 100644 --- a/packages/i18n/src/locales/en-US/trace.ts +++ b/packages/i18n/src/locales/en-US/trace.ts @@ -89,6 +89,7 @@ export const trace = { footer: { completed: 'Completed · {{seconds}}s · {{steps}} steps', failed: 'Failed · {{tools}} tools', + cancelled: 'Cancelled · {{tools}} tools', stopped: 'Stopped early · {{reason}} · {{tools}} tools{{detail}}', stopReasons: { budget_exhausted: 'budget exhausted', diff --git a/packages/i18n/src/locales/zh-CN/trace.ts b/packages/i18n/src/locales/zh-CN/trace.ts index 19cb0428..7b0f2cd0 100644 --- a/packages/i18n/src/locales/zh-CN/trace.ts +++ b/packages/i18n/src/locales/zh-CN/trace.ts @@ -86,6 +86,7 @@ export const trace = { footer: { completed: '已完成 · {{seconds}} 秒 · {{steps}} 个步骤', failed: '失败 · {{tools}} 个工具', + cancelled: '已取消 · {{tools}} 个工具', stopped: '已提前停止 · {{reason}} · {{tools}} 个工具{{detail}}', stopReasons: { budget_exhausted: '运行预算耗尽', diff --git a/packages/ui/src/atoms/runAtoms.ts b/packages/ui/src/atoms/runAtoms.ts index 2f061cee..30ee052e 100644 --- a/packages/ui/src/atoms/runAtoms.ts +++ b/packages/ui/src/atoms/runAtoms.ts @@ -59,6 +59,7 @@ export interface GuardStopDetail { signal?: string; tool?: string; count?: number; + retriesInWindow?: number; } /** diff --git a/packages/ui/src/components/agent/AgentPanel.tsx b/packages/ui/src/components/agent/AgentPanel.tsx index 77efd27e..4706cc4a 100644 --- a/packages/ui/src/components/agent/AgentPanel.tsx +++ b/packages/ui/src/components/agent/AgentPanel.tsx @@ -2,7 +2,7 @@ import React, { useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { ArrowUp, ChevronLeft, ChevronRight, Square, Sparkles } from 'lucide-react'; import { useAtom, useAtomValue, useSetAtom } from 'jotai'; -import type { ApiError, FolioTrace, PortfolioSnapshot, Quote, ToolCall } from '@finagent/core'; +import type { ApiError, FolioTrace, PortfolioSnapshot, Quote, Run, StopReason, ToolCall } from '@finagent/core'; import { activeMessagesAtom, activeSessionIdAtom, @@ -380,28 +380,59 @@ export const AgentPanel: React.FC = () => { * Completed/failed run footer with the secondary Trace affordance (V9.1 §12). * The semantic activity above remains the primary experience. */ -const RunFooter: React.FC<{ +export const RunFooter: React.FC<{ lastRun: LastRunSummary | null; activeSessionId: string | null; onOpenTrace: () => void; }> = ({ lastRun, activeSessionId, onOpenTrace }) => { const { t } = useTranslation(); + const client = useFinagentClient(); + // #17: a guard stop writes its stop_reason only onto the persisted Run record + // — the event stream carries RUN_CANCELLED for every safeguard stop — so once + // the run settles, read the record back and surface why it actually stopped. + const [persistedStop, setPersistedStop] = useState | null>(null); + const terminal = lastRun !== null && lastRun.status !== 'running' && lastRun.sessionId === activeSessionId; + useEffect(() => { + if (!terminal || !lastRun) { + setPersistedStop(null); + return; + } + let released = false; + void client.kernel + .listRuns(lastRun.sessionId) + .then((result) => { + if (released || !result.ok) return; + const run = result.data.find((candidate) => candidate.id === lastRun.runId); + if (run) setPersistedStop({ stopReason: run.stopReason, stopDetail: run.stopDetail }); + }) + .catch(() => undefined); + return () => { + released = true; + }; + }, [terminal, lastRun?.runId, lastRun?.sessionId, client]); if (!lastRun || lastRun.status === 'running' || lastRun.sessionId !== activeSessionId) return null; const durationSec = lastRun.completedAt != null && lastRun.completedAt >= lastRun.startedAt ? Math.max(0, Math.round((lastRun.completedAt - lastRun.startedAt) / 100) / 10) : undefined; const failed = lastRun.status === 'failed'; - const stopReason = isGuardStopReason(lastRun.stopReason) ? lastRun.stopReason : undefined; + // The event-stream projection can never carry a guard stop reason (every + // safeguard stop surfaces as RUN_CANCELLED), so the persisted record wins. + const stopReason = isGuardStopReason(lastRun.stopReason ?? persistedStop?.stopReason) + ? (lastRun.stopReason ?? persistedStop?.stopReason)! + : undefined; + const stopDetail = lastRun.stopDetail ?? persistedStop?.stopDetail; const summary = stopReason ? t('trace.footer.stopped', { reason: t(`trace.footer.stopReasons.${stopReason}`), - detail: formatStopDetail(lastRun.stopDetail), + detail: formatStopDetail(stopDetail), tools: lastRun.toolCount, }) : failed ? t('trace.footer.failed', { tools: lastRun.toolCount }) - : t('trace.footer.completed', { seconds: durationSec ?? 0, steps: lastRun.toolCount }); + : lastRun.status === 'cancelled' + ? t('trace.footer.cancelled', { tools: lastRun.toolCount }) + : t('trace.footer.completed', { seconds: durationSec ?? 0, steps: lastRun.toolCount }); return (
(['budget_exhausted', 'loop_detected', 'retry_storm']); +const GUARD_STOP_REASONS = new Set(['budget_exhausted', 'loop_detected', 'retry_storm']); -function isGuardStopReason(reason: LastRunSummary['stopReason']): reason is GuardStopReason { +function isGuardStopReason(reason: StopReason | undefined): reason is GuardStopReason { return reason !== undefined && GUARD_STOP_REASONS.has(reason); } @@ -436,6 +467,9 @@ function formatStopDetail(detail: LastRunSummary['stopDetail']): string { if (detail?.tool && detail.count !== undefined) { return ` · ${detail.tool} ×${detail.count}`; } + if (detail?.retriesInWindow !== undefined) { + return ` · ${detail.retriesInWindow} retries`; + } return ''; } /** diff --git a/packages/ui/src/components/agent/RunFooter.test.tsx b/packages/ui/src/components/agent/RunFooter.test.tsx new file mode 100644 index 00000000..94a1cd05 --- /dev/null +++ b/packages/ui/src/components/agent/RunFooter.test.tsx @@ -0,0 +1,151 @@ +import { afterAll, beforeAll, describe, expect, it } from 'bun:test'; +import React, { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import type { Run } from '@finagent/core'; +import { installHappyDom } from '../../test/setupHappyDom'; +import { withI18n } from '../../test/i18n'; +import { FinagentClientProvider, fallbackClient, type FinagentClient } from '../../client'; +import { RunFooter } from './AgentPanel'; + +let restoreDom: (() => void) | undefined; + +beforeAll(() => { + restoreDom = installHappyDom().restore; +}); + +afterAll(() => { + restoreDom?.(); +}); + +const baseRun: Run = { + id: 'run-1', + sessionId: 's1', + status: 'cancelled', + input: 'q', + startedAt: 1_700_000_000_000, + completedAt: 1_700_000_001_000, +}; + +function lastRun(overrides: Partial[0]['lastRun']> & { status?: 'completed' | 'failed' | 'cancelled' }) { + return { + runId: 'run-1', + sessionId: 's1', + status: 'cancelled' as const, + startedAt: 1_700_000_000_000, + completedAt: 1_700_000_001_000, + toolCount: 2, + workspaceContext: undefined, + ...overrides, + }; +} + +function clientWithRuns(runs: Run[]): FinagentClient { + return { + ...fallbackClient, + kernel: { + ...fallbackClient.kernel, + listRuns: async () => ({ ok: true as const, data: runs }), + }, + }; +} + +async function renderFooter(container: HTMLElement, root: ReturnType, props: { lastRun: ReturnType; runs?: Run[] }) { + const client = clientWithRuns(props.runs ?? []); + await act(async () => { + root.render( + withI18n( + + undefined} /> + + ) + ); + }); + // The footer reads the persisted run back asynchronously; flush the effect. + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); +} + +describe('RunFooter stop-reason display (#17)', () => { + it('renders a plain cancelled run without claiming it completed', async () => { + const container = document.createElement('div'); + const root = createRoot(container); + await renderFooter(container, root, { + lastRun: lastRun({}), + runs: [{ ...baseRun, stopReason: undefined }], + }); + + const footer = container.querySelector('[data-testid="run-footer"]'); + expect(footer?.textContent).toContain('Cancelled · 2 tools'); + expect(footer?.textContent).not.toContain('Completed'); + root.unmount(); + }); + + it('surfaces a persisted budget stop from the run record', async () => { + const container = document.createElement('div'); + const root = createRoot(container); + await renderFooter(container, root, { + lastRun: lastRun({}), + runs: [ + { + ...baseRun, + stopReason: 'budget_exhausted', + stopDetail: { key: 'modelCalls', limit: 1, used: 1 }, + }, + ], + }); + + const footer = container.querySelector('[data-testid="run-footer"]'); + expect(footer?.textContent).toContain('Stopped early · budget exhausted · 2 tools · modelCalls 1/1'); + root.unmount(); + }); + + it('surfaces a persisted retry storm with its evidence', async () => { + const container = document.createElement('div'); + const root = createRoot(container); + await renderFooter(container, root, { + lastRun: lastRun({}), + runs: [ + { + ...baseRun, + stopReason: 'retry_storm', + stopDetail: { signal: 'retry_storm', retriesInWindow: 3, windowMs: 60_000 }, + }, + ], + }); + + const footer = container.querySelector('[data-testid="run-footer"]'); + expect(footer?.textContent).toContain('Stopped early · too many retries · 2 tools · 3 retries'); + root.unmount(); + }); + + it('prefers a guard stop carried by the event projection over the record', async () => { + const container = document.createElement('div'); + const root = createRoot(container); + await renderFooter(container, root, { + lastRun: lastRun({ + stopReason: 'loop_detected', + stopDetail: { signal: 'repeated_tool_call', tool: 'get_quote', count: 2 }, + }), + runs: [{ ...baseRun, stopReason: 'cancelled' }], + }); + + const footer = container.querySelector('[data-testid="run-footer"]'); + expect(footer?.textContent).toContain('Stopped early · loop detected · 2 tools · get_quote ×2'); + root.unmount(); + }); + + it('keeps the completed footer for ordinary runs', async () => { + const container = document.createElement('div'); + const root = createRoot(container); + await renderFooter(container, root, { + lastRun: lastRun({ status: 'completed' }), + runs: [{ ...baseRun, status: 'completed', stopReason: 'completed' }], + }); + + const footer = container.querySelector('[data-testid="run-footer"]'); + expect(footer?.textContent).toContain('Completed ·'); + expect(footer?.textContent).not.toContain('Cancelled'); + root.unmount(); + }); +});