Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added docs/screenshots/pr-425/after-cancelled-run.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/screenshots/pr-425/before-cancelled-run.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions packages/i18n/src/locales/en-US/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
1 change: 1 addition & 0 deletions packages/i18n/src/locales/zh-CN/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export const trace = {
footer: {
completed: '已完成 · {{seconds}} 秒 · {{steps}} 个步骤',
failed: '失败 · {{tools}} 个工具',
cancelled: '已取消 · {{tools}} 个工具',
stopped: '已提前停止 · {{reason}} · {{tools}} 个工具{{detail}}',
stopReasons: {
budget_exhausted: '运行预算耗尽',
Expand Down
1 change: 1 addition & 0 deletions packages/ui/src/atoms/runAtoms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export interface GuardStopDetail {
signal?: string;
tool?: string;
count?: number;
retriesInWindow?: number;
}

/**
Expand Down
48 changes: 41 additions & 7 deletions packages/ui/src/components/agent/AgentPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<Pick<Run, 'stopReason' | 'stopDetail'> | 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 (
<div
data-testid="run-footer"
Expand All @@ -423,9 +454,9 @@ const RunFooter: React.FC<{
);
};

const GUARD_STOP_REASONS = new Set<GuardStopReason>(['budget_exhausted', 'loop_detected', 'retry_storm']);
const GUARD_STOP_REASONS = new Set<string>(['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);
}

Expand All @@ -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 '';
}
/**
Expand Down
151 changes: 151 additions & 0 deletions packages/ui/src/components/agent/RunFooter.test.tsx
Original file line number Diff line number Diff line change
@@ -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<Parameters<typeof RunFooter>[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<typeof createRoot>, props: { lastRun: ReturnType<typeof lastRun>; runs?: Run[] }) {
const client = clientWithRuns(props.runs ?? []);
await act(async () => {
root.render(
withI18n(
<FinagentClientProvider client={client}>
<RunFooter lastRun={props.lastRun} activeSessionId="s1" onOpenTrace={() => undefined} />
</FinagentClientProvider>
)
);
});
// 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();
});
});