Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
10 changes: 9 additions & 1 deletion docs/design/live-journal-truncation-recovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ The daemon keeps a bounded in-memory live journal for an unfinished turn. Consec

The marker previously had no prompt ownership, the SDK rendered a generic message, and WebUI either hid the marker behind history pagination or left the retained tail permanently visible. This design keeps the existing resource limits and eviction policy while making the loss precise and repairing the visible tail without another model request.

Web Shell renders the parent transcript in summary mode and discards nested subagent updates, but those updates previously still consumed the parent live-journal limits. A long-running subagent could therefore evict the visible root Agent status and leave the summary UI with only the truncation marker.

## Protocol and SDK

The compaction engine maintains independently bounded `full` and `summary` live journals. Both share the completed-turn compaction and event high-water mark. The full journal retains every update. The summary journal excludes `session_update` frames carrying a non-empty `_meta.parentToolCallId`, while retaining root updates and all non-session events. Two exceptions mirror the main-transcript projection. First, nested `agent_message_chunk` frames whose `_meta.usage` carries a numeric `inputTokens` or `outputTokens` are retained: the main transcript consumes exactly those frames for subagent token accounting, so dropping them would silently lose nested usage from the restored conversation's totals. Second, a frame whose `_meta.parentToolCallId` equals its own `toolCallId` is treated as root, matching the UI normalizer's self-reference guard (`normalizeToolUpdate` drops a self-parent), so both projections agree such a frame is a root tool block. The two journals share one pair of caps (entry count and byte size), so a single in-flight turn can retain up to twice the cap of journal heap; operators sizing daemon memory from `maxJournalBytes x live sessions` must double the journal term, including any adaptively grown cap.

`session/load` accepts optional `liveReplayMode: 'full' | 'summary'`. Omission means `full`, preserving SDK, `/acp`, and other daemon consumers. WebUI requests `summary` only when its existing `subagentTranscriptMode` is summary; Web Shell already selects that mode for the main transcript. Persisted transcript pagination remains complete and unchanged. Concurrent restores of the same session only coalesce on identical shapes; the single exception is that a `summary` request may share an in-flight `full` restore — the summary journal is a strict subset, and once the restore settles the daemon recomputes the waiter's replay fields for its own mode from the registered session, so the waiter never inherits the owner's unprojected full journal or its truncation marker. A `full` request never shares an in-flight `summary` restore (that projection would lack the nested detail the full client expects), so that direction stays fenced with `restore_in_progress`.

For a live-journal marker returned by `session/load`, the bridge copies the session's authoritative `activePromptId` to the marker envelope as optional `promptId`. The persisted event and event schema version do not change. An older daemon without this field is repairable only when the retained live events have exactly one prompt ID.

`DaemonHistoryTruncatedData` exposes the existing optional `scope` and `maxEvents` fields. Validation rejects malformed optional values. Normalized status data retains the complete daemon payload. The text distinguishes replay-history truncation from live-turn truncation, states that the newest events were retained and older replay events were discarded, and promises post-terminal recovery only when `fullTranscriptAvailable` is true.
Expand Down Expand Up @@ -37,7 +43,9 @@ The checkpoint inherits the current transcript store's effective `maxBlocks`, wh
- New clients accept old payloads and safely decline ambiguous automatic repair.
- Default `reloadSession` behavior remains configured replay; only the internal repair path requests memory replay.
- Daemon persistence, transcript APIs, journal limits, and oldest-first eviction are unchanged.
- Existing load callers and `/acp` continue to receive full live replay by default.
- Summary and full journals track truncation independently, so full-journal pressure does not create a summary marker.

## Verification

Unit coverage exercises marker ownership, post-terminal compaction, payload validation, precise status text, prompt matching, replay validation, atomic suffix replacement, duplicate-side-effect suppression, history preservation, failure fallback, and reload-source propagation. Daemon integration tests use a deterministic mock ACP agent and a three-event journal to observe the live marker from a second client, verify the complete compacted turn after terminal, and mount the real WebUI provider to prove that recovery adds one load and no model request.
Unit coverage exercises marker ownership, post-terminal compaction, independent full/summary limits, default-full compatibility, request validation and propagation, precise status text, prompt matching, replay validation, atomic suffix replacement, duplicate-side-effect suppression, history preservation, failure fallback, and reload-source propagation. Daemon integration tests use a deterministic mock ACP agent and a three-event journal to observe the live marker from a second client, verify the complete compacted turn after terminal, and mount the real WebUI provider to prove that recovery adds one load and no model request.
288 changes: 288 additions & 0 deletions packages/acp-bridge/src/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5076,6 +5076,78 @@ describe('createAcpSessionBridge', () => {
await bridge.shutdown();
});

