A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): opening busy sessions no longer re-transfers the full transcript (#2260)
Florian Brand9661a1151525
diff --git a/packages/coding-agent/.changes/debug-slow-chat-loading.md b/packages/coding-agent/.changes/debug-slow-chat-loading.mdnew file mode 100644index 0000000000..fe32fb5492--- /dev/null+++ b/packages/coding-agent/.changes/debug-slow-chat-loading.md@@ -0,0 +1,6 @@+- Sped up opening long live sessions: events arriving during the snapshot load now replay incrementally instead of each one triggering a full transcript re-transfer.+- Capped resync and settings-rebuild transcript renders to the recent tail, matching the initial open.+- Stopped the chat from re-fetching the whole transcript when a live event lands between attach and the first render.+- Fixed event ordering and snapshot recovery when opening busy sessions, switching sessions, or reconnecting, while preserving live updates in headless modes.+- Fixed snapshot transfers continuing after a session closes.+- Limited memory retained by live updates while a slow snapshot loads.diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.tsindex f73f51ca36..34f39e4a03 100644--- a/packages/coding-agent/src/main.ts+++ b/packages/coding-agent/src/main.ts@@ -1067,6 +1067,7 @@ async function createDaemonClientConnection(options: {const attach = async (summary: SessionSummary) => {const connection = await DaemonAgentConnection.attach(client, getDaemonSummaryActiveSessionId(summary), {closeClientOnDispose: true,+ deferSessionEvents: options.config.executionMode === "interactive",sendClientEnv: true,ownedSession: options.clientOwned,ownedSessionRecoveryConfig: options.clientOwned ? options.config : undefined,diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.tsindex cba3b6d22d..c9a63b90ba 100644--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts@@ -37,6 +37,7 @@ import {type DaemonReplayInfo,type DaemonSessionClosedReason,type DaemonSessionSnapshot,+ isDaemonDialogExtensionUiRequest,isUnknownDaemonCommandError,} from "../daemon/daemon-protocol.js";import {@@ -103,6 +104,7 @@ type DaemonSnapshotBegin = Extract<DaemonOutbound, { type: "session_snapshot_beginterface DaemonSnapshotAssembly {begin?: DaemonSnapshotBegin;+ apply?: (snapshot: DaemonSessionSnapshot) => void;chunks: Map<number, AgentMessage[]>;promise: Promise<DaemonSessionSnapshot>;resolve: (snapshot: DaemonSessionSnapshot) => void;@@ -115,6 +117,9 @@ const DAEMON_LONG_RUNNING_REQUEST_TIMEOUT_MS = 24 * 60 * 60 * 1000;export const DAEMON_RECONNECT_TIMEOUT_MS = 60_000;export const DAEMON_SNAPSHOT_TIMEOUT_MS = 30_000;const MAX_IGNORED_SNAPSHOT_IDS = 128;+// Overflow replaces the initial render with a fresh attach snapshot.+const MAX_DEFERRED_SESSION_EVENTS = 1000;+const MAX_PENDING_EXTENSION_UI_REQUESTS = 128;const UPDATE_RECONNECT_TIMEOUT_MS = 120000;const UPDATE_RECONNECT_RETRY_MS = 100;const MAX_COMPLETED_SNAPSHOTS = 128;@@ -165,6 +170,14 @@ function reconnectDaemonTransportAfterUpdate(client: DaemonTransportClient): Proexport interface DaemonAgentConnectionOptions {closeClientOnDispose?: boolean;+ /**+ * Defer session events between attach and the first+ * flushBufferedSessionEvents() call. The interactive connection opts in so+ * its initial render can use the attach snapshot as-is (no full+ * get_messages re-fetch) and apply buffered events on top afterwards.+ * Watchers and one-shot clients leave this off and keep live delivery.+ */+ deferSessionEvents?: boolean;/** Secondary watchers pass false to stay on the shared control-plane socket. */directTransport?: boolean;/** Restart/probe the detached supervisor after a transient socket loss. */@@ -223,6 +236,7 @@ export function buildSessionTreeFromFlatNodes(export class DaemonAgentConnection implements AgentConnection {private readonly listeners = new Set<AgentConnectionEventListener>();+ private readonly pendingExtensionUiRequests: Extract<DaemonOutbound, { type: "extension_ui_request" }>[] = [];private readonly unsubscribeDaemonMessages: () => void;private readonly unsubscribeDaemonClose: () => void;private readonly clientId = `daemon-agent-connection:${randomUUID()}`;@@ -235,6 +249,15 @@ export class DaemonAgentConnection implements AgentConnection {private childRosterSequence: number | undefined;private latestSnapshot: AgentConnectionSnapshot | undefined;private latestSnapshotIsFresh = false;+ private deferredSessionEvents: {+ event: AgentSessionEvent;+ sequence: number | undefined;+ generation: string | undefined;+ }[] = [];+ private deferSessionEvents = false;+ private deferredSessionEventsOverflowed = false;+ private deferredSessionEventFlush: Promise<void> | undefined;+ private sessionRevision = 0;private attachedSessionId: string | undefined;private attachedSessionFile: string | undefined;private daemonLogPath: string | undefined;@@ -264,6 +287,7 @@ export class DaemonAgentConnection implements AgentConnection {if (options.recoverDaemon) {this.client.enableRequestRecovery();}+ this.deferSessionEvents = options.deferSessionEvents === true;this.unsubscribeDaemonMessages = this.client.onMessage((message) => {void this.handleDaemonMessage(message).catch((error: unknown) => {try {@@ -374,6 +398,8 @@ export class DaemonAgentConnection implements AgentConnection {}async attach(options?: { recoverable?: boolean }): Promise<void> {+ if (this.disposed || this.terminalCloseEmitted) throw new Error("Daemon session closed during attach");+ const sessionRevision = this.sessionRevision;const supportsExtensionUi = this.options.supportsExtensionUi !== false;const result = await this.requestData<SessionSummary | DaemonAttachResult>({@@ -406,9 +432,55 @@ export class DaemonAgentConnection implements AgentConnection {},},undefined,- options,+ {+ ...options,+ onResponse: (response) => {+ if (+ !response.success ||+ this.disposed ||+ this.terminalCloseEmitted ||+ sessionRevision !== this.sessionRevision+ )+ return;+ const result = response.data as SessionSummary | DaemonAttachResult;+ this.activeSessionId = getAttachActiveSessionId(result);+ if ("snapshot" in result && result.snapshotStream) {+ this.getSnapshotAssembly(result.snapshotStream.id).apply = (snapshot) => {+ if (sessionRevision === this.sessionRevision) this.applySessionSnapshot(snapshot, result.replay);+ };+ }+ },+ },);+ if (this.disposed || this.terminalCloseEmitted) throw new Error("Daemon session closed during attach");+ if (sessionRevision !== this.sessionRevision) {+ if ("snapshot" in result && result.snapshotStream) {+ const snapshotId = result.snapshotStream.id;+ const assembly = this.snapshotAssemblies.get(snapshotId);+ if (assembly) {+ this.rejectSnapshotAssembly(snapshotId, assembly, new Error("Snapshot attach was superseded"));+ this.snapshotAssemblies.delete(snapshotId);+ }+ this.ignoreSnapshotId(snapshotId);+ }+ return;+ }this.activeSessionId = getAttachActiveSessionId(result);+ if ("snapshot" in result && result.snapshotStream) {+ await this.waitForSnapshot(result.snapshotStream.id);+ } else {+ const attachCursor = getAttachLastEventCursor(result);+ if (attachCursor) this.observeEventCursor(attachCursor);+ this.lastEventSequence = maxEventSequence(this.lastEventSequence, getAttachLastEventSequence(result));+ if ("snapshot" in result) {+ this.applySessionSnapshot(result.snapshot, result.replay);+ } else {+ this.latestSnapshot = undefined;+ this.latestSnapshotIsFresh = false;+ }+ }+ if (this.disposed || this.terminalCloseEmitted) throw new Error("Daemon session closed during attach");+ if (sessionRevision !== this.sessionRevision) return;const summary = "snapshot" in result ? result.snapshot.summary : result;this.attachedSessionId = summary.sessionId;this.attachedSessionFile =@@ -416,28 +488,6 @@ export class DaemonAgentConnection implements AgentConnection {this.captureDaemonLogPath();this.updateReconnectFailed = false;this.terminalCloseEmitted = false;- const attachCursor = getAttachLastEventCursor(result);- if (attachCursor) {- this.observeEventCursor(attachCursor);- }- this.lastEventSequence = maxEventSequence(this.lastEventSequence, getAttachLastEventSequence(result));- if ("snapshot" in result) {- const snapshot = result.snapshotStream- ? await this.waitForSnapshot(result.snapshotStream.id)- : result.snapshot;- this.latestSnapshot = mapDaemonSessionSnapshot(snapshot, result.replay);- if (Array.isArray(snapshot.children)) this.childRosterSequence = snapshot.lastEventSequence;- if (this.lastEventSequence !== undefined) {- this.latestSnapshot.lastEventSequence = this.lastEventSequence;- }- if (this.lastEventCursor) {- this.latestSnapshot.lastEventCursor = this.lastEventCursor;- }- this.latestSnapshotIsFresh = true;- } else {- this.latestSnapshot = undefined;- this.latestSnapshotIsFresh = false;- }// The roster bar is an accessory: its subscribe failure must never fail an// otherwise-recovered session. The bar degrades; the next reconnect or rebind// re-attaches through this same seam.@@ -461,6 +511,7 @@ export class DaemonAgentConnection implements AgentConnection {subscribe(listener: AgentConnectionEventListener): () => void {this.listeners.add(listener);+ for (const request of this.pendingExtensionUiRequests.splice(0)) void this.handleDaemonMessage(request);return () => {this.listeners.delete(listener);};@@ -528,6 +579,95 @@ export class DaemonAgentConnection implements AgentConnection {return this.latestSnapshot;}+ /**+ * Stop deferring session events and replay everything buffered so far. The+ * interactive UI calls this once its initial transcript render is complete,+ * so deferred events apply on top of a fully rendered chat.+ */+ flushBufferedSessionEvents(): Promise<void> {+ if (this.deferredSessionEventFlush) return this.deferredSessionEventFlush;+ if (!this.deferSessionEvents) {+ return Promise.resolve();+ }+ this.deferredSessionEventFlush = Promise.resolve()+ .then(async () => {+ const deliveries: Promise<void>[] = [];+ while (!this.disposed && !this.terminalCloseEmitted) {+ if (this.deferredSessionEventsOverflowed) {+ this.deferredSessionEventsOverflowed = false;+ // Reattach provides one consistent snapshot, including the streaming message.+ const sessionRevision = this.sessionRevision;+ try {+ await this.attach();+ } catch (error) {+ if (sessionRevision === this.sessionRevision) throw error;+ }+ if (this.disposed || this.terminalCloseEmitted) return;+ if (sessionRevision !== this.sessionRevision || this.deferredSessionEventsOverflowed) continue;+ const snapshot = await this.getInitialSnapshot();+ if (sessionRevision === this.sessionRevision)+ deliveries.push(this.emit({ type: "session_resynced", snapshot }));+ continue;+ }+ const deferred = this.deferredSessionEvents.shift();+ if (!deferred) {+ this.stopDeferringSessionEvents();+ break;+ }+ const { event, sequence } = deferred;+ this.observeStreamingMessage(event);+ if (event.type === "rlm_child_update") {+ this.childRosterSequence = maxEventSequence(this.childRosterSequence, sequence);+ this.observeRlmChildUpdate(event.child);+ }+ this.latestSnapshotIsFresh = false;+ // Enqueue the whole replay before yielding; the UI serializes its rendering.+ deliveries.push(this.emit({ type: "session_event", event }));+ }+ await Promise.all(deliveries);+ })+ .catch(async (error: unknown) => {+ if (this.disposed || this.terminalCloseEmitted) return;+ this.terminalCloseEmitted = true;+ await this.emit({ type: "closed", error: `Failed to recover deferred session events: ${String(error)}` });+ })+ .finally(() => {+ this.stopDeferringSessionEvents();+ this.deferredSessionEventFlush = undefined;+ });+ return this.deferredSessionEventFlush;+ }++ private stopDeferringSessionEvents(): void {+ this.deferSessionEvents = false;+ this.deferredSessionEvents.length = 0;+ this.deferredSessionEventsOverflowed = false;+ }++ /**+ * Keep only events newer than the snapshot in the same worker generation.+ */+ private dropDeferredSessionEventsThrough(+ snapshotSequence: number | undefined,+ snapshotCursor: DaemonEventCursor | undefined,+ ): void {+ if (+ snapshotCursor?.generation !== this.lastEventCursor?.generation ||+ (snapshotSequence !== undefined &&+ this.lastEventSequence !== undefined &&+ snapshotSequence >= this.lastEventSequence)+ ) {+ this.deferredSessionEventsOverflowed = false;+ }+ this.deferredSessionEvents = this.deferredSessionEvents.filter(+ (entry) =>+ entry.generation === snapshotCursor?.generation &&+ (entry.sequence !== undefined && snapshotSequence !== undefined+ ? entry.sequence > snapshotSequence+ : entry.sequence === undefined && snapshotSequence === undefined),+ );+ }+async getRlmChildSnapshots(): Promise<AgentConnectionRlmChildAgentSnapshot[]> {if (!this.client.supportsServerCapability("authoritative_child_roster")) {throw new DaemonCapabilityUnavailableError("get_rlm_children", "authoritative_child_roster");@@ -1344,7 +1484,12 @@ export class DaemonAgentConnection implements AgentConnection {latestSnapshot: this.latestSnapshot,latestSnapshotIsFresh: this.latestSnapshotIsFresh,retiredEventGenerations: new Set(this.retiredEventGenerations),+ deferredSessionEvents: this.deferredSessionEvents,+ deferredSessionEventsOverflowed: this.deferredSessionEventsOverflowed,};+ this.sessionRevision++;+ this.deferredSessionEvents = [];+ this.deferredSessionEventsOverflowed = false;this.activeSessionId = targetActiveSessionId;this.lastEventCursor = undefined;this.lastEventSequence = undefined;@@ -1389,7 +1534,7 @@ export class DaemonAgentConnection implements AgentConnection {}}} else {- this.applyReplacementSnapshot(result.snapshot, result.replay);+ this.applySessionSnapshot(result.snapshot, result.replay);await this.emit({type: "session_replaced",state: result.snapshot.state,@@ -1404,6 +1549,8 @@ export class DaemonAgentConnection implements AgentConnection {this.lastEventSequence = previousState.lastEventSequence;this.latestSnapshot = previousState.latestSnapshot;this.latestSnapshotIsFresh = previousState.latestSnapshotIsFresh;+ this.deferredSessionEvents = previousState.deferredSessionEvents;+ this.deferredSessionEventsOverflowed = previousState.deferredSessionEventsOverflowed;this.retiredEventGenerations.clear();for (const generation of previousState.retiredEventGenerations) {this.retiredEventGenerations.add(generation);@@ -1536,6 +1683,7 @@ export class DaemonAgentConnection implements AgentConnection {);}this.disposed = true;+ this.pendingExtensionUiRequests.length = 0;this.updateRestartPending = false;await Promise.allSettled([...this.activeSideQuestionIds].map((id) => this.abortSideQuestion(id)));await this.rosterStore?.dispose().catch(() => undefined);@@ -1588,7 +1736,7 @@ export class DaemonAgentConnection implements AgentConnection {let deadline: number | undefined;let attempt = 0;let lastError: Error = cause;- while (!this.disposed) {+ while (!this.disposed && !this.terminalCloseEmitted) {// A held direct link owns session liveness: control-plane recovery retries unbounded,// and the bounded session-plane deadline arms only once the direct link is gone.const directSessionHeld = this.client instanceof DaemonRoutedClient && this.client.hasDirectTransport;@@ -1601,7 +1749,7 @@ export class DaemonAgentConnection implements AgentConnection {let controlPlaneHandshakeComplete = false;try {await this.options.recoverDaemon?.();- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}await this.client.connect(1000);@@ -1625,15 +1773,16 @@ export class DaemonAgentConnection implements AgentConnection {}// This loop owns the retry: a socket close must reject these instead of parking them behind a hello it can never produce.await this.attach({ recoverable: false });- if (!this.disposed) {+ if (!this.disposed && !this.terminalCloseEmitted) {const snapshot = await this.getInitialSnapshot({ recoverable: false });+ if (this.disposed || this.terminalCloseEmitted) return;void this.emit({ type: "session_resynced", snapshot });void this.emit({ type: "connection_status", status: "connected" });}return;} catch (error) {lastError = error instanceof Error ? error : new Error(String(error));- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}// A direct-half failure must not tear down a control-plane socket with a completed handshake.@@ -1655,7 +1804,7 @@ export class DaemonAgentConnection implements AgentConnection {await new Promise((resolveDelay) => setTimeout(resolveDelay, delayMs));}}- if (!this.disposed) {+ if (!this.disposed && !this.terminalCloseEmitted) {this.sessionInputPauses.clear();this.sessionInputPauseGeneration++;this.client.close();@@ -1689,6 +1838,7 @@ export class DaemonAgentConnection implements AgentConnection {}private async handleDaemonMessage(message: DaemonOutbound): Promise<void> {+ if (this.disposed || this.terminalCloseEmitted) return;if (message.type === "heartbeats_changed") {await this.emit({ type: "heartbeats_changed" });return;@@ -1696,6 +1846,34 @@ export class DaemonAgentConnection implements AgentConnection {if (!this.isMessageForActiveSession(message)) {return;}+ // Requests bypass snapshot deferral and must not advance the replay cursor.+ if (message.type === "extension_ui_request") {+ const cursor = getDaemonMessageCursor(message);+ if (cursor && this.retiredEventGenerations.has(cursor.generation)) return;+ // Retain attach-time requests until the UI subscribes; snapshots cannot restore them.+ if (this.listeners.size === 0) {+ if (this.pendingExtensionUiRequests.length >= MAX_PENDING_EXTENSION_UI_REQUESTS) {+ // Discard older non-dialog updates before cancelling a dialog that cannot be queued.+ const disposable = this.pendingExtensionUiRequests.findIndex(+ (request) => !isDaemonDialogExtensionUiRequest(request.method),+ );+ if (disposable === -1) {+ if (isDaemonDialogExtensionUiRequest(message.method)) {+ await this.respondToExtensionUiRequest(message.id, { cancelled: true });+ }+ return;+ }+ this.pendingExtensionUiRequests.splice(disposable, 1);+ }+ this.pendingExtensionUiRequests.push(message);+ return;+ }+ await this.emit({+ type: "extension_ui_request",+ request: { id: message.id, method: message.method, payload: message.payload },+ });+ return;+ }if ("snapshotId" in message && this.ignoredSnapshotIds.has(message.snapshotId)) {if (message.type === "session_snapshot_end" || message.type === "session_snapshot_failed") {this.ignoredSnapshotIds.delete(message.snapshotId);@@ -1743,6 +1921,20 @@ export class DaemonAgentConnection implements AgentConnection {this.observeDaemonEventSequence(message);if (message.type === "session_event") {+ if (this.deferSessionEvents) {+ if (this.deferredSessionEventsOverflowed) return;+ if (this.deferredSessionEvents.length >= MAX_DEFERRED_SESSION_EVENTS) {+ this.deferredSessionEvents.length = 0;+ this.deferredSessionEventsOverflowed = true;+ } else {+ this.deferredSessionEvents.push({+ event: message.event,+ sequence: getDaemonMessageSequence(message),+ generation: getDaemonMessageCursor(message)?.generation,+ });+ }+ return;+ }if (message.event.type !== "refine_complete" && message.event.type !== "refine_failed") {this.observeStreamingMessage(message.event);}@@ -1771,25 +1963,19 @@ export class DaemonAgentConnection implements AgentConnection {return;}if (message.type === "session_resynced") {- this.attachedSessionId = message.snapshot.state.sessionId;- this.attachedSessionFile = message.snapshot.state.sessionFile;- this.latestSnapshot = mapDaemonSessionSnapshot(message.snapshot);- if (Array.isArray(message.snapshot.children)) {- this.childRosterSequence = message.snapshot.lastEventSequence;- }- if (this.lastEventSequence !== undefined) {- this.latestSnapshot.lastEventSequence = this.lastEventSequence;- }- if (this.lastEventCursor) {- this.latestSnapshot.lastEventCursor = this.lastEventCursor;- }- this.latestSnapshotIsFresh = true;- await this.emit({ type: "session_resynced", snapshot: this.latestSnapshot });+ this.applySessionSnapshot(message.snapshot);+ await this.emit({ type: "session_resynced", snapshot: this.latestSnapshot! });return;}if (message.type === "session_replaced") {+ this.sessionRevision++;+ this.pendingExtensionUiRequests.length = 0;this.attachedSessionId = message.state.sessionId;this.attachedSessionFile = message.state.sessionFile;+ // Buffered events belong to the replaced session; they must never+ // replay onto the new one. The replacement snapshot rebuilds state.+ this.deferredSessionEvents.length = 0;+ this.deferredSessionEventsOverflowed = false;if (message.snapshotFollows) {this.latestSnapshotIsFresh = false;return;@@ -1810,17 +1996,6 @@ export class DaemonAgentConnection implements AgentConnection {await this.emit({ type: "session_replaced", state: message.state, messages: message.messages });return;}- if (message.type === "extension_ui_request") {- await this.emit({- type: "extension_ui_request",- request: {- id: message.id,- method: message.method,- payload: message.payload,- },- });- return;- }if (message.type === "extension_error") {await this.emit({type: "extension_error",@@ -1838,7 +2013,9 @@ export class DaemonAgentConnection implements AgentConnection {return;}this.terminalCloseEmitted = true;- await this.emit({ type: "closed", error: this.formatDaemonSessionClosedError(message.reason) });+ const error = this.formatDaemonSessionClosedError(message.reason);+ this.rejectSnapshotAssemblies(new Error(error));+ await this.emit({ type: "closed", error });}}@@ -1889,6 +2066,7 @@ export class DaemonAgentConnection implements AgentConnection {if (this.updateReconnectPromise) {return this.updateReconnectPromise;}+ this.pendingExtensionUiRequests.length = 0;void this.emit({type: "connection_status",status: "reconnecting",@@ -1897,14 +2075,14 @@ export class DaemonAgentConnection implements AgentConnection {const reconnectPromise = reconnectDaemonTransportAfterUpdate(this.client).then(() => this.restoreConnectionAfterUpdate()).then(() => {- if (!this.disposed) {+ if (!this.disposed && !this.terminalCloseEmitted) {void this.emit({ type: "connection_status", status: "connected" });}}).catch(async (error: unknown) => {this.updateRestartPending = false;this.updateReconnectFailed = true;- if (!this.disposed) {+ if (!this.disposed && !this.terminalCloseEmitted) {this.terminalCloseEmitted = true;await this.emit({type: "closed",@@ -1929,15 +2107,15 @@ export class DaemonAgentConnection implements AgentConnection {}const deadline = Date.now() + UPDATE_RECONNECT_TIMEOUT_MS;let lastError: unknown;- while (!this.disposed && Date.now() < deadline) {+ while (!this.disposed && !this.terminalCloseEmitted && Date.now() < deadline) {try {await this.client.reconnect(1000);- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}// This loop owns the retry: a socket close must reject these instead of parking them behind a hello it can never produce.const response = await this.client.request({ type: "list" }, 30000, { recoverable: false });- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}if (!response.success) {@@ -1951,19 +2129,20 @@ export class DaemonAgentConnection implements AgentConnection {(sessionId !== undefined && summary.sessionId === sessionId)),);if (restored?.activeSessionId) {- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}+ this.sessionRevision++;this.activeSessionId = restored.activeSessionId;this.lastEventSequence = undefined;this.lastEventCursor = undefined;this.retiredEventGenerations.clear();await this.attach({ recoverable: false });- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}const snapshot = await this.getInitialSnapshot({ recoverable: false });- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}this.updateRestartPending = false;@@ -1973,9 +2152,10 @@ export class DaemonAgentConnection implements AgentConnection {} catch (error) {lastError = error;}+ if (this.disposed || this.terminalCloseEmitted) return;await delay(UPDATE_RECONNECT_RETRY_MS);}- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}throw lastError ?? new Error("the restored session did not become available");@@ -2050,7 +2230,7 @@ export class DaemonAgentConnection implements AgentConnection {}try {const snapshot = await this.getInitialSnapshot();- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}this.attachedSessionId = snapshot.state.sessionId;@@ -2061,7 +2241,7 @@ export class DaemonAgentConnection implements AgentConnection {await this.emit({ type: "session_resynced", snapshot });}} catch (recoveryError) {- if (this.disposed) {+ if (this.disposed || this.terminalCloseEmitted) {return;}this.terminalCloseEmitted = true;@@ -2088,7 +2268,8 @@ export class DaemonAgentConnection implements AgentConnection {}}- private applyReplacementSnapshot(snapshot: DaemonSessionSnapshot, replay?: DaemonReplayInfo): void {+ private applySessionSnapshot(snapshot: DaemonSessionSnapshot, replay?: DaemonReplayInfo): void {+ this.dropDeferredSessionEventsThrough(snapshot.lastEventSequence, snapshot.lastEventCursor);if (snapshot.lastEventCursor) {this.observeEventCursor(snapshot.lastEventCursor);}@@ -2096,6 +2277,8 @@ export class DaemonAgentConnection implements AgentConnection {this.attachedSessionId = snapshot.state.sessionId;this.attachedSessionFile = snapshot.state.sessionFile;this.latestSnapshot = mapDaemonSessionSnapshot(snapshot, replay);+ this.latestSnapshot.lastEventSequence = this.lastEventSequence;+ this.latestSnapshot.lastEventCursor = this.lastEventCursor;this.childRosterSequence = Array.isArray(snapshot.children) ? snapshot.lastEventSequence : undefined;this.latestSnapshotIsFresh = true;}@@ -2151,34 +2334,28 @@ export class DaemonAgentConnection implements AgentConnection {lastEventSequence: message.lastEventSequence,lastEventCursor: message.lastEventCursor,};- if (message.lastEventCursor) {- this.observeEventCursor(message.lastEventCursor);- }- this.lastEventSequence = maxEventSequence(this.lastEventSequence, message.lastEventSequence);- this.attachedSessionId = snapshot.state.sessionId;- this.attachedSessionFile = snapshot.state.sessionFile;- this.latestSnapshot = mapDaemonSessionSnapshot(snapshot);- this.latestSnapshotIsFresh = true;- assembly.resolve(snapshot);const purpose = assembly.begin.purpose ?? "attach";+ // Attach owns the revision guard, but its snapshot must precede the next record in this socket read.+ if (purpose === "attach") assembly.apply?.(snapshot);+ assembly.resolve(snapshot);clearTimeout(assembly.timeout);- if (purpose !== "attach") {- this.snapshotAssemblies.delete(message.snapshotId);- if (this.pendingReattachActiveSessionIds.has(message.activeSessionId)) {- this.completedSnapshots.set(message.snapshotId, snapshot);- while (this.completedSnapshots.size > MAX_COMPLETED_SNAPSHOTS) {- const oldest = this.completedSnapshots.keys().next().value;- if (oldest === undefined) {- break;- }- this.completedSnapshots.delete(oldest);+ if (purpose === "attach") return;+ this.applySessionSnapshot(snapshot);+ this.snapshotAssemblies.delete(message.snapshotId);+ if (this.pendingReattachActiveSessionIds.has(message.activeSessionId)) {+ this.completedSnapshots.set(message.snapshotId, snapshot);+ while (this.completedSnapshots.size > MAX_COMPLETED_SNAPSHOTS) {+ const oldest = this.completedSnapshots.keys().next().value;+ if (oldest === undefined) {+ break;}+ this.completedSnapshots.delete(oldest);}}if (purpose === "replacement") {await this.emit({ type: "session_replaced", state: snapshot.state, messages });} else if (purpose === "resync") {- await this.emit({ type: "session_resynced", snapshot: this.latestSnapshot });+ await this.emit({ type: "session_resynced", snapshot: this.latestSnapshot! });}}@@ -2253,6 +2430,7 @@ export class DaemonAgentConnection implements AgentConnection {private observeEventCursor(cursor: DaemonEventCursor): void {const current = this.lastEventCursor;+ if (current?.generation !== cursor.generation) this.lastEventSequence = cursor.sequence;if (current && current.generation !== cursor.generation) {this.retiredEventGenerations.add(current.generation);}diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.tsindex 0ae4094b37..894d639664 100644--- a/packages/coding-agent/src/modes/agent-connection/types.ts+++ b/packages/coding-agent/src/modes/agent-connection/types.ts@@ -645,6 +645,13 @@ export interface AgentConnection {getState(): Promise<AgentConnectionState>;getInitialSnapshot(): Promise<AgentConnectionSnapshot>;+ /**+ * Replay session events the adapter deferred between attach and this call.+ * Only deferring adapters implement it; the interactive UI calls it once+ * its initial transcript render is complete, so deferred events apply on+ * top of a fully rendered chat instead of racing the initial build.+ */+ flushBufferedSessionEvents?(): Promise<void>;getRlmChildSnapshots(): Promise<AgentConnectionRlmChildAgentSnapshot[]>;getMessages(): Promise<AgentMessage[]>;getSessionHeader(): Promise<AgentConnectionSessionHeader | undefined>;diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.tsindex 8673849cb7..06a21edb4c 100644--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts@@ -342,6 +342,7 @@ async function openAgentsViewSession(try {const connection = await DaemonAgentConnection.attach(client, summary.activeSessionId, {closeClientOnDispose: true,+ deferSessionEvents: true,recoverDaemon: options.recoverDaemon,reconnectTimeoutMs: options.reconnectTimeoutMs,telemetryDisabled: options.config.telemetryDisabled,@@ -369,6 +370,7 @@ async function openAgentsViewSession(const resumed = await resumeSavedAgentsViewSession(client, options.config, summary);const connection = await DaemonAgentConnection.attach(client, resumed.activeSessionId, {closeClientOnDispose: true,+ deferSessionEvents: true,recoverDaemon: options.recoverDaemon,reconnectTimeoutMs: options.reconnectTimeoutMs,telemetryDisabled: options.config.telemetryDisabled,diff --git a/packages/coding-agent/src/modes/daemon/active-session-state.ts b/packages/coding-agent/src/modes/daemon/active-session-state.tsindex f71711831a..a1403ce272 100644--- a/packages/coding-agent/src/modes/daemon/active-session-state.ts+++ b/packages/coding-agent/src/modes/daemon/active-session-state.ts@@ -2,7 +2,12 @@ import { randomUUID } from "node:crypto";import type { Socket } from "node:net";import type { AgentSessionRuntime } from "../../core/agent-session-runtime.js";import type { AgentStatus } from "../../core/session-manager.js";-import type { DaemonClientCapability, DaemonEventSequence, DaemonExtensionUIResponse } from "./daemon-protocol.js";+import type {+ DaemonClientCapability,+ DaemonEventSequence,+ DaemonExtensionUIResponse,+ DaemonOutbound,+} from "./daemon-protocol.js";import { formatSessionDisplayId, matchesSessionIdSuffix } from "./daemon-session-id.js";export interface DaemonSocketClient {@@ -26,6 +31,21 @@ export interface DaemonSocketClient {transport?: "jsonl" | "private-framed";snapshotStreaming?: boolean;snapshotActiveSessionIds?: Set<string>;+ /**+ * Session frames withheld while a snapshot stream is active for that session+ * (worker side: DaemonOutbound). They replay when the stream completes+ * instead of each one triggering a full snapshot re-transfer.+ */+ deferredSessionOutbounds?: Map<string, { frames: DaemonOutbound[]; bytes: number }>;+ /** Worker-side sessions whose deferral buffer overflowed this stream. */+ deferredSessionFramesDropped?: Set<string>;+ /**+ * Relay payloads withheld while a snapshot stream is active for that session+ * (supervisor side: serialized buffers). Same replay-on-completion policy.+ */+ deferredSessionPayloads?: Map<string, { payloads: Buffer[]; bytes: number }>;+ /** Supervisor-side sessions whose deferral buffer overflowed this stream. */+ deferredSessionPayloadsDropped?: Set<string>;snapshotActiveSessionCounts?: Map<string, number>;snapshotTransferAbortControllers?: Map<string, AbortController>;snapshotTransferTails?: Map<string, Promise<void>>;diff --git a/packages/coding-agent/src/modes/daemon/daemon-client.ts b/packages/coding-agent/src/modes/daemon/daemon-client.tsindex f75cbed8e2..a396a567cc 100644--- a/packages/coding-agent/src/modes/daemon/daemon-client.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-client.ts@@ -35,6 +35,8 @@ export type DaemonClientProgressListener = (message: DaemonRequestProgress) => vexport interface DaemonClientRequestOptions {onProgress?: DaemonClientProgressListener;+ /** Runs synchronously before the reader dispatches any records following this response. */+ onResponse?: (response: DaemonResponse) => void;/*** False opts out of reconnect parking: a close rejects so the caller's own retry loop stays live.* Any caller that owns its own bounded retry MUST pass false; a parked request waits for a hello@@ -397,7 +399,14 @@ export class DaemonClient {return new Promise((resolve, reject) => {const pending: PendingDaemonRequest = {- resolve,+ resolve: (response) => {+ try {+ options.onResponse?.(response);+ resolve(response);+ } catch (error) {+ reject(error);+ }+ },reject,timeoutMs,commandType: command.type,diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex e50d7c5213..2bdfa8eee6 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -372,6 +372,14 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([const DAEMON_CLIENT_CAPABILITY_SET: ReadonlySet<string> = new Set(DAEMON_SUPPORTED_CLIENT_CAPABILITIES);const CLIENT_CATCHUP_RETRY_MS = 250;+/**+ * Upper bound on frames deferred per client and session while a snapshot+ * stream is active. Deferral spans one stream (seconds), so overflow means a+ * pathologically slow client; the sender then falls back to a catch-up+ * snapshot instead of buffering without limit.+ */+const MAX_DEFERRED_SESSION_FRAMES = 256;+const MAX_DEFERRED_SESSION_BYTES = 8 * 1024 * 1024;const UPDATE_RESTART_ABORT_BASH_TIMEOUT_MS = 5000;const SUPERVISOR_FENCE_POLL_MS = 250;const UPDATE_RESTART_MARKER =@@ -5553,7 +5561,7 @@ export class AgentDaemon {await deliverSnapshotFailure(new Error(`Snapshot ${stream.id} was aborted`));return;}- await this.writeWorkerSnapshotRecord(+ const snapshotDelivered = await this.writeWorkerSnapshotRecord(client,{type: "session_snapshot_end",@@ -5566,6 +5574,14 @@ export class AgentDaemon {purpose,transferSignal,);+ if (!snapshotDelivered) return;+ // A replay failure needs a resync; the snapshot is already delivered.+ try {+ this.flushDeferredSessionFrames(client, result.activeSessionId);+ } catch (error) {+ this.log(`could not replay deferred frames for ${result.activeSessionId}: ${String(error)}`);+ this.queueClientCatchup(client, result.activeSessionId, "resync");+ }} catch (error) {if (transferSignal.aborted) {await deliverSnapshotFailure(new Error(`Snapshot ${stream.id} was aborted`));@@ -5579,6 +5595,14 @@ export class AgentDaemon {if (client.snapshotTransferTails.get(result.activeSessionId) === transfer) {client.snapshotTransferTails.delete(result.activeSessionId);}+ // A failed final stream must recover any events held behind an earlier snapshot.+ if (+ (client.snapshotActiveSessionCounts?.get(result.activeSessionId) ?? 1) === 1 &&+ client.deferredSessionOutbounds?.get(result.activeSessionId)?.frames.length &&+ client.attachedActiveSessionIds.has(result.activeSessionId)+ ) {+ this.queueClientCatchup(client, result.activeSessionId, "resync");+ }finishClientSnapshotStreaming(client, result.activeSessionId);transcript.dispose?.();if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {@@ -6915,20 +6939,37 @@ export class AgentDaemon {if (!shouldSendDaemonOutboundToClient(client, sequencedMessage)) {continue;}+ // Snapshots cannot recover extension requests, so never defer or drop them.+ if (sequencedMessage.type === "extension_ui_request") {+ this.write(client, sequencedMessage);+ continue;+ }if (sequencedMessage.type === "session_closed") {+ this.discardDeferredSessionFrames(client, state.activeSessionId);client.catchupActiveSessionIds?.delete(state.activeSessionId);client.catchupPurposes?.delete(state.activeSessionId);this.write(client, sequencedMessage);continue;}if (client.snapshotActiveSessionIds?.has(state.activeSessionId)) {- this.queueClientCatchup(- client,- state.activeSessionId,- sequencedMessage.type === "session_replaced" ? "replacement" : "resync",- );+ // A replacement swaps the session wholesale; buffered frames from+ // the old session must never replay, so fall back to a replacement+ // catch-up snapshot.+ if (sequencedMessage.type === "session_replaced") {+ this.discardDeferredSessionFrames(client, state.activeSessionId);+ client.deferredSessionFramesDropped ??= new Set();+ client.deferredSessionFramesDropped.add(state.activeSessionId);+ this.queueClientCatchup(client, state.activeSessionId, "replacement");+ continue;+ }+ if (this.deferSessionFrame(client, state.activeSessionId, sequencedMessage)) {+ continue;+ }+ // The deferral buffer overflowed: fall back to a full resync.+ this.queueClientCatchup(client, state.activeSessionId, "resync");continue;}+ if (client.deferredSessionFramesDropped?.has(state.activeSessionId)) continue;if (client.backpressured === true) {this.queueClientCatchup(client,@@ -6962,11 +7003,25 @@ export class AgentDaemon {// Mark before the registry read so later events queue behind this snapshot.const snapshotSignal = markClientSnapshotStreaming(client, state.activeSessionId);void this.prepareReplacementSnapshot(client, state, message, snapshotSignal).catch((error) => {- finishClientSnapshotStreaming(client, state.activeSessionId);this.log(`could not prepare replacement snapshot: ${String(error)}`);- if (!client.socket.destroyed && this.sessions.get(state.activeSessionId) === state) {- this.write(client, message);+ if (+ !client.socket.destroyed &&+ !snapshotSignal.aborted &&+ client.attachedActiveSessionIds.has(state.activeSessionId) &&+ this.sessions.get(state.activeSessionId) === state+ ) {+ try {+ this.write(client, message);+ this.flushDeferredSessionFrames(client, state.activeSessionId);+ } catch (replayError) {+ client.deferredSessionFramesDropped ??= new Set();+ client.deferredSessionFramesDropped.add(state.activeSessionId);+ this.discardDeferredSessionFrames(client, state.activeSessionId);+ this.queueClientCatchup(client, state.activeSessionId, "replacement");+ this.log(`could not replay replacement events: ${String(replayError)}`);+ }}+ finishClientSnapshotStreaming(client, state.activeSessionId);if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {void this.catchUpBackpressuredClient(client).catch((catchupError) =>this.log(`could not catch up replacement snapshot: ${String(catchupError)}`),@@ -7360,12 +7415,15 @@ export class AgentDaemon {if (!state || !state.clients.has(client)) {continue;}+ // Buffer events before snapshot preparation can yield with a captured transcript.+ const snapshotSignal = markClientSnapshotStreaming(client, activeSessionId);+ let snapshotStarted = false;try {const result = await this.createAttachResult(client, state, {type: "attach",activeSessionId,});- if (this.sessions.get(activeSessionId) !== state || !state.clients.has(client)) {+ if (snapshotSignal.aborted || this.sessions.get(activeSessionId) !== state || !state.clients.has(client)) {continue;}if (@@ -7381,27 +7439,21 @@ export class AgentDaemon {snapshotFollows: true,meta: createDaemonEventMeta(activeSessionId,- state.lastEventSequence,+ result.lastEventSequence,undefined,state.eventGeneration,),});}const snapshotId = snapshotTransferId(result.snapshot);- const snapshotSignal = markClientSnapshotStreaming(client, activeSessionId);- let transcript: SnapshotTranscriptChunkSource;- try {- transcript = createSnapshotTranscriptChunks({- activeSessionId,- snapshotId,- messages: result.snapshot.messages,- targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,- signal: snapshotSignal,- });- } catch (error) {- finishClientSnapshotStreaming(client, activeSessionId);- throw error;- }+ const transcript = createSnapshotTranscriptChunks({+ activeSessionId,+ snapshotId,+ messages: result.snapshot.messages,+ targetChunkBytes: SNAPSHOT_TARGET_CHUNK_BYTES,+ signal: snapshotSignal,+ });+ snapshotStarted = true;await this.streamWorkerSnapshot(client,{@@ -7423,7 +7475,7 @@ export class AgentDaemon {}const meta = createDaemonEventMeta(activeSessionId,- state.lastEventSequence,+ result.lastEventSequence,undefined,state.eventGeneration,);@@ -7437,19 +7489,29 @@ export class AgentDaemon {meta,}: { type: "session_resynced", activeSessionId, snapshot: result.snapshot, meta };- if (!this.write(client, catchup)) {+ const accepted = this.write(client, catchup);+ this.flushDeferredSessionFrames(client, activeSessionId);+ if (!accepted) {for (const remaining of pending.slice(index + 1)) {this.queueClientCatchup(client, remaining.activeSessionId, remaining.purpose);}return "retry-later";}} catch (error) {+ if (snapshotSignal.aborted || this.sessions.get(activeSessionId) !== state || !state.clients.has(client)) {+ continue;+ }+ client.deferredSessionFramesDropped ??= new Set();+ client.deferredSessionFramesDropped.add(activeSessionId);+ this.discardDeferredSessionFrames(client, activeSessionId);for (const remaining of pending.slice(index)) {this.queueClientCatchup(client, remaining.activeSessionId, remaining.purpose);}this.log(`could not catch up client ${client.id} for ${activeSessionId}: ${String(error)}`);this.scheduleClientCatchupRetry(client);return "retry-later";+ } finally {+ if (!snapshotStarted) finishClientSnapshotStreaming(client, activeSessionId);}}return "drained";@@ -7470,6 +7532,57 @@ export class AgentDaemon {}}+ /** Hold live frames until the snapshot finishes; false requests a catch-up. */+ private deferSessionFrame(client: DaemonSocketClient, activeSessionId: string, message: DaemonOutbound): boolean {+ if (client.deferredSessionFramesDropped?.has(activeSessionId)) {+ return false;+ }+ const deferred = client.deferredSessionOutbounds?.get(activeSessionId) ?? { frames: [], bytes: 0 };+ const serialized = serializeJsonLine(message);+ const bytes = Buffer.byteLength(serialized);+ if (+ deferred.frames.length >= MAX_DEFERRED_SESSION_FRAMES ||+ deferred.bytes + bytes > MAX_DEFERRED_SESSION_BYTES+ ) {+ // A catch-up snapshot supersedes the buffered frames.+ client.deferredSessionFramesDropped ??= new Set();+ client.deferredSessionFramesDropped.add(activeSessionId);+ this.discardDeferredSessionFrames(client, activeSessionId);+ return false;+ }+ // Providers mutate nested streaming content after each event is emitted.+ deferred.frames.push(JSON.parse(serialized) as DaemonOutbound);+ deferred.bytes += bytes;+ client.deferredSessionOutbounds ??= new Map();+ client.deferredSessionOutbounds.set(activeSessionId, deferred);+ return true;+ }++ /** Replay frames deferred during a completed snapshot stream, in order. */+ private flushDeferredSessionFrames(client: DaemonSocketClient, activeSessionId: string): void {+ // A queued snapshot would overwrite an earlier replay of this shared buffer.+ if ((client.snapshotActiveSessionCounts?.get(activeSessionId) ?? 1) > 1) return;+ const frames = client.deferredSessionOutbounds?.get(activeSessionId)?.frames;+ if (!frames || frames.length === 0) {+ return;+ }+ client.deferredSessionOutbounds?.delete(activeSessionId);+ if (!client.attachedActiveSessionIds.has(activeSessionId)) return;+ for (const frame of frames) {+ if (client.socket.destroyed) {+ return;+ }+ if (client.backpressured || !this.write(client, frame)) {+ this.queueClientCatchup(client, activeSessionId, "resync");+ return;+ }+ }+ }++ private discardDeferredSessionFrames(client: DaemonSocketClient, activeSessionId: string): void {+ client.deferredSessionOutbounds?.delete(activeSessionId);+ }+// The AgentSession doesn't know its own daemon active-session id, so fill it in here.private stampRlmChildActiveSessionId(message: DaemonOutbound): void {if (@@ -7699,6 +7812,7 @@ export function getChildActiveSessionStates(export function detachClientFromActiveSession(client: DaemonSocketClient, state: ActiveSessionState): void {state.clients.delete(client);client.attachedActiveSessionIds.delete(state.activeSessionId);+ client.deferredSessionFramesDropped?.delete(state.activeSessionId);removeDaemonClientSessionCapabilities(client, state.activeSessionId);if (state.clients.size === 0) {cancelPendingExtensionUiRequests(state);@@ -7736,6 +7850,9 @@ function daemonClientSupportsExtensionUi(client: DaemonSocketClient, activeSessi}export function markClientSnapshotStreaming(client: DaemonSocketClient, activeSessionId: string): AbortSignal {+ if (!client.snapshotActiveSessionIds?.has(activeSessionId)) {+ client.deferredSessionFramesDropped?.delete(activeSessionId);+ }client.snapshotStreaming = true;client.snapshotActiveSessionIds ??= new Set();client.snapshotActiveSessionIds.add(activeSessionId);@@ -7771,11 +7888,12 @@ export function finishClientSnapshotStreaming(client: DaemonSocketClient, activeclient.snapshotActiveSessionCounts?.delete(activeSessionId);client.snapshotActiveSessionIds?.delete(activeSessionId);client.snapshotTransferAbortControllers?.delete(activeSessionId);+ // A failed or aborted stream replays nothing; drop what it withheld so+ // the next stream does not inherit stale frames.+ client.deferredSessionOutbounds?.delete(activeSessionId);+ client.deferredSessionPayloads?.delete(activeSessionId);}client.snapshotStreaming = (client.snapshotActiveSessionIds?.size ?? 0) > 0;- if (!client.snapshotStreaming) {- client.backpressured = false;- }}export function cancelPendingExtensionUiRequests(state: ActiveSessionState): void {diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 5a2782c777..dc6c501874 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -202,6 +202,14 @@ const UPDATE_RESTART_WORKER_REQUEST_TIMEOUT_MS = 90_000;// an abandoned prepare leaves the daemon permanently fenced with workers stopped.const UPDATE_RESTART_PREPARE_DEADLINE_MS = 100_000;const WORKER_RETRY_DELAYS_MS = [250, 1000, 5000] as const;+/**+ * Upper bound on relay payloads deferred per client and session while a+ * snapshot stream is active. Deferral spans one stream (seconds), so overflow+ * means a pathologically slow client; the supervisor then falls back to a+ * catch-up snapshot instead of buffering without limit.+ */+const MAX_DEFERRED_SESSION_PAYLOADS = 256;+const MAX_DEFERRED_SESSION_BYTES = 8 * 1024 * 1024;const DEFERRED_RECOVERY_RECHECK_MS = 5000;// ~2.5 minutes of probing: each round is one 5s defer recheck plus a ~11s three-delay probe pass.const MAX_DEFERRED_RECOVERY_ROUNDS = 10;@@ -1477,6 +1485,8 @@ export class DaemonSupervisor {return;}cleaned = true;+ clearTimeout(client.catchupRetryTimer);+ client.catchupRetryTimer = undefined;client.detachInput();this.sessionInputPauseEpochs.set(client, (this.sessionInputPauseEpochs.get(client) ?? 0) + 1);const ownerClientId = this.protocolClientId(client);@@ -2074,6 +2084,7 @@ export class DaemonSupervisor {this.write(client, success(command.id, command.type, attached.result));this.detachClient(client, command.activeSessionId);releaseSnapshotReservation();+ this.releaseDeferredSessionPayloads(client, targetActiveSessionId, true);return undefined;} catch (error) {releaseTranscript?.();@@ -2081,6 +2092,7 @@ export class DaemonSupervisor {this.detachClient(client, targetActiveSessionId);}releaseSnapshotReservation();+ this.releaseDeferredSessionPayloads(client, targetActiveSessionId, targetWasAttached);throw error;}}@@ -5358,24 +5370,31 @@ export class DaemonSupervisor {releaseSnapshotReservation = this.reserveSnapshotStream(client, result.activeSessionId),): Promise<void> {const stream = result.snapshotStream;- const releaseTranscript = retainedTranscriptRelease ?? transcript.retain();- if (!stream || client.socket.destroyed) {+ const signal = client.snapshotTransferAbortControllers?.get(result.activeSessionId)?.signal;+ if (!stream || client.socket.destroyed || signal?.aborted) {releaseSnapshotReservation();- releaseTranscript();+ retainedTranscriptRelease?.();+ this.releaseDeferredSessionPayloads(client, result.activeSessionId, false);return;}+ const releaseTranscript = retainedTranscriptRelease ?? transcript.retain();const { messages: _messages, ...snapshotHeader } = result.snapshot;+ let snapshotDelivered = false;try {if (- !(await this.writeSnapshotRecord(client, {- type: "session_snapshot_begin",- activeSessionId: result.activeSessionId,- snapshotId: stream.id,- snapshot: snapshotHeader,- messageCount: stream.messageCount,- targetChunkBytes: stream.targetChunkBytes,- purpose,- }))+ !(await this.writeSnapshotRecord(+ client,+ {+ type: "session_snapshot_begin",+ activeSessionId: result.activeSessionId,+ snapshotId: stream.id,+ snapshot: snapshotHeader,+ messageCount: stream.messageCount,+ targetChunkBytes: stream.targetChunkBytes,+ purpose,+ },+ signal,+ ))) {return;}@@ -5383,8 +5402,9 @@ export class DaemonSupervisor {while (true) {let chunk: Buffer | undefined;try {- chunk = await transcript.waitForChunk(chunkCount);+ chunk = await transcript.waitForChunk(chunkCount, signal);} catch (error) {+ if (signal?.aborted) return;const streamError = error instanceof Error ? error : new Error(String(error));this.failWorkerSnapshotCache(worker, result.activeSessionId, streamError, false, stream.id);throw streamError;@@ -5392,29 +5412,39 @@ export class DaemonSupervisor {if (!chunk) {break;}- if (!(await this.writeSnapshotBuffer(client, chunk))) {+ if (!(await this.writeSnapshotBuffer(client, chunk, signal))) {return;}chunkCount++;}- await this.writeSnapshotRecord(client, {- type: "session_snapshot_end",- activeSessionId: result.activeSessionId,- snapshotId: stream.id,- chunkCount,- lastEventSequence: result.lastEventSequence,- lastEventCursor: result.lastEventCursor,- });+ snapshotDelivered = await this.writeSnapshotRecord(+ client,+ {+ type: "session_snapshot_end",+ activeSessionId: result.activeSessionId,+ snapshotId: stream.id,+ chunkCount,+ lastEventSequence: result.lastEventSequence,+ lastEventCursor: result.lastEventCursor,+ },+ signal,+ );} catch (error) {+ if (signal?.aborted) return;const streamError = error instanceof Error ? error : new Error(String(error));if (!client.socket.destroyed) {try {- const delivered = await this.writeSnapshotRecord(client, {- type: "session_snapshot_failed",- activeSessionId: result.activeSessionId,- snapshotId: stream.id,- error: streamError.message,- });+ const delivered = await this.writeSnapshotRecord(+ client,+ {+ type: "session_snapshot_failed",+ activeSessionId: result.activeSessionId,+ snapshotId: stream.id,+ error: streamError.message,+ },+ signal,+ );+ if (signal?.aborted) return;if (!delivered && !client.socket.destroyed) {client.socket.destroy(streamError);}@@ -5424,12 +5454,25 @@ export class DaemonSupervisor {}throw streamError;} finally {+ if (+ !snapshotDelivered &&+ client.attachedActiveSessionIds.has(result.activeSessionId) &&+ client.deferredSessionPayloads?.get(result.activeSessionId)?.payloads.length+ ) {+ this.queueCatchup(client, result.activeSessionId, "resync");+ }releaseSnapshotReservation();releaseTranscript();+ this.releaseDeferredSessionPayloads(client, result.activeSessionId, snapshotDelivered);}}private reserveSnapshotStream(client: DaemonSocketClient, activeSessionId: string): () => void {+ if (!client.snapshotActiveSessionIds?.has(activeSessionId)) {+ client.deferredSessionPayloadsDropped?.delete(activeSessionId);+ client.snapshotTransferAbortControllers ??= new Map();+ client.snapshotTransferAbortControllers.set(activeSessionId, new AbortController());+ }client.snapshotStreaming = true;client.snapshotActiveSessionIds ??= new Set();client.snapshotActiveSessionIds.add(activeSessionId);@@ -5450,11 +5493,9 @@ export class DaemonSupervisor {} else {client.snapshotActiveSessionCounts?.delete(activeSessionId);client.snapshotActiveSessionIds?.delete(activeSessionId);+ client.snapshotTransferAbortControllers?.delete(activeSessionId);}client.snapshotStreaming = (client.snapshotActiveSessionIds?.size ?? 0) > 0;- if (!client.snapshotStreaming) {- client.backpressured = false;- }if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {void this.catchUpClient(client).catch((error) =>this.log(`Failed to catch up client ${client.id}: ${String(error)}`),@@ -5463,17 +5504,26 @@ export class DaemonSupervisor {};}- private writeSnapshotRecord(client: DaemonSocketClient, message: DaemonOutbound): Promise<boolean> {- return this.writeSnapshotBuffer(client, Buffer.from(serializeJsonLine(message)));+ private writeSnapshotRecord(+ client: DaemonSocketClient,+ message: DaemonOutbound,+ signal?: AbortSignal,+ ): Promise<boolean> {+ return this.writeSnapshotBuffer(client, Buffer.from(serializeJsonLine(message)), signal);}- private async writeSnapshotBuffer(client: DaemonSocketClient, buffer: Uint8Array): Promise<boolean> {- if (client.socket.destroyed) {+ private async writeSnapshotBuffer(+ client: DaemonSocketClient,+ buffer: Uint8Array,+ signal?: AbortSignal,+ ): Promise<boolean> {+ if (client.socket.destroyed || signal?.aborted) {return false;}if (this.writeSerialized(client, buffer)) {return true;}+ if (signal?.aborted) return false;return new Promise<boolean>((resolveDrain) => {let settled = false;const finish = (value: boolean) => {@@ -5484,6 +5534,7 @@ export class DaemonSupervisor {client.socket.off("drain", onDrain);client.socket.off("close", onClose);client.socket.off("error", onClose);+ signal?.removeEventListener("abort", onClose);resolveDrain(value);};const onDrain = () => finish(true);@@ -5491,6 +5542,7 @@ export class DaemonSupervisor {client.socket.once("drain", onDrain);client.socket.once("close", onClose);client.socket.once("error", onClose);+ signal?.addEventListener("abort", onClose, { once: true });});}@@ -5504,6 +5556,7 @@ export class DaemonSupervisor {}client.catchupActiveSessionIds?.delete(resolvedId);client.catchupPurposes?.delete(resolvedId);+ client.deferredSessionPayloadsDropped?.delete(resolvedId);this.write(client, { type: "session_detached", activeSessionId: resolvedId });void this.syncWorkerExtensionUi(resolvedId);void this.evictEmptySessionOnLastDetach(resolvedId);@@ -5912,10 +5965,38 @@ export class DaemonSupervisor {if (outboundType === "extension_ui_request" && !client.supportsExtensionUi) {continue;}+ // Snapshots cannot recover extension requests, so never defer or drop them.+ if (outboundType === "extension_ui_request") {+ this.writeSerialized(client, publicPayload);+ continue;+ }+ if (outboundType === "session_closed") {+ client.snapshotTransferAbortControllers?.get(activeSessionId)?.abort();+ this.discardDeferredSessionPayloads(client, activeSessionId);+ client.catchupActiveSessionIds?.delete(activeSessionId);+ client.catchupPurposes?.delete(activeSessionId);+ this.writeSerialized(client, publicPayload);+ continue;+ }if (client.snapshotActiveSessionIds?.has(activeSessionId)) {- this.queueCatchup(client, activeSessionId, outboundType === "session_replaced" ? "replacement" : "resync");+ // A replacement swaps the session wholesale; buffered payloads from+ // the old session must never replay, so fall back to a replacement+ // catch-up snapshot.+ if (outboundType === "session_replaced") {+ this.discardDeferredSessionPayloads(client, activeSessionId);+ client.deferredSessionPayloadsDropped ??= new Set();+ client.deferredSessionPayloadsDropped.add(activeSessionId);+ this.queueCatchup(client, activeSessionId, "replacement");+ continue;+ }+ if (this.deferSessionPayload(client, activeSessionId, publicPayload)) {+ continue;+ }+ // The deferral buffer overflowed: fall back to a full resync.+ this.queueCatchup(client, activeSessionId, "resync");continue;}+ if (client.deferredSessionPayloadsDropped?.has(activeSessionId)) continue;if (client.backpressured === true) {this.queueCatchup(client, activeSessionId, outboundType === "session_replaced" ? "replacement" : "resync");continue;@@ -5986,18 +6067,94 @@ export class DaemonSupervisor {}}+ /** Hold relayed payloads until the snapshot finishes; false requests a catch-up. */+ private deferSessionPayload(client: DaemonSocketClient, activeSessionId: string, payload: Buffer): boolean {+ if (client.deferredSessionPayloadsDropped?.has(activeSessionId)) {+ return false;+ }+ const deferred = client.deferredSessionPayloads?.get(activeSessionId) ?? { payloads: [], bytes: 0 };+ if (+ deferred.payloads.length >= MAX_DEFERRED_SESSION_PAYLOADS ||+ deferred.bytes + payload.byteLength > MAX_DEFERRED_SESSION_BYTES+ ) {+ // A catch-up snapshot supersedes the buffered payloads.+ client.deferredSessionPayloadsDropped ??= new Set();+ client.deferredSessionPayloadsDropped.add(activeSessionId);+ this.discardDeferredSessionPayloads(client, activeSessionId);+ return false;+ }+ deferred.payloads.push(payload);+ deferred.bytes += payload.byteLength;+ client.deferredSessionPayloads ??= new Map();+ client.deferredSessionPayloads.set(activeSessionId, deferred);+ return true;+ }++ /** Replay payloads deferred during a completed snapshot stream, in order. */+ private flushDeferredSessionPayloads(client: DaemonSocketClient, activeSessionId: string): void {+ const payloads = client.deferredSessionPayloads?.get(activeSessionId)?.payloads;+ if (!payloads || payloads.length === 0) {+ return;+ }+ client.deferredSessionPayloads?.delete(activeSessionId);+ if (!client.attachedActiveSessionIds.has(activeSessionId)) return;+ for (const payload of payloads) {+ if (client.socket.destroyed) {+ return;+ }+ if (client.backpressured || !this.writeSerialized(client, payload)) {+ this.queueCatchup(client, activeSessionId, "resync");+ return;+ }+ }+ }++ private discardDeferredSessionPayloads(client: DaemonSocketClient, activeSessionId: string): void {+ client.deferredSessionPayloads?.delete(activeSessionId);+ }++ /**+ * Flush or discard the payloads withheld during a snapshot stream. Only the+ * last active stream for the session owns them; an overlapping stream+ * replays them after it completes.+ */+ private releaseDeferredSessionPayloads(+ client: DaemonSocketClient,+ activeSessionId: string,+ delivered: boolean,+ ): void {+ if (client.snapshotActiveSessionIds?.has(activeSessionId)) {+ return;+ }+ if (delivered) {+ this.flushDeferredSessionPayloads(client, activeSessionId);+ } else {+ this.discardDeferredSessionPayloads(client, activeSessionId);+ }+ }+private catchUpClient(client: DaemonSocketClient): Promise<void> {if (client.catchupPromise) {return client.catchupPromise;}- if (client.snapshotStreaming || client.backpressured) {+ if (client.snapshotStreaming || client.backpressured || client.catchupRetryTimer) {return Promise.resolve();}- const catchup = this.drainClientCatchupQueue(client).finally(() => {- if (client.catchupPromise === catchup) {- client.catchupPromise = undefined;- }- });+ const catchup = this.drainClientCatchupQueue(client)+ .catch((error) => {+ this.log(`Failed to catch up client ${client.id}: ${String(error)}`);+ if (client.socket.destroyed || !client.catchupActiveSessionIds?.size) return;+ client.catchupRetryTimer = setTimeout(() => {+ client.catchupRetryTimer = undefined;+ void this.catchUpClient(client);+ }, 250);+ client.catchupRetryTimer.unref();+ })+ .finally(() => {+ if (client.catchupPromise === catchup) {+ client.catchupPromise = undefined;+ }+ });client.catchupPromise = catchup;return catchup;}@@ -6023,9 +6180,12 @@ export class DaemonSupervisor {}));client.catchupActiveSessionIds?.clear();client.catchupPurposes?.clear();+ let retryError: Error | undefined;for (let index = 0; index < pending.length; index++) {const { activeSessionId, purpose } = pending[index]!;let releaseTranscript: (() => void) | undefined;+ const releaseSnapshotReservation = this.reserveSnapshotStream(client, activeSessionId);+ const snapshotSignal = client.snapshotTransferAbortControllers?.get(activeSessionId)?.signal;try {const attached = await this.attachClient(client, {type: "attach",@@ -6061,6 +6221,7 @@ export class DaemonSupervisor {transcript,purpose,releaseTranscript,+ releaseSnapshotReservation,);releaseTranscript = undefined;continue;@@ -6086,7 +6247,10 @@ export class DaemonSupervisor {snapshot: attached.result.snapshot,meta,};- if (!this.write(client, catchup)) {+ const accepted = this.write(client, catchup);+ releaseSnapshotReservation();+ this.releaseDeferredSessionPayloads(client, activeSessionId, true);+ if (!accepted) {for (const remaining of pending.slice(index + 1)) {this.queueCatchup(client, remaining.activeSessionId, remaining.purpose);}@@ -6094,9 +6258,20 @@ export class DaemonSupervisor {}} catch (error) {releaseTranscript?.();- this.log(`Failed to catch up client ${client.id} for ${activeSessionId}: ${String(error)}`);+ if (client.attachedActiveSessionIds.has(activeSessionId) && !snapshotSignal?.aborted) {+ this.queueCatchup(client, activeSessionId, purpose);+ }+ client.deferredSessionPayloadsDropped ??= new Set();+ client.deferredSessionPayloadsDropped.add(activeSessionId);+ this.discardDeferredSessionPayloads(client, activeSessionId);+ retryError ??= error instanceof Error ? error : new Error(String(error));+ } finally {+ releaseSnapshotReservation();+ this.releaseDeferredSessionPayloads(client, activeSessionId, false);}}+ // Retry failed sessions only after the rest of the batch has had a chance to recover.+ if (retryError) throw retryError;}private async prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest> {diff --git a/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts b/packages/coding-agent/src/modes/daemon/daemon-worker-client.tsindex 8e416ee5ad..1f70fe04bf 100644--- a/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts@@ -153,9 +153,9 @@ export class DaemonWorkerClient {command: DaemonCommandBody,timeoutMs = 30_000,// Progress/recovery options are supervisor-transport features; a direct request fails fast instead of replaying (no double execution).- _options: DaemonClientRequestOptions = {},+ options: DaemonClientRequestOptions = {},): Promise<DaemonResponse> {- return this.requestWire(command, timeoutMs);+ return this.requestWire(command, timeoutMs, options.onResponse);}requestWorker(command: DaemonWorkerCommandBody, timeoutMs = 30_000): Promise<DaemonResponse> {@@ -201,7 +201,11 @@ export class DaemonWorkerClient {this.directClosingReason = undefined;}- private async requestWire(command: DaemonWorkerWireCommandBody, timeoutMs: number): Promise<DaemonResponse> {+ private async requestWire(+ command: DaemonWorkerWireCommandBody,+ timeoutMs: number,+ onResponse?: DaemonClientRequestOptions["onResponse"],+ ): Promise<DaemonResponse> {if (!this.channel || !this.socket || this.socket.destroyed) {throw new Error("Daemon worker client is not connected");}@@ -214,7 +218,18 @@ export class DaemonWorkerClient {new DaemonWorkerProbeTimeoutError(`Timed out waiting for daemon worker response to ${command.type}`),);}, timeoutMs);- this.pending.set(id, { resolve, reject, timeout });+ this.pending.set(id, {+ resolve: (response) => {+ try {+ onResponse?.(response);+ resolve(response);+ } catch (error) {+ reject(error);+ }+ },+ reject,+ timeout,+ });});try {await this.channel.send(diff --git a/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.ts b/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.tsindex 874c5632e7..9d1fc39cf4 100644--- a/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.ts+++ b/packages/coding-agent/src/modes/daemon/snapshot-transcript-cache.ts@@ -93,7 +93,9 @@ export class SnapshotTranscriptCache {this.snapshotId = options.snapshotId;this.activeSessionId = options.activeSessionId;if (options.messages) {- this.encodeMessages(options.messages);+ for (const chunk of createSnapshotTranscriptChunks({ ...options, messages: options.messages })) {+ this.storeChunk(chunk);+ }this.completed = true;}}@@ -173,7 +175,8 @@ export class SnapshotTranscriptCache {this.chunkWaiters.clear();}- waitForChunk(index: number): Promise<Buffer | undefined> {+ waitForChunk(index: number, signal?: AbortSignal): Promise<Buffer | undefined> {+ if (signal?.aborted) return Promise.reject(signal.reason);if (this.failure) {return Promise.reject(this.failure);}@@ -185,8 +188,24 @@ export class SnapshotTranscriptCache {}return new Promise((resolve, reject) => {const waiters = this.chunkWaiters.get(index) ?? [];- waiters.push({ resolve, reject });+ const onAbort = () => {+ waiters.splice(waiters.indexOf(waiter), 1);+ if (waiters.length === 0) this.chunkWaiters.delete(index);+ reject(signal?.reason);+ };+ const waiter = {+ resolve: (buffer: Buffer | undefined) => {+ signal?.removeEventListener("abort", onAbort);+ resolve(buffer);+ },+ reject: (error: Error) => {+ signal?.removeEventListener("abort", onAbort);+ reject(error);+ },+ };+ waiters.push(waiter);this.chunkWaiters.set(index, waiters);+ signal?.addEventListener("abort", onAbort, { once: true });});}@@ -224,35 +243,6 @@ export class SnapshotTranscriptCache {this.chunks.length = 0;}- private encodeMessages(messages: readonly AgentMessage[]): void {- let serializedMessages: string[] = [];- let serializedBytes = 0;- const flush = () => {- if (serializedMessages.length === 0) {- return;- }- const index = this.chunks.length;- const prefix =- `{"type":"session_snapshot_chunk","activeSessionId":${JSON.stringify(this.options.activeSessionId)},` +- `"snapshotId":${JSON.stringify(this.options.snapshotId)},"index":${index},"messages":[`;- const line = Buffer.from(`${prefix}${serializedMessages.join(",")}]}\n`);- this.storeChunk(line);- serializedMessages = [];- serializedBytes = 0;- };-- for (const message of messages) {- const serialized = JSON.stringify(message);- const bytes = Buffer.byteLength(serialized) + (serializedMessages.length > 0 ? 1 : 0);- if (serializedMessages.length > 0 && serializedBytes + bytes > this.targetChunkBytes) {- flush();- }- serializedMessages.push(serialized);- serializedBytes += bytes;- }- flush();- }-private storeChunk(buffer: Buffer): void {this.totalBytes += buffer.length;const memoryLimit = this.options.memoryCacheBytes ?? SNAPSHOT_MEMORY_CACHE_BYTES;diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 69a6a22366..ee9d749fc8 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -1006,6 +1006,9 @@ export class InteractiveMode {// Serializes session event handling; see subscribeToAgentprivate sessionEventQueue: Promise<void> = Promise.resolve();+ // The in-flight initial transcript render, if any. Session resync/replacement+ // renders await it so they never interleave with a half-built transcript.+ private initialRenderPromise: Promise<void> | undefined = undefined;private sessionEventGeneration = 0;private fastModeToggleQueue: Promise<void> = Promise.resolve();@@ -1417,9 +1420,6 @@ export class InteractiveMode {// fd powers autocomplete, and rg is available for shell commands.const [fdPath, rgResult] = await Promise.all([ensureTool("fd"), ensureToolWithStatus("rg")]);this.fdPath = fdPath;- if (rgResult.status === "unavailable") {- this.showWarning(formatMissingRipgrepMessage(rgResult));- }this.ui.addChild(this.headerContainer);@@ -1497,6 +1497,9 @@ export class InteractiveMode {await this.rebindCurrentSession();await this.renderInitialMessages();+ if (rgResult.status === "unavailable") {+ this.showWarning(formatMissingRipgrepMessage(rgResult));+ }onThemeChange(() => {this.ui.invalidate();@@ -2531,7 +2534,6 @@ export class InteractiveMode {const extensionRunner = localSessionHost.getExtensionRunner();this.setupExtensionShortcuts(extensionRunner);- this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });}private applyRuntimeSettings(): void {@@ -2842,7 +2844,6 @@ export class InteractiveMode {setRegisteredThemes(this.uiServices.getThemes());await this.refreshConnectionCatalog();this.setupAutocompleteProvider();- this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });}this.subscribeToAgent();await this.subscribeToRosterBar();@@ -2955,6 +2956,7 @@ export class InteractiveMode {await this.renderSessionContext(this.getSessionContextFromConnectionSnapshot(snapshot), {clearChat: true,updateFooter: true,+ limitTranscript: true,});await this.restoreStreamingMessageFromSnapshot(snapshot.streamingMessage);this.updatePendingMessagesDisplay();@@ -5030,6 +5032,10 @@ export class InteractiveMode {} else if (event.type === "session_replaced") {const generation = ++this.sessionEventGeneration;const run = this.sessionEventQueue.then(async () => {+ if (generation !== this.sessionEventGeneration) return;+ // Let an in-flight initial render finish before clearing the+ // chat for the new session.+ await this.initialRenderPromise?.catch(() => undefined);if (generation !== this.sessionEventGeneration) return;this.resetSideQuestion();this.resetExtensionUI();@@ -5047,6 +5053,10 @@ export class InteractiveMode {if (generation !== this.sessionEventGeneration) return false;await this.refreshCommandCatalogForCurrentSession?.();if (generation !== this.sessionEventGeneration) return false;+ // Never rebuild the transcript while an initial render is+ // mid-flight; queue behind it instead.+ await this.initialRenderPromise?.catch(() => undefined);+ if (generation !== this.sessionEventGeneration) return false;await this.renderResyncedSession(event.snapshot);return true;});@@ -6508,26 +6518,46 @@ export class InteractiveMode {}async renderInitialMessages(): Promise<void> {- const snapshot = await this.agentConnection.getInitialSnapshot();- const context = this.getSessionContextFromConnectionSnapshot(snapshot);- const state = snapshot.state;- const streamingMessage = snapshot.streamingMessage;- this.rlmNodeId = snapshot.parent?.childId;- this.seedSubagentSummary(snapshot.children);- this.applyConnectionStateSnapshot(state);- this.restoreTurnStartFromMessages(context.messages);- await this.renderSessionContext(context, {- updateFooter: true,- populateHistory: true,- limitTranscript: true,- });- await this.restoreStreamingMessageFromSnapshot(streamingMessage);+ // Serialize with any in-flight initial render: resync/replacement handlers+ // re-enter this method, and two concurrent transcript builds race the+ // chat container.+ const previousRender = this.initialRenderPromise;+ const render = (async () => {+ await previousRender?.catch(() => undefined);+ const snapshot = await this.agentConnection.getInitialSnapshot();+ const context = this.getSessionContextFromConnectionSnapshot(snapshot);+ const state = snapshot.state;+ const streamingMessage = snapshot.streamingMessage;+ this.rlmNodeId = snapshot.parent?.childId;+ this.seedSubagentSummary(snapshot.children);+ this.applyConnectionStateSnapshot(state);+ this.restoreTurnStartFromMessages(context.messages);+ await this.renderSessionContext(context, {+ clearChat: true,+ updateFooter: true,+ populateHistory: true,+ limitTranscript: true,+ });+ await this.restoreStreamingMessageFromSnapshot(streamingMessage);+ this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });- // Show compaction info if session was compacted- const compactionCount = state.compactionCount;- if (compactionCount > 0) {- const times = compactionCount === 1 ? "1 time" : `${compactionCount} times`;- this.showStatus(`Session compacted ${times}`);+ // Show compaction info if session was compacted+ const compactionCount = state.compactionCount;+ if (compactionCount > 0) {+ const times = compactionCount === 1 ? "1 time" : `${compactionCount} times`;+ this.showStatus(`Session compacted ${times}`);+ }+ })();+ this.initialRenderPromise = render;+ try {+ await render;+ } finally {+ if (this.initialRenderPromise === render) {+ this.initialRenderPromise = undefined;+ // Release deferred events even if the last queued render failed. Do not+ // await listener delivery: session-replaced handlers share that queue.+ void this.agentConnection.flushBufferedSessionEvents?.();+ }}}@@ -6571,7 +6601,7 @@ export class InteractiveMode {private async rebuildChatFromMessages(): Promise<void> {const context = await this.agentConnection.getSessionContext();- await this.renderSessionContext(context, { clearChat: true });+ await this.renderSessionContext(context, { clearChat: true, limitTranscript: true });}private handleEscape(): void {diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.tsindex 1c03ecfa6c..566f1d3757 100644--- a/packages/coding-agent/test/agent-connection-daemon.test.ts+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts@@ -1,5 +1,6 @@+import { PassThrough } from "node:stream";import type { AgentMessage } from "@earendil-works/pi-agent-core";-import { getModel } from "@earendil-works/pi-ai";+import { fauxAssistantMessage, getModel } from "@earendil-works/pi-ai";import { describe, expect, it, vi } from "vitest";import { MissingSessionCwdError } from "../src/core/session-cwd.js";import { SessionImportFileNotFoundError } from "../src/core/session-import-errors.js";@@ -33,6 +34,8 @@ import {} from "../src/modes/daemon/daemon-protocol.js";import { DaemonRoutedClient } from "../src/modes/daemon/daemon-routed-client.js";import type { DaemonWorkerClient } from "../src/modes/daemon/daemon-worker-client.js";+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";+import { attachJsonlLineReader, serializeJsonLine } from "../src/modes/rpc/jsonl.js";class FakeDaemonClient {readonly requests: DaemonCommand[] = [];@@ -106,7 +109,7 @@ class FakeDaemonClient {success: true,data: { sessions: this.updateRestartSessions },};- case "attach":+ case "attach": {if (this.attachFailures > 0) {this.attachFailures--;throw new Error("attach failed");@@ -123,7 +126,7 @@ class FakeDaemonClient {error: "Unknown active session: missing",};}- return {+ const response: DaemonResponse = {type: "response",command: command.type,success: true,@@ -131,6 +134,9 @@ class FakeDaemonClient {this.attachResultFactory?.(command) ??createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),};+ options.onResponse?.(response);+ return response;+ }case "get_queue":return {type: "response",@@ -880,7 +886,7 @@ describe("DaemonAgentConnection", () => {const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);await expect(DaemonAgentConnection.attach(routed, "active-1")).rejects.toThrow("Reason: shutdown");- expect(attachOptions).toEqual([{ recoverable: false }]);+ expect(attachOptions).toEqual([expect.objectContaining({ recoverable: false })]);});it("absorbs a direct loss inside the held roster re-attach into a session-plane reattach", async () => {@@ -1765,7 +1771,7 @@ describe("DaemonAgentConnection", () => {expect(fakeClient.requests).toEqual([]);});- it("reattaches an open window to its restored session after an update restart", async () => {+ it.each([false, true])("reattaches after an update restart (deferring=%s)", async (deferSessionEvents) => {const fakeClient = new FakeDaemonClient();fakeClient.emitCloseOnClose = true;const restoredMessages: AgentMessage[] = [{ role: "user", content: "restored prompt", timestamp: 2 }];@@ -1782,7 +1788,9 @@ describe("DaemonAgentConnection", () => {state: createConnectionState(command.activeSessionId, "session-current"),messages: command.activeSessionId === "active-restored" ? restoredMessages : [],});- const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original", {+ deferSessionEvents,+ });const events: AgentConnectionEvent[] = [];const restored = new Promise<AgentConnectionEvent>((resolve) => {connection.subscribe((event) => {@@ -1793,6 +1801,7 @@ describe("DaemonAgentConnection", () => {});});await connection.attach();+ if (deferSessionEvents) emitSequencedSessionEvent(fakeClient, "active-original", 100);fakeClient.emitMessage({type: "session_closed",@@ -1811,6 +1820,7 @@ describe("DaemonAgentConnection", () => {messages: restoredMessages,},});+ await connection.flushBufferedSessionEvents();expect(fakeClient.reconnectCount).toBe(1);expect(fakeClient.requests.map((request) => request.type)).toEqual(["attach", "list", "attach"]);expect(fakeClient.requests.at(-1)).toMatchObject({@@ -2573,6 +2583,107 @@ describe("DaemonAgentConnection", () => {expect(events).toEqual([]);});+ it.each([+ ["headless", "message_end"],+ ["headless", "message_update"],+ ["reconnect", "message_end"],+ ["reconnect", "message_update"],+ ] as const)("preserves %s %s coalesced with attach snapshot completion", async (mode, eventType) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: mode === "reconnect",+ recoverDaemon: async () => {},+ });+ const input = new PassThrough();+ const detachReader = attachJsonlLineReader(input, (line) => fakeClient.emitMessage(JSON.parse(line)));+ try {+ if (mode === "reconnect") {+ await connection.attach();+ await connection.flushBufferedSessionEvents();+ }+ const message = fauxAssistantMessage("new response");+ fakeClient.attachResultFactory = (command) => {+ const full = createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12, {+ state: { ...createConnectionState("active-1", "session-current"), isStreaming: true },+ streamingMessage: fauxAssistantMessage("old partial response"),+ });+ const { messages: _messages, ...snapshot } = full.snapshot;+ const records: DaemonOutbound[] = [+ {+ type: "session_snapshot_begin",+ activeSessionId: "active-1",+ snapshotId: "coalesced",+ snapshot,+ messageCount: 0,+ targetChunkBytes: 512 * 1024,+ },+ {+ type: "session_snapshot_end",+ activeSessionId: "active-1",+ snapshotId: "coalesced",+ chunkCount: 0,+ lastEventSequence: 12,+ lastEventCursor: full.lastEventCursor,+ },+ {+ type: "session_event",+ activeSessionId: "active-1",+ event:+ eventType === "message_end"+ ? { type: eventType, message }+ : {+ type: eventType,+ message,+ assistantMessageEvent: {+ type: "text_delta",+ contentIndex: 0,+ delta: "response",+ partial: message,+ },+ },+ meta: {+ id: "active-1:13",+ protocol: DAEMON_PROTOCOL_INFO,+ activeSessionId: "active-1",+ sequence: 13,+ cursor: { generation: "generation-active-1", sequence: 13 },+ emittedAt: "2026-01-01T00:00:00.000Z",+ },+ },+ ];+ // All records dispatch before the attach response's promise continuation.+ queueMicrotask(() => input.write(records.map(serializeJsonLine).join("")));+ return { ...full, snapshotStream: { id: "coalesced", messageCount: 0, targetChunkBytes: 512 * 1024 } };+ };+ const events: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ events.push(event);+ });+ if (mode === "reconnect") {+ fakeClient.connected = false;+ fakeClient.emitClose(new Error("socket closed"));+ await vi.waitFor(() => expect(events.some((event) => event.type === "session_resynced")).toBe(true));+ } else {+ await connection.attach();+ }+ const snapshot = await connection.getInitialSnapshot();+ expect(snapshot.streamingMessage).toEqual(eventType === "message_end" ? undefined : message);+ expect(snapshot.lastEventCursor).toEqual({ generation: "generation-active-1", sequence: 13 });+ expect(fakeClient.requests.map((request) => request.type)).toContain("get_messages");+ expect(events).toContainEqual(+ expect.objectContaining({ type: "session_event", event: expect.objectContaining({ type: eventType }) }),+ );+ for (const event of events) {+ if (event.type === "session_resynced")+ expect(event.snapshot.streamingMessage).toEqual(snapshot.streamingMessage);+ }+ } finally {+ detachReader();+ input.destroy();+ await connection.dispose();+ }+ });+it("distinguishes chunked catch-up snapshots from runtime replacements", async () => {const fakeClient = new FakeDaemonClient();const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");@@ -2858,6 +2969,80 @@ describe("DaemonAgentConnection", () => {expect(resyncs).toBe(1);});+ it.each([+ ["reconnect", "attach"],+ ["reconnect", "snapshot"],+ ["reconnect", "backoff"],+ ["update", "attach"],+ ["update", "snapshot"],+ ["update", "backoff"],+ ] as const)("stops %s after a terminal close during %s", async (recovery, stage) => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ recoverDaemon: async () => undefined,+ reconnectTimeoutMs: 1000,+ });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ try {+ await connection.attach();+ fakeClient.updateRestartSessions = [{ activeSessionId: "active-1", sessionId: "session-current" }];+ const request = fakeClient.request.bind(fakeClient);+ vi.spyOn(fakeClient, "request").mockImplementation(async (...args) => {+ const response = await request(...args);+ if (args[0].type === "attach") {+ if (stage === "backoff") throw new Error("attach temporarily unavailable");+ if (stage === "attach") await gate;+ }+ return response;+ });+ const getInitialSnapshot = connection.getInitialSnapshot.bind(connection);+ const snapshotRead = vi.spyOn(connection, "getInitialSnapshot").mockImplementation(async (...args) => {+ const snapshot = await getInitialSnapshot(...args);+ if (stage === "snapshot") await gate;+ return snapshot;+ });+ const events: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ events.push(event);+ });+ fakeClient.connected = false;+ fakeClient.emitClose(+ recovery === "update"+ ? new DaemonSocketClosedError("/tmp/fake.sock", "update")+ : new Error("Daemon socket closed"),+ );+ await vi.advanceTimersByTimeAsync(0);+ expect(fakeClient.requests.filter((request) => request.type === "attach")).toHaveLength(2);+ if (stage === "snapshot") expect(snapshotRead).toHaveBeenCalledOnce();+ const requestCount = fakeClient.requests.length;+ const reconnectCount = fakeClient.reconnectCount;+ const resetCount = fakeClient.resetTransportCount;+ const closeCount = fakeClient.closeCount;+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "active-1", reason: "killed" });+ release();+ await vi.advanceTimersByTimeAsync(120100);+ expect(fakeClient.requests).toHaveLength(requestCount);+ expect(fakeClient.reconnectCount).toBe(reconnectCount);+ expect(fakeClient.resetTransportCount).toBe(resetCount);+ expect(fakeClient.closeCount).toBe(closeCount);+ expect(events).toEqual([+ expect.objectContaining({ type: "connection_status", status: "reconnecting" }),+ expect.objectContaining({+ type: "closed",+ error: expect.stringContaining("The daemon stopped this agent session."),+ }),+ ]);+ } finally {+ release();+ await connection.dispose();+ vi.useRealTimers();+ }+ });+it("does not reconnect after disposal while daemon recovery is pending", async () => {const fakeClient = new FakeDaemonClient();let finishRecovery: (() => void) | undefined;@@ -3749,3 +3934,980 @@ describe("DaemonAgentConnection", () => {expect(fakeClient.closeCount).toBe(1);});});++const DEFERRAL_EVENT_BASE_SEQUENCE = 13;++function emitSequencedSessionEvent(client: FakeDaemonClient, activeSessionId: string, sequence: number): void {+ client.emitMessage({+ type: "session_event",+ activeSessionId,+ event: { type: "session_info_changed", name: String(sequence) },+ meta: {+ id: `${activeSessionId}:${sequence}`,+ protocol: DAEMON_PROTOCOL_INFO,+ activeSessionId,+ sequence,+ cursor: { generation: `generation-${activeSessionId}`, sequence },+ emittedAt: "2026-01-01T00:00:00.000Z",+ },+ } satisfies DaemonOutbound);+}++async function nextMessageLoopTurn(): Promise<void> {+ await new Promise<void>((resolve) => setImmediate(resolve));+ await new Promise<void>((resolve) => setImmediate(resolve));+}++describe("DaemonAgentConnection deferred session events", () => {+ it("defers events between attach and flush so the attach snapshot stays usable", async () => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ try {+ await connection.attach();+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ });++ emitSequencedSessionEvent(fakeClient, "active-1", DEFERRAL_EVENT_BASE_SEQUENCE);+ await nextMessageLoopTurn();+ expect(delivered).toEqual([]);++ fakeClient.requests.length = 0;+ const snapshot = await connection.getInitialSnapshot();+ expect(fakeClient.requests.map((request) => request.type)).not.toContain("get_messages");+ expect(snapshot.state.activeSessionId).toBe("active-1");++ await connection.flushBufferedSessionEvents();+ expect(delivered).toHaveLength(1);+ expect(delivered[0]).toMatchObject({ type: "session_event" });++ emitSequencedSessionEvent(fakeClient, "active-1", DEFERRAL_EVENT_BASE_SEQUENCE + 1);+ await nextMessageLoopTurn();+ expect(delivered).toHaveLength(2);+ } finally {+ await connection.dispose();+ }+ });++ it("delivers events live and refetches when deferral is not opted in", async () => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ try {+ await connection.attach();+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ });++ emitSequencedSessionEvent(fakeClient, "active-1", DEFERRAL_EVENT_BASE_SEQUENCE);+ await nextMessageLoopTurn();+ expect(delivered).toHaveLength(1);++ fakeClient.requests.length = 0;+ await connection.getInitialSnapshot();+ expect(fakeClient.requests.map((request) => request.type)).toContain("get_messages");+ } finally {+ await connection.dispose();+ }+ });++ it("drops deferred events a resync snapshot already contains", async () => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ try {+ await connection.attach();+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ });++ const resyncSequence = DEFERRAL_EVENT_BASE_SEQUENCE + 2;+ emitSequencedSessionEvent(fakeClient, "active-1", DEFERRAL_EVENT_BASE_SEQUENCE);+ emitSequencedSessionEvent(fakeClient, "active-1", DEFERRAL_EVENT_BASE_SEQUENCE + 1);+ fakeClient.emitMessage({+ type: "session_resynced",+ activeSessionId: "active-1",+ snapshot: createAttachResult("active-1", undefined, undefined, resyncSequence).snapshot,+ meta: {+ id: `active-1:${resyncSequence}`,+ protocol: DAEMON_PROTOCOL_INFO,+ activeSessionId: "active-1",+ sequence: resyncSequence,+ cursor: { generation: "generation-active-1", sequence: resyncSequence },+ emittedAt: "2026-01-01T00:00:00.000Z",+ },+ } satisfies DaemonOutbound);+ await nextMessageLoopTurn();+ expect(delivered.filter((event) => event.type === "session_resynced")).toHaveLength(1);+ expect(delivered.filter((event) => event.type === "session_event")).toEqual([]);++ await connection.flushBufferedSessionEvents();+ expect(delivered.filter((event) => event.type === "session_event")).toEqual([]);++ emitSequencedSessionEvent(fakeClient, "active-1", resyncSequence + 1);+ await connection.flushBufferedSessionEvents();+ expect(delivered.filter((event) => event.type === "session_event")).toHaveLength(1);+ } finally {+ await connection.dispose();+ }+ });++ it("resyncs an already rendered snapshot when deferral overflows", async () => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ try {+ await connection.attach();+ const renderedSnapshot = await connection.getInitialSnapshot();+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ });++ // The initial renderer already has its snapshot when the buffer overflows.+ for (let index = 0; index <= 1000; index++) {+ emitSequencedSessionEvent(fakeClient, "active-1", DEFERRAL_EVENT_BASE_SEQUENCE + index);+ }+ await nextMessageLoopTurn();+ expect(delivered).toHaveLength(0);+ const recoveredMessages: AgentMessage[] = [{ role: "user", content: "recovered", timestamp: 1 }];+ fakeClient.attachResultFactory = (command) => {+ emitSequencedSessionEvent(fakeClient, "active-1", 1014);+ return createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 1013, {+ messages: recoveredMessages,+ });+ };+ await connection.flushBufferedSessionEvents();+ expect(renderedSnapshot.messages).toEqual([]);+ expect(delivered).toEqual([+ expect.objectContaining({+ type: "session_resynced",+ snapshot: expect.objectContaining({ messages: recoveredMessages }),+ }),+ { type: "session_event", event: { type: "session_info_changed", name: "1014" } },+ ]);++ emitSequencedSessionEvent(fakeClient, "active-1", 1015);+ await nextMessageLoopTurn();+ expect(delivered).toHaveLength(3);+ } finally {+ await connection.dispose();+ }+ });++ it.each([true, false])(+ "finishes overflow recovery under continuous traffic (snapshot covers overflow=%s)",+ async (covered) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ let release!: () => void;+ const rendering = new Promise<void>((resolve) => {+ release = resolve;+ });+ try {+ await connection.attach();+ let sequence = 12;+ for (let index = 0; index <= 1000; index++) emitSequencedSessionEvent(fakeClient, "active-1", ++sequence);+ let attaches = 0;+ fakeClient.attachResultFactory = (command) => {+ if (++attaches > 3) throw new Error("overflow recovery did not terminate");+ const before = sequence;+ if (covered || attaches === 1) {+ for (let index = 0; index <= 1000; index++)+ emitSequencedSessionEvent(fakeClient, "active-1", ++sequence);+ }+ return createAttachResult(+ command.activeSessionId,+ command.clientId,+ command.capabilities,+ !covered && attaches === 1 ? before : sequence,+ );+ };+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ if (event.type === "session_resynced") return rendering;+ });+ const flush = connection.flushBufferedSessionEvents();+ await nextMessageLoopTurn();+ expect(attaches).toBe(covered ? 1 : 2);+ expect(delivered.at(-1)).toMatchObject({+ type: "session_resynced",+ snapshot: { lastEventSequence: sequence },+ });+ const beforeLive = delivered.length;+ for (let index = 0; index < 2000; index++) emitSequencedSessionEvent(fakeClient, "active-1", ++sequence);+ expect(delivered.slice(beforeLive)).toHaveLength(2000);+ release();+ await flush;+ expect(attaches).toBe(covered ? 1 : 2);+ expect(delivered.some((event) => event.type === "closed")).toBe(false);+ } finally {+ release();+ await connection.dispose();+ }+ },+ );++ it.each([+ ["replacement", false],+ ["replacement", true],+ ["streamed replacement", true],+ ["reattach", false],+ ["reattach", true],+ ] as const)("discards overflow recovery across %s (recovery started=%s)", async (change, recoveryStarted) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ try {+ await connection.attach();+ for (let sequence = 13; sequence <= 1013; sequence++)+ emitSequencedSessionEvent(fakeClient, "active-1", sequence);+ const request = fakeClient.request.bind(fakeClient);+ vi.spyOn(fakeClient, "request").mockImplementation(async (command, ...options) => {+ if (command.type === "attach" && change === "streamed replacement") {+ const result = createAttachResult("active-1", undefined, undefined, 1013);+ result.snapshotStream = { id: "old-recovery", messageCount: 0, targetChunkBytes: 512 * 1024 };+ fakeClient.emitMessage({+ type: "session_snapshot_begin",+ activeSessionId: "active-1",+ snapshotId: "old-recovery",+ snapshot: result.snapshot,+ messageCount: 0,+ targetChunkBytes: 512 * 1024,+ purpose: "attach",+ });+ return { type: "response", command: command.type, success: true, data: result };+ }+ if (command.type === "attach") await gate;+ if (command.type === "switch_session")+ return {+ type: "response",+ command: command.type,+ success: false,+ error: "Session already active",+ errorInfo: {+ code: "session_already_active",+ activeSessionId: "active-2",+ sessionPath: "/tmp/target.jsonl",+ },+ };+ if (command.type === "reattach")+ return {+ type: "response",+ command: command.type,+ success: true,+ data: createAttachResult("active-2", undefined, undefined, 1),+ };+ return request(command, ...options);+ });+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ });+ const flush = recoveryStarted ? connection.flushBufferedSessionEvents() : undefined;+ await nextMessageLoopTurn();+ if (change === "reattach") {+ await connection.switchSession("/tmp/target.jsonl");+ } else {+ fakeClient.emitMessage({+ type: "session_replaced",+ activeSessionId: "active-1",+ state: createConnectionState("active-1", "replacement"),+ messages: [],+ });+ }+ const activeSessionId = change === "reattach" ? "active-2" : "active-1";+ const sequence = change === "reattach" ? 2 : 1014;+ emitSequencedSessionEvent(fakeClient, activeSessionId, sequence);+ if (change === "streamed replacement") {+ fakeClient.emitMessage({+ type: "session_snapshot_end",+ activeSessionId: "active-1",+ snapshotId: "old-recovery",+ chunkCount: 0,+ lastEventSequence: 1013,+ lastEventCursor: { generation: "generation-active-1", sequence: 1013 },+ });+ }+ release();+ await (flush ?? connection.flushBufferedSessionEvents());+ expect(delivered.map((event) => event.type)).toEqual(["session_replaced", "session_event"]);+ expect(delivered[1]).toEqual({+ type: "session_event",+ event: { type: "session_info_changed", name: String(sequence) },+ });+ if (change !== "reattach")+ expect(+ (connection as unknown as { latestSnapshot: { state: AgentConnectionState } }).latestSnapshot.state+ .sessionId,+ ).toBe("replacement");+ expect((await connection.getState()).activeSessionId).toBe(activeSessionId);+ } finally {+ release();+ await connection.dispose();+ }+ });++ it("does not advance event cursors for an attach superseded before its snapshot finishes", async () => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ try {+ await connection.attach();+ fakeClient.attachResultFactory = (command) => ({+ ...createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 100),+ snapshotStream: { id: "superseded", messageCount: 0, targetChunkBytes: 512 * 1024 },+ });+ const pendingAttach = connection.attach();+ await nextMessageLoopTurn();+ fakeClient.emitMessage({+ type: "session_snapshot_begin",+ activeSessionId: "active-1",+ snapshotId: "superseded",+ snapshot: createAttachResult("active-1", undefined, undefined, 100).snapshot,+ messageCount: 0,+ targetChunkBytes: 512 * 1024,+ purpose: "attach",+ });+ fakeClient.emitMessage({+ type: "session_replaced",+ activeSessionId: "active-1",+ state: createConnectionState("active-1", "replacement"),+ messages: [],+ });+ fakeClient.emitMessage({+ type: "session_snapshot_end",+ activeSessionId: "active-1",+ snapshotId: "superseded",+ chunkCount: 0,+ lastEventSequence: 100,+ lastEventCursor: { generation: "generation-active-1", sequence: 100 },+ });+ await pendingAttach;+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ });+ emitSequencedSessionEvent(fakeClient, "active-1", 13);+ await connection.flushBufferedSessionEvents();+ expect(delivered).toEqual([{ type: "session_event", event: { type: "session_info_changed", name: "13" } }]);+ const snapshot = await connection.getInitialSnapshot();+ expect(snapshot.lastEventCursor).toEqual({ generation: "generation-active-1", sequence: 13 });+ } finally {+ await connection.dispose();+ }+ });++ it.each([0, 2, 3])(+ "releases a superseded attach with %i snapshot frames received before its response",+ async (frameCount) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ let release!: () => void;+ const responseGate = new Promise<void>((resolve) => {+ release = resolve;+ });+ try {+ await connection.attach();+ const result = createAttachResult("active-1", undefined, undefined, 100);+ fakeClient.attachResultFactory = () => ({+ ...result,+ snapshotStream: { id: "abandoned", messageCount: 1, targetChunkBytes: 512 * 1024 },+ });+ const request = fakeClient.request.bind(fakeClient);+ vi.spyOn(fakeClient, "request").mockImplementation(async (...args) => {+ const response = await request(...args);+ if (args[0].type === "attach") await responseGate;+ return response;+ });+ const frames: DaemonOutbound[] = [+ {+ type: "session_snapshot_begin",+ activeSessionId: "active-1",+ snapshotId: "abandoned",+ snapshot: result.snapshot,+ messageCount: 1,+ targetChunkBytes: 512 * 1024,+ purpose: "attach",+ },+ {+ type: "session_snapshot_chunk",+ activeSessionId: "active-1",+ snapshotId: "abandoned",+ index: 0,+ messages: [{ role: "user", content: "old transcript", timestamp: 1 }],+ },+ {+ type: "session_snapshot_end",+ activeSessionId: "active-1",+ snapshotId: "abandoned",+ chunkCount: 1,+ lastEventSequence: 100,+ },+ ];+ const pendingAttach = connection.attach();+ for (const frame of frames.slice(0, frameCount)) fakeClient.emitMessage(frame);+ fakeClient.emitMessage({+ type: "session_replaced",+ activeSessionId: "active-1",+ state: createConnectionState("active-1", "replacement"),+ messages: [],+ });+ release();+ await pendingAttach;+ expect(+ (connection as unknown as { snapshotAssemblies: Map<string, unknown> }).snapshotAssemblies.size,+ ).toBe(0);+ for (const frame of frames.slice(frameCount)) fakeClient.emitMessage(frame);+ await nextMessageLoopTurn();+ expect(+ (connection as unknown as { snapshotAssemblies: Map<string, unknown> }).snapshotAssemblies.size,+ ).toBe(0);+ expect((await connection.getInitialSnapshot()).state.sessionId).toBe("replacement");+ } finally {+ release();+ await connection.dispose();+ }+ },+ );++ it.each(["before response", "during stream", "after end"] as const)(+ "rejects a closed attach immediately %s",+ async (timing) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ const result = createAttachResult("active-1", undefined, undefined, 12);+ fakeClient.attachResultFactory = () => ({+ ...result,+ snapshotStream: { id: "closed", messageCount: 0, targetChunkBytes: 512 * 1024 },+ });+ const rejected = vi.fn();+ const resolved = vi.fn();+ const events: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ events.push(event);+ });+ const pendingAttach = connection.attach().then(resolved, rejected);+ try {+ if (timing !== "before response") await nextMessageLoopTurn();+ fakeClient.emitMessage({+ type: "session_snapshot_begin",+ activeSessionId: "active-1",+ snapshotId: "closed",+ snapshot: result.snapshot,+ messageCount: 0,+ targetChunkBytes: 512 * 1024,+ purpose: "attach",+ });+ if (timing === "after end") {+ fakeClient.emitMessage({+ type: "session_snapshot_end",+ activeSessionId: "active-1",+ snapshotId: "closed",+ chunkCount: 0,+ lastEventSequence: 12,+ });+ }+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "active-1", reason: "killed" });+ await nextMessageLoopTurn();+ expect(rejected).toHaveBeenCalledExactlyOnceWith(expect.any(Error));+ expect(resolved).not.toHaveBeenCalled();+ expect(+ (connection as unknown as { snapshotAssemblies: Map<string, unknown> }).snapshotAssemblies.size,+ ).toBe(0);+ expect(fakeClient.closeCount).toBe(0);+ for (const purpose of ["attach", "replacement", "resync"] as const) {+ fakeClient.emitMessage({+ type: "session_snapshot_begin",+ activeSessionId: "active-1",+ snapshotId: purpose,+ snapshot: result.snapshot,+ messageCount: 1,+ targetChunkBytes: 512 * 1024,+ purpose,+ });+ fakeClient.emitMessage({+ type: "session_snapshot_chunk",+ activeSessionId: "active-1",+ snapshotId: purpose,+ index: 0,+ messages: [{ role: "user", content: "late transcript", timestamp: 1 }],+ });+ fakeClient.emitMessage({+ type: "session_snapshot_end",+ activeSessionId: "active-1",+ snapshotId: purpose,+ chunkCount: 1,+ lastEventSequence: 12,+ });+ }+ fakeClient.emitMessage({+ type: "session_snapshot_failed",+ activeSessionId: "active-1",+ snapshotId: "failed-after-close",+ error: "stream closed",+ });+ expect(+ (connection as unknown as { snapshotAssemblies: Map<string, unknown> }).snapshotAssemblies.size,+ ).toBe(0);+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "active-1", reason: "killed" });+ await nextMessageLoopTurn();+ expect(+ (connection as unknown as { snapshotAssemblies: Map<string, unknown> }).snapshotAssemblies.size,+ ).toBe(0);+ expect(events).toEqual([expect.objectContaining({ type: "closed" })]);+ const requestCount = fakeClient.requests.length;+ await expect(connection.attach()).rejects.toThrow("closed");+ expect(fakeClient.requests).toHaveLength(requestCount);+ } finally {+ await connection.dispose();+ await pendingAttach;+ }+ },+ );++ it.each(["session_replaced", "session_resynced"] as const)(+ "drops a %s superseded during the initial render",+ async (type) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ let release!: () => void;+ const initialRenderPromise = new Promise<void>((resolve) => {+ release = resolve;+ });+ const ui = {+ agentConnection: connection,+ sessionEventQueue: Promise.resolve(),+ sessionEventGeneration: 0,+ initialRenderPromise,+ refreshCommandCatalogForCurrentSession: vi.fn(async () => {}),+ renderResyncedSession: vi.fn(async () => {}),+ resetSideQuestion: vi.fn(),+ resetExtensionUI: vi.fn(),+ applyConnectionStateSnapshot: vi.fn(),+ resetCurrentSessionRenderState: vi.fn(),+ rebindCurrentSession: vi.fn(async () => {}),+ renderInitialMessages: vi.fn(async () => {}),+ ui: { requestRender: vi.fn() },+ showError: vi.fn(),+ };+ try {+ await connection.attach();+ (InteractiveMode.prototype as unknown as { subscribeToAgent(this: typeof ui): void }).subscribeToAgent.call(+ ui,+ );+ const snapshot = createAttachResult("active-1", undefined, undefined, 12).snapshot;+ fakeClient.emitMessage(+ type === "session_replaced"+ ? { type, activeSessionId: "active-1", state: snapshot.state, messages: [] }+ : { type, activeSessionId: "active-1", snapshot },+ );+ await nextMessageLoopTurn();+ const state = createConnectionState("active-1", "latest");+ fakeClient.emitMessage({ type: "session_replaced", activeSessionId: "active-1", state, messages: [] });+ release();+ await ui.sessionEventQueue;+ expect(ui.renderResyncedSession).not.toHaveBeenCalled();+ expect(ui.resetSideQuestion).toHaveBeenCalledOnce();+ expect(ui.resetExtensionUI).toHaveBeenCalledOnce();+ expect(ui.applyConnectionStateSnapshot).toHaveBeenCalledExactlyOnceWith(state);+ expect(ui.resetCurrentSessionRenderState).toHaveBeenCalledOnce();+ expect(ui.rebindCurrentSession).toHaveBeenCalledOnce();+ expect(ui.renderInitialMessages).toHaveBeenCalledOnce();+ expect(ui.ui.requestRender).toHaveBeenCalledOnce();+ expect(ui.showError).not.toHaveBeenCalled();+ } finally {+ release();+ await connection.dispose();+ }+ },+ );++ it("keeps live events behind the whole replay and shares concurrent flushes", async () => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ try {+ await connection.attach();+ const delivered: string[] = [];+ const ui = {+ agentConnection: connection,+ sessionEventQueue: Promise.resolve(),+ sessionEventGeneration: 0,+ handleEvent: async (event: { type: string; name?: string }) => {+ delivered.push(event.name!);+ if (delivered.length === 1) await gate;+ },+ showError: vi.fn(),+ };+ (InteractiveMode.prototype as unknown as { subscribeToAgent(this: typeof ui): void }).subscribeToAgent.call(+ ui,+ );+ emitSequencedSessionEvent(fakeClient, "active-1", 13);+ emitSequencedSessionEvent(fakeClient, "active-1", 14);+ const flush = connection.flushBufferedSessionEvents();+ await nextMessageLoopTurn();+ emitSequencedSessionEvent(fakeClient, "active-1", 15);+ expect(connection.flushBufferedSessionEvents()).toBe(flush);+ expect(delivered).toEqual(["13"]);+ release();+ await flush;+ await ui.sessionEventQueue;+ expect(delivered).toEqual(["13", "14", "15"]);+ expect(ui.showError).not.toHaveBeenCalled();+ } finally {+ release();+ await connection.dispose();+ }+ });++ it("leaves streaming state in the attach snapshot unchanged until replay", async () => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ try {+ await connection.attach();+ const message = fauxAssistantMessage("streaming response");+ fakeClient.emitMessage({+ type: "session_event",+ activeSessionId: "active-1",+ event: { type: "message_start", message },+ });+ const snapshot = await connection.getInitialSnapshot();+ expect(snapshot.streamingMessage).toBeUndefined();+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ });+ await connection.flushBufferedSessionEvents();+ expect(delivered).toEqual([{ type: "session_event", event: { type: "message_start", message } }]);+ expect((await connection.getInitialSnapshot()).streamingMessage).toEqual(message);+ } finally {+ await connection.dispose();+ }+ });++ it.each([true, false])(+ "delivers attach-time extension prompts without skipping transcript events (subscribed=%s)",+ async (subscribed) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ try {+ const delivered: AgentConnectionEvent[] = [];+ const listener = (event: AgentConnectionEvent) => {+ delivered.push(event);+ };+ if (subscribed) connection.subscribe(listener);+ fakeClient.attachResultFactory = (command) => {+ fakeClient.emitMessage({+ type: "extension_ui_request",+ activeSessionId: "active-1",+ id: "editor-request",+ method: "editor",+ payload: { title: "Edit" },+ meta: {+ id: "active-1:14",+ protocol: DAEMON_PROTOCOL_INFO,+ activeSessionId: "active-1",+ sequence: 14,+ cursor: { generation: "generation-active-1", sequence: 14 },+ emittedAt: "2026-01-01T00:00:00.000Z",+ },+ });+ return createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12);+ };+ await connection.attach();+ // The transport releases earlier transcript events only after the snapshot.+ emitSequencedSessionEvent(fakeClient, "active-1", 13);+ if (!subscribed) {+ expect(delivered).toEqual([]);+ connection.subscribe(listener);+ }+ expect(delivered).toEqual([+ {+ type: "extension_ui_request",+ request: { id: "editor-request", method: "editor", payload: { title: "Edit" } },+ },+ ]);+ await connection.flushBufferedSessionEvents();+ expect(delivered.at(-1)).toEqual({+ type: "session_event",+ event: { type: "session_info_changed", name: "13" },+ });+ const additionalListener = vi.fn();+ connection.subscribe(additionalListener);+ expect(additionalListener).not.toHaveBeenCalled();+ } finally {+ await connection.dispose();+ }+ },+ );++ it.each(["notify", "setStatus", "setWidget"])(+ "bounds attach-time %s updates without dropping queued dialogs",+ async (method) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ try {+ await connection.attach();+ fakeClient.emitMessage({+ type: "extension_ui_request",+ activeSessionId: "active-1",+ id: "dialog",+ method: "editor",+ payload: { title: "Edit" },+ });+ for (let index = 0; index < 2000; index++) {+ fakeClient.emitMessage({+ type: "extension_ui_request",+ activeSessionId: "active-1",+ id: String(index),+ method,+ payload: {+ message: String(index),+ statusKey: "progress",+ statusText: String(index),+ widgetKey: "progress",+ widgetLines: [String(index)],+ },+ });+ }+ const listener = vi.fn();+ connection.subscribe(listener);+ expect(listener).toHaveBeenCalledTimes(128);+ expect(listener).toHaveBeenNthCalledWith(1, {+ type: "extension_ui_request",+ request: { id: "dialog", method: "editor", payload: { title: "Edit" } },+ });+ expect(listener).toHaveBeenLastCalledWith({+ type: "extension_ui_request",+ request: expect.objectContaining({ id: "1999", method }),+ });+ expect(fakeClient.requests.filter((request) => request.type === "extension_ui_response")).toEqual([]);+ } finally {+ await connection.dispose();+ }+ },+ );++ it("cancels excess attach-time dialogs when the backlog contains only dialogs", async () => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ try {+ await connection.attach();+ for (let index = 0; index < 129; index++) {+ fakeClient.emitMessage({+ type: "extension_ui_request",+ activeSessionId: "active-1",+ id: String(index),+ method: "editor",+ payload: { title: "Edit" },+ });+ }+ fakeClient.emitMessage({+ type: "extension_ui_request",+ activeSessionId: "active-1",+ id: "notification",+ method: "notify",+ payload: { message: "Update" },+ });+ expect(fakeClient.requests.filter((request) => request.type === "extension_ui_response")).toEqual([+ {+ type: "extension_ui_response",+ activeSessionId: "active-1",+ requestId: "128",+ response: { cancelled: true },+ },+ ]);+ const listener = vi.fn();+ connection.subscribe(listener);+ expect(listener).toHaveBeenCalledTimes(128);+ expect(listener).toHaveBeenLastCalledWith({+ type: "extension_ui_request",+ request: { id: "127", method: "editor", payload: { title: "Edit" } },+ });+ } finally {+ await connection.dispose();+ }+ });++ it.each(["disposed", "replaced", "restarted", "update-session", "update-transport"])(+ "discards queued extension prompts when %s before subscription",+ async (boundary) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");+ try {+ await connection.attach();+ fakeClient.emitMessage({+ type: "extension_ui_request",+ activeSessionId: "active-1",+ id: "old",+ method: "editor",+ payload: { title: "Old" },+ meta: {+ id: "old:13",+ protocol: DAEMON_PROTOCOL_INFO,+ activeSessionId: "active-1",+ sequence: 13,+ cursor: { generation: "generation-active-1", sequence: 13 },+ emittedAt: "2026-01-01T00:00:00.000Z",+ },+ });+ if (boundary === "disposed") await connection.dispose();+ else if (boundary === "replaced")+ fakeClient.emitMessage({+ type: "session_replaced",+ activeSessionId: "active-1",+ state: createConnectionState("active-1", "replacement"),+ messages: [],+ });+ else if (boundary.startsWith("update-")) {+ fakeClient.updateRestartSessions = [{ activeSessionId: "active-1", sessionId: "session-current" }];+ if (boundary === "update-session") {+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "active-1", reason: "update" });+ } else {+ fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "update"));+ }+ } else {+ const snapshot = createAttachResult("active-1", undefined, undefined, 1).snapshot;+ snapshot.lastEventCursor = { generation: "restarted", sequence: 1 };+ fakeClient.emitMessage({ type: "session_resynced", activeSessionId: "active-1", snapshot });+ }+ const listener = vi.fn();+ connection.subscribe(listener);+ expect(listener).not.toHaveBeenCalled();+ if (boundary.startsWith("update-")) {+ await vi.waitFor(() =>+ expect(listener).toHaveBeenCalledWith({ type: "connection_status", status: "connected" }),+ );+ expect(listener).not.toHaveBeenCalledWith(expect.objectContaining({ type: "extension_ui_request" }));+ fakeClient.emitMessage({+ type: "extension_ui_request",+ activeSessionId: "active-1",+ id: "new",+ method: "editor",+ payload: { title: "New" },+ });+ expect(listener).toHaveBeenLastCalledWith({+ type: "extension_ui_request",+ request: { id: "new", method: "editor", payload: { title: "New" } },+ });+ }+ } finally {+ await connection.dispose();+ }+ },+ );++ it.each([1, 1001])(+ "drops %i buffered events and overflow superseded by a restarted worker snapshot",+ async (count) => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ try {+ await connection.attach();+ for (let index = 0; index < count; index++) emitSequencedSessionEvent(fakeClient, "active-1", 100 + index);+ const snapshot = createAttachResult("active-1", undefined, undefined, 1).snapshot;+ snapshot.lastEventCursor = { generation: "restarted", sequence: 1 };+ fakeClient.emitMessage({+ type: "session_snapshot_begin",+ activeSessionId: "active-1",+ snapshotId: "restart",+ snapshot,+ messageCount: 0,+ targetChunkBytes: 512 * 1024,+ purpose: "resync",+ });+ fakeClient.emitMessage({+ type: "session_snapshot_end",+ activeSessionId: "active-1",+ snapshotId: "restart",+ chunkCount: 0,+ lastEventSequence: 1,+ lastEventCursor: snapshot.lastEventCursor,+ });+ await nextMessageLoopTurn();+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ });+ await connection.flushBufferedSessionEvents();+ expect(delivered).toEqual([]);+ expect(fakeClient.requests.filter((request) => request.type === "attach")).toHaveLength(1);+ expect((await connection.getInitialSnapshot()).lastEventSequence).toBe(1);+ } finally {+ await connection.dispose();+ }+ },+ );++ it("replays only newer target-session events when reattaching with an inline snapshot", async () => {+ const fakeClient = new FakeDaemonClient();+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {+ deferSessionEvents: true,+ });+ try {+ await connection.attach();+ emitSequencedSessionEvent(fakeClient, "active-1", 13);+ const request = fakeClient.request.bind(fakeClient);+ vi.spyOn(fakeClient, "request").mockImplementation(async (command, ...options) => {+ if (command.type === "switch_session")+ return {+ type: "response",+ command: command.type,+ success: false,+ error: "Session already active",+ errorInfo: {+ code: "session_already_active",+ activeSessionId: "active-2",+ sessionPath: "/tmp/target.jsonl",+ },+ };+ if (command.type === "reattach") {+ emitSequencedSessionEvent(fakeClient, "active-2", 2);+ return {+ type: "response",+ command: command.type,+ success: true,+ data: createAttachResult("active-2", undefined, undefined, 1),+ };+ }+ return request(command, ...options);+ });+ await connection.switchSession("/tmp/target.jsonl");+ const delivered: AgentConnectionEvent[] = [];+ connection.subscribe((event) => {+ delivered.push(event);+ });+ await connection.flushBufferedSessionEvents();+ expect(delivered).toEqual([{ type: "session_event", event: { type: "session_info_changed", name: "2" } }]);+ } finally {+ await connection.dispose();+ }+ });+});diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.tsindex f7614733fa..11deb1a47a 100644--- a/packages/coding-agent/test/daemon-client.test.ts+++ b/packages/coding-agent/test/daemon-client.test.ts@@ -388,6 +388,33 @@ describe("DaemonClient", () => {client.close();});+ it.each([false, true])("handles the response before coalesced records (callback throws=%s)", async (throws) => {+ const client = new DaemonClient("/tmp/prime-agent.sock");+ const connect = client.connect();+ const socket = netMock.sockets[0]!;+ socket.emit("connect");+ await connect;+ emitHello(socket);+ const order: string[] = [];+ client.onMessage((message) => order.push(message.type));+ const request = client.request({ type: "attach", activeSessionId: "active-1" }, 30000, {+ onResponse: () => {+ order.push("response");+ if (throws) throw new Error("response callback failed");+ },+ });+ const { id } = JSON.parse(socket.writes[0]!) as { id: string };+ socket.emit(+ "data",+ `${JSON.stringify({ id, type: "response", command: "attach", success: true })}\n` ++ `${JSON.stringify({ type: "session_detached", activeSessionId: "active-1" })}\n`,+ );+ expect(order).toEqual(["response", "session_detached"]);+ if (throws) await expect(request).rejects.toThrow("response callback failed");+ else await expect(request).resolves.toMatchObject({ id, success: true });+ client.close();+ });+it("serializes list commands with all sessions requested", async () => {const client = new DaemonClient("/tmp/prime-agent.sock");diff --git a/packages/coding-agent/test/daemon-deferred-session-frames.test.ts b/packages/coding-agent/test/daemon-deferred-session-frames.test.tsnew file mode 100644index 0000000000..d5ef046535--- /dev/null+++ b/packages/coding-agent/test/daemon-deferred-session-frames.test.ts@@ -0,0 +1,1029 @@+import type { Socket } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { PassThrough } from "node:stream";+import type { AgentMessage } from "@earendil-works/pi-agent-core";+import { fauxAssistantMessage } from "@earendil-works/pi-ai";+import { describe, expect, it, vi } from "vitest";+import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";+import { AgentDaemon, markClientSnapshotStreaming } from "../src/modes/daemon/daemon-mode.js";+import {+ DAEMON_PROTOCOL_INFO,+ type DaemonAttachResult,+ type DaemonCommand,+ type DaemonOutbound,+ type DaemonResponse,+} from "../src/modes/daemon/daemon-protocol.js";+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";+import { type DaemonWorkerFrameHeader, isDaemonWorkerFrameHeader } from "../src/modes/daemon/daemon-worker-protocol.js";+import { SnapshotTranscriptCache } from "../src/modes/daemon/snapshot-transcript-cache.js";+import { type PrivateFrame, PrivateFrameDecoder } from "../src/modes/session-worker/private-framing.js";++const activeSessionId = "active-deferred";+const snapshotId = "snapshot-deferred";++function summary(): SessionSummary {+ return {+ id: activeSessionId,+ activeSessionId,+ lifecycle: "live",+ activity: "idle",+ isSessionActive: false,+ sessionId: "session-deferred",+ cwd: "/tmp",+ isStreaming: false,+ isCompacting: false,+ attachedClients: 0,+ messageCount: 1,+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },+ };+}++function streamedResult(): DaemonAttachResult {+ return {+ protocol: DAEMON_PROTOCOL_INFO,+ activeSessionId,+ snapshot: {+ activeSessionId,+ summary: summary(),+ state: { activeSessionId, sessionId: "session-deferred" } as DaemonAttachResult["snapshot"]["state"],+ messages: [],+ lastEventSequence: 1,+ lastEventCursor: { generation: "generation-deferred", sequence: 1 },+ },+ replay: { status: "complete", toSequence: 1 },+ lastEventSequence: 1,+ lastEventCursor: { generation: "generation-deferred", sequence: 1 },+ snapshotStream: { id: snapshotId, messageCount: 0, targetChunkBytes: 512 * 1024 },+ client: { id: "client", capabilities: ["chunked_snapshot"] },+ };+}++function sessionEventMessage(sequence: number): DaemonOutbound {+ return {+ type: "session_event",+ activeSessionId,+ event: { type: "session_info_changed", name: `change-${sequence}` },+ meta: {+ id: `${activeSessionId}:${sequence}`,+ protocol: DAEMON_PROTOCOL_INFO,+ activeSessionId,+ sequence,+ cursor: { generation: "generation-deferred", sequence },+ emittedAt: "2026-01-01T00:00:00.000Z",+ },+ };+}++function socketClient(socket: PassThrough, extra: Partial<DaemonSocketClient> = {}): DaemonSocketClient {+ return {+ id: "client",+ socket: socket as unknown as Socket,+ attachedActiveSessionIds: new Set([activeSessionId]),+ catchupActiveSessionIds: new Set(),+ detachInput: () => {},+ supportsExtensionUi: false,+ capabilities: new Set(["chunked_snapshot"]),+ ...extra,+ } as DaemonSocketClient;+}++async function nextMacroTaskTurn(): Promise<void> {+ await new Promise<void>((resolve) => setImmediate(resolve));+ await new Promise<void>((resolve) => setImmediate(resolve));+}++interface SupervisorWorkerHarness {+ descriptor: { workerId: string; lifecycle: "ready"; pid: number };+ client?: { close: ReturnType<typeof vi.fn>; request: ReturnType<typeof vi.fn> };+ summaries: Map<string, SessionSummary>;+ snapshotCache: Map<string, DaemonAttachResult>;+ transcriptCaches: Map<string, SnapshotTranscriptCache>;+ snapshotGenerations: Map<string, Map<string, unknown>>;+ snapshotLoads: Map<string, Promise<DaemonAttachResult>>;+ intentionalStop: boolean;+ stopRevision: number;+}++describe("deferred session frames during snapshot streams", () => {+ it.each(["snapshot", "dropped", "backpressure"])(+ "delivers extension prompts through worker and supervisor during %s",+ (phase) => {+ const daemon = new AgentDaemon(join(tmpdir(), "extension-frames-worker.sock"), {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const supervisor = new DaemonSupervisor(join(tmpdir(), "extension-frames-supervisor.sock"), {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: join(tmpdir(), "extension-frames-supervisor-state"),+ });+ const workerSocket = new PassThrough();+ const supervisorSocket = new PassThrough();+ const workerClient = socketClient(workerSocket, { supportsExtensionUi: true, transport: "private-framed" });+ const supervisorClient = socketClient(supervisorSocket, { supportsExtensionUi: true });+ for (const client of [workerClient, supervisorClient]) {+ if (phase === "snapshot") client.snapshotActiveSessionIds = new Set([activeSessionId]);+ if (phase === "backpressure") client.backpressured = true;+ if (phase === "dropped") {+ client.deferredSessionFramesDropped = new Set([activeSessionId]);+ client.deferredSessionPayloadsDropped = new Set([activeSessionId]);+ }+ }+ const worker = {+ snapshotCache: new Map(),+ snapshotLoads: new Map(),+ transcriptCaches: new Map(),+ } as unknown as SupervisorWorkerHarness;+ const routing = supervisor as unknown as {+ clients: Set<DaemonSocketClient>;+ handleWorkerFrame(worker: SupervisorWorkerHarness, frame: PrivateFrame<DaemonWorkerFrameHeader>): void;+ };+ routing.clients.add(supervisorClient);+ const written: DaemonOutbound[] = [];+ supervisorSocket.on("data", (payload: Buffer) => written.push(JSON.parse(payload.toString())));+ const decoder = new PrivateFrameDecoder(isDaemonWorkerFrameHeader);+ workerSocket.on("data", (payload: Buffer) => {+ for (const frame of decoder.push(payload)) routing.handleWorkerFrame(worker, frame);+ });+ try {+ (+ daemon as unknown as { broadcastToSession(state: ActiveSessionState, message: DaemonOutbound): void }+ ).broadcastToSession(+ {+ activeSessionId,+ clients: new Set([workerClient]),+ lastEventSequence: 1,+ eventGeneration: "generation-deferred",+ } as ActiveSessionState,+ {+ type: "extension_ui_request",+ activeSessionId,+ id: "editor-request",+ method: "editor",+ payload: { title: "Edit" },+ },+ );+ expect(written).toEqual([+ expect.objectContaining({ type: "extension_ui_request", id: "editor-request", method: "editor" }),+ ]);+ expect(workerClient.deferredSessionOutbounds?.size ?? 0).toBe(0);+ expect(supervisorClient.deferredSessionPayloads?.size ?? 0).toBe(0);+ } finally {+ workerSocket.destroy();+ supervisorSocket.destroy();+ }+ },+ );++ it.each([+ [1, false, "stream"],+ [2, false, "stream"],+ [2, true, "stream"],+ [1, false, "replacement-failure"],+ [1, false, "replacement-replay-failure"],+ [1, false, "replacement-write-failure"],+ [1, false, "catchup"],+ [1, false, "inline-catchup"],+ ] as const)("worker: replay (%i, fail=%s, %s)", async (streamCount, failFinal, preparation) => {+ const replayFailed = preparation === "replacement-replay-failure" || preparation === "replacement-write-failure";+ const daemon = new AgentDaemon(join(tmpdir(), "deferred-frames-worker.sock"), {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const socket = new PassThrough();+ socket.on("error", () => {});+ const written: Buffer[] = [];+ socket.on("data", (chunk: Buffer) => written.push(Buffer.from(chunk)));+ const client = socketClient(socket, { transport: "private-framed" });+ if (preparation === "inline-catchup") client.capabilities.clear();+ const state = {+ activeSessionId,+ clients: new Set([client]),+ eventGeneration: "generation-deferred",+ lastEventSequence: 1,+ runtime: { metadata: { kind: "top-level" as const, createdAt: 1 } },+ } as unknown as ActiveSessionState;+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAttachResult(): Promise<DaemonAttachResult>;+ flushDeferredSessionFrames(client: DaemonSocketClient, activeSessionId: string): void;+ write(client: DaemonSocketClient, message: DaemonOutbound): boolean;+ drainBackpressuredClientCatchups(client: DaemonSocketClient): Promise<"drained" | "retry-later">;+ catchUpBackpressuredClient(client: DaemonSocketClient): Promise<void>;+ broadcastToSession(state: ActiveSessionState, message: DaemonOutbound): void;+ streamWorkerSnapshot(+ client: DaemonSocketClient,+ result: DaemonAttachResult,+ transcript: AsyncIterable<Buffer> & { dispose?(): void },+ purpose: "attach",+ signal: AbortSignal,+ snapshotAlreadyMarked: boolean,+ ): Promise<void>;+ };+ vi.spyOn(internals, "catchUpBackpressuredClient").mockResolvedValue();+ internals.sessions.set(activeSessionId, state);+ if (replayFailed) {+ vi.spyOn(+ internals,+ preparation === "replacement-replay-failure" ? "flushDeferredSessionFrames" : "write",+ ).mockImplementationOnce(() => {+ throw new Error("replacement delivery failed");+ });+ }++ let releaseChunk: () => void = () => {};+ const chunkGate = new Promise<void>((resolve) => {+ releaseChunk = resolve;+ });+ async function* gatedTranscript(fail = false): AsyncGenerator<Buffer> {+ yield Buffer.from(`{"type":"session_snapshot_chunk"}`);+ await chunkGate;+ if (fail) throw new Error("last snapshot failed");+ yield Buffer.from(`{"type":"session_snapshot_chunk"}`);+ }+ const transcript = gatedTranscript();++ let stream: Promise<unknown>;+ if (preparation !== "stream") {+ vi.spyOn(internals, "createAttachResult").mockImplementation(async () => {+ const result = streamedResult();+ await chunkGate;+ if (preparation.startsWith("replacement")) throw new Error("snapshot preparation failed");+ return result;+ });+ if (preparation.endsWith("catchup")) {+ client.deferredSessionFramesDropped = new Set([activeSessionId]);+ client.catchupActiveSessionIds?.add(activeSessionId);+ if (preparation === "inline-catchup") client.catchupPurposes = new Map([[activeSessionId, "replacement"]]);+ stream = internals.drainBackpressuredClientCatchups(client);+ } else {+ internals.broadcastToSession(state, {+ type: "session_replaced",+ activeSessionId,+ state: streamedResult().snapshot.state,+ messages: [],+ });+ stream = chunkGate.then(nextMacroTaskTurn);+ }+ } else {+ stream = internals.streamWorkerSnapshot(+ client,+ streamedResult(),+ transcript,+ "attach",+ markClientSnapshotStreaming(client, activeSessionId),+ true,+ );+ }+ await nextMacroTaskTurn();+ const streams = [stream];+ for (let index = 1; index < streamCount; index++) {+ streams.push(+ internals.streamWorkerSnapshot(+ client,+ streamedResult(),+ gatedTranscript(failFinal),+ "attach",+ markClientSnapshotStreaming(client, activeSessionId),+ true,+ ),+ );+ }+ // The stream is parked between chunks; events broadcast now are withheld.+ internals.broadcastToSession(state, sessionEventMessage(2));+ internals.broadcastToSession(state, sessionEventMessage(3));+ if (preparation === "inline-catchup") state.lastEventSequence = 3;+ if (preparation !== "stream") {+ expect(written).toHaveLength(0);+ expect(client.deferredSessionOutbounds?.get(activeSessionId)?.frames).toHaveLength(2);+ } else expect(written.length).toBeGreaterThan(0);++ releaseChunk();+ const outcomes = await Promise.allSettled(streams);+ expect(outcomes.filter((outcome) => outcome.status === "rejected")).toHaveLength(failFinal ? 1 : 0);++ const decoder = new PrivateFrameDecoder(isDaemonWorkerFrameHeader);+ const frames = decoder.push(Buffer.concat(written));+ if (preparation === "inline-catchup") expect(JSON.parse(frames[0]!.payload.toString()).meta.sequence).toBe(1);+ const outboundTypes = frames.map((frame) => (frame.header.kind === "outbound" ? frame.header.outboundType : ""));+ expect(outboundTypes).toEqual([+ ...(preparation.startsWith("replacement")+ ? preparation === "replacement-write-failure"+ ? []+ : ["session_replaced"]+ : preparation === "catchup"+ ? ["session_snapshot_begin", "session_snapshot_end"]+ : preparation === "inline-catchup"+ ? ["session_replaced"]+ : Array.from({ length: streamCount }, (_, index) =>+ failFinal && index === streamCount - 1+ ? ["session_snapshot_begin", "session_snapshot_chunk", "session_snapshot_failed"]+ : [+ "session_snapshot_begin",+ "session_snapshot_chunk",+ "session_snapshot_chunk",+ "session_snapshot_end",+ ],+ ).flat()),+ ...(failFinal || replayFailed ? [] : ["session_event", "session_event"]),+ ]);+ const replayed = frames+ .filter((frame) => frame.header.kind === "outbound" && frame.header.outboundType === "session_event")+ .map((frame) => JSON.parse(frame.payload.toString("utf8")));+ expect(replayed).toEqual(+ failFinal || replayFailed+ ? []+ : [+ expect.objectContaining({ event: { type: "session_info_changed", name: "change-2" } }),+ expect.objectContaining({ event: { type: "session_info_changed", name: "change-3" } }),+ ],+ );+ expect(client.catchupActiveSessionIds?.size ?? 0).toBe(failFinal || replayFailed ? 1 : 0);+ if (replayFailed) {+ const before = written.length;+ internals.broadcastToSession(state, sessionEventMessage(4));+ expect(written).toHaveLength(before);+ expect(client.catchupPurposes?.get(activeSessionId)).toBe("replacement");+ expect(internals.catchUpBackpressuredClient).toHaveBeenCalledOnce();+ }+ expect(client.snapshotActiveSessionCounts?.size ?? 0).toBe(0);+ expect(client.deferredSessionOutbounds?.size ?? 0).toBe(0);+ socket.destroy();+ });++ it.each(["jsonl", "private-framed"] as const)(+ "worker: freezes mutable streaming frames for %s replay",+ (transport) => {+ const daemon = new AgentDaemon(join(tmpdir(), "deferred-mutable-frames.sock"), {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const socket = new PassThrough();+ const written: Buffer[] = [];+ socket.on("data", (chunk: Buffer) => written.push(Buffer.from(chunk)));+ const client = socketClient(socket, { transport, snapshotActiveSessionIds: new Set([activeSessionId]) });+ const state = {+ activeSessionId,+ clients: new Set([client]),+ eventGeneration: "generation-deferred",+ lastEventSequence: 1,+ } as ActiveSessionState;+ const internals = daemon as unknown as {+ broadcastToSession(state: ActiveSessionState, message: DaemonOutbound): void;+ flushDeferredSessionFrames(client: DaemonSocketClient, activeSessionId: string): void;+ };+ try {+ const message = fauxAssistantMessage("first");+ const text = message.content[0];+ if (text?.type !== "text") throw new Error("Expected a text block");+ internals.broadcastToSession(state, {+ type: "session_event",+ activeSessionId,+ event: { type: "message_start", message: { ...message } },+ });+ const toolCall = { type: "toolCall" as const, id: "tool", name: "lookup", arguments: { query: "first" } };+ message.content.push(toolCall);+ for (const query of ["second", "third"]) {+ text.text = query;+ toolCall.arguments.query = query;+ internals.broadcastToSession(state, {+ type: "session_event",+ activeSessionId,+ event: {+ type: "message_update",+ message: { ...message },+ assistantMessageEvent: { type: "toolcall_delta", contentIndex: 1, delta: query, partial: message },+ },+ });+ }+ const bufferedBytes = client.deferredSessionOutbounds?.get(activeSessionId)?.bytes;+ text.text = "future".repeat(1000);+ toolCall.arguments.query = "future";+ expect(written).toHaveLength(0);+ internals.flushDeferredSessionFrames(client, activeSessionId);+ const payloads =+ transport === "private-framed"+ ? new PrivateFrameDecoder(isDaemonWorkerFrameHeader)+ .push(Buffer.concat(written))+ .map((frame) => frame.payload)+ : written;+ const replayed = payloads.map((payload) => JSON.parse(payload.toString()));+ expect(replayed[0]).toMatchObject({ event: { message: { content: [{ type: "text", text: "first" }] } } });+ if (transport === "private-framed") {+ expect(replayed.slice(1)).toMatchObject([+ { type: "assistant_stream_delta", toolCallArguments: { query: "second" } },+ { type: "assistant_stream_delta", toolCallArguments: { query: "third" } },+ ]);+ } else {+ expect(Buffer.concat(written).length).toBe(bufferedBytes);+ for (const [index, query] of ["second", "third"].entries()) {+ expect(replayed[index + 1]).toMatchObject({+ event: {+ message: {+ content: [+ { type: "text", text: query },+ { type: "toolCall", arguments: { query } },+ ],+ },+ },+ });+ }+ }+ } finally {+ socket.destroy();+ }+ },+ );++ it.each([+ ["count", 257, 0],+ ["single payload", 1, 2 * 1024 * 1024],+ ["total bytes", 2, 1024 * 1024],+ ] as const)("worker: catches up when the deferral %s limit overflows", async (_limit, count, textLength) => {+ const daemon = new AgentDaemon(join(tmpdir(), "deferred-frames-overflow.sock"), {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const socket = new PassThrough();+ socket.on("error", () => {});+ const written: Buffer[] = [];+ socket.on("data", (chunk: Buffer) => written.push(Buffer.from(chunk)));+ const client = socketClient(socket, { transport: "private-framed" });+ const state = {+ activeSessionId,+ clients: new Set([client]),+ eventGeneration: "generation-deferred",+ lastEventSequence: 1,+ runtime: { metadata: { kind: "top-level" as const, createdAt: 1 } },+ } as unknown as ActiveSessionState;+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ broadcastToSession(state: ActiveSessionState, message: DaemonOutbound): void;+ streamWorkerSnapshot(+ client: DaemonSocketClient,+ result: DaemonAttachResult,+ transcript: AsyncIterable<Buffer> & { dispose?(): void },+ purpose: "attach",+ signal: AbortSignal,+ snapshotAlreadyMarked: boolean,+ ): Promise<void>;+ queueClientCatchup(+ client: DaemonSocketClient,+ activeSessionId: string,+ purpose: "replacement" | "resync",+ ): void;+ };+ const queueClientCatchup = vi.fn();+ internals.queueClientCatchup = queueClientCatchup;+ internals.sessions.set(activeSessionId, state);+ const snapshotSignal = markClientSnapshotStreaming(client, activeSessionId);++ let releaseChunk: () => void = () => {};+ const chunkGate = new Promise<void>((resolve) => {+ releaseChunk = resolve;+ });+ async function* gatedTranscript(): AsyncGenerator<Buffer> {+ yield Buffer.from(`{"type":"session_snapshot_chunk"}`);+ await chunkGate;+ yield Buffer.from(`{"type":"session_snapshot_chunk"}`);+ }+ const transcript = gatedTranscript();++ const stream = internals.streamWorkerSnapshot(+ client,+ streamedResult(),+ transcript,+ "attach",+ snapshotSignal,+ true,+ );+ await nextMacroTaskTurn();+ for (let index = 0; index < count; index++) {+ const outbound = sessionEventMessage(index + 2);+ if (textLength && outbound.type === "session_event") {+ const message = fauxAssistantMessage("é".repeat(textLength));+ outbound.event = {+ type: "message_update",+ message,+ assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "é", partial: message },+ };+ }+ internals.broadcastToSession(state, outbound);+ if (index < count - 1)+ expect(client.deferredSessionOutbounds?.get(activeSessionId)?.frames).toHaveLength(index + 1);+ }+ expect(client.deferredSessionOutbounds?.size ?? 0).toBe(0);+ // Once overflow requests a snapshot, later events cannot restart a partial replay.+ internals.broadcastToSession(state, sessionEventMessage(count + 2));+ expect(client.deferredSessionOutbounds?.size ?? 0).toBe(0);+ releaseChunk();+ await stream;++ const decoder = new PrivateFrameDecoder(isDaemonWorkerFrameHeader);+ const frames = decoder.push(Buffer.concat(written));+ const outboundTypes = frames.map((frame) => (frame.header.kind === "outbound" ? frame.header.outboundType : ""));+ expect(outboundTypes).toEqual([+ "session_snapshot_begin",+ "session_snapshot_chunk",+ "session_snapshot_chunk",+ "session_snapshot_end",+ ]);+ expect(queueClientCatchup).toHaveBeenCalledWith(client, activeSessionId, "resync");+ socket.destroy();+ });++ it.each(["resync", "replacement"] as const)(+ "supervisor: failed %s does not block healthy sessions",+ async (purpose) => {+ const supervisor = new DaemonSupervisor(join(tmpdir(), "catchup-fairness.sock"), {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: join(tmpdir(), "catchup-fairness-state"),+ });+ const socket = new PassThrough();+ const written: DaemonOutbound[] = [];+ socket.on("data", (chunk: Buffer) => written.push(JSON.parse(chunk.toString())));+ const sessions = [activeSessionId, "also-failing", "healthy"];+ const client = socketClient(socket, {+ capabilities: new Set(),+ attachedActiveSessionIds: new Set(sessions),+ catchupActiveSessionIds: new Set(sessions),+ catchupPurposes: new Map(sessions.map((id) => [id, purpose])),+ });+ const internals = supervisor as unknown as {+ attachClient(+ client: DaemonSocketClient,+ command: { activeSessionId: string },+ ): Promise<{ result: DaemonAttachResult }>;+ catchUpClient(client: DaemonSocketClient): Promise<void>;+ };+ const attach = vi.spyOn(internals, "attachClient").mockImplementation(async (_client, command) => {+ if (command.activeSessionId !== "healthy") throw new Error("worker remains unavailable");+ const result = streamedResult();+ result.activeSessionId =+ result.snapshot.activeSessionId =+ result.snapshot.state.activeSessionId =+ "healthy";+ return { result };+ });+ try {+ await internals.catchUpClient(client);+ expect(attach.mock.calls.map(([, command]) => command.activeSessionId)).toEqual(sessions);+ expect(written).toEqual([+ expect.objectContaining({+ type: purpose === "replacement" ? "session_replaced" : "session_resynced",+ activeSessionId: "healthy",+ }),+ ]);+ expect(client.catchupActiveSessionIds).toEqual(new Set(sessions.slice(0, 2)));+ expect(client.catchupRetryTimer).toBeDefined();+ client.catchupActiveSessionIds?.add("healthy");+ client.catchupPurposes?.set("healthy", purpose);+ await vi.waitFor(() => expect(written).toHaveLength(2));+ expect(attach.mock.calls.map(([, command]) => command.activeSessionId)).toEqual([...sessions, ...sessions]);+ expect(written[1]).toMatchObject({ type: written[0]?.type, activeSessionId: "healthy" });+ expect(client.catchupPurposes).toEqual(new Map(sessions.slice(0, 2).map((id) => [id, purpose])));+ expect(client.snapshotActiveSessionCounts?.size ?? 0).toBe(0);+ } finally {+ clearTimeout(client.catchupRetryTimer);+ socket.destroy();+ }+ },+ );++ const supervisorScenarios = [+ "attached",+ "catchup",+ "inline-catchup",+ "failed-catchup",+ "failed-replacement-catchup",+ "failed-inline-catchup",+ "inline-reattach",+ "failed-reattach",+ "failed-new-reattach",+ "detached",+ "replaced",+ "failed",+ "failed-detached",+ "oversized",+ "byte-limit",+ "count-limit",+ "closed",+ "oversized-closed",+ "replaced-closed",+ "pending-closed",+ "backpressured-closed",+ ];+ it.each(supervisorScenarios)("supervisor: replay (%s)", async (scenario) => {+ const overflow = scenario.startsWith("oversized") || scenario.endsWith("-limit");+ const closed = scenario.endsWith("closed");+ const reattach = scenario.endsWith("reattach");+ const catchup = scenario.endsWith("catchup");+ const failedCatchup = catchup && scenario.startsWith("failed");+ const purpose = scenario.includes("replacement") ? "replacement" : "resync";+ const supervisor = new DaemonSupervisor(join(tmpdir(), "deferred-frames-supervisor.sock"), {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: join(tmpdir(), "deferred-frames-supervisor-state"),+ });+ const worker: SupervisorWorkerHarness = {+ descriptor: { workerId: "worker-deferred", lifecycle: "ready", pid: 987_654 },+ client: { close: vi.fn(), request: vi.fn(async () => ({ success: true })) },+ summaries: new Map([[activeSessionId, summary()]]),+ snapshotCache: new Map<string, DaemonAttachResult>(),+ transcriptCaches: new Map<string, SnapshotTranscriptCache>(),+ snapshotGenerations: new Map<string, Map<string, unknown>>(),+ snapshotLoads: new Map<string, Promise<DaemonAttachResult>>(),+ intentionalStop: false,+ stopRevision: 0,+ };+ const socket = new PassThrough();+ socket.on("error", () => {});+ const written: string[] = [];+ socket.on("data", (chunk: Buffer) => {+ written.push(chunk.toString("utf8"));+ if (scenario === "backpressured-closed" && written.length === 1) socket.pause();+ });+ const client = socketClient(socket);+ const internals = supervisor as unknown as {+ clients: Set<DaemonSocketClient>;+ workers: Map<string, SupervisorWorkerHarness>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<DaemonResponse | undefined>;+ findWorkerForClient(): Promise<{ worker: SupervisorWorkerHarness; summary: SessionSummary }>;+ attachClient(): Promise<{+ worker: SupervisorWorkerHarness;+ result: DaemonAttachResult;+ transcript?: SnapshotTranscriptCache;+ }>;+ drainClientCatchups(client: DaemonSocketClient): Promise<void>;+ catchUpClient(client: DaemonSocketClient): Promise<void>;+ streamSnapshot(+ client: DaemonSocketClient,+ worker: SupervisorWorkerHarness,+ result: DaemonAttachResult,+ transcript: SnapshotTranscriptCache,+ purpose: "attach",+ ): Promise<void>;+ handleWorkerFrame(worker: SupervisorWorkerHarness, frame: PrivateFrame<DaemonWorkerFrameHeader>): void;+ };+ if (!failedCatchup) vi.spyOn(internals, "catchUpClient").mockResolvedValue();+ internals.clients.add(client);+ internals.workers.set(worker.descriptor.workerId, worker);++ const messages: AgentMessage[] = [+ {+ role: "user",+ content: scenario === "backpressured-closed" ? "x".repeat(128 * 1024) : "stable",+ timestamp: 1,+ },+ ];+ const transcript = new SnapshotTranscriptCache({+ activeSessionId,+ snapshotId,+ messages: scenario === "pending-closed" ? undefined : messages,+ cacheRoot: tmpdir(),+ });+ let releaseChunk: () => void = () => {};+ const chunkGate = new Promise<void>((resolve) => {+ releaseChunk = resolve;+ });+ const waitForChunk = transcript.waitForChunk.bind(transcript);+ transcript.waitForChunk = async (index: number, signal?: AbortSignal) => {+ if (index === 1) {+ await chunkGate;+ if (scenario.startsWith("failed")) throw new Error("snapshot failed");+ }+ return waitForChunk(index, signal);+ };++ let stream: Promise<unknown>;+ if (reattach || catchup) {+ if (reattach || scenario.includes("inline")) client.capabilities.clear();+ if (scenario === "failed-new-reattach") client.attachedActiveSessionIds.delete(activeSessionId);+ vi.spyOn(internals, "findWorkerForClient").mockResolvedValue({ worker, summary: summary() });+ vi.spyOn(internals, "attachClient").mockImplementation(async () => {+ const result = { ...streamedResult(), snapshotStream: undefined };+ await chunkGate;+ if (scenario.startsWith("failed")) throw new Error("reattach failed");+ return { worker, result, transcript };+ });+ if (catchup) {+ client.deferredSessionPayloadsDropped = new Set([activeSessionId]);+ client.catchupActiveSessionIds?.add(activeSessionId);+ client.catchupPurposes = new Map([[activeSessionId, purpose]]);+ stream = failedCatchup ? internals.catchUpClient(client) : internals.drainClientCatchups(client);+ } else {+ client.attachedActiveSessionIds.add("old-session");+ stream = internals.handleCommand(client, {+ type: "reattach",+ activeSessionId: "old-session",+ targetActiveSessionId: activeSessionId,+ });+ }+ } else {+ stream = internals.streamSnapshot(client, worker, streamedResult(), transcript, "attach");+ }+ const completion = stream.catch((error: unknown) => error);+ await nextMacroTaskTurn();+ // The stream is parked before the end record; relayed frames are withheld.+ if (scenario.startsWith("replaced")) {+ internals.handleWorkerFrame(worker, {+ header: {+ kind: "outbound",+ outboundType: "session_replaced",+ activeSessionId,+ payloadEncoding: "jsonl",+ },+ payload: Buffer.from(+ `${JSON.stringify({ type: "session_replaced", activeSessionId, state: streamedResult().snapshot.state, messages: [] })}\n`,+ ),+ });+ }+ const eventFrame: PrivateFrame<DaemonWorkerFrameHeader> = {+ header: {+ kind: "outbound",+ outboundType: "session_event",+ activeSessionId,+ sessionEventType: "session_info_changed",+ payloadEncoding: "jsonl",+ },+ payload: Buffer.from(+ `${JSON.stringify({+ ...sessionEventMessage(2),+ padding: "x".repeat(+ scenario.startsWith("oversized") ? 8 * 1024 * 1024 : scenario === "byte-limit" ? 4 * 1024 * 1024 : 0,+ ),+ })}\n`,+ ),+ };+ internals.handleWorkerFrame(worker, eventFrame);+ if (scenario === "byte-limit") internals.handleWorkerFrame(worker, eventFrame);+ if (scenario === "count-limit") {+ for (let index = 1; index < 257; index++) internals.handleWorkerFrame(worker, eventFrame);+ }+ if (overflow) {+ expect(client.deferredSessionPayloads?.size ?? 0).toBe(0);+ expect(client.catchupActiveSessionIds?.has(activeSessionId)).toBe(true);+ }+ internals.handleWorkerFrame(worker, {+ header: {+ kind: "outbound",+ outboundType: "session_event",+ activeSessionId,+ sessionEventType: "session_info_changed",+ payloadEncoding: "jsonl",+ },+ payload: Buffer.from(`${JSON.stringify(sessionEventMessage(3))}\n`),+ });++ const closeFrame: PrivateFrame<DaemonWorkerFrameHeader> = {+ header: { kind: "outbound", outboundType: "session_closed", activeSessionId, payloadEncoding: "jsonl" },+ payload: Buffer.from(`${JSON.stringify({ type: "session_closed", activeSessionId, reason: "killed" })}\n`),+ };+ if (catchup) expect(client.deferredSessionPayloads?.get(activeSessionId)?.payloads).toHaveLength(2);+ if (closed && !overflow) internals.handleWorkerFrame(worker, closeFrame);+ if (scenario.endsWith("detached")) client.attachedActiveSessionIds.delete(activeSessionId);+ releaseChunk();+ const error = await completion;+ if (scenario === "backpressured-closed") {+ socket.resume();+ await nextMacroTaskTurn();+ }+ if (closed && overflow) internals.handleWorkerFrame(worker, closeFrame);+ if (scenario.startsWith("failed") && !catchup) expect(error).toBeInstanceOf(Error);+ else expect(error).toBeUndefined();++ const lines = written.join("").split("\n").filter(Boolean);+ const parsed = lines.map((line) => JSON.parse(line) as { type: string });+ expect(parsed.map((entry) => entry.type)).toEqual(+ failedCatchup+ ? []+ : scenario === "inline-catchup"+ ? ["session_resynced", "session_event", "session_event"]+ : reattach+ ? [+ ...(scenario === "inline-reattach" ? ["response", "session_detached"] : []),+ ...(scenario === "failed-new-reattach"+ ? ["session_detached"]+ : ["session_event", "session_event"]),+ ]+ : [+ "session_snapshot_begin",+ ...(scenario === "pending-closed" ? [] : ["session_snapshot_chunk"]),+ ...(closed && !overflow ? ["session_closed"] : []),+ ...(closed && !overflow+ ? []+ : [scenario.startsWith("failed") ? "session_snapshot_failed" : "session_snapshot_end"]),+ ...(closed && overflow ? ["session_closed"] : []),+ ...(scenario === "attached" || scenario === "catchup"+ ? ["session_event", "session_event"]+ : []),+ ],+ );+ expect(client.deferredSessionPayloads?.size ?? 0).toBe(0);+ expect(client.snapshotActiveSessionCounts?.size ?? 0).toBe(0);+ expect(client.snapshotTransferAbortControllers?.size ?? 0).toBe(0);+ expect(client.catchupActiveSessionIds?.size ?? 0).toBe(+ !closed && (scenario === "replaced" || scenario === "failed" || failedCatchup || overflow) ? 1 : 0,+ );+ if (failedCatchup) {+ expect(client.catchupPurposes?.get(activeSessionId)).toBe(purpose);+ expect(client.catchupRetryTimer).toBeDefined();+ internals.handleWorkerFrame(worker, eventFrame);+ await internals.catchUpClient(client);+ expect(written).toHaveLength(0);+ expect(internals.attachClient).toHaveBeenCalledOnce();+ transcript.waitForChunk = waitForChunk;+ const result = streamedResult();+ result.lastEventSequence = result.snapshot.lastEventSequence = 3;+ result.lastEventCursor = result.snapshot.lastEventCursor = { generation: "generation-deferred", sequence: 3 };+ vi.mocked(internals.attachClient).mockResolvedValue({ worker, result, transcript });+ const expected = client.capabilities.has("chunked_snapshot")+ ? [+ ...(purpose === "replacement" ? ["session_replaced"] : []),+ "session_snapshot_begin",+ "session_snapshot_chunk",+ "session_snapshot_end",+ ]+ : ["session_resynced"];+ await vi.waitFor(() => expect(written.map((line) => JSON.parse(line).type)).toEqual(expected));+ expect(client.catchupActiveSessionIds?.size).toBe(0);+ expect(client.catchupRetryTimer).toBeUndefined();+ expect(client.snapshotActiveSessionCounts?.size ?? 0).toBe(0);+ internals.handleWorkerFrame(worker, {+ ...eventFrame,+ payload: Buffer.from(`${JSON.stringify(sessionEventMessage(4))}\n`),+ });+ expect(JSON.parse(written.at(-1)!).type).toBe("session_event");+ }+ if (!closed && (scenario === "replaced" || overflow)) {+ const before = written.length;+ const frame: PrivateFrame<DaemonWorkerFrameHeader> = {+ header: { kind: "outbound", outboundType: "session_event", activeSessionId, payloadEncoding: "jsonl" },+ payload: Buffer.from(`${JSON.stringify(sessionEventMessage(4))}\n`),+ };+ internals.handleWorkerFrame(worker, frame);+ expect(written).toHaveLength(before);+ const replacement = internals.streamSnapshot(client, worker, streamedResult(), transcript, "attach");+ internals.handleWorkerFrame(worker, frame);+ await replacement;+ expect(written.map((line) => JSON.parse(line).type).slice(before)).toEqual([+ "session_snapshot_begin",+ "session_snapshot_chunk",+ "session_snapshot_end",+ "session_event",+ ]);+ }+ transcript.dispose();+ socket.destroy();+ });++ it.each(["backpressure", "closed", "detached", "replaced"] as const)("worker: stop after %s", async (scenario) => {+ const daemon = new AgentDaemon(join(tmpdir(), "deferred-frames-stop.sock"), {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const socket = new PassThrough();+ const client = socketClient(socket);+ const written: DaemonOutbound[] = [];+ socket.on("data", (chunk: Buffer) => {+ const message = JSON.parse(chunk.toString("utf8")) as DaemonOutbound;+ written.push(message);+ if (scenario === "backpressure" && message.type === "session_snapshot_end") socket.pause();+ });+ const write = vi.spyOn(socket, "write");+ const state = {+ activeSessionId,+ clients: new Set([client]),+ eventGeneration: "generation-deferred",+ lastEventSequence: 1,+ runtime: { metadata: { kind: "top-level", createdAt: 1 } },+ } as unknown as ActiveSessionState;+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ catchUpBackpressuredClient(client: DaemonSocketClient): Promise<void>;+ broadcastToSession(state: ActiveSessionState, message: DaemonOutbound): void;+ streamWorkerSnapshot(+ client: DaemonSocketClient,+ result: DaemonAttachResult,+ transcript: AsyncIterable<Buffer>,+ purpose: "attach",+ signal: AbortSignal,+ marked: boolean,+ ): Promise<void>;+ };+ vi.spyOn(internals, "catchUpBackpressuredClient").mockResolvedValue();+ internals.sessions.set(activeSessionId, state);+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ async function* transcript(): AsyncGenerator<Buffer> {+ await gate;+ yield Buffer.from('{"type":"session_snapshot_chunk"}\n');+ }+ const stream = internals.streamWorkerSnapshot(+ client,+ streamedResult(),+ transcript(),+ "attach",+ markClientSnapshotStreaming(client, activeSessionId),+ true,+ );+ try {+ await nextMacroTaskTurn();+ internals.broadcastToSession(state, {+ ...sessionEventMessage(2),+ type: "session_event",+ activeSessionId,+ event: { type: "session_info_changed", name: "x".repeat(128 * 1024) },+ });+ internals.broadcastToSession(state, sessionEventMessage(3));+ if (scenario === "closed")+ internals.broadcastToSession(state, { type: "session_closed", activeSessionId, reason: "killed" });+ if (scenario === "detached") client.attachedActiveSessionIds.delete(activeSessionId);+ if (scenario === "replaced") {+ internals.broadcastToSession(state, {+ type: "session_replaced",+ activeSessionId,+ state: streamedResult().snapshot.state,+ messages: [],+ });+ internals.broadcastToSession(state, sessionEventMessage(4));+ }+ release();+ await stream;+ const eventWrites = write.mock.calls.filter(([chunk]) => JSON.parse(String(chunk)).type === "session_event");+ expect(eventWrites).toHaveLength(scenario === "backpressure" ? 1 : 0);+ expect(client.deferredSessionOutbounds?.size ?? 0).toBe(0);+ if (scenario === "backpressure") {+ expect(socket.writableNeedDrain).toBe(true);+ expect(client.backpressured).toBe(true);+ expect(client.catchupActiveSessionIds?.has(activeSessionId)).toBe(true);+ internals.broadcastToSession(state, sessionEventMessage(4));+ expect(+ write.mock.calls.filter(([chunk]) => JSON.parse(String(chunk)).type === "session_event"),+ ).toHaveLength(1);+ }+ if (scenario === "closed") expect(written.some((message) => message.type === "session_closed")).toBe(true);+ if (scenario === "replaced") {+ internals.broadcastToSession(state, sessionEventMessage(5));+ expect(written.some((message) => message.type === "session_event")).toBe(false);+ expect(client.catchupPurposes?.get(activeSessionId)).toBe("replacement");+ const replacement = internals.streamWorkerSnapshot(+ client,+ streamedResult(),+ transcript(),+ "attach",+ markClientSnapshotStreaming(client, activeSessionId),+ true,+ );+ internals.broadcastToSession(state, sessionEventMessage(6));+ await replacement;+ expect(written.filter((message) => message.type === "session_event")).toEqual([sessionEventMessage(6)]);+ }+ } finally {+ release();+ socket.destroy();+ await stream;+ }+ });++ it("supervisor: preserves replay backpressure when another session's snapshot finishes", () => {+ const supervisor = new DaemonSupervisor(join(tmpdir(), "deferred-backpressure-supervisor.sock"), {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ descriptorDir: join(tmpdir(), "deferred-backpressure-state"),+ });+ const socket = new PassThrough();+ const client = socketClient(socket, {+ deferredSessionPayloads: new Map([+ [activeSessionId, { payloads: [Buffer.alloc(128 * 1024), Buffer.from("later")], bytes: 128 * 1024 + 5 }],+ ]),+ });+ const internals = supervisor as unknown as {+ reserveSnapshotStream(client: DaemonSocketClient, activeSessionId: string): () => void;+ flushDeferredSessionPayloads(client: DaemonSocketClient, activeSessionId: string): void;+ };+ try {+ const finishOtherSnapshot = internals.reserveSnapshotStream(client, "other-session");+ const write = vi.spyOn(socket, "write");+ internals.flushDeferredSessionPayloads(client, activeSessionId);+ finishOtherSnapshot();+ expect(write).toHaveBeenCalledOnce();+ expect(client.backpressured).toBe(true);+ expect(client.catchupActiveSessionIds?.has(activeSessionId)).toBe(true);+ expect(client.deferredSessionPayloads?.size ?? 0).toBe(0);+ } finally {+ socket.destroy();+ }+ });+});diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex eed9af4939..d52cc66414 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -4023,45 +4023,70 @@ describe("daemon mode helpers", () => {expect(client.attachedActiveSessionIds).not.toContain(state.activeSessionId);});- it("drops a backpressure catch-up when the client detaches during snapshot creation", async () => {- const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {- defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },- createRuntime: vi.fn(),- });- const state = makeState("active");- const write = vi.fn(() => true);- const client = makeClient("client-1", state.activeSessionId);- client.socket = { destroyed: false, write } as unknown as Socket;- client.catchupActiveSessionIds = new Set([state.activeSessionId]);- state.clients.add(client);- let releaseSnapshot!: () => void;- const snapshotGate = new Promise<void>((resolve) => {- releaseSnapshot = resolve;- });- const result = {- activeSessionId: state.activeSessionId,- snapshot: { summary: {}, state: {}, messages: [], lastEventSequence: 0 },- lastEventSequence: 0,- } as unknown as DaemonAttachResult;- const internals = daemon as unknown as {- sessions: Map<string, ActiveSessionState>;- createAttachResult: ReturnType<typeof vi.fn>;- drainBackpressuredClientCatchups(client: DaemonSocketClient): Promise<void>;- };- internals.sessions.set(state.activeSessionId, state);- internals.createAttachResult = vi.fn(async () => {- await snapshotGate;- return result;- });+ it.each(["inline-detached", "chunked-detached", "chunked-failed"])(+ "releases a catch-up reservation: %s",+ async (outcome) => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const state = makeState("active");+ const write = vi.fn(() => true);+ const client = makeClient("client-1", state.activeSessionId);+ client.socket = { destroyed: false, write } as unknown as Socket;+ if (outcome.startsWith("chunked")) {+ client.transport = "private-framed";+ client.capabilities = new Set(["chunked_snapshot"]);+ }+ client.catchupActiveSessionIds = new Set([state.activeSessionId]);+ state.clients.add(client);+ let releaseSnapshot!: () => void;+ const snapshotGate = new Promise<void>((resolve) => {+ releaseSnapshot = resolve;+ });+ const result = {+ activeSessionId: state.activeSessionId,+ snapshot: { summary: {}, state: {}, messages: [], lastEventSequence: 0 },+ lastEventSequence: 0,+ } as unknown as DaemonAttachResult;+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAttachResult: ReturnType<typeof vi.fn>;+ drainBackpressuredClientCatchups(client: DaemonSocketClient): Promise<void>;+ broadcastToSession(state: ActiveSessionState, message: DaemonOutbound): void;+ };+ internals.sessions.set(state.activeSessionId, state);+ internals.createAttachResult = vi.fn(async () => {+ await snapshotGate;+ if (outcome === "chunked-failed") throw new Error("snapshot preparation failed");+ return result;+ });- const catchup = internals.drainBackpressuredClientCatchups(client);- await vi.waitFor(() => expect(internals.createAttachResult).toHaveBeenCalledOnce());- state.clients.delete(client);- client.attachedActiveSessionIds.delete(state.activeSessionId);- releaseSnapshot();- await catchup;- expect(write).not.toHaveBeenCalled();- });+ const catchup = internals.drainBackpressuredClientCatchups(client);+ await vi.waitFor(() => expect(internals.createAttachResult).toHaveBeenCalledOnce());+ expect(client.snapshotStreaming).toBe(true);+ if (outcome.endsWith("detached")) {+ state.clients.delete(client);+ client.attachedActiveSessionIds.delete(state.activeSessionId);+ }+ releaseSnapshot();+ await catchup;+ clearTimeout(client.catchupRetryTimer);+ if (outcome === "chunked-failed") {+ internals.broadcastToSession(state, {+ type: "session_event",+ activeSessionId: state.activeSessionId,+ event: { type: "session_info_changed", name: "during retry" },+ });+ expect(client.deferredSessionFramesDropped?.has(state.activeSessionId)).toBe(true);+ }+ expect(write).not.toHaveBeenCalled();+ expect(client.snapshotStreaming).not.toBe(true);+ expect(client.snapshotActiveSessionCounts?.size ?? 0).toBe(0);+ expect(client.snapshotTransferAbortControllers?.size ?? 0).toBe(0);+ expect(client.catchupActiveSessionIds?.has(state.activeSessionId)).toBe(outcome === "chunked-failed");+ },+ );it("marks a chunked attach as snapshotting before deferred streaming", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-snapshot-order-"));diff --git a/packages/coding-agent/test/daemon-routed-client.test.ts b/packages/coding-agent/test/daemon-routed-client.test.tsindex 592e5de659..926854b72f 100644--- a/packages/coding-agent/test/daemon-routed-client.test.ts+++ b/packages/coding-agent/test/daemon-routed-client.test.ts@@ -114,14 +114,40 @@ describe("DaemonWorkerClient direct decoding", () => {const client = new DaemonWorkerClient("/tmp/prime-agent-direct.sock");const internals = client as unknown as {socket: Socket;+ channel: { send: ReturnType<typeof vi.fn>; close: ReturnType<typeof vi.fn> };directPeer: boolean;handleFrame(frame: { header: Record<string, unknown>; payload: Buffer }): void;};internals.socket = { destroyed: false, destroy: destroyed } as unknown as Socket;+ internals.channel = { send: vi.fn().mockResolvedValue(undefined), close: vi.fn() };internals.directPeer = true;return { client, internals, destroyed };}+ it.each([false, true])("handles the response before following frames (callback throws=%s)", async (throws) => {+ const { client, internals } = makeDirectClient();+ const order: string[] = [];+ client.onMessage((message) => order.push(message.type));+ const request = client.request({ type: "attach", activeSessionId: "active-1" }, 30000, {+ onResponse: () => {+ order.push("response");+ if (throws) throw new Error("response callback failed");+ },+ });+ internals.handleFrame({+ header: { kind: "outbound", outboundType: "response", requestId: "worker_1" },+ payload: Buffer.from(JSON.stringify({ type: "response", command: "attach", success: true })),+ });+ internals.handleFrame({+ header: { kind: "outbound", outboundType: "session_detached", payloadEncoding: "jsonl" },+ payload: Buffer.from(JSON.stringify({ type: "session_detached", activeSessionId: "active-1" })),+ });+ expect(order).toEqual(["response", "session_detached"]);+ if (throws) await expect(request).rejects.toThrow("response callback failed");+ else await expect(request).resolves.toMatchObject({ success: true });+ client.close();+ });+it("emits decoded outbound frames to message listeners", () => {const { client, internals } = makeDirectClient();const messages: DaemonOutbound[] = [];diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.tsindex 34756d4e93..a07e3f3dc1 100644--- a/packages/coding-agent/test/interactive-mode-status.test.ts+++ b/packages/coding-agent/test/interactive-mode-status.test.ts@@ -719,6 +719,7 @@ describe("InteractiveMode working timer", () => {updateWorkingLoaderMessage: vi.fn(),renderSessionContext: vi.fn(async () => {}),restoreStreamingMessageFromSnapshot: vi.fn(async () => {}),+ showLoadedResources: vi.fn(),showStatus: vi.fn(),stopWorkingLoader: vi.fn(),createWorkingLoader: vi.fn(() => ({})),@@ -738,6 +739,78 @@ describe("InteractiveMode working timer", () => {};}+ test.each(["success", "snapshot failure", "render failure"])(+ "releases deferred events after the last queued render: %s",+ async (outcome) => {+ const snapshot = { state: createConnectionState(), messages: [userMessage("Only one copy.", 100)] };+ const firstSnapshot = createDeferred<AgentConnectionSnapshot>();+ const lastSnapshot = createDeferred<AgentConnectionSnapshot>();+ const flushBufferedSessionEvents = vi.fn(() => new Promise<void>(() => {}));+ const harness = Object.assign(+ {},+ createInitialTimerHarness(snapshot),+ createRenderSessionContextHarness().harness,+ {+ agentConnection: {+ getInitialSnapshot: vi+ .fn()+ .mockReturnValueOnce(firstSnapshot.promise)+ .mockReturnValueOnce(lastSnapshot.promise),+ flushBufferedSessionEvents,+ },+ renderSessionContext: vi.fn(renderSessionContext),+ },+ );+ Object.setPrototypeOf(harness, InteractiveMode.prototype);+ const first = harness.renderInitialMessages();+ const last = harness.renderInitialMessages();+ const completion =+ outcome === "success" ? expect(last).resolves.toBeUndefined() : expect(last).rejects.toThrow(outcome);+ firstSnapshot.resolve(snapshot);+ await first;+ expect(flushBufferedSessionEvents).not.toHaveBeenCalled();+ const firstChildren = [...harness.chatContainer.children];+ expect(firstChildren.length).toBeGreaterThan(0);+ if (outcome === "snapshot failure") lastSnapshot.reject(new Error(outcome));+ else {+ if (outcome === "render failure") harness.renderSessionContext.mockRejectedValueOnce(new Error(outcome));+ lastSnapshot.resolve(snapshot);+ }+ await completion;+ expect(flushBufferedSessionEvents).toHaveBeenCalledOnce();+ expect(harness.chatContainer.children).toHaveLength(firstChildren.length);+ if (outcome === "success") {+ expect(harness.chatContainer.children.some((child) => firstChildren.includes(child))).toBe(false);+ }+ },+ );++ test("preserves resource diagnostics through initial and repeated transcript renders", async () => {+ const snapshot = { state: createConnectionState(), messages: [userMessage("Hello.", 100)] };+ const harness = Object.assign(+ {},+ createInitialTimerHarness(snapshot),+ createRenderSessionContextHarness().harness,+ {+ options: { verbose: false },+ connectionCommands: [],+ connectionResourceSnapshot: {+ diagnostics: { skills: [{ type: "warning", message: "Resource warning" }] },+ },+ formatDiagnostics: () => "Resource warning",+ showLoadedResources: (InteractiveMode.prototype as unknown as { showLoadedResources(): void })+ .showLoadedResources,+ renderSessionContext,+ },+ );+ Object.setPrototypeOf(harness, InteractiveMode.prototype);+ for (let render = 0; render < 2; render++) {+ await harness.renderInitialMessages();+ const text = harness.chatContainer.render(80).join("\n");+ expect(text.match(/Resource warning/g)).toHaveLength(1);+ }+ });+test("restores the first active-run starter instead of a steering message", async () => {const harness = createInitialTimerHarness({state: createConnectionState({ isStreaming: true }),@@ -1509,6 +1582,7 @@ describe("InteractiveMode connection events", () => {renderSessionContext: renderSessionContextMock,restoreStreamingMessageFromSnapshot,restoreTurnStartFromMessages: vi.fn(),+ showLoadedResources: vi.fn(),showStatus: vi.fn(),} as unknown as InteractiveMode;@@ -1524,11 +1598,13 @@ describe("InteractiveMode connection events", () => {).toHaveBeenCalledTimes(2);expect(renderSessionContextMock).toHaveBeenCalledTimes(2);expect(renderSessionContextMock).toHaveBeenNthCalledWith(1, expect.anything(), {+ clearChat: true,updateFooter: true,populateHistory: true,limitTranscript: true,});expect(renderSessionContextMock).toHaveBeenNthCalledWith(2, expect.anything(), {+ clearChat: true,updateFooter: true,populateHistory: true,limitTranscript: true,@@ -1800,7 +1876,11 @@ describe("InteractiveMode connection events", () => {expect((fakeThis as unknown as { activeBashComponent: unknown }).activeBashComponent).toBe(activeBashComponent);expect((fakeThis as unknown as { renderSessionContext: ReturnType<typeof vi.fn> }).renderSessionContext,- ).toHaveBeenCalledWith(expect.anything(), { clearChat: true, updateFooter: true });+ ).toHaveBeenCalledWith(expect.anything(), {+ clearChat: true,+ updateFooter: true,+ limitTranscript: true,+ });expect(startAssistantStreamingMessage).toHaveBeenCalledWith(streamingMessage);expect((fakeThis as unknown as { turnStartedAt: number | undefined }).turnStartedAt).toBe(100);expect((fakeThis as unknown as { workingStartedAt: number | undefined }).workingStartedAt).toBe(100);@@ -2163,7 +2243,7 @@ describe("InteractiveMode transcript rebuild", () => {await fakeThis.rebuildChatFromMessages();- expect(fakeThis.renderSessionContext).toHaveBeenCalledWith(context, { clearChat: true });+ expect(fakeThis.renderSessionContext).toHaveBeenCalledWith(context, { clearChat: true, limitTranscript: true });expect(fakeThis.chatContainer.children).toEqual([rebuiltChild]);expect(fakeThis.chatContainer.children).not.toContain(staleChild);});diff --git a/packages/coding-agent/test/snapshot-transcript-cache.test.ts b/packages/coding-agent/test/snapshot-transcript-cache.test.tsindex 287ee5301c..c00eb38277 100644--- a/packages/coding-agent/test/snapshot-transcript-cache.test.ts+++ b/packages/coding-agent/test/snapshot-transcript-cache.test.ts@@ -80,6 +80,27 @@ describe("snapshot transcript cache", () => {cache.dispose();});+ it("cancels a pending reader without failing the shared transcript", async () => {+ const cache = new SnapshotTranscriptCache({+ activeSessionId: "active-abort",+ snapshotId: "snapshot-abort",+ cacheRoot: tempDir(),+ });+ const controller = new AbortController();+ const cancelled = cache.waitForChunk(0, controller.signal);+ const live = cache.waitForChunk(0);+ const reason = new Error("session closed");+ controller.abort(reason);+ await expect(cancelled).rejects.toBe(reason);+ const chunk = Buffer.from("chunk");+ cache.appendEncodedChunk(chunk);+ await expect(live).resolves.toEqual(chunk);+ await expect(cache.waitForChunk(0, controller.signal)).rejects.toBe(reason);+ cache.markComplete();+ expect(cache.complete).toBe(true);+ cache.dispose();+ });+it("defers disposal until active snapshot readers finish", () => {const cache = new SnapshotTranscriptCache({activeSessionId: "active-d",diff --git a/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts b/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.tsindex 4a5f91a3eb..1d0c219ca1 100644--- a/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts+++ b/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts@@ -440,6 +440,8 @@ describe("ENG-4602 snapshot transfer containment", () => {await new Promise<void>((resolve) => setImmediate(resolve));await new Promise<void>((resolve) => setImmediate(resolve));expect(request).toHaveBeenCalledWith(expect.objectContaining({ type: "attach" }));+ clearTimeout(client.catchupRetryTimer);+ client.socket.destroy();});it("holds catch-up behind duplicate validation and rejects it on mismatch", async () => {@@ -499,8 +501,15 @@ describe("ENG-4602 snapshot transfer containment", () => {);await failedCatchup;- // The published-cache drop requeued the rejected waiter: it retries with a fresh snapshot request.- expect(request).toHaveBeenCalledWith(expect.objectContaining({ type: "attach", activeSessionId }));+ // The rejected waiter requests a fresh snapshot after the catch-up retry delay.+ try {+ await vi.waitFor(() =>+ expect(request).toHaveBeenCalledWith(expect.objectContaining({ type: "attach", activeSessionId })),+ );+ } finally {+ clearTimeout(client.catchupRetryTimer);+ client.socket.destroy();+ }expect(streamSnapshot).not.toHaveBeenCalled();expect(worker.snapshotCache.has(activeSessionId)).toBe(false);expect(worker.transcriptCaches.has(activeSessionId)).toBe(false);diff --git a/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts b/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.tsindex ec856ec32d..04a86323ed 100644--- a/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts+++ b/packages/coding-agent/test/suite/regressions/4603-worker-recovery.test.ts@@ -1086,7 +1086,7 @@ printf '%s\\n' "$listeners" | awk -v pids="$ENG_4603_LSOF_PIDS" 'expect(listenersBeforeShutdown).toContain(`p${successor.child.pid}`);const shutdown = await runCli(paths, ["shutdown", "--force", "--json"], 60_000, lsofEnvironment);- expect(shutdown.code).toBe(0);+ expect(shutdown.code, `${shutdown.stdout}\n${shutdown.stderr}`).toBe(0);const shutdownResult = JSON.parse(shutdown.stdout) as { stopped: unknown[]; failed: unknown[] };expect(exactProcessIsAlive(unrelated.child.pid!, unrelated.identity?.processStartId)).toBe(true);const unrelatedClient = await connectEventually(unrelatedPaths.socketPath);diff --git a/packages/tui/.changes/debug-slow-chat-loading.md b/packages/tui/.changes/debug-slow-chat-loading.mdnew file mode 100644index 0000000000..9afedcd87e--- /dev/null+++ b/packages/tui/.changes/debug-slow-chat-loading.md@@ -0,0 +1,2 @@+- Sped up transcript rendering on image-capable terminals: a cell-size response now re-renders only image components instead of invalidating every component cache.+- Sped up width calculations for plain text when rendering long transcripts.diff --git a/packages/tui/src/components/image.ts b/packages/tui/src/components/image.tsindex 9b05309818..6c09cc5f95 100644--- a/packages/tui/src/components/image.ts+++ b/packages/tui/src/components/image.ts@@ -1,6 +1,7 @@import {allocateImageId,getCapabilities,+ getCellDimensionsVersion,getImageDimensions,type ImageDimensions,imageFallback,@@ -47,6 +48,7 @@ export class Image implements Component {private cachedLines?: string[];private cachedWidth?: number;private cachedFullscreenFallback?: boolean;+ private cachedCellDimensionsVersion?: number;constructor(base64Data: string,@@ -72,10 +74,17 @@ export class Image implements Component {this.cachedLines = undefined;this.cachedWidth = undefined;this.cachedFullscreenFallback = undefined;+ this.cachedCellDimensionsVersion = undefined;}render(width: number): string[] {- if (this.cachedLines && this.cachedWidth === width && this.cachedFullscreenFallback === fullscreenFallback) {+ const cellDimensionsVersion = getCellDimensionsVersion();+ if (+ this.cachedLines &&+ this.cachedWidth === width &&+ this.cachedFullscreenFallback === fullscreenFallback &&+ this.cachedCellDimensionsVersion === cellDimensionsVersion+ ) {return this.cachedLines;}@@ -129,6 +138,7 @@ export class Image implements Component {this.cachedLines = lines;this.cachedWidth = width;this.cachedFullscreenFallback = fullscreenFallback;+ this.cachedCellDimensionsVersion = cellDimensionsVersion;return lines;}diff --git a/packages/tui/src/index.ts b/packages/tui/src/index.tsindex 0249871678..37430472f1 100644--- a/packages/tui/src/index.ts+++ b/packages/tui/src/index.ts@@ -102,6 +102,7 @@ export {encodeKitty,getCapabilities,getCellDimensions,+ getCellDimensionsVersion,getGifDimensions,getImageDimensions,getJpegDimensions,diff --git a/packages/tui/src/terminal-image.ts b/packages/tui/src/terminal-image.tsindex 6a84716c66..d0145c5569 100644--- a/packages/tui/src/terminal-image.ts+++ b/packages/tui/src/terminal-image.ts@@ -31,12 +31,24 @@ let cachedCapabilities: TerminalCapabilities | null = null;// Default cell dimensions - updated by TUI when terminal responds to querylet cellDimensions: CellDimensions = { widthPx: 9, heightPx: 18 };+// Bumped whenever the cell dimensions actually change. Image components keep+// this in their cache key so a cell-size response only re-renders images+// instead of invalidating every component cache.+let cellDimensionsVersion = 0;+export function getCellDimensions(): CellDimensions {return cellDimensions;}export function setCellDimensions(dims: CellDimensions): void {- cellDimensions = dims;+ if (dims.widthPx !== cellDimensions.widthPx || dims.heightPx !== cellDimensions.heightPx) {+ cellDimensions = dims;+ cellDimensionsVersion++;+ }+}++export function getCellDimensionsVersion(): number {+ return cellDimensionsVersion;}export function detectCapabilities(): TerminalCapabilities {diff --git a/packages/tui/src/tui.ts b/packages/tui/src/tui.tsindex a3db69e009..6c45635690 100644--- a/packages/tui/src/tui.ts+++ b/packages/tui/src/tui.ts@@ -1037,8 +1037,8 @@ export class TUI extends Container {}setCellDimensions({ widthPx, heightPx });- // Invalidate all components so images re-render with correct dimensions.- this.invalidate();+ // Images keep the cell-dimensions version in their cache key, so a change+ // here re-renders only image components on the next frame.this.requestRender();return true;}diff --git a/packages/tui/src/utils.ts b/packages/tui/src/utils.tsindex f26f5ea0a1..6c4d2d0a6d 100644--- a/packages/tui/src/utils.ts+++ b/packages/tui/src/utils.ts@@ -29,6 +29,7 @@ function couldBeEmoji(segment: string): boolean {}// Regexes for character classification (same as string-width library)+const nonPrintableAsciiRegex = /[^\x20-\x7e]/;const zeroWidthRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;const leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;const rgiEmojiRegex = /^\p{RGI_Emoji}$/v;@@ -38,13 +39,7 @@ const WIDTH_CACHE_SIZE = 512;const widthCache = new Map<string, number>();function isPrintableAscii(str: string): boolean {- for (let i = 0; i < str.length; i++) {- const code = str.charCodeAt(i);- if (code < 0x20 || code > 0x7e) {- return false;- }- }- return true;+ return !nonPrintableAsciiRegex.test(str);}function truncateFragmentToWidth(text: string, maxWidth: number): { text: string; width: number } {diff --git a/packages/tui/test/truncate-to-width.test.ts b/packages/tui/test/truncate-to-width.test.tsindex f9a110c2a5..ae11e78cb1 100644--- a/packages/tui/test/truncate-to-width.test.ts+++ b/packages/tui/test/truncate-to-width.test.ts@@ -62,6 +62,20 @@ describe("truncateToWidth", () => {});describe("visibleWidth", () => {+ it("keeps controls and non-ASCII characters out of the printable ASCII fast path", () => {+ for (const [text, width] of [+ ["", 0],+ [" ~", 2],+ ["abc\n", 3],+ ["a\x1fb", 2],+ ["a\x7fb", 2],+ ["abc\t", 6],+ ["a界b", 4],+ ] as const) {+ assert.strictEqual(visibleWidth(text), width);+ }+ });+it("counts tabs inline and skips ANSI inline", () => {assert.strictEqual(visibleWidth("\t\x1b[31m界\x1b[0m"), 5);});diff --git a/packages/tui/test/tui-cell-size-input.test.ts b/packages/tui/test/tui-cell-size-input.test.tsindex 0ca515d4b9..f1c68275ae 100644--- a/packages/tui/test/tui-cell-size-input.test.ts+++ b/packages/tui/test/tui-cell-size-input.test.ts@@ -1,6 +1,13 @@import assert from "node:assert";import { describe, it } from "node:test";-import { getCellDimensions, resetCapabilitiesCache, setCellDimensions } from "../src/terminal-image.js";+import { Image } from "../src/components/image.js";+import {+ getCellDimensions,+ getCellDimensionsVersion,+ resetCapabilitiesCache,+ setCapabilities,+ setCellDimensions,+} from "../src/terminal-image.js";import { type Component, TUI } from "../src/tui.js";import { VirtualTerminal } from "./virtual-terminal.js";@@ -41,7 +48,80 @@ function withImageTerminal<T>(fn: () => T): T {}}+class InvalidateRecorder implements Component {+ readonly invalidateCalls: number[] = [];+ private renderCount = 0;++ render(): string[] {+ this.renderCount++;+ return [""];+ }++ handleInput(_data: string): void {}++ invalidate(): void {+ this.invalidateCalls.push(this.renderCount);+ }+}++describe("cell dimension versioning", () => {+ it("bumps the version only when the dimensions change", () => {+ setCellDimensions({ widthPx: 9, heightPx: 18 });+ const initialVersion = getCellDimensionsVersion();+ setCellDimensions({ widthPx: 9, heightPx: 18 });+ assert.strictEqual(getCellDimensionsVersion(), initialVersion);+ setCellDimensions({ widthPx: 8, heightPx: 18 });+ assert.strictEqual(getCellDimensionsVersion(), initialVersion + 1);+ assert.deepStrictEqual(getCellDimensions(), { widthPx: 8, heightPx: 18 });+ });++ it("re-renders images when cell dimensions change", () => {+ setCapabilities({ images: "kitty", trueColor: true, hyperlinks: true });+ setCellDimensions({ widthPx: 9, heightPx: 18 });+ const image = new Image(+ "aGVsbG8=",+ "image/png",+ { fallbackColor: (value) => value },+ {},+ {+ widthPx: 100,+ heightPx: 100,+ },+ );+ const initialLines = image.render(80);+ const cachedLines = image.render(80);+ assert.strictEqual(cachedLines, initialLines);++ setCellDimensions({ widthPx: 8, heightPx: 18 });+ const reRenderedLines = image.render(80);+ // 60 cells wide: 9px cells scale 100px to 540px -> 30 rows at 18px rows;+ // 8px cells scale to 480px -> 27 rows. The cache key must pick up the change.+ assert.strictEqual(initialLines.length, 30);+ assert.strictEqual(reRenderedLines.length, 27);+ resetCapabilitiesCache();+ });+});+describe("TUI cell size responses", () => {+ it("does not invalidate sibling components when a cell size response arrives", () => {+ withImageTerminal(() => {+ setCellDimensions({ widthPx: 9, heightPx: 18 });++ const terminal = new VirtualTerminal(80, 24);+ const tui = new TUI(terminal);+ const recorder = new InvalidateRecorder();++ tui.addChild(recorder);+ tui.start();++ terminal.sendInput("\x1b[6;36;18t");+ assert.deepStrictEqual(getCellDimensions(), { widthPx: 18, heightPx: 36 });+ assert.deepStrictEqual(recorder.invalidateCalls, []);++ tui.stop();+ });+ });+it("forwards bare escape even when a cell size query was sent at startup", () => {withImageTerminal(() => {const terminal = new VirtualTerminal(80, 24);