Skip to content
Merged
3 changes: 3 additions & 0 deletions packages/acp-bridge/src/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2303,6 +2303,7 @@ describe('createAcpSessionBridge', () => {
compactedReplay: [],
liveJournal: [],
lastEventId: 0,
eventEpoch: expect.any(String),
});
expect(handles[0]?.agent.loadSessionCalls).toEqual([
{
Expand Down Expand Up @@ -3357,6 +3358,7 @@ describe('createAcpSessionBridge', () => {
hasActivePrompt: false,
state: { modes: null },
lastEventId: 0,
eventEpoch: expect.any(String),
});
expect(handles[0]?.agent.loadSessionCalls).toHaveLength(0);
expect(handles[0]?.agent.resumeSessionCalls).toEqual([
Expand Down Expand Up @@ -3402,6 +3404,7 @@ describe('createAcpSessionBridge', () => {
hasActivePrompt: false,
state: { _meta: { tag: 'restored-foo' } },
lastEventId: expect.any(Number),
eventEpoch: expect.any(String),
});
expect(attached.clientId).not.toBe(loaded.clientId);
expect(handles[0]?.agent.loadSessionCalls).toHaveLength(1);
Expand Down
40 changes: 35 additions & 5 deletions packages/acp-bridge/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3495,7 +3495,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
}
};

const createSessionEventBus = (): EventBus =>
const createSessionEventBus = (sessionId: string): EventBus =>
new EventBus(
eventRingSize,
undefined,
Expand All @@ -3507,6 +3507,18 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
);
},
}),
{
// Fired once, on the FIRST ingest/seed failure (the bus keeps the
// degraded flag set silently afterwards). The bus doesn't know its
// session, so the sessionId context is injected here.
onCompactionError: (err) => {
writeStderrLine(
`qwen serve: compaction degraded for session=${sessionId}; replay snapshot may lag behind live events: ${
err instanceof Error ? err.message : String(err)
}`,
);
},
},
);

// §2.3 publish helpers — centralise cache + generation + bus publish so
Expand Down Expand Up @@ -3661,7 +3673,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
ci: ChannelInfo,
sessionId: string,
workspaceCwd: string,
events = createSessionEventBus(),
events = createSessionEventBus(sessionId),
options: {
drainEarlyEvents?: boolean;
lifecycleReason?: string;
Expand Down Expand Up @@ -3916,6 +3928,8 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
| 'compactedReplay'
| 'liveJournal'
| 'lastEventId'
| 'eventEpoch'
| 'replayDegraded'
| 'partial'
| 'replayError'
| 'historyHasMore'
Expand All @@ -3929,22 +3943,32 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
: {}),
}
: {};
// Clients seed their reconnect cursor from `lastEventId`; the epoch
// token must travel with it so a daemon restart between this response
// and the first subscribe is detected (stale cursor + dead epoch).
const eventEpoch = entry.events.epoch;
const snapshot = entry.events.snapshotReplay();
if (!snapshot) {
return { lastEventId: entry.events.lastEventId, ...replayStatus };
return {
lastEventId: entry.events.lastEventId,
eventEpoch,
...replayStatus,
};
}
if (action === 'load') {
return {
compactedReplay: snapshot.compactedTurns,
liveJournal: snapshot.liveJournal,
lastEventId: snapshot.lastEventId,
eventEpoch,
...replayStatus,
...(snapshot.degraded ? { replayDegraded: true } : {}),
...(entry.restoreHistoryHasMore === true
? { historyHasMore: true }
: {}),
};
}
return { lastEventId: snapshot.lastEventId, ...replayStatus };
return { lastEventId: snapshot.lastEventId, eventEpoch, ...replayStatus };
};

const restoredArtifactSnapshotFromState = (
Expand Down Expand Up @@ -4118,7 +4142,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
throw new SessionLimitExceededError(maxSessions);
}

const restoreEvents = createSessionEventBus();
const restoreEvents = createSessionEventBus(req.sessionId);
let registeredEntry: SessionEntry | undefined;
let ci: ChannelInfo | undefined;
// Live counter shared with coalesced waiters (see InFlightRestore
Expand Down Expand Up @@ -5596,6 +5620,12 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
return entry.events.lastEventId;
},

