Skip to content

Commit 4b133ff

Browse files
johnnyhuycodex
andauthored
fix: distinguish interrupted tool calls from completion (#48)
Co-authored-by: OpenAI Codex <[email protected]>
1 parent f122358 commit 4b133ff

11 files changed

Lines changed: 185 additions & 18 deletions

File tree

‎src/renderer/components/WorkbenchControls.tsx‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
import { BracketButton } from './BracketButton';
99
import { FigureFrame } from './FigureFrame';
1010
import { Markdown } from './Markdown';
11-
import type { Entry } from '../timeline';
11+
import { toolStatus, type Entry } from '../timeline';
1212
import type { ModelInfo, SlashCommand } from '../api';
1313

1414
const icons = import.meta.glob<string>('../assets/workbench/*.svg', {
@@ -446,7 +446,7 @@ export const TranscriptRow = memo(function TranscriptRow({
446446
? 'activity-terminal'
447447
: entry.tool === 'read'
448448
? 'file'
449-
: entry.ok
449+
: entry.ok && !entry.interrupted
450450
? 'check'
451451
: 'file'
452452
}
@@ -455,10 +455,14 @@ export const TranscriptRow = memo(function TranscriptRow({
455455
{entry.tool}
456456
{entry.args ? ` / ${entry.args}` : ''}
457457
</span>
458-
<small>
459-
{entry.running ? 'Running' : entry.ok ? 'Done' : 'Failed'}
460-
</small>
458+
<small>{toolStatus(entry)}</small>
461459
</summary>
460+
{entry.interrupted && (
461+
<p className="wb-tool-notice wb-muted">
462+
No completion result was recorded. The tool may have made changes;
463+
check before retrying.
464+
</p>
465+
)}
462466
{entry.oldText !== undefined || entry.newText !== undefined ? (
463467
<ToolDiffSection
464468
text={entry.input || 'No input.'}

‎src/renderer/export-session.ts‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { Entry } from './timeline';
1+
import { toolStatus, type Entry } from './timeline';
22

33
export type SessionExportInput = {
44
title: string;
@@ -19,11 +19,6 @@ function fenced(text: string): string {
1919
return `${fence}\n${text.replace(/\n$/, '')}\n${fence}`;
2020
}
2121

22-
function toolStatus(entry: Extract<Entry, { kind: 'tool' }>): string {
23-
if (entry.running) return 'Running';
24-
return entry.ok ? 'Done' : 'Failed';
25-
}
26-
2722
function toolHeading(entry: Extract<Entry, { kind: 'tool' }>): string {
2823
const args =
2924
entry.args.length > 120 ? `${entry.args.slice(0, 120)}...` : entry.args;
@@ -60,11 +55,14 @@ function summarySection(entries: Entry[]): string {
6055
`- ${messages} ${messages === 1 ? 'message' : 'messages'}: ${users} from you, ${assistants} from Pi.`,
6156
];
6257
if (tools.length > 0) {
63-
const done = tools.filter((e) => !e.running && e.ok).length;
64-
const failed = tools.filter((e) => !e.running && !e.ok).length;
65-
const running = tools.filter((e) => e.running).length;
58+
const done = tools.filter((e) => toolStatus(e) === 'Done').length;
59+
const failed = tools.filter((e) => toolStatus(e) === 'Failed').length;
60+
const running = tools.filter((e) => toolStatus(e) === 'Running').length;
61+
const interrupted = tools.filter(
62+
(e) => toolStatus(e) === 'Interrupted',
63+
).length;
6664
lines.push(
67-
`- ${tools.length} ${tools.length === 1 ? 'tool call' : 'tool calls'}: ${done} done, ${failed} failed, ${running} running.`,
65+
`- ${tools.length} ${tools.length === 1 ? 'tool call' : 'tool calls'}: ${done} done, ${failed} failed, ${running} running${interrupted ? `, ${interrupted} interrupted` : ''}.`,
6866
`- Tools used: ${[...new Set(tools.map((e) => e.tool))].join(', ')}.`,
6967
);
7068
}

‎src/renderer/timeline.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ type Entry =
1515
output: string;
1616
running: boolean;
1717
ok: boolean;
18+
interrupted?: boolean;
1819
};
1920

2021
type AgentContent = {
@@ -142,6 +143,7 @@ function entriesFromMessages(messages: unknown[]): Entry[] {
142143
output: '',
143144
running: false,
144145
ok: true,
146+
interrupted: true,
145147
};
146148
tools.set(p.id, tool);
147149
entries.push(tool);
@@ -154,6 +156,7 @@ function entriesFromMessages(messages: unknown[]): Entry[] {
154156
if (tool) {
155157
tool.output = resultText(m.content);
156158
tool.ok = m.isError !== true;
159+
tool.interrupted = false;
157160
}
158161
}
159162
}
@@ -181,6 +184,11 @@ function applyEvent(
181184
break;
182185
case 'agent_end':
183186
running = false;
187+
for (let i = 0; i < next.length; i++) {
188+
const entry = next[i];
189+
if (entry.kind === 'tool' && entry.running)
190+
next[i] = { ...entry, running: false, interrupted: true };
191+
}
184192
break;
185193
case 'message_start': {
186194
const message = event.message as AgentMessage | undefined;
@@ -249,6 +257,7 @@ function applyEvent(
249257
output: resultText(result?.content),
250258
running: false,
251259
ok: event.isError !== true,
260+
interrupted: false,
252261
} as Entry;
253262
}
254263
break;
@@ -257,5 +266,11 @@ function applyEvent(
257266
return { entries: next, running };
258267
}
259268

260-
export { entriesFromMessages, applyEvent };
269+
function toolStatus(entry: Extract<Entry, { kind: 'tool' }>): string {
270+
if (entry.running) return 'Running';
271+
if (entry.interrupted) return 'Interrupted';
272+
return entry.ok ? 'Done' : 'Failed';
273+
}
274+
275+
export { entriesFromMessages, applyEvent, toolStatus };
261276
export type { Entry, ToolLine };

‎src/renderer/useWorkbench.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,12 @@ export function useWorkbench() {
166166
setTabs((prev) =>
167167
prev.map((tab) =>
168168
tab.runtimeId === sessionId
169-
? { ...tab, running: false, exited: true }
169+
? {
170+
...tab,
171+
entries: applyEvent(tab.entries, { type: 'agent_end' }).entries,
172+
running: false,
173+
exited: true,
174+
}
170175
: tab,
171176
),
172177
);

‎src/renderer/workbench.css‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,10 @@ html[data-reduced-motion='true'] .wb-shell *::after {
706706
font-size: 12px;
707707
color: var(--copy);
708708
}
709+
.wb-tool-notice {
710+
margin: 0;
711+
padding: 0 12px 10px;
712+
}
709713
.wb-tool-section h3 {
710714
margin: 0;
711715
padding: 8px 12px 0;

‎tests/e2e/app.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,24 @@ describe('Figma workbench in Electron', () => {
399399
expect(errors).toEqual([]);
400400
});
401401

402+
it('settles a stopped tool as interrupted and preserves partial output', async () => {
403+
await win.getByRole('button', { name: 'New session', exact: true }).click();
404+
await win.getByLabel('Message pi').fill('Start interrupted tool fixture');
405+
await win.getByRole('button', { name: 'Send', exact: true }).click();
406+
const card = win.locator('.wb-tool').filter({ hasText: 'build-project' });
407+
await card.locator('summary').getByText('Running', { exact: true }).waitFor();
408+
await win.getByRole('button', { name: 'Stop', exact: true }).click();
409+
await card.locator('summary').getByText('Interrupted', { exact: true }).waitFor();
410+
await card.locator('summary').click();
411+
await card.getByText('Building project...', { exact: true }).waitFor();
412+
await card.getByText(/check before retrying/).waitFor();
413+
expect(await card.locator('summary').textContent()).not.toContain('Done');
414+
const screenshot = path.join(shots, '10-interrupted-tool.png');
415+
await win.screenshot({ path: screenshot });
416+
await fs.mkdir(path.join(ROOT, '.tmp/proof'), { recursive: true });
417+
await fs.copyFile(screenshot, path.join(ROOT, '.tmp/proof/interrupted-tool.png'));
418+
});
419+
402420
it('keeps the desktop layouts usable at the minimum window size', async () => {
403421
await win.getByRole('button', { name: 'New session', exact: true }).click();
404422
await win.setViewportSize({ width: 900, height: 600 });

‎tests/fixtures/pi-rpc.cjs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,15 @@ readline.createInterface({ input: process.stdin }).on('line', (line) => {
275275
reply();
276276
streaming = true;
277277
event('agent_start');
278+
if (command.message === 'Start interrupted tool fixture') {
279+
event('tool_execution_start', {
280+
toolCallId: 'interrupted-build', toolName: 'bash', args: { command: 'build-project' },
281+
});
282+
event('tool_execution_update', {
283+
toolCallId: 'interrupted-build', partialResult: { content: [{ type: 'text', text: 'Building project...' }] },
284+
});
285+
break;
286+
}
278287
event('message_start', { message: { role: 'assistant' } });
279288
event('message_update', {
280289
assistantMessageEvent: {

‎tests/integration/ToolCard.test.tsx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,4 +154,16 @@ describe('<TranscriptRow> tool card', () => {
154154
expect(container.textContent).toContain('Running');
155155
expect(container.textContent).toContain('Waiting for output');
156156
});
157+
158+
it('shows interrupted calls with partial output and no success claim', () => {
159+
const entry = { ...toolEntry, interrupted: true, output: 'Partial progress' };
160+
const { container, getByText } = render(
161+
<TranscriptRow entry={entry} expanded={new Map([[entry.key, true]])} />,
162+
);
163+
expect(getByText('Interrupted')).toBeTruthy();
164+
expect(container.querySelector('summary')?.textContent).not.toContain('Done');
165+
expect(container.textContent).toContain('check before retrying');
166+
expect(container.querySelectorAll('.wb-tool-section pre')[1]?.textContent).toBe('Partial progress');
167+
expect(container.querySelector('summary img')?.getAttribute('src')).not.toContain('/check.svg');
168+
});
157169
});

‎tests/integration/useWorkbench.test.tsx‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,64 @@ afterEach(() => {
6464
});
6565

6666
describe('workbench root switching', () => {
67+
it('settles unfinished tool cards when their runtime exits', async () => {
68+
const fixture = apiFixture();
69+
const openSession = vi
70+
.fn<PidexApi['openSession']>()
71+
.mockResolvedValue({ sessionId: 'runtime' });
72+
const sessionCommands = vi
73+
.fn<PidexApi['sessionCommands']>()
74+
.mockResolvedValue({ commands: [] });
75+
Object.assign(fixture, { openSession, sessionCommands });
76+
const { result } = renderHook(useWorkbench);
77+
await waitFor(() => expect(result.current.ws?.name).toBe('api'));
78+
act(() =>
79+
result.current.showSession({
80+
cwd: '/code/api',
81+
id: 'archive',
82+
file: '/sessions/archive.jsonl',
83+
title: 'Build',
84+
model: '',
85+
timestamp: '',
86+
messageCount: 0,
87+
}),
88+
);
89+
await waitFor(() => expect(result.current.tabs).toHaveLength(1));
90+
const onEvent = fixture.onSessionEvent.mock.calls[0][0];
91+
const onExit = fixture.onSessionExit.mock.calls[0][0];
92+
act(() => {
93+
onEvent({
94+
sessionId: 'runtime',
95+
event: {
96+
type: 'tool_execution_start',
97+
toolCallId: 'build',
98+
toolName: 'bash',
99+
args: { command: 'build' },
100+
},
101+
});
102+
onEvent({
103+
sessionId: 'runtime',
104+
event: {
105+
type: 'tool_execution_update',
106+
toolCallId: 'build',
107+
partialResult: { content: [{ type: 'text', text: 'Partial build' }] },
108+
},
109+
});
110+
onExit({ sessionId: 'other-runtime' });
111+
});
112+
expect(result.current.tabs[0].entries[0]).toMatchObject({ running: true });
113+
act(() => onExit({ sessionId: 'runtime' }));
114+
expect(result.current.tabs[0]).toMatchObject({
115+
running: false,
116+
exited: true,
117+
});
118+
expect(result.current.tabs[0].entries[0]).toMatchObject({
119+
running: false,
120+
interrupted: true,
121+
output: 'Partial build',
122+
});
123+
});
124+
67125
it('rejects late catalog, file, model and defaults results from a previous root', async () => {
68126
const fixture = apiFixture();
69127
const oldCatalog = deferred<WorkspaceCatalog>();

‎tests/unit/export-session.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,16 @@ describe('sessionExportMarkdown', () => {
111111
expect(running).toContain('## bash / npm test (Running)');
112112
});
113113

114+
it('counts interrupted tools separately and retains their partial output', () => {
115+
const markdown = sessionExportMarkdown({
116+
title: 'Interrupted build', cwd: '/repo/app', model: '', exportedAt,
117+
entries: [bashDone, { ...bashDone, key: 'interrupted', interrupted: true, output: 'Building...' }],
118+
});
119+
expect(markdown).toContain('2 tool calls: 1 done, 0 failed, 0 running, 1 interrupted.');
120+
expect(markdown).toContain('## bash / npm test (Interrupted)');
121+
expect(markdown).toContain('Building...');
122+
});
123+
114124
it('keeps an empty input and output readable', () => {
115125
const markdown = sessionExportMarkdown({
116126
title: 'T',

0 commit comments

Comments
 (0)