it('selects summary live replay without changing the default full replay', async () => {
const handle = makeChannel();
const bridge = makeBridge({
channelFactory: async () => handle.channel,
maxJournalEvents: 2,
});
const session = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
await handle.agentConnection.sessionUpdate({
sessionId: session.sessionId,
update: {
sessionUpdate: 'tool_call_update',
toolCallId: 'agent-1',
status: 'in_progress',
},
});
await handle.agentConnection.sessionUpdate({
sessionId: session.sessionId,
update: {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'nested detail' },
_meta: { parentToolCallId: 'agent-1' },
},
});
await handle.agentConnection.sessionUpdate({
sessionId: session.sessionId,
update: {
sessionUpdate: 'tool_call_update',
toolCallId: 'agent-1',
status: 'completed',
},
});

const full = await bridge.loadSession({
sessionId: session.sessionId,
workspaceCwd: WS_A,
historyReplay: 'response',
});
expect(full.liveJournal).toContainEqual(
expect.objectContaining({
type: 'session_update',
data: expect.objectContaining({
update: expect.objectContaining({
_meta: { parentToolCallId: 'agent-1' },
}),
}),
}),
);

const summary = await bridge.loadSession({
sessionId: session.sessionId,
workspaceCwd: WS_A,
historyReplay: 'response',
historyPageSize: 100,
liveReplayMode: 'summary',
});
expect(summary.liveJournal).not.toContainEqual(
expect.objectContaining({
data: expect.objectContaining({
update: expect.objectContaining({
_meta: { parentToolCallId: 'agent-1' },
}),
}),
}),
);
expect(summary.liveJournal).not.toContainEqual(
expect.objectContaining({ type: 'history_truncated' }),
);
expect(summary.liveJournal?.map((event) => event.id)).toEqual([1, 3]);

await bridge.shutdown();
});

