Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix(coding-agent): attach active resumed sessions (#443)

ktccf741368655
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 420c77c18a..67bb85e391 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -7,6 +7,7 @@
- Changed shell commands to use discoverable agent, schedule, package, model, session, update, doctor, and full-shutdown verbs without exposing the background daemon hierarchy ([ENG-4538](https://linear.app/primeintellect/issue/ENG-4538/standardize-bash-command-conventions-and-improve-command-discovery)).
- Fixed unsupported Node versions crashing before startup by requiring Node 22.8.0 or newer and showing upgrade guidance before loading the CLI ([ENG-4260](https://linear.app/primeintellect/issue/ENG-4260/incorrect-node-version-breaks-first-launch)).
- Added `@` file-path autocomplete to new-agent and reply prompts in the Agents View.
+- Fixed resuming a daemon-resident session to attach the requesting client to its existing worker without disturbing other clients ([ENG-4656](https://linear.app/primeintellect/issue/ENG-4656/resuming-prime-agent-sessions-should-attach)).
- Fixed daemon-owned updates terminating their updater before the daemon restart and session restore completed ([ENG-4606](https://linear.app/primeintellect/issue/ENG-4606/benign-error-on-prime-agent-update)).
- Fixed first-launch Prime login and kept onboarding visible between team and model selection ([ENG-4658](https://linear.app/primeintellect/issue/ENG-4658/fix-onboarding-login-enter-key-and-model-selector-flicker)).
- Fixed active heartbeat sessions appearing under Needs Input or Completed instead of a dedicated Heartbeats section ([ENG-4654](https://linear.app/primeintellect/issue/ENG-4654/categorize-heartbeat-sessions-as-working)).
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index 6c09153885..e61e9fb271 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -60,7 +60,7 @@ import {
MissingSessionCwdError,
type SessionCwdIssue,
} from "./core/session-cwd.js";
-import { SessionAlreadyActiveError } from "./core/session-lease.js";
+import { canonicalSessionPath, SessionAlreadyActiveError } from "./core/session-lease.js";
import { SessionManager } from "./core/session-manager.js";
import { SettingsManager } from "./core/settings-manager.js";
import { printTimings, resetTimings, time } from "./core/timings.js";
@@ -955,12 +955,12 @@ export function findActiveDaemonSessionSummaryForSessionFile(
summaries: readonly SessionSummary[],
sessionPath: string,
): SessionSummary | undefined {
- const resolvedSessionPath = resolve(sessionPath);
+ const resolvedSessionPath = canonicalSessionPath(sessionPath);
return summaries.find(
(summary) =>
summary.activeSessionId !== undefined &&
summary.sessionFile !== undefined &&
- resolve(summary.sessionFile) === resolvedSessionPath,
+ canonicalSessionPath(summary.sessionFile) === resolvedSessionPath,
);
}
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.ts
index e2e9539523..d52adf4ca7 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
@@ -13,6 +13,7 @@ import type {
} from "../../core/cron-jobs.js";
import type { RefinementResult } from "../../core/refinement/index.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
+import { SessionAlreadyActiveError } from "../../core/session-lease.js";
import type { SessionStats } from "../../core/session-stats.js";
import { type DaemonClient, getDaemonSocketCloseReason } from "../daemon/daemon-client.js";
import { deserializeDaemonError } from "../daemon/daemon-errors.js";
@@ -86,6 +87,7 @@ export const DAEMON_SNAPSHOT_TIMEOUT_MS = 30_000;
const MAX_IGNORED_SNAPSHOT_IDS = 128;
const UPDATE_RECONNECT_TIMEOUT_MS = 120000;
const UPDATE_RECONNECT_RETRY_MS = 100;
+const MAX_COMPLETED_SNAPSHOTS = 128;
const updateTransportReconnects = new WeakMap<DaemonClient, Promise<void>>();
function delay(ms: number): Promise<void> {
@@ -172,6 +174,9 @@ export class DaemonAgentConnection implements AgentConnection {
private updateReconnectPromise?: Promise<void>;
private readonly activeSideQuestionIds = new Set<string>();
private readonly snapshotAssemblies = new Map<string, DaemonSnapshotAssembly>();
+ private readonly completedSnapshots = new Map<string, DaemonSessionSnapshot>();
+ private readonly pendingReattachActiveSessionIds = new Set<string>();
+ private readonly snapshotRecoveryPromises = new Map<string, Promise<void>>();
private readonly ignoredSnapshotIds = new Set<string>();
private reconnectPromise?: Promise<void>;
private disposed = false;
@@ -787,12 +792,91 @@ export class DaemonAgentConnection implements AgentConnection {
sessionPath: string,
options?: AgentConnectionSwitchSessionOptions,
): Promise<{ cancelled: boolean }> {
- return this.requestData<{ cancelled: boolean }>({
- type: "switch_session",
- activeSessionId: this.activeSessionId,
- sessionPath,
- cwdOverride: options?.cwdOverride,
- });
+ const sourceActiveSessionId = this.activeSessionId;
+ try {
+ return await this.requestData<{ cancelled: boolean }>({
+ type: "switch_session",
+ activeSessionId: sourceActiveSessionId,
+ sessionPath,
+ cwdOverride: options?.cwdOverride,
+ });
+ } catch (error) {
+ if (!(error instanceof SessionAlreadyActiveError) || !error.activeSessionId) {
+ throw error;
+ }
+ if (error.activeSessionId === sourceActiveSessionId) {
+ return { cancelled: false };
+ }
+ return this.reattachSession(sourceActiveSessionId, error.activeSessionId);
+ }
+ }
+
+ private async reattachSession(
+ sourceActiveSessionId: string,
+ targetActiveSessionId: string,
+ ): Promise<{ cancelled: false }> {
+ const previousState = {
+ lastEventCursor: this.lastEventCursor,
+ lastEventSequence: this.lastEventSequence,
+ latestSnapshot: this.latestSnapshot,
+ latestSnapshotIsFresh: this.latestSnapshotIsFresh,
+ retiredEventGenerations: new Set(this.retiredEventGenerations),
+ };
+ this.activeSessionId = targetActiveSessionId;
+ this.lastEventCursor = undefined;
+ this.lastEventSequence = undefined;
+ this.latestSnapshot = undefined;
+ this.latestSnapshotIsFresh = false;
+ this.retiredEventGenerations.clear();
+ this.pendingReattachActiveSessionIds.add(targetActiveSessionId);
+ let reattached = false;
+ try {
+ const result = await this.requestData<DaemonAttachResult>({
+ type: "reattach",
+ activeSessionId: sourceActiveSessionId,
+ targetActiveSessionId,
+ supportsExtensionUi: true,
+ clientId: this.clientId,
+ capabilities: ["attach_snapshot", "event_sequence", "extension_ui", "slim_attach", "chunked_snapshot"],
+ env: this.options.sendClientEnv ? collectDaemonClientEnv() : undefined,
+ });
+ reattached = true;
+ this.activeSessionId = result.activeSessionId;
+ this.activeSideQuestionIds.clear();
+ if (result.snapshotStream) {
+ try {
+ await this.waitForSnapshot(result.snapshotStream.id);
+ } catch (snapshotError) {
+ await this.snapshotRecoveryPromises.get(result.snapshotStream.id);
+ if (!this.latestSnapshotIsFresh) {
+ throw snapshotError;
+ }
+ }
+ } else {
+ this.applyReplacementSnapshot(result.snapshot, result.replay);
+ await this.emit({
+ type: "session_replaced",
+ state: result.snapshot.state,
+ messages: result.snapshot.messages,
+ });
+ }
+ return { cancelled: false };
+ } catch (error) {
+ if (!reattached) {
+ this.activeSessionId = sourceActiveSessionId;
+ this.lastEventCursor = previousState.lastEventCursor;
+ this.lastEventSequence = previousState.lastEventSequence;
+ this.latestSnapshot = previousState.latestSnapshot;
+ this.latestSnapshotIsFresh = previousState.latestSnapshotIsFresh;
+ this.retiredEventGenerations.clear();
+ for (const generation of previousState.retiredEventGenerations) {
+ this.retiredEventGenerations.add(generation);
+ }
+ }
+ throw error;
+ } finally {
+ this.pendingReattachActiveSessionIds.delete(targetActiveSessionId);
+ }
}
async fork(
@@ -986,10 +1070,21 @@ export class DaemonAgentConnection implements AgentConnection {
const assembly = this.getSnapshotAssembly(message.snapshotId);
const purpose = assembly.begin?.purpose ?? "attach";
const snapshotError = new Error(message.error);
+ const recoveryPromise =
+ purpose === "replacement" || purpose === "resync"
+ ? this.recoverFailedSnapshot(purpose, snapshotError)
+ : undefined;
+ if (recoveryPromise) {
+ this.snapshotRecoveryPromises.set(message.snapshotId, recoveryPromise);
+ }
this.rejectSnapshotAssembly(message.snapshotId, assembly, snapshotError);
this.ignoreSnapshotId(message.snapshotId);
- if (purpose === "replacement" || purpose === "resync") {
- await this.recoverFailedSnapshot(purpose, snapshotError);
+ if (recoveryPromise) {
+ try {
+ await recoveryPromise;
+ } finally {
+ this.snapshotRecoveryPromises.delete(message.snapshotId);
+ }
}
return;
}
@@ -1245,6 +1340,8 @@ export class DaemonAgentConnection implements AgentConnection {
assembly.reject(error);
}
this.snapshotAssemblies.clear();
+ this.completedSnapshots.clear();
+ this.snapshotRecoveryPromises.clear();
this.ignoredSnapshotIds.clear();
}
@@ -1297,15 +1394,32 @@ export class DaemonAgentConnection implements AgentConnection {
}
private async waitForSnapshot(snapshotId: string): Promise<DaemonSessionSnapshot> {
+ const completed = this.completedSnapshots.get(snapshotId);
+ if (completed) {
+ this.completedSnapshots.delete(snapshotId);
+ return completed;
+ }
const assembly = this.getSnapshotAssembly(snapshotId);
try {
return await assembly.promise;
} finally {
clearTimeout(assembly.timeout);
this.snapshotAssemblies.delete(snapshotId);
+ this.completedSnapshots.delete(snapshotId);
}
}
+ private applyReplacementSnapshot(snapshot: DaemonSessionSnapshot, replay?: DaemonReplayInfo): void {
+ if (snapshot.lastEventCursor) {
+ this.observeEventCursor(snapshot.lastEventCursor);
+ }
+ this.lastEventSequence = maxEventSequence(this.lastEventSequence, snapshot.lastEventSequence);
+ this.attachedSessionId = snapshot.state.sessionId;
+ this.attachedSessionFile = snapshot.state.sessionFile;
+ this.latestSnapshot = mapDaemonSessionSnapshot(snapshot, replay);
+ this.latestSnapshotIsFresh = true;
+ }
+
private async completeSnapshotAssembly(
message: Extract<DaemonOutbound, { type: "session_snapshot_end" }>,
): Promise<void> {
@@ -1370,6 +1484,16 @@ export class DaemonAgentConnection implements AgentConnection {
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 === "replacement") {
await this.emit({ type: "session_replaced", state: snapshot.state, messages });
@@ -1542,6 +1666,7 @@ function getDaemonMessageCursor(message: DaemonOutbound): DaemonEventCursor | un
function invalidatesCachedSnapshot(commandType: DaemonCommandBody["type"]): boolean {
switch (commandType) {
case "attach":
+ case "reattach":
case "detach":
case "list":
case "list_saved_sessions":
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 0090c211dc..9fbc48d385 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -293,6 +293,14 @@ export type DaemonCommand =
supportsExtensionUi?: boolean;
} & DaemonAttachClientMetadata &
DaemonClientEnv)
+ | ({
+ id?: string;
+ type: "reattach";
+ activeSessionId: string;
+ targetActiveSessionId: string;
+ supportsExtensionUi?: boolean;
+ } & DaemonAttachClientMetadata &
+ DaemonClientEnv)
| { id?: string; type: "detach"; activeSessionId?: string }
| { id?: string; type: "kill"; activeSessionId: string }
| { id?: string; type: "rename"; activeSessionId: string; name: string }
@@ -687,6 +695,7 @@ const READ_ONLY_DAEMON_COMMANDS: ReadonlySet<DaemonCommand["type"]> = new Set([
"list",
"list_saved_sessions",
"attach",
+ "reattach",
"agent_messages_status",
"wait_for_idle",
"get_state",
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 361d9195c6..223f7e4259 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -27,7 +27,7 @@ import {
ORPHAN_PROCESS_JOURNAL_ENV,
readActiveOrphanProcesses,
} from "../../core/orphan-process-journal.js";
-import { getProcessStartId } from "../../core/session-lease.js";
+import { canonicalSessionPath, getProcessStartId } from "../../core/session-lease.js";
import type { SessionInfo } from "../../core/session-manager.js";
import { signalProcessGroupOrProcess } from "../../utils/child-process.js";
import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";
@@ -108,6 +108,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"list_saved_sessions",
"create",
"attach",
+ "reattach",
"detach",
"kill",
"rename",
@@ -963,6 +964,50 @@ export class DaemonSupervisor {
}
return success(command.id, "attach", attached.result);
}
+ case "reattach": {
+ const target = await this.findWorker(command.targetActiveSessionId);
+ const targetActiveSessionId = target.summary.activeSessionId ?? target.summary.id;
+ if (targetActiveSessionId === command.activeSessionId) {
+ return success(command.id, command.type, { cancelled: false });
+ }
+ const targetWasAttached = client.attachedActiveSessionIds.has(targetActiveSessionId);
+ const releaseSnapshotReservation = this.reserveSnapshotStream(client, targetActiveSessionId);
+ client.attachedActiveSessionIds.add(targetActiveSessionId);
+ try {
+ const attached = await this.attachClient(client, {
+ ...command,
+ type: "attach",
+ activeSessionId: targetActiveSessionId,
+ });
+ if (client.capabilities.has("chunked_snapshot")) {
+ const transcript = this.getOrCreateTranscriptCache(attached.worker, attached.result);
+ const streamedResult = this.createStreamedAttachResult(attached.result, transcript);
+ this.write(client, success(command.id, command.type, streamedResult));
+ this.detachClient(client, command.activeSessionId);
+ void this.streamSnapshot(
+ client,
+ attached.worker,
+ streamedResult,
+ transcript,
+ "replacement",
+ releaseSnapshotReservation,
+ ).catch((error) =>
+ this.log(`Failed to stream reattach snapshot for ${targetActiveSessionId}: ${String(error)}`),
+ );
+ return undefined;
+ }
+ this.write(client, success(command.id, command.type, attached.result));
+ this.detachClient(client, command.activeSessionId);
+ releaseSnapshotReservation();
+ return undefined;
+ } catch (error) {
+ if (!targetWasAttached) {
+ this.detachClient(client, targetActiveSessionId);
+ }
+ releaseSnapshotReservation();
+ throw error;
+ }
+ }
case "detach":
this.detachClient(client, command.activeSessionId);
return success(command.id, "detach");
@@ -1292,7 +1337,7 @@ export class DaemonSupervisor {
}
}
const key = createCommand.sessionPath
- ? resolve(createCommand.sessionPath)
+ ? canonicalSessionPath(createCommand.sessionPath)
: `new:${command.id ? createCommandIdempotencyKey(clientId, command.id) : createActiveSessionId()}`;
const pending = this.openingWorkers.get(key);
if (pending) {
@@ -2083,10 +2128,10 @@ export class DaemonSupervisor {
}
private findWorkerBySessionFile(sessionFile: string): WorkerMatch | undefined {
- const target = resolve(sessionFile);
+ const target = canonicalSessionPath(sessionFile);
for (const worker of this.workers.values()) {
for (const summary of worker.summaries.values()) {
- if (summary.sessionFile && resolve(summary.sessionFile) === target) {
+ if (summary.sessionFile && canonicalSessionPath(summary.sessionFile) === target) {
return { worker, summary };
}
}
@@ -2180,6 +2225,7 @@ export class DaemonSupervisor {
}
result = await loading;
}
+ const wasAttached = client.attachedActiveSessionIds.has(activeSessionId);
client.attachedActiveSessionIds.add(activeSessionId);
try {
const publicSummary = this.publicSummary(match.worker, result.snapshot.summary);
@@ -2214,7 +2260,9 @@ export class DaemonSupervisor {
await this.syncWorkerExtensionUi(activeSessionId);
return { result: publicResult, worker: match.worker };
} catch (error) {
- client.attachedActiveSessionIds.delete(activeSessionId);
+ if (!wasAttached) {
+ client.attachedActiveSessionIds.delete(activeSessionId);
+ }
throw error;
}
}
@@ -2272,22 +2320,14 @@ export class DaemonSupervisor {
result: DaemonAttachResult,
transcript: SnapshotTranscriptCache,
purpose: "attach" | "replacement" | "resync" = "attach",
+ releaseSnapshotReservation = this.reserveSnapshotStream(client, result.activeSessionId),
): Promise<void> {
const stream = result.snapshotStream;
if (!stream || client.socket.destroyed) {
+ releaseSnapshotReservation();
return;
}
const releaseTranscript = transcript.retain();
- client.snapshotStreaming = true;
- if (!client.snapshotActiveSessionIds) {
- client.snapshotActiveSessionIds = new Set();
- }
- client.snapshotActiveSessionIds.add(result.activeSessionId);
- client.snapshotActiveSessionCounts ??= new Map();
- client.snapshotActiveSessionCounts.set(
- result.activeSessionId,
- (client.snapshotActiveSessionCounts.get(result.activeSessionId) ?? 0) + 1,
- );
const { messages: _messages, ...snapshotHeader } = result.snapshot;
try {
if (
@@ -2342,25 +2382,44 @@ export class DaemonSupervisor {
}
throw streamError;
} finally {
- const streamCount = client.snapshotActiveSessionCounts?.get(result.activeSessionId) ?? 1;
+ releaseSnapshotReservation();
+ releaseTranscript();
+ }
+ }
+
+ private reserveSnapshotStream(client: DaemonSocketClient, activeSessionId: string): () => void {
+ client.snapshotStreaming = true;
+ client.snapshotActiveSessionIds ??= new Set();
+ client.snapshotActiveSessionIds.add(activeSessionId);
+ client.snapshotActiveSessionCounts ??= new Map();
+ client.snapshotActiveSessionCounts.set(
+ activeSessionId,
+ (client.snapshotActiveSessionCounts.get(activeSessionId) ?? 0) + 1,
+ );
+ let released = false;
+ return () => {
+ if (released) {
+ return;
+ }
+ released = true;
+ const streamCount = client.snapshotActiveSessionCounts?.get(activeSessionId) ?? 1;
if (streamCount > 1) {
- client.snapshotActiveSessionCounts?.set(result.activeSessionId, streamCount - 1);
+ client.snapshotActiveSessionCounts?.set(activeSessionId, streamCount - 1);
} else {
- client.snapshotActiveSessionCounts?.delete(result.activeSessionId);
- client.snapshotActiveSessionIds?.delete(result.activeSessionId);
+ client.snapshotActiveSessionCounts?.delete(activeSessionId);
+ client.snapshotActiveSessionIds?.delete(activeSessionId);
}
client.snapshotStreaming = (client.snapshotActiveSessionIds?.size ?? 0) > 0;
if (!client.snapshotStreaming) {
client.backpressured = false;
}
- this.flushPendingReplacementSnapshot(client, result.activeSessionId);
- releaseTranscript();
+ this.flushPendingReplacementSnapshot(client, activeSessionId);
if (!client.snapshotStreaming && client.catchupActiveSessionIds?.size) {
void this.catchUpClient(client).catch((error) =>
this.log(`Failed to catch up client ${client.id}: ${String(error)}`),
);
}
- }
+ };
}
private writeSnapshotRecord(client: DaemonSocketClient, message: DaemonOutbound): Promise<boolean> {
@@ -2402,6 +2461,8 @@ export class DaemonSupervisor {
if (!client.attachedActiveSessionIds.delete(resolvedId)) {
continue;
}
+ client.catchupActiveSessionIds?.delete(resolvedId);
+ client.catchupPurposes?.delete(resolvedId);
this.dropPendingReplacementSnapshot(client, resolvedId);
this.write(client, { type: "session_detached", activeSessionId: resolvedId });
void this.syncWorkerExtensionUi(resolvedId);
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index e15de7cbbe..b9cd8c65a9 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -7,6 +7,7 @@ import {
DAEMON_PROTOCOL_INFO,
type DaemonOutbound,
isDaemonCommandEnvelope,
+ isDaemonMutatingCommand,
} from "../src/modes/daemon/daemon-protocol.js";
describe("daemon protocol helpers", () => {
@@ -48,6 +49,12 @@ describe("daemon protocol helpers", () => {
expect(isDaemonCommandEnvelope(createDaemonCommandEnvelope(command, "cmd-1", "client-1", 1))).toBe(false);
});
+ it("keeps attachment routing out of the durable mutation journal", () => {
+ expect(isDaemonMutatingCommand({ type: "attach" })).toBe(false);
+ expect(isDaemonMutatingCommand({ type: "reattach" })).toBe(false);
+ expect(isDaemonMutatingCommand({ type: "switch_session" })).toBe(true);
+ });
+
it("reports replay availability from resume cursors", () => {
expect(createDaemonReplayInfo(undefined, 5, "generation-1")).toEqual({
status: "complete",
diff --git a/packages/coding-agent/test/main-interactive-routing.test.ts b/packages/coding-agent/test/main-interactive-routing.test.ts
index 129dce791d..590600b108 100644
--- a/packages/coding-agent/test/main-interactive-routing.test.ts
+++ b/packages/coding-agent/test/main-interactive-routing.test.ts
@@ -1,3 +1,6 @@
+import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { describe, expect, test } from "vitest";
import type { CreateAgentSessionOptions } from "../src/core/sdk.js";
import {
@@ -244,6 +247,25 @@ describe("daemon-backed interactive session manager routing", () => {
),
).toBe(activeSummary);
});
+
+ test("finds an active daemon session through a symlinked resume path", () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-agent-resume-"));
+ try {
+ const sessionFile = join(directory, "session.jsonl");
+ const symlink = join(directory, "session-link.jsonl");
+ writeFileSync(sessionFile, "");
+ symlinkSync(sessionFile, symlink);
+ const activeSummary = makeSessionSummary({
+ id: "active-1",
+ activeSessionId: "active-1",
+ sessionFile,
+ });
+
+ expect(findActiveDaemonSessionSummaryForSessionFile([activeSummary], symlink)).toBe(activeSummary);
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+ });
});
describe("agents view command parsing", () => {
diff --git a/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts b/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts
new file mode 100644
index 0000000000..c0c0167900
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts
@@ -0,0 +1,309 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { describe, expect, it, vi } from "vitest";
+import { DaemonAgentConnection } from "../../../src/modes/agent-connection/daemon-agent-connection.js";
+import type { AgentConnectionEvent, AgentConnectionState } from "../../../src/modes/agent-connection/types.js";
+import type { DaemonSocketClient } from "../../../src/modes/daemon/active-session-state.js";
+import type {
+ DaemonClient,
+ DaemonClientCloseListener,
+ DaemonClientMessageListener,
+} from "../../../src/modes/daemon/daemon-client.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";
+
+const sourceActiveSessionId = "source-active";
+const targetActiveSessionId = "target-active";
+
+class ResumeDaemonClient {
+ readonly requests: DaemonCommand[] = [];
+ private readonly messageListeners = new Set<DaemonClientMessageListener>();
+ private readonly closeListeners = new Set<DaemonClientCloseListener>();
+
+ constructor(private readonly switchTarget = targetActiveSessionId) {}
+
+ async request(command: DaemonCommand): Promise<DaemonResponse> {
+ this.requests.push(command);
+ if (command.type === "attach") {
+ return {
+ type: "response",
+ command: command.type,
+ success: true,
+ data: createAttachResult(command.activeSessionId),
+ };
+ }
+ if (command.type === "switch_session") {
+ return {
+ type: "response",
+ command: command.type,
+ success: false,
+ error: `Session is already active in ${this.switchTarget}: ${command.sessionPath}`,
+ errorInfo: {
+ code: "session_already_active",
+ sessionPath: command.sessionPath,
+ activeSessionId: this.switchTarget,
+ },
+ };
+ }
+ if (command.type === "reattach") {
+ const result = createAttachResult(command.targetActiveSessionId, [
+ { role: "user", content: "target prompt", timestamp: 2 },
+ ]);
+ const snapshotId = "target-snapshot";
+ const { messages, ...snapshot } = result.snapshot;
+ this.emitMessage({
+ type: "session_snapshot_begin",
+ activeSessionId: command.targetActiveSessionId,
+ snapshotId,
+ snapshot,
+ messageCount: messages.length,
+ targetChunkBytes: 512 * 1024,
+ purpose: "replacement",
+ });
+ this.emitMessage({
+ type: "session_snapshot_chunk",
+ activeSessionId: command.targetActiveSessionId,
+ snapshotId,
+ index: 0,
+ messages,
+ });
+ this.emitMessage({
+ type: "session_snapshot_end",
+ activeSessionId: command.targetActiveSessionId,
+ snapshotId,
+ chunkCount: 1,
+ lastEventSequence: result.lastEventSequence,
+ lastEventCursor: result.lastEventCursor,
+ });
+ return {
+ type: "response",
+ command: command.type,
+ success: true,
+ data: {
+ ...result,
+ snapshot: { ...result.snapshot, messages: [] },
+ snapshotStream: {
+ id: snapshotId,
+ messageCount: messages.length,
+ targetChunkBytes: 512 * 1024,
+ },
+ },
+ };
+ }
+ if (command.type === "detach") {
+ return { type: "response", command: command.type, success: true };
+ }
+ throw new Error(`Unexpected command: ${command.type}`);
+ }
+
+ onMessage(listener: DaemonClientMessageListener): () => void {
+ this.messageListeners.add(listener);
+ return () => this.messageListeners.delete(listener);
+ }
+
+ onClose(listener: DaemonClientCloseListener): () => void {
+ this.closeListeners.add(listener);
+ return () => this.closeListeners.delete(listener);
+ }
+
+ emitMessage(message: DaemonOutbound): void {
+ for (const listener of this.messageListeners) {
+ listener(message);
+ }
+ }
+
+ close(): void {}
+}
+
+function createConnectionState(activeSessionId: string): AgentConnectionState {
+ return {
+ activeSessionId,
+ cwd: "/tmp/project",
+ model: undefined,
+ thinkingLevel: "medium",
+ serviceTier: "default",
+ availableThinkingLevels: ["minimal", "low", "medium", "high", "xhigh"],
+ isStreaming: false,
+ isCompacting: false,
+ isBashRunning: false,
+ retryAttempt: 0,
+ steeringMode: "all",
+ followUpMode: "one-at-a-time",
+ sessionFile: `/tmp/${activeSessionId}.jsonl`,
+ sessionId: `${activeSessionId}-session`,
+ sessionDir: "/tmp/sessions",
+ leafId: `${activeSessionId}-leaf`,
+ autoCompactionEnabled: true,
+ messageCount: 1,
+ pendingMessageCount: 0,
+ compactionCount: 0,
+ goal: { active: false, status: "idle", tokensUsed: 0, timeUsedSeconds: 0, continuationsUsed: 0 },
+ scopedModels: [],
+ activeToolNames: [],
+ contextUsage: undefined,
+ };
+}
+
+function createAttachResult(activeSessionId: string, messages: AgentMessage[] = []): DaemonAttachResult {
+ const state = createConnectionState(activeSessionId);
+ const lastEventCursor = { generation: `generation-${activeSessionId}`, sequence: 3 };
+ const summary: SessionSummary = {
+ id: activeSessionId,
+ activeSessionId,
+ lifecycle: "live",
+ activity: "idle",
+ sessionId: state.sessionId,
+ sessionFile: state.sessionFile,
+ cwd: state.cwd,
+ isStreaming: false,
+ isCompacting: false,
+ attachedClients: 1,
+ messageCount: messages.length,
+ pendingMessageCount: 0,
+ };
+ return {
+ protocol: DAEMON_PROTOCOL_INFO,
+ activeSessionId,
+ snapshot: {
+ activeSessionId,
+ summary,
+ state,
+ messages,
+ lastEventSequence: 3,
+ lastEventCursor,
+ },
+ replay: { status: "complete", toSequence: 3, toCursor: lastEventCursor },
+ lastEventSequence: 3,
+ lastEventCursor,
+ client: {
+ id: "client-1",
+ capabilities: ["attach_snapshot", "event_sequence", "chunked_snapshot"],
+ },
+ };
+}
+
+function asDaemonClient(client: ResumeDaemonClient): DaemonClient {
+ return client as unknown as DaemonClient;
+}
+
+function createSocketClient(id: string, attachedActiveSessionIds: string[]): DaemonSocketClient {
+ return {
+ id,
+ socket: { destroyed: false } as DaemonSocketClient["socket"],
+ attachedActiveSessionIds: new Set(attachedActiveSessionIds),
+ detachInput: () => {},
+ supportsExtensionUi: true,
+ capabilities: new Set(["attach_snapshot", "event_sequence", "extension_ui", "slim_attach", "chunked_snapshot"]),
+ };
+}
+
+interface SupervisorHarness {
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<DaemonResponse | undefined>;
+}
+
+describe("ENG-4656 active session resume", () => {
+ it("reattaches /resume to the existing worker even when the snapshot arrives with the response", async () => {
+ const client = new ResumeDaemonClient();
+ const connection = await DaemonAgentConnection.attach(asDaemonClient(client), sourceActiveSessionId);
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ events.push(event);
+ });
+
+ await expect(connection.switchSession("/tmp/target-active.jsonl")).resolves.toEqual({ cancelled: false });
+
+ expect(client.requests.map((request) => request.type)).toEqual(["attach", "switch_session", "reattach"]);
+ expect(client.requests[2]).toMatchObject({
+ type: "reattach",
+ activeSessionId: sourceActiveSessionId,
+ targetActiveSessionId,
+ });
+ await expect(connection.getState()).resolves.toMatchObject({
+ activeSessionId: targetActiveSessionId,
+ sessionId: `${targetActiveSessionId}-session`,
+ });
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ type: "session_replaced",
+ state: expect.objectContaining({ activeSessionId: targetActiveSessionId }),
+ }),
+ );
+ await connection.dispose();
+ expect(client.requests.at(-1)).toMatchObject({ type: "detach", activeSessionId: targetActiveSessionId });
+ });
+
+ it("keeps other source and target clients attached when one client moves", async () => {
+ const movingClient = createSocketClient("moving", [sourceActiveSessionId]);
+ const sourcePeer = createSocketClient("source-peer", [sourceActiveSessionId]);
+ const targetPeer = createSocketClient("target-peer", [targetActiveSessionId]);
+ const operations: string[] = [];
+ const targetSummary = createAttachResult(targetActiveSessionId).snapshot.summary;
+ const targetWorker = {};
+ const releaseReservation = vi.fn(() => operations.push("release"));
+ const write = vi.fn((_client: DaemonSocketClient, message: DaemonOutbound) => {
+ operations.push(message.type === "response" ? "response" : message.type);
+ return true;
+ });
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ clients: new Set([movingClient, sourcePeer, targetPeer]),
+ findWorker: vi.fn(async () => ({ worker: targetWorker, summary: targetSummary })),
+ reserveSnapshotStream: vi.fn(() => {
+ operations.push("reserve");
+ return releaseReservation;
+ }),
+ attachClient: vi.fn(async (client: DaemonSocketClient) => {
+ expect(client.attachedActiveSessionIds.has(targetActiveSessionId)).toBe(true);
+ operations.push("attach");
+ client.attachedActiveSessionIds.add(targetActiveSessionId);
+ return { worker: targetWorker, result: createAttachResult(targetActiveSessionId) };
+ }),
+ getOrCreateTranscriptCache: vi.fn(() => ({})),
+ createStreamedAttachResult: vi.fn((result: DaemonAttachResult) => ({
+ ...result,
+ snapshotStream: { id: "snapshot-1", messageCount: 0, targetChunkBytes: 512 * 1024 },
+ })),
+ streamSnapshot: vi.fn(async () => {
+ operations.push("stream");
+ releaseReservation();
+ }),
+ matchWorkers: vi.fn(() => []),
+ dropPendingReplacementSnapshot: vi.fn(),
+ syncWorkerExtensionUi: vi.fn(async () => undefined),
+ write,
+ log: vi.fn(),
+ }) as SupervisorHarness;
+
+ await supervisor.handleCommand(movingClient, {
+ type: "reattach",
+ activeSessionId: sourceActiveSessionId,
+ targetActiveSessionId,
+ capabilities: [...movingClient.capabilities],
+ });
+
+ expect([...movingClient.attachedActiveSessionIds]).toEqual([targetActiveSessionId]);
+ expect([...sourcePeer.attachedActiveSessionIds]).toEqual([sourceActiveSessionId]);
+ expect([...targetPeer.attachedActiveSessionIds]).toEqual([targetActiveSessionId]);
+ expect(operations).toEqual(["reserve", "attach", "response", "session_detached", "stream", "release"]);
+ });
+
+ it("leaves repeated --resume clients independently attached to the same worker", async () => {
+ const firstClient = new ResumeDaemonClient();
+ const secondClient = new ResumeDaemonClient();
+ const [first, second] = await Promise.all([
+ DaemonAgentConnection.attach(asDaemonClient(firstClient), targetActiveSessionId),
+ DaemonAgentConnection.attach(asDaemonClient(secondClient), targetActiveSessionId),
+ ]);
+
+ expect(firstClient.requests.map((request) => request.type)).toEqual(["attach"]);
+ expect(secondClient.requests.map((request) => request.type)).toEqual(["attach"]);
+ await Promise.all([first.dispose(), second.dispose()]);
+ expect(firstClient.requests.at(-1)).toMatchObject({ type: "detach", activeSessionId: targetActiveSessionId });
+ expect(secondClient.requests.at(-1)).toMatchObject({ type: "detach", activeSessionId: targetActiveSessionId });
+ });
+});