getSessionEventEpoch(sessionId) {
const entry = byId.get(sessionId);
if (!entry) throw new SessionNotFoundError(sessionId);
return entry.events.epoch;
},

getSessionReplaySnapshot(sessionId) {
const entry = byId.get(sessionId);
if (!entry) throw new SessionNotFoundError(sessionId);
Expand Down
20 changes: 20 additions & 0 deletions packages/acp-bridge/src/bridgeTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,19 @@ export interface BridgeRestoredSession extends BridgeSession {
historyHasMore?: boolean;
/** High-water mark event ID — client uses this as initial SSE cursor. */
lastEventId?: number;
/**
* Epoch token of the session's event bus. Clients echo it (with
* `lastEventId`) on SSE subscribe so a daemon restart between this
* response and the subscribe is detected deterministically instead of
* via the numeric heuristic.
*/
eventEpoch?: string;
/**
* True when the compaction engine failed at some point, so
* `compactedReplay`/`liveJournal` may silently miss events. Clients
* should prefer the full transcript over this replay.
*/
replayDegraded?: boolean;
}

export interface BridgeSessionTranscriptPageRequest {
Expand Down Expand Up @@ -829,6 +842,13 @@ export interface AcpSessionBridge {
*/
getSessionLastEventId(sessionId: string): number;

/**
* Return the epoch token of this session's event bus. Regenerated on
* every bus construction (daemon restart), never persisted. Throws
* `SessionNotFoundError` when the id is unknown.
*/
getSessionEventEpoch(sessionId: string): string;

/**
* Return the current compacted replay snapshot for a loaded session, when
* the bridge has a compaction engine configured.
Expand Down
196 changes: 196 additions & 0 deletions packages/acp-bridge/src/compactionEngine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1697,3 +1697,199 @@ describe('parentToolCallId-aware text merging', () => {
);
});
});

describe('turn attribution preservation (DAEMON-007)', () => {
/**
* Stamp top-level prompt/originator attribution and/or a `data.sessionId`
* onto a factory-built event, mirroring what the bridge publishes.
*/
function withAttribution(
event: BridgeEvent,
attrs: {
promptId?: string;
originatorClientId?: string;
sessionId?: string;
},
): BridgeEvent {
const out: BridgeEvent = { ...event };
if (attrs.promptId !== undefined) out.promptId = attrs.promptId;
if (attrs.originatorClientId !== undefined) {
out.originatorClientId = attrs.originatorClientId;
}
if (attrs.sessionId !== undefined) {
out.data = {
sessionId: attrs.sessionId,
...(event.data as Record<string, unknown>),
};
}
return out;
}

function compactedUpdates(
engine: TurnBoundaryCompactionEngine,
sessionUpdate: string,
): BridgeEvent[] {
return engine
.snapshot()
.compactedTurns.filter(
(e) =>
e.type === 'session_update' &&
(e.data as { update?: { sessionUpdate?: string } }).update
?.sessionUpdate === sessionUpdate,
);
}

it('merged text event keeps top-level promptId/originatorClientId and data.sessionId', () => {
const engine = new TurnBoundaryCompactionEngine();
engine.ingest(
withAttribution(makeTextChunk(1, 'hello '), {
promptId: 'p1',
originatorClientId: 'client-a',
sessionId: 's-1',
}),
);
engine.ingest(
withAttribution(makeTextChunk(2, 'world'), {
promptId: 'p1',
originatorClientId: 'client-a',
sessionId: 's-1',
}),
);
engine.ingest(makeTurnComplete(3));

const [merged] = compactedUpdates(engine, 'agent_message_chunk');
expect(merged).toBeDefined();
expect(merged!.promptId).toBe('p1');
expect(merged!.originatorClientId).toBe('client-a');
expect((merged!.data as { sessionId?: string }).sessionId).toBe('s-1');
expect(
(merged!.data as { update: { content: { text: string } } }).update.content
.text,
).toBe('hello world');
});

it('merged thought event keeps attribution, latest chunk wins', () => {
const engine = new TurnBoundaryCompactionEngine();
engine.ingest(
withAttribution(makeThoughtChunk(1, 'thinking '), {
promptId: 'p1',
sessionId: 's-1',
}),
);
// Later chunk carries a fresher stamp — the merged event must carry it.
engine.ingest(
withAttribution(makeThoughtChunk(2, 'harder'), {
promptId: 'p2',
originatorClientId: 'client-b',
sessionId: 's-1',
}),
);
engine.ingest(makeTurnComplete(3));

const [merged] = compactedUpdates(engine, 'agent_thought_chunk');
expect(merged!.promptId).toBe('p2');
expect(merged!.originatorClientId).toBe('client-b');
expect((merged!.data as { sessionId?: string }).sessionId).toBe('s-1');
});

it('keeps an earlier attribution when a later chunk carries none', () => {
const engine = new TurnBoundaryCompactionEngine();
engine.ingest(
withAttribution(makeTextChunk(1, 'a'), {
promptId: 'p1',
originatorClientId: 'client-a',
sessionId: 's-1',
}),
);
engine.ingest(makeTextChunk(2, 'b'));
engine.ingest(makeTurnComplete(3));

const [merged] = compactedUpdates(engine, 'agent_message_chunk');
expect(merged!.promptId).toBe('p1');
expect(merged!.originatorClientId).toBe('client-a');
expect((merged!.data as { sessionId?: string }).sessionId).toBe('s-1');
});

it('subagent (parentToolCallId) merge path also preserves attribution', () => {
const engine = new TurnBoundaryCompactionEngine();
engine.ingest(
withAttribution(makeTextChunkWithParent(1, 'sub ', 'task-A'), {
promptId: 'p1',
sessionId: 's-1',
}),
);
engine.ingest(
withAttribution(makeTextChunkWithParent(2, 'agent', 'task-A'), {
promptId: 'p1',
sessionId: 's-1',
}),
);
engine.ingest(makeTurnComplete(3));

const [merged] = compactedUpdates(engine, 'agent_message_chunk');
expect(merged!.promptId).toBe('p1');
expect((merged!.data as { sessionId?: string }).sessionId).toBe('s-1');
});

it('folded tool_call keeps latest promptId/originatorClientId and data.sessionId', () => {
const engine = new TurnBoundaryCompactionEngine();
engine.ingest(
withAttribution(makeToolCall(1, 'tc1', 'running', { title: 'Read' }), {
promptId: 'p1',
originatorClientId: 'client-a',
sessionId: 's-1',
}),
);
engine.ingest(
withAttribution(makeToolCallUpdate(2, 'tc1', 'done'), {
promptId: 'p1',
originatorClientId: 'client-a',
sessionId: 's-1',
}),
);
engine.ingest(makeTurnComplete(3));

const [folded] = compactedUpdates(engine, 'tool_call');
expect(folded!.promptId).toBe('p1');
expect(folded!.originatorClientId).toBe('client-a');
expect((folded!.data as { sessionId?: string }).sessionId).toBe('s-1');
expect((folded!.data as { update: { status: string } }).update.status).toBe(
'done',
);
});

it('folded tool_call falls back to the existing stamp when the update carries none', () => {
const engine = new TurnBoundaryCompactionEngine();
engine.ingest(
withAttribution(makeToolCall(1, 'tc1', 'running'), {
promptId: 'p1',
originatorClientId: 'client-a',
}),
);
engine.ingest(makeToolCallUpdate(2, 'tc1', 'done'));
engine.ingest(makeTurnComplete(3));

const [folded] = compactedUpdates(engine, 'tool_call');
expect(folded!.promptId).toBe('p1');
expect(folded!.originatorClientId).toBe('client-a');
});

it('does not invent attribution fields when source events carry none', () => {
const engine = new TurnBoundaryCompactionEngine();
engine.ingest(makeTextChunk(1, 'hello '));
engine.ingest(makeTextChunk(2, 'world'));
engine.ingest(makeToolCall(3, 'tc1', 'running'));
engine.ingest(makeToolCallUpdate(4, 'tc1', 'done'));
engine.ingest(makeTurnComplete(5));

const [mergedText] = compactedUpdates(engine, 'agent_message_chunk');
expect('promptId' in mergedText!).toBe(false);
expect('originatorClientId' in mergedText!).toBe(false);
expect('sessionId' in (mergedText!.data as object)).toBe(false);

const [folded] = compactedUpdates(engine, 'tool_call');
expect('promptId' in folded!).toBe(false);
expect('originatorClientId' in folded!).toBe(false);
expect('sessionId' in (folded!.data as object)).toBe(false);
});
});
Loading
Loading