Skip to content

Durable coding-agent harnesses (Claude Code, Codex, OpenCode, Pi, fx) on a Workflow SDK World

OpenCode, Claude Code, Codex: a resumed turn says its reply starts over (restart) (#4)

Pranay Prakashc74d5666e37c
diff --git a/packages/demo-ui/src/Compare.tsx b/packages/demo-ui/src/Compare.tsx
index 7d73d88..de41434 100644
--- a/packages/demo-ui/src/Compare.tsx
+++ b/packages/demo-ui/src/Compare.tsx
@@ -102,6 +102,30 @@ export function foldItems(items: Item[], e: any): Item[] {
return i < 0 ? items : items.map((it, j) => (j === i && it.kind === 'tool' ? { ...it, done: true, error: !!e.isError } : it));
}
if (e.type === 'error' || e.type === 'failed') return [...items, { kind: 'error', text: String(e.message ?? 'error') }];
+ // A turn a crash cut off resumed and its model answers again. The text the log kept (`e.parts`) streamed first, so what
+ // the turn shows past its length is the cut-off reply, at the end: that goes. Counted in characters, as a steer can
+ // split one reply into two rows. The turn starts at its message: a steer joins the turn it steers.
+ if (e.type === 'restart') {
+ const kept = Array.isArray(e.parts) ? e.parts.join('').length : 0;
+ const start = items.findLastIndex((it) => it.kind === 'user' && !it.steer);
+ let excess = items.slice(start + 1).reduce((n, it) => n + (it.kind === 'text' ? it.text.length : 0), 0) - kept;
+ if (excess <= 0) return items;
+ const out = [...items];
+ // The cut-off reply is the turn's last text, with steers in it: a tool call before it ended a kept step.
+ for (let i = out.length - 1; i > start && excess > 0; i--) {
+ const it = out[i]!;
+ if (it.kind === 'user' && it.steer) continue;
+ if (it.kind !== 'text') break;
+ if (it.text.length <= excess) {
+ excess -= it.text.length;
+ out.splice(i, 1);
+ } else {
+ out[i] = { kind: 'text', text: it.text.slice(0, it.text.length - excess) };
+ excess = 0;
+ }
+ }
+ return out;
+ }
return items;
}
diff --git a/packages/demo-ui/src/compare.test.ts b/packages/demo-ui/src/compare.test.ts
index 8e39d5d..2bc3978 100644
--- a/packages/demo-ui/src/compare.test.ts
+++ b/packages/demo-ui/src/compare.test.ts
@@ -21,6 +21,34 @@ describe('compare foldItems', () => {
{ kind: 'text', text: 'done' },
]);
});
+ it('drops the cut-off reply on restart, and keeps text the log kept', () => {
+ const fold = (events: object[]) => events.reduce<Item[]>((items, e) => foldItems(items, e), [{ kind: 'user', text: 'hi' }]);
+ const before = [{ type: 'text', delta: 'Sending it.' }, { type: 'tool_start', name: 'mail' }, { type: 'tool_end', name: 'mail' }, { type: 'text', delta: 'The email went' }];
+ expect(fold([...before, { type: 'restart', text: 'Sending it.', parts: ['Sending it.'] }, { type: 'text', delta: 'Done.' }])).toEqual([
+ { kind: 'user', text: 'hi' },
+ { kind: 'text', text: 'Sending it.' },
+ { kind: 'tool', name: 'mail', done: true, error: false },
+ { kind: 'text', text: 'Done.' },
+ ]);
+ // A crash mid-tool: nothing streamed was cut off.
+ const midTool = fold([{ type: 'text', delta: 'Sending it.' }, { type: 'tool_start', name: 'mail' }]);
+ expect(foldItems(midTool, { type: 'restart', text: 'Sending it.', parts: ['Sending it.'] })).toBe(midTool);
+ // A reply the log kept whole stays.
+ const kept = fold([{ type: 'text', delta: 'All done.' }]);
+ expect(foldItems(kept, { type: 'restart', text: 'All done.', parts: ['All done.'] })).toBe(kept);
+ // A cut-off reply that repeats text the log kept before the tool still goes: the count, not the words, tells them apart.
+ const repeat = fold([{ type: 'text', delta: 'Done.' }, { type: 'tool_start', name: 'mail' }, { type: 'tool_end', name: 'mail' }, { type: 'text', delta: 'Done.' }]);
+ expect(foldItems(repeat, { type: 'restart', text: 'Done.', parts: ['Done.'] })).toEqual(repeat.slice(0, -1));
+ // A steer joins the turn it steers: the text the log kept before it counts.
+ const steered = [...fold([{ type: 'text', delta: 'Sending it.' }]), { kind: 'user', text: 'and cc me', steer: true } as Item, { kind: 'text', text: 'The email went' } as Item];
+ expect(foldItems(steered, { type: 'restart', text: 'Sending it.', parts: ['Sending it.'] })).toEqual(steered.slice(0, -1));
+ // A steer mid-reply splits one kept reply into two rows: both stay.
+ const split = [...fold([{ type: 'text', delta: 'Sending' }]), { kind: 'user', text: 'and cc me', steer: true } as Item, { kind: 'text', text: ' it.' } as Item];
+ expect(foldItems(split, { type: 'restart', text: 'Sending it.', parts: ['Sending it.'] })).toBe(split);
+ // ...and a cut-off reply split by one goes as a whole, the steer kept.
+ const cut = [...fold([{ type: 'text', delta: 'Sending it.' }, { type: 'tool_start', name: 'mail' }, { type: 'tool_end', name: 'mail' }, { type: 'text', delta: 'The email' }]), { kind: 'user', text: 'and cc me', steer: true } as Item, { kind: 'text', text: ' went' } as Item];
+ expect(foldItems(cut, { type: 'restart', text: 'Sending it.', parts: ['Sending it.'] })).toEqual([...cut.slice(0, 3), cut[4]]);
+ });
it('returns the same array for events that show nothing', () => {
const items: Item[] = [];
expect(foldItems(items, { type: 'mark', name: 'idle' })).toBe(items);
diff --git a/packages/demo-ui/src/hooks.ts b/packages/demo-ui/src/hooks.ts
index 3f4491c..ddda0d5 100644
--- a/packages/demo-ui/src/hooks.ts
+++ b/packages/demo-ui/src/hooks.ts
@@ -388,6 +388,9 @@ export function useSession(client: DemoClient | undefined, id: string | undefine
// Run-ahead: speculative output the log does not have is retracted
// (a rejected write rewinds the drive; it streams the turn again).
if (event?.type === 'rewind' || event?.type === 'submit-failed') live.reset();
+ // A turn a crash cut off resumed and its model answers again: the cut-off text never reached the log, so it goes; what
+ // the log kept shows from the next read, and the resumed reply streams after it.
+ if (event?.type === 'restart') live.reset();
if (event?.type === 'submit-failed') {
put({ error: `A prompt did not become durable yet (${String(event.error ?? 'write failed')}); the drive re-issues it.` });
}
diff --git a/packages/harness-claude-code/src/harness.ts b/packages/harness-claude-code/src/harness.ts
index 15e8b81..f066b03 100644
--- a/packages/harness-claude-code/src/harness.ts
+++ b/packages/harness-claude-code/src/harness.ts
@@ -20,6 +20,7 @@ import {
placeSubmissions,
type ProviderTool,
recoveryNote,
+ restartEvent,
replayBy,
type SessionMachine,
type SessionProcess,
@@ -821,6 +822,8 @@ export function claudeCodeHarness(options: ClaudeCodeHarnessOptions = {}): Harne
const note = recoveryNote(ctx.state(), { prompts: !!open && lostPrompts(ctx.state(), open.placed, store).length > 0 });
if (note) {
if (open) ledger.turn(open.placed[0] ?? `open:${open.since}`);
+ // The CLI answers again from the interrupted step: what a reader saw of its reply is replaced by what the log kept.
+ ctx.live(restartEvent(note.turn));
await send(note.text, note.pending, { synthetic: 'recovery' });
await runTurn();
}
diff --git a/packages/harness-codex/src/harness.ts b/packages/harness-codex/src/harness.ts
index 292d9fc..0630083 100644
--- a/packages/harness-codex/src/harness.ts
+++ b/packages/harness-codex/src/harness.ts
@@ -18,6 +18,7 @@ import {
NativeJournal,
placeSubmissions,
recoveryNote,
+ restartEvent,
type SessionMachine,
type SessionProcess,
settleAbandonedModelSteps,
@@ -1086,6 +1087,8 @@ export function codexHarness(options: CodexHarnessOptions = {}): Harness {
const n = transcriptOf(ctx.state()).filter((r) => r.data.type === 'message' && r.data.role === 'user').length;
journal.message({ type: 'message', role: 'user', text: notes ? `${notes}\n\n${text}` : text, synthetic: 'recovery' } satisfies TranscriptEntry);
await placeSubmissions(ctx, note.pending);
+ // Codex answers again from the interrupted step: what a reader saw of its reply is replaced by what the log kept.
+ ctx.live(restartEvent(note.turn));
// Its client id names the submissions the note carries: once Codex has recorded it, they are not owed again.
await turn(text, recoveryClientId(n, [...owed, ...note.pending]));
}
diff --git a/packages/harness-opencode/src/harness.test.ts b/packages/harness-opencode/src/harness.test.ts
index f0fba45..8bec22b 100644
--- a/packages/harness-opencode/src/harness.test.ts
+++ b/packages/harness-opencode/src/harness.test.ts
@@ -282,7 +282,8 @@ describe('the OpenCode drive', () => {
open(h);
await admit(h);
await h.request({ type: 'barrier', kind: 'primary' });
- h.commit(['session.step.started'], ['session.tool.input.started', { id: 'toolu_pay', name: 'unsafe_make_payment' }], ['session.tool.called', { id: 'toolu_pay', input: pay }]);
+ h.send({ type: 'text', delta: 'Paying acme now.' });
+ h.commit(['session.step.started'], ['session.text.ended', { text: 'Paying acme now.' }], ['session.tool.input.started', { id: 'toolu_pay', name: 'unsafe_make_payment' }], ['session.tool.called', { id: 'toolu_pay', input: pay }]);
await h.request({ type: 'tool', callId: 'toolu_pay', name: 'unsafe_make_payment', input: pay });
};
let note = '';
@@ -323,6 +324,17 @@ describe('the OpenCode drive', () => {
const entries = transcriptOf(state).map((r) => r.data);
expect(entries).toContainEqual({ type: 'message', role: 'user', text: note, synthetic: 'recovery' });
expect(entries.at(-1)).toEqual({ type: 'turn', status: 'completed' });
+ // The live stream: the first drive's text, then `restart` with what the log kept of the turn, before the resumed reply.
+ const abort = new AbortController();
+ const live: { type?: string; text?: string; delta?: string }[] = [];
+ for await (const ev of b.sessions.live(sessionId, { signal: abort.signal }) as AsyncIterable<{ type?: string }>) {
+ live.push(ev);
+ if (ev.type === 'idle' && live.some((e) => e.type === 'restart')) abort.abort();
+ }
+ expect(live.filter((e) => e.type === 'text' || e.type === 'restart')).toEqual([
+ { type: 'text', delta: 'Paying acme now.' },
+ { type: 'restart', text: 'Paying acme now.', parts: ['Paying acme now.'] },
+ ]);
expect(b.errors).toEqual([]);
});
@@ -388,6 +400,19 @@ describe('the OpenCode drive', () => {
const entries = transcriptOf(state).map((r) => r.data);
expect(entries).toContainEqual({ type: 'message', role: 'user', text: note, synthetic: 'recovery' });
expect(entries.at(-1)).toEqual({ type: 'turn', status: 'completed' });
+ // The cut-off reply streamed live and was never in the log: `restart` keeps only "Sending it.", then the resumed reply streams.
+ const abort = new AbortController();
+ const live: { type?: string; text?: string; delta?: string }[] = [];
+ for await (const ev of b.sessions.live(sessionId, { signal: abort.signal }) as AsyncIterable<{ type?: string }>) {
+ live.push(ev);
+ if (ev.type === 'idle' && live.some((e) => e.type === 'restart')) abort.abort();
+ }
+ const restart = live.findIndex((e) => e.type === 'restart');
+ expect(live[restart]).toEqual({ type: 'restart', text: 'Sending it.', parts: ['Sending it.'] });
+ const text = (from: number, to: number) => live.slice(from, to).flatMap((e) => (e.type === 'text' ? [e.delta] : [])).join('');
+ expect(text(0, restart)).toMatch(/^Sending it\..+/);
+ // The stand-in's crashed host can still stream a few deltas as the next drive starts (a real crash writes nothing more).
+ expect(text(restart + 1, live.length)).toMatch(/Recovered from the log: the email went out\.$/);
expect(b.errors).toEqual([]);
});
diff --git a/packages/harness-opencode/src/harness.ts b/packages/harness-opencode/src/harness.ts
index ac654ec..f4f077e 100644
--- a/packages/harness-opencode/src/harness.ts
+++ b/packages/harness-opencode/src/harness.ts
@@ -19,6 +19,7 @@ import {
type OpenTurn,
openTurn as findOpenTurn,
recoveryNote,
+ restartEvent,
replayBy,
type ToolBridge,
toolBridge,
@@ -748,6 +749,8 @@ class OpenCodeDrive {
// The note quotes the turn's prompts when OpenCode may have lost them.
const note = recoveryNote(state, { pending: [], prompts: lost.length > 0 })!.text;
this.journal.message({ type: 'message', role: 'user', text: note, synthetic: 'recovery' });
+ // OpenCode starts the step the crash cut off over: what a reader saw of its reply is replaced by what the log kept (`restartEvent`).
+ this.ctx.live(restartEvent(opening.turn));
const [s0, t0] = [this.starts, this.terminals];
await this.request({ type: 'recover', note });
await this.turn(() => this.starts > s0 || this.terminals > t0);
diff --git a/packages/harness-process/src/index.ts b/packages/harness-process/src/index.ts
index ec16be4..4b095b5 100644
--- a/packages/harness-process/src/index.ts
+++ b/packages/harness-process/src/index.ts
@@ -22,7 +22,7 @@ export { clip, failureText, Mutex, toolBridge, toolKey } from './tools.ts';
export type { BridgedTool, ToolBridge, ToolBridgeOptions, ToolResult } from './tools.ts';
export { zodFromJsonSchema, zodShapeFromJsonSchema } from './zod.ts';
export type { JsonSchemaObject } from './zod.ts';
-export { openTurn, recoveryNote } from './recovery.ts';
+export { openTurn, recoveryNote, restartEvent } from './recovery.ts';
export type { OpenTurn, RecoveryCall, RecoveryNote, RecoveryOptions } from './recovery.ts';
export { defaultRoot, defaultShell, GROUP_REGISTRY_SCRIPT, groupAlive, groupOf, identity, isAlive, killRegistered, ownGroup, ProcessHost, watchParent } from './host.ts';
export type { Exit, HostedProcess, PidRecord, ProcessHostOptions, SessionDir, SpawnOptions, WatchOptions } from './host.ts';
diff --git a/packages/harness-process/src/recovery.ts b/packages/harness-process/src/recovery.ts
index 57004ed..57e4956 100644
--- a/packages/harness-process/src/recovery.ts
+++ b/packages/harness-process/src/recovery.ts
@@ -121,3 +121,19 @@ const indent = (t: string) => t.split('\n').map((l) => ` ${l}`);
function clip(t: string, max: number): string {
return t.length <= max ? t : `${t.slice(0, max)}… [${t.length - max} more characters]`;
}
+
+/**
+ * The live event a harness sends as it resumes a turn a crash cut off,
+ * before the model answers again: the model starts the step the crash
+ * interrupted over, so what a reader saw of its reply is replaced.
+ * `text` is the turn's text as the log kept it (the assistant text of its
+ * finished steps, and the text before each tool call); a reader shows it in
+ * place of what it showed of the turn so far (everything since the last
+ * `idle`), and appends what streams after it. `parts` is the same text, one
+ * entry per kept step, for a reader that shows tool calls between them: a
+ * turn on screen with more text than `parts` has a cut-off reply last.
+ */
+export function restartEvent(turn: OpenTurn): { type: 'restart'; text: string; parts: string[] } {
+ const parts = turn.entries.flatMap((r) => (r.data?.type === 'message' && r.data.role === 'assistant' && r.data.text ? [r.data.text] : []));
+ return { type: 'restart', text: parts.join('\n\n'), parts };
+}
diff --git a/packages/harness-process/test/restart-event.test.ts b/packages/harness-process/test/restart-event.test.ts
new file mode 100644
index 0000000..65eab2e
--- /dev/null
+++ b/packages/harness-process/test/restart-event.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import type { OpenTurn } from '../src/records.ts';
+import { restartEvent } from '../src/recovery.ts';
+
+const entry = (data: unknown, seq: number) => ({ seq, at: seq, data }) as OpenTurn['entries'][number];
+
+describe('restartEvent', () => {
+ it("carries the turn's assistant text the log kept (finished steps, the text before a tool call), never a recovery note", () => {
+ const turn: OpenTurn = {
+ since: -1,
+ placed: ['s1'],
+ calls: [],
+ entries: [
+ entry({ type: 'message', role: 'assistant', text: 'Checking the file.', toolCalls: [{ id: 't1', name: 'read' }] }, 1),
+ entry({ type: 'message', role: 'user', text: '[Recovery] Your previous turn was interrupted.', synthetic: 'recovery' }, 2),
+ entry({ type: 'message', role: 'assistant', text: '', toolCalls: [{ id: 't2', name: 'bash' }] }, 3),
+ entry({ type: 'message', role: 'assistant', text: 'It has 3 lines.' }, 4),
+ ],
+ };
+ expect(restartEvent(turn)).toEqual({ type: 'restart', text: 'Checking the file.\n\nIt has 3 lines.', parts: ['Checking the file.', 'It has 3 lines.'] });
+ expect(restartEvent({ ...turn, entries: [] })).toEqual({ type: 'restart', text: '', parts: [] });
+ });
+});