describe('adaptive live-journal growth pool', () => {
it('grows a breaching session from the pool instead of truncating', async () => {
const gate = deferred<void>();
Expand Down Expand Up @@ -6519,6 +6591,69 @@ describe('createAcpSessionBridge', () => {
await bridge.shutdown();
});

it('preserves summary replay when a restore loses the registration race', async () => {
const load = deferred<LoadSessionResponse>();
const handle = makeChannel({
loadSessionImpl: () => load.promise,
newSessionImpl: () => ({ sessionId: 'raced-summary' }),
});
const bridge = makeBridge({
sessionScope: 'thread',
maxSessions: 5,
maxJournalEvents: 2,
channelFactory: async () => handle.channel,
});

const restoring = bridge.loadSession({
sessionId: 'raced-summary',
workspaceCwd: WS_A,
historyReplay: 'response',
liveReplayMode: 'summary',
});
await vi.waitFor(() => {
expect(handle.agent.loadSessionCalls).toHaveLength(1);
});
await bridge.spawnOrAttach({
workspaceCwd: WS_A,
sessionScope: 'thread',
});
await handle.agentConnection.sessionUpdate({
sessionId: 'raced-summary',
update: {
sessionUpdate: 'tool_call_update',
toolCallId: 'agent-1',
status: 'in_progress',
},
});
await handle.agentConnection.sessionUpdate({
sessionId: 'raced-summary',
update: {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'nested detail' },
_meta: { parentToolCallId: 'agent-1' },
},
});
await handle.agentConnection.sessionUpdate({
sessionId: 'raced-summary',
update: {
sessionUpdate: 'tool_call_update',
toolCallId: 'agent-1',
status: 'completed',
},
});

load.resolve({});
const restored = await restoring;

expect(restored.attached).toBe(true);
expect(restored.liveJournal).not.toContainEqual(
expect.objectContaining({ type: 'history_truncated' }),
);
expect(restored.liveJournal?.map((event) => event.id)).toEqual([1, 3]);

await bridge.shutdown();
});

it('coalesces response restores with the same history page', async () => {
const load = deferred<LoadSessionResponse>();
const handle = makeChannel({ loadSessionImpl: () => load.promise });
Expand Down Expand Up @@ -6582,6 +6717,46 @@ describe('createAcpSessionBridge', () => {
},
);

it.each(['sumary', null, 0, false])(
'rejects invalid live replay mode %j before restore',
async (liveReplayMode) => {
const handle = makeChannel();
const channelFactory = vi.fn(async () => handle.channel);
const bridge = makeBridge({ channelFactory });

await expect(
bridge.loadSession({
sessionId: 'invalid-live-replay-mode',
workspaceCwd: WS_A,
liveReplayMode,
} as unknown as Parameters<typeof bridge.loadSession>[0]),
).rejects.toThrow('Invalid liveReplayMode');
expect(channelFactory).not.toHaveBeenCalled();
expect(handle.agent.loadSessionCalls).toHaveLength(0);
expect(() =>
bridge.getSessionSummary('invalid-live-replay-mode'),
).toThrow(SessionNotFoundError);

await bridge.shutdown();
},
);

it('rejects an invalid live replay mode on resume', async () => {
const handle = makeChannel();
const bridge = makeBridge({ channelFactory: async () => handle.channel });

await expect(
bridge.resumeSession({
sessionId: 'invalid-resume-live-replay-mode',
workspaceCwd: WS_A,
liveReplayMode: 'sumary',
} as unknown as Parameters<typeof bridge.resumeSession>[0]),
).rejects.toThrow('Invalid liveReplayMode');
expect(handle.agent.resumeSessionCalls).toHaveLength(0);

await bridge.shutdown();
});

it.each([
['a different explicit page', 500],
['an omitted page', undefined],
Expand Down Expand Up @@ -6751,6 +6926,119 @@ describe('createAcpSessionBridge', () => {
await bridge.shutdown();
});

it('lets a summary load coalesce onto an in-flight full restore', async () => {
const load = deferred<LoadSessionResponse>();
const handle = makeChannel({ loadSessionImpl: () => load.promise });
const bridge = makeBridge({
channelFactory: async () => handle.channel,
maxJournalEvents: 2,
});

const first = bridge.loadSession({
sessionId: 'coalesce-live-replay-mode',
workspaceCwd: WS_A,
historyReplay: 'response',
liveReplayMode: 'full',
});
await vi.waitFor(() => {
expect(handle.agent.loadSessionCalls).toHaveLength(1);
});

// Flood the in-flight restore's journals past the two-entry cap: root
// frames around a burst of nested subagent chunks. The full journal
// truncates and evicts the early root frame; the summary journal keeps
// both root frames marker-free.
await handle.agentConnection.sessionUpdate({
sessionId: 'coalesce-live-replay-mode',
update: {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'root-before' },
},
});
for (const text of ['nested-a', 'nested-b', 'nested-c']) {
await handle.agentConnection.sessionUpdate({
sessionId: 'coalesce-live-replay-mode',
update: {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text },
_meta: { parentToolCallId: 'agent-1' },
},
});
}
await handle.agentConnection.sessionUpdate({
sessionId: 'coalesce-live-replay-mode',
update: {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'root-after' },
},
});

// The summary journal is a strict subset of the full journal, so the
// summary waiter shares the in-flight full restore; once the restore
// settles, the bridge recomputes the waiter's own-mode replay fields
// from the registered entry.
const second = bridge.loadSession({
sessionId: 'coalesce-live-replay-mode',
workspaceCwd: WS_A,
historyReplay: 'response',
liveReplayMode: 'summary',
});

load.resolve({});
const [r1, r2] = await Promise.all([first, second]);
expect(r1.attached).toBe(false);
expect(r2.attached).toBe(true);
expect(handle.agent.loadSessionCalls).toHaveLength(1);

// The owner's full-mode view carries the truncation marker; the
// coalesced summary waiter must NOT inherit it — its re-projected
// journal retains the root frames, excludes the nested frames, and
// never truncated.
expect(r1.liveJournal).toContainEqual(
expect.objectContaining({ type: 'history_truncated' }),
);
expect(r2.liveJournal).not.toContainEqual(
expect.objectContaining({ type: 'history_truncated' }),
);
const waiterJournal = JSON.stringify(r2.liveJournal);
expect(waiterJournal).toContain('root-before');
expect(waiterJournal).toContain('root-after');
expect(waiterJournal).not.toContain('nested-');
await bridge.shutdown();
});

it('rejects a full load joining an in-flight summary restore', async () => {
const load = deferred<LoadSessionResponse>();
const handle = makeChannel({ loadSessionImpl: () => load.promise });
const bridge = makeBridge({ channelFactory: async () => handle.channel });

const first = bridge.loadSession({
sessionId: 'coalesce-live-replay-mode-full-after-summary',
workspaceCwd: WS_A,
historyReplay: 'response',
liveReplayMode: 'summary',
});
await vi.waitFor(() => {
expect(handle.agent.loadSessionCalls).toHaveLength(1);
});

// A full request cannot share the in-flight summary restore — the
// projection lacks the nested detail the full client expects — so it
// stays fenced instead of coalescing onto the wrong replay.
await expect(
bridge.loadSession({
sessionId: 'coalesce-live-replay-mode-full-after-summary',
workspaceCwd: WS_A,
historyReplay: 'response',
liveReplayMode: 'full',
}),
).rejects.toBeInstanceOf(RestoreInProgressError);

load.resolve({});
await first;
await bridge.shutdown();
});

it('survives spawn-owner disconnect kill while a coalesced restore is mid-flight', async () => {
let releaseLoad: ((value: LoadSessionResponse) => void) | undefined;
const factory: ChannelFactory = async () =>
Expand Down
Loading
Loading