Skip to content

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

Rust

preserve daemon sessions across self-updates (#369)

kt4615258150a2
diff --git a/packages/ai/scripts/generate-models.ts b/packages/ai/scripts/generate-models.ts
index e3e7e0d313..cf976738d9 100644
--- a/packages/ai/scripts/generate-models.ts
+++ b/packages/ai/scripts/generate-models.ts
@@ -427,6 +427,25 @@ function mergePrimeInferenceModels(
return Array.from(models.values());
}
+function refreshPrimeInferenceAliasLimits(
+ snapshotModels: Model<"openai-completions">[],
+ catalogModels: Model<"openai-completions">[],
+): Model<"openai-completions">[] {
+ const liveModels = new Map(catalogModels.map((model) => [model.id.toLowerCase(), model]));
+ return snapshotModels.map((model) => {
+ const canonicalId = PRIME_INFERENCE_OPENROUTER_ALIASES[model.id.toLowerCase()];
+ const canonical = canonicalId ? liveModels.get(canonicalId) : undefined;
+ if (!canonical) {
+ return model;
+ }
+ return {
+ ...model,
+ contextWindow: canonical.contextWindow,
+ maxTokens: canonical.maxTokens,
+ };
+ });
+}
+
function includesCatalogCapability(value: unknown, capabilities: readonly string[]): boolean {
if (!Array.isArray(value)) {
return false;
@@ -633,6 +652,7 @@ async function fetchPrimeInferenceModels(): Promise<Model<"openai-completions">[
(model) => liveIds.has(model.id.toLowerCase()) || model.id.toLowerCase().startsWith("internal/"),
);
}
+ snapshotModels = refreshPrimeInferenceAliasLimits(snapshotModels, catalogModels);
const models = mergePrimeInferenceModels(snapshotModels, catalogModels);
console.log(`Loaded ${models.length} Prime Inference models (${catalogModels.length} from the live catalog)`);
return models;
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 3d172e3fdb..00ff6e3604 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -5,6 +5,9 @@
- Added `/btw` and `/side` for one-turn inline side questions that use the current context without changing the main session ([ENG-4509](https://linear.app/primeintellect/issue/ENG-4509/add-btw-and-side-side-question-flows)).
- Changed scheduled heartbeat prompts to steer (interrupt the current turn) by default, with a `steer`/`follow_up` delivery mode selectable via `/heartbeat --steer|--follow-up` and the `rlm_heartbeat` skill's `delivery_mode` argument.
- Changed the new-chat splash to show only version, model, and cwd metadata and rotate among five example prompts.
+- Fixed self-updates losing restored daemon sessions to a socket cleanup race and leaving open session or agents-view windows disconnected.
+- Changed daemon connection errors to report the failed operation, session identity, recovery steps, socket, and diagnostic log instead of raw protocol reasons.
+- Fixed Agents View retrying after an intentional daemon shutdown instead of stopping with restart guidance.
- Fixed stale heartbeat jobs reopening archived, deleted, or concurrently terminated sessions ([ENG-4519](https://linear.app/primeintellect/issue/ENG-4519/heartbeats-rebirth-sessions-that-were-previously-killed)).
## [0.2.8] - 2026-07-09
diff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.ts
index 394e477540..31cdbed1c1 100644
--- a/packages/coding-agent/src/cli/daemon-launch.ts
+++ b/packages/coding-agent/src/cli/daemon-launch.ts
@@ -107,28 +107,36 @@ export class StaleDaemonError extends Error {
}
}
-async function waitForDaemonGone(socketPath: string, timeoutMs = 5000): Promise<boolean> {
+async function waitForDaemonGone(socketPath: string, timeoutMs = 5000, requireSocketCleanup = false): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
- if (!(await canConnectToDaemon(socketPath, 250))) {
+ if (
+ !(await canConnectToDaemon(socketPath, 250)) &&
+ (!requireSocketCleanup || process.platform === "win32" || !existsSync(socketPath))
+ ) {
return true;
}
await delay(25);
}
- return false;
+ // A daemon can exit without removing its Unix socket (for example, after a crash
+ // during shutdown). Once the cleanup grace has elapsed, a non-listening socket
+ // is safe for the replacement daemon's guarded startup path to reclaim.
+ return requireSocketCleanup && !(await canConnectToDaemon(socketPath, 250));
}
-export async function shutdownDaemonAndWait(socketPath: string): Promise<boolean> {
+export async function shutdownDaemonAndWait(socketPath: string, timeoutMs = 5000): Promise<boolean> {
const client = new DaemonClient(socketPath);
+ let shutdownAccepted = false;
try {
await client.connect(1000);
- await client.request({ type: "shutdown" }).catch(() => undefined);
+ const response = await client.request({ type: "shutdown" });
+ shutdownAccepted = response.success;
} catch {
// A connect failure isn't treated as "gone"; waitForDaemonGone is the source of truth.
} finally {
client.close();
}
- return waitForDaemonGone(socketPath);
+ return waitForDaemonGone(socketPath, timeoutMs, shutdownAccepted);
}
// activeSessions is undefined when the daemon is reachable but its sessions couldn't
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 b1ec3f9a42..3158a314e7 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
@@ -1,13 +1,14 @@
import { randomUUID } from "node:crypto";
import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
import type { ImageContent, Transport } from "@earendil-works/pi-ai";
+import { getAgentLogPath, getDaemonLogPath } from "../../config.js";
import type { CompactionResult } from "../../core/compaction/index.js";
import type { ContextTreeNode } from "../../core/context-tree.js";
import type { AgentCronJob, AgentHeartbeatDeliveryMode, AgentHeartbeatUpdateAction } from "../../core/cron-jobs.js";
import type { RefinementResult } from "../../core/refinement/index.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
import type { SessionStats } from "../../core/session-stats.js";
-import type { DaemonClient } from "../daemon/daemon-client.js";
+import { type DaemonClient, getDaemonSocketCloseReason } from "../daemon/daemon-client.js";
import { deserializeDaemonError } from "../daemon/daemon-errors.js";
import {
collectDaemonClientEnv,
@@ -15,6 +16,7 @@ import {
type DaemonCommand,
type DaemonOutbound,
type DaemonReplayInfo,
+ type DaemonSessionClosedReason,
type DaemonSessionSnapshot,
isUnknownDaemonCommandError,
} from "../daemon/daemon-protocol.js";
@@ -61,6 +63,51 @@ type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : n
type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
export const DAEMON_REFINE_REQUEST_TIMEOUT_MS = 10 * 60 * 1000;
+const UPDATE_RECONNECT_TIMEOUT_MS = 120000;
+const UPDATE_RECONNECT_RETRY_MS = 100;
+const updateTransportReconnects = new WeakMap<DaemonClient, Promise<void>>();
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function formatErrorSentence(error: unknown): string {
+ const message = (error instanceof Error ? error.message : String(error)).trim();
+ if (!message) {
+ return "Unknown daemon error.";
+ }
+ return /[.!?]$/.test(message) ? message : `${message}.`;
+}
+
+function reconnectDaemonTransportAfterUpdate(client: DaemonClient): Promise<void> {
+ const existing = updateTransportReconnects.get(client);
+ if (existing) {
+ return existing;
+ }
+ const reconnectPromise = Promise.resolve()
+ .then(async () => {
+ client.disconnectForReconnect("update");
+ const deadline = Date.now() + UPDATE_RECONNECT_TIMEOUT_MS;
+ let lastError: unknown;
+ while (Date.now() < deadline) {
+ try {
+ await client.reconnect(1000);
+ return;
+ } catch (error) {
+ lastError = error;
+ }
+ await delay(UPDATE_RECONNECT_RETRY_MS);
+ }
+ throw lastError ?? new Error("the updated daemon did not become available");
+ })
+ .finally(() => {
+ if (updateTransportReconnects.get(client) === reconnectPromise) {
+ updateTransportReconnects.delete(client);
+ }
+ });
+ updateTransportReconnects.set(client, reconnectPromise);
+ return reconnectPromise;
+}
export interface DaemonAgentConnectionOptions {
closeClientOnDispose?: boolean;
@@ -87,6 +134,14 @@ export class DaemonAgentConnection implements AgentConnection {
private lastEventSequence: number | undefined;
private latestSnapshot: AgentConnectionSnapshot | undefined;
private latestSnapshotIsFresh = false;
+ private attachedSessionId: string | undefined;
+ private attachedSessionFile: string | undefined;
+ private daemonLogPath: string | undefined;
+ private updateRestartPending = false;
+ private updateReconnectFailed = false;
+ private terminalCloseEmitted = false;
+ private updateReconnectPromise?: Promise<void>;
+ private disposed = false;
private readonly activeSideQuestionIds = new Set<string>();
constructor(
@@ -97,8 +152,24 @@ export class DaemonAgentConnection implements AgentConnection {
this.unsubscribeDaemonMessages = this.client.onMessage((message) => {
void this.handleDaemonMessage(message);
});
+ this.captureDaemonLogPath();
this.unsubscribeDaemonClose = this.client.onClose((error) => {
- void this.emit({ type: "closed", error: error.message });
+ if (this.disposed || this.terminalCloseEmitted) {
+ return;
+ }
+ const closeReason = getDaemonSocketCloseReason(error);
+ if (closeReason === "shutdown") {
+ this.terminalCloseEmitted = true;
+ void this.emit({ type: "closed", error: this.formatDaemonSessionClosedError("shutdown") });
+ return;
+ }
+ if ((this.updateRestartPending || closeReason === "update") && !this.updateReconnectFailed) {
+ this.updateRestartPending = true;
+ void this.reconnectAfterUpdate();
+ return;
+ }
+ this.terminalCloseEmitted = true;
+ void this.emit({ type: "closed", error: this.formatDaemonConnectionClosedError(error) });
});
}
@@ -134,6 +205,13 @@ export class DaemonAgentConnection implements AgentConnection {
},
});
this.activeSessionId = getAttachActiveSessionId(result);
+ const summary = "snapshot" in result ? result.snapshot.summary : result;
+ this.attachedSessionId = summary.sessionId;
+ this.attachedSessionFile =
+ summary.sessionFile ?? ("snapshot" in result ? result.snapshot.state.sessionFile : undefined);
+ this.captureDaemonLogPath();
+ this.updateReconnectFailed = false;
+ this.terminalCloseEmitted = false;
this.lastEventSequence = maxEventSequence(this.lastEventSequence, getAttachLastEventSequence(result));
if ("snapshot" in result) {
this.latestSnapshot = mapDaemonAttachSnapshot(result);
@@ -718,6 +796,8 @@ export class DaemonAgentConnection implements AgentConnection {
}
async dispose(): Promise<void> {
+ this.disposed = true;
+ this.updateRestartPending = false;
await Promise.allSettled([...this.activeSideQuestionIds].map((id) => this.abortSideQuestion(id)));
this.unsubscribeDaemonMessages();
this.unsubscribeDaemonClose();
@@ -773,6 +853,8 @@ export class DaemonAgentConnection implements AgentConnection {
return;
}
if (message.type === "session_replaced") {
+ this.attachedSessionId = message.state.sessionId;
+ this.attachedSessionFile = message.state.sessionFile;
const latestSnapshot: AgentConnectionSnapshot = {
state: message.state,
messages: message.messages,
@@ -797,8 +879,141 @@ export class DaemonAgentConnection implements AgentConnection {
return;
}
if (message.type === "session_closed") {
- await this.emit({ type: "closed", error: message.reason });
+ if (message.reason === "update") {
+ this.captureDaemonLogPath();
+ this.updateRestartPending = true;
+ void this.reconnectAfterUpdate();
+ return;
+ }
+ this.terminalCloseEmitted = true;
+ await this.emit({ type: "closed", error: this.formatDaemonSessionClosedError(message.reason) });
+ }
+ }
+
+ private captureDaemonLogPath(): void {
+ const socketPath = this.client.hello?.socketPath;
+ if (socketPath) {
+ this.daemonLogPath = getDaemonLogPath(socketPath);
+ }
+ }
+
+ private formatDaemonSessionClosedError(reason: DaemonSessionClosedReason): string {
+ const explanation: Record<DaemonSessionClosedReason, string> = {
+ killed:
+ "The daemon stopped this agent session. Its transcript remains saved and can be reopened from Agents View.",
+ shutdown:
+ "The Prime Agent daemon shut down while this window was attached. The session transcript remains saved; restart Prime Agent and reopen it from Agents View.",
+ completed:
+ "The daemon closed this agent session after it completed. Its transcript remains available from Agents View.",
+ replaced:
+ "The daemon replaced this agent session with another session. Reopen the current session from Agents View.",
+ update:
+ "The Prime Agent daemon restarted for an update, but this window did not restore automatically. The session transcript remains saved; restart Prime Agent and reopen it from Agents View.",
+ };
+ return `${explanation[reason]} ${this.formatDaemonDiagnosticContext()}`;
+ }
+
+ private formatDaemonConnectionClosedError(error: Error): string {
+ return `Lost connection to the Prime Agent daemon. Cause: ${formatErrorSentence(error)} The session transcript remains saved; restart Prime Agent or reopen the session from Agents View. ${this.formatDaemonDiagnosticContext()}`;
+ }
+
+ private formatUpdateReconnectError(error: unknown): string {
+ return `The Prime Agent daemon restarted for an update, but this window could not reconnect to its restored session before the recovery timeout expired. Last error: ${formatErrorSentence(error)} The session transcript remains saved; restart Prime Agent and reopen it from Agents View. ${this.formatDaemonDiagnosticContext()}`;
+ }
+
+ private formatDaemonDiagnosticContext(): string {
+ const details: string[] = [];
+ if (this.attachedSessionId) {
+ details.push(`Session ID: ${this.attachedSessionId}.`);
}
+ if (this.attachedSessionFile) {
+ details.push(`Session file: ${this.attachedSessionFile}.`);
+ }
+ details.push(`Diagnostic log: ${this.daemonLogPath ?? getAgentLogPath()}.`);
+ return details.join(" ");
+ }
+
+ private reconnectAfterUpdate(): Promise<void> {
+ if (this.updateReconnectPromise) {
+ return this.updateReconnectPromise;
+ }
+ const reconnectPromise = reconnectDaemonTransportAfterUpdate(this.client)
+ .then(() => this.restoreConnectionAfterUpdate())
+ .catch(async (error: unknown) => {
+ this.updateRestartPending = false;
+ this.updateReconnectFailed = true;
+ if (!this.disposed) {
+ this.terminalCloseEmitted = true;
+ await this.emit({
+ type: "closed",
+ error: this.formatUpdateReconnectError(error),
+ });
+ }
+ })
+ .finally(() => {
+ if (this.updateReconnectPromise === reconnectPromise) {
+ this.updateReconnectPromise = undefined;
+ }
+ });
+ this.updateReconnectPromise = reconnectPromise;
+ return reconnectPromise;
+ }
+
+ private async restoreConnectionAfterUpdate(): Promise<void> {
+ const sessionId = this.attachedSessionId;
+ const sessionFile = this.attachedSessionFile;
+ if (!sessionId && !sessionFile) {
+ throw new Error("the previous session identity is unavailable");
+ }
+ const deadline = Date.now() + UPDATE_RECONNECT_TIMEOUT_MS;
+ let lastError: unknown;
+ while (!this.disposed && Date.now() < deadline) {
+ try {
+ await this.client.reconnect(1000);
+ if (this.disposed) {
+ return;
+ }
+ const response = await this.client.request({ type: "list" }, 30000);
+ if (this.disposed) {
+ return;
+ }
+ if (!response.success) {
+ throw deserializeDaemonError(response);
+ }
+ const sessions = readSessionSummaries(response.data);
+ const restored = sessions.find(
+ (summary) =>
+ summary.activeSessionId !== undefined &&
+ ((sessionFile !== undefined && summary.sessionFile === sessionFile) ||
+ (sessionId !== undefined && summary.sessionId === sessionId)),
+ );
+ if (restored?.activeSessionId) {
+ if (this.disposed) {
+ return;
+ }
+ this.activeSessionId = restored.activeSessionId;
+ this.lastEventSequence = undefined;
+ await this.attach();
+ if (this.disposed) {
+ return;
+ }
+ const snapshot = await this.getInitialSnapshot();
+ if (this.disposed) {
+ return;
+ }
+ this.updateRestartPending = false;
+ await this.emit({ type: "session_replaced", state: snapshot.state, messages: snapshot.messages });
+ return;
+ }
+ } catch (error) {
+ lastError = error;
+ }
+ await delay(UPDATE_RECONNECT_RETRY_MS);
+ }
+ if (this.disposed) {
+ return;
+ }
+ throw lastError ?? new Error("the restored session did not become available");
}
private isMessageForActiveSession(message: DaemonOutbound): boolean {
@@ -835,6 +1050,13 @@ export class DaemonAgentConnection implements AgentConnection {
}
}
+function readSessionSummaries(value: unknown): SessionSummary[] {
+ if (!value || typeof value !== "object" || !Array.isArray((value as { sessions?: unknown }).sessions)) {
+ throw new Error("Daemon returned an invalid session list response");
+ }
+ return (value as { sessions: SessionSummary[] }).sessions;
+}
+
function getAttachActiveSessionId(result: SessionSummary | DaemonAttachResult): string {
if ("snapshot" in result) {
return result.activeSessionId;
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.ts
index 947faf8bda..14fe28e6e7 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
@@ -22,8 +22,13 @@ import { findExactModelReferenceMatch } from "../../core/model-resolver.js";
import { SessionManager } from "../../core/session-manager.js";
import { DaemonAgentConnection } from "../agent-connection/daemon-agent-connection.js";
import type { AgentConnectionSavedSessionInfo } from "../agent-connection/types.js";
-import { DaemonClient } from "../daemon/daemon-client.js";
-import { type DaemonCommand, type DaemonResponse, isUnknownDaemonCommandError } from "../daemon/daemon-protocol.js";
+import { DaemonClient, getDaemonSocketCloseReason } from "../daemon/daemon-client.js";
+import {
+ type DaemonClosingReason,
+ type DaemonCommand,
+ type DaemonResponse,
+ isUnknownDaemonCommandError,
+} from "../daemon/daemon-protocol.js";
import {
resolveAttachModelFallbackMessage,
type SessionSummary,
@@ -81,6 +86,8 @@ import {
} from "./agents-view-state.js";
const POLL_INTERVAL_MS = 1000;
+const RECONNECT_TIMEOUT_MS = 120000;
+const RECONNECT_RETRY_MS = 1000;
const EXIT_HINT_DURATION_MS = 2000;
const DELETE_CONFIRM_DURATION_MS = 2000;
const STATUS_MESSAGE_DURATION_MS = 4500;
@@ -208,6 +215,10 @@ export function formatAgentsViewStatusLine(text: string): string {
return text.replace(/\s+/g, " ").trim();
}
+export function shouldReconnectAgentsViewDaemon(reason: DaemonClosingReason | undefined): boolean {
+ return reason !== "shutdown";
+}
+
export function createAgentsViewReplyHeadline(text: string | undefined): string | undefined {
return text
?.split("\n")
@@ -376,6 +387,10 @@ class AgentsViewMode implements Component, Focusable {
private readonly fullscreenDock: Component;
private readonly keybindings: KeybindingsManager;
private client: DaemonClient | undefined;
+ private unsubscribeClientClose: (() => void) | undefined;
+ private reconnectPromise: Promise<void> | undefined;
+ private reconnectTimedOut = false;
+ private daemonShutdownReceived = false;
private resolveRun: ((result: AgentsViewRunResult) => void) | undefined;
private pollTimer: NodeJS.Timeout | undefined;
private animationTimer: NodeJS.Timeout | undefined;
@@ -470,6 +485,7 @@ class AgentsViewMode implements Component, Focusable {
async run(): Promise<AgentsViewRunResult> {
this.client = new DaemonClient(this.options.socketPath);
await this.client.connect();
+ this.subscribeToClientClose(this.client);
this.ui.addChild(this);
this.ui.setFocus(this);
@@ -492,7 +508,6 @@ class AgentsViewMode implements Component, Focusable {
});
await this.refreshSessions();
- await this.sendInitialPrompts();
this.loadStartupNotices();
this.pollTimer = setInterval(() => {
void this.refreshSessions();
@@ -772,7 +787,7 @@ class AgentsViewMode implements Component, Focusable {
/** Sticky messages (e.g. billing warnings) stay until the user acknowledges them with any keypress. */
private clearStickyStatusMessage(): void {
- if (!this.statusMessageSticky) {
+ if (!this.statusMessageSticky || this.daemonShutdownReceived) {
return;
}
this.statusMessageSticky = false;
@@ -1725,29 +1740,42 @@ class AgentsViewMode implements Component, Focusable {
}
private async refreshSessions(): Promise<void> {
+ if (this.reconnectPromise || this.daemonShutdownReceived) {
+ return;
+ }
const client = this.requireClient();
try {
const response = await client.request(createAgentsViewListCommand());
const data = requireDaemonData(response);
- const sessions = expectSessionList(data);
- this.lastListedSummaries = sessions;
- const visibleSessions = sessions.filter((summary) =>
- shouldShowAgentsViewSession(summary, this.inactiveAgentIdentities.has(getSummaryIdentity(summary))),
- );
- this.lastVisibleSummaries = this.withPendingDeleteSession(visibleSessions);
- this.rows = buildAgentsViewRows(
- this.lastVisibleSummaries,
- this.expandedSubagentParents,
- this.programShownParents,
- );
- this.applyPendingAncestorExpansion();
- this.restoreSelection();
- this.ui.requestRender();
+ this.applySessionList(expectSessionList(data));
+ await this.sendInitialPrompts();
} catch (error) {
- this.setStatusMessage(formatError("Failed to refresh agents", error));
+ if (!this.reconnectPromise) {
+ if (client.isConnected) {
+ this.setStatusMessage(formatError("Failed to refresh agents", error));
+ } else {
+ this.startClientReconnect(client, error);
+ }
+ }
}
}
+ private applySessionList(sessions: SessionSummary[]): void {
+ this.lastListedSummaries = sessions;
+ const visibleSessions = sessions.filter((summary) =>
+ shouldShowAgentsViewSession(summary, this.inactiveAgentIdentities.has(getSummaryIdentity(summary))),
+ );
+ this.lastVisibleSummaries = this.withPendingDeleteSession(visibleSessions);
+ this.rows = buildAgentsViewRows(
+ this.lastVisibleSummaries,
+ this.expandedSubagentParents,
+ this.programShownParents,
+ );
+ this.applyPendingAncestorExpansion();
+ this.restoreSelection();
+ this.ui.requestRender();
+ }
+
private withPendingDeleteSession(sessions: readonly SessionSummary[]): SessionSummary[] {
const pending = this.pendingDeleteAgent;
if (!pending) {
@@ -1824,12 +1852,87 @@ class AgentsViewMode implements Component, Focusable {
flushFullscreen: false,
});
stopThemeWatcher();
+ this.unsubscribeClientClose?.();
+ this.unsubscribeClientClose = undefined;
this.client?.close();
this.client = undefined;
this.resolveRun?.(result);
this.resolveRun = undefined;
}
+ private subscribeToClientClose(client: DaemonClient): void {
+ this.unsubscribeClientClose?.();
+ this.unsubscribeClientClose = client.onClose((error) => {
+ if (!shouldReconnectAgentsViewDaemon(getDaemonSocketCloseReason(error))) {
+ this.handleDaemonShutdown(client, error);
+ return;
+ }
+ this.startClientReconnect(client, error);
+ });
+ }
+
+ private handleDaemonShutdown(client: DaemonClient, error: Error): void {
+ if (this.stopped || client !== this.client) {
+ return;
+ }
+ this.daemonShutdownReceived = true;
+ this.reconnectTimedOut = false;
+ this.setStatusMessage(`Prime Agent daemon shut down. Restart Prime Agent to reconnect. ${error.message}`, {
+ tone: "error",
+ sticky: true,
+ });
+ this.applySessionList([]);
+ }
+
+ private startClientReconnect(client: DaemonClient, error: unknown): void {
+ if (this.stopped || client !== this.client || this.reconnectPromise || this.daemonShutdownReceived) {
+ return;
+ }
+ if (!this.reconnectTimedOut) {
+ this.setStatusMessage("Daemon restarted; reconnecting...", { sticky: true });
+ }
+ const reconnectPromise = this.reconnectClient(client, error).finally(() => {
+ if (this.reconnectPromise === reconnectPromise) {
+ this.reconnectPromise = undefined;
+ }
+ });
+ this.reconnectPromise = reconnectPromise;
+ }
+
+ private async reconnectClient(client: DaemonClient, initialError: unknown): Promise<void> {
+ const deadline = Date.now() + RECONNECT_TIMEOUT_MS;
+ let lastError = initialError;
+ while (!this.stopped && !this.daemonShutdownReceived && client === this.client && Date.now() < deadline) {
+ try {
+ await client.reconnect(1000);
+ const response = await client.request(createAgentsViewListCommand());
+ const data = requireDaemonData(response);
+ const sessions = expectSessionList(data);
+ this.daemonShutdownReceived = false;
+ this.reconnectTimedOut = false;
+ this.setStatusMessage("Reconnected after daemon restart", { render: false });
+ this.applySessionList(sessions);
+ await this.sendInitialPrompts();
+ return;
+ } catch (error) {
+ lastError = error;
+ }
+ await new Promise<void>((resolve) => {
+ const retryTimer = setTimeout(resolve, RECONNECT_RETRY_MS);
+ retryTimer.unref?.();
+ });
+ }
+ if (!this.stopped && !this.daemonShutdownReceived && client === this.client) {
+ this.reconnectTimedOut = true;
+ this.setStatusMessage(formatError("Daemon unavailable; retrying", lastError), {
+ tone: "error",
+ sticky: true,
+ render: false,
+ });
+ this.applySessionList([]);
+ }
+ }
+
private requireClient(): DaemonClient {
if (!this.client) {
throw new Error("Agents view daemon client is not connected");
diff --git a/packages/coding-agent/src/modes/daemon/daemon-client.ts b/packages/coding-agent/src/modes/daemon/daemon-client.ts
index 8cb20461fa..96787fd78d 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-client.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-client.ts
@@ -1,6 +1,8 @@
import { createConnection, type Socket } from "node:net";
+import { getDaemonLogPath } from "../../config.js";
import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";
import type {
+ DaemonClosingReason,
DaemonCommand,
DaemonOutbound,
DaemonRequestProgress,
@@ -21,6 +23,29 @@ export interface DaemonClientRequestOptions {
onProgress?: DaemonClientProgressListener;
}
+function daemonEndpointDetails(socketPath: string): string {
+ return `Socket: ${socketPath}. Daemon log: ${getDaemonLogPath(socketPath)}.`;
+}
+
+export class DaemonSocketClosedError extends Error {
+ constructor(
+ socketPath: string,
+ readonly daemonClosingReason?: DaemonClosingReason,
+ cause?: string,
+ ) {
+ const reasonDetails = daemonClosingReason ? ` Reason: ${daemonClosingReason}.` : "";
+ const causeDetails = cause ? ` Cause: ${cause}.` : "";
+ super(
+ `Connection to the Prime Agent daemon closed.${reasonDetails}${causeDetails} ${daemonEndpointDetails(socketPath)}`,
+ );
+ this.name = "DaemonSocketClosedError";
+ }
+}
+
+export function getDaemonSocketCloseReason(error: Error): DaemonClosingReason | undefined {
+ return error instanceof DaemonSocketClosedError ? error.daemonClosingReason : undefined;
+}
+
export class DaemonClient {
private socket?: Socket;
private detachReader?: () => void;
@@ -37,6 +62,8 @@ export class DaemonClient {
>();
private requestId = 0;
private helloMessage?: DaemonHello;
+ private daemonClosingReason?: DaemonClosingReason;
+ private reconnectPromise?: Promise<void>;
private readonly helloWaiters = new Set<{
resolve: (hello: DaemonHello) => void;
reject: (error: Error) => void;
@@ -49,13 +76,19 @@ export class DaemonClient {
return this.helloMessage;
}
+ get isConnected(): boolean {
+ return this.socket !== undefined && !this.socket.destroyed;
+ }
+
/** Wait for the daemon_hello greeting sent on connect. */
async waitForHello(timeoutMs = 3000): Promise<DaemonHello> {
if (this.helloMessage) {
return this.helloMessage;
}
if (!this.socket || this.socket.destroyed) {
- throw new Error("Daemon client is not connected");
+ throw new Error(
+ `Cannot wait for the Prime Agent daemon handshake because the daemon is not connected. ${daemonEndpointDetails(this.socketPath)}`,
+ );
}
return new Promise<DaemonHello>((resolve, reject) => {
const waiter = {
@@ -63,7 +96,11 @@ export class DaemonClient {
reject,
timeout: setTimeout(() => {
this.helloWaiters.delete(waiter);
- reject(new Error("Timed out waiting for daemon hello"));
+ reject(
+ new Error(
+ `Timed out after ${timeoutMs}ms waiting for the Prime Agent daemon handshake. ${daemonEndpointDetails(this.socketPath)}`,
+ ),
+ );
}, timeoutMs),
};
this.helloWaiters.add(waiter);
@@ -72,9 +109,11 @@ export class DaemonClient {
async connect(timeoutMs = 3000): Promise<void> {
if (this.socket) {
- throw new Error("Daemon client is already connected");
+ throw new Error(`Prime Agent daemon client is already connected. ${daemonEndpointDetails(this.socketPath)}`);
}
+ this.helloMessage = undefined;
+ this.daemonClosingReason = undefined;
const socket = createConnection(this.socketPath);
this.socket = socket;
this.detachReader = attachJsonlLineReader(socket, (line) => this.handleLine(line));
@@ -84,7 +123,11 @@ export class DaemonClient {
cleanup();
this.clearSocketReference(socket);
socket.destroy();
- reject(new Error(`Timed out connecting to daemon socket: ${this.socketPath}`));
+ reject(
+ new Error(
+ `Timed out after ${timeoutMs}ms connecting to the Prime Agent daemon. ${daemonEndpointDetails(this.socketPath)}`,
+ ),
+ );
}, timeoutMs);
const cleanup = () => {
clearTimeout(timeout);
@@ -98,14 +141,56 @@ export class DaemonClient {
const onError = (error: Error) => {
cleanup();
this.clearSocketReference(socket);
- reject(error);
+ reject(
+ new Error(
+ `Failed to connect to the Prime Agent daemon: ${error.message}. ${daemonEndpointDetails(this.socketPath)}`,
+ ),
+ );
};
socket.once("connect", onConnect);
socket.once("error", onError);
});
- socket.on("error", (error) => this.notifyClosed(socket, error));
- socket.on("close", () => this.notifyClosed(socket, new Error("Daemon socket closed")));
+ socket.on("error", (error) =>
+ this.notifyClosed(
+ socket,
+ this.daemonClosingReason
+ ? new DaemonSocketClosedError(this.socketPath, this.daemonClosingReason, error.message)
+ : error,
+ ),
+ );
+ socket.on("close", () =>
+ this.notifyClosed(socket, new DaemonSocketClosedError(this.socketPath, this.daemonClosingReason)),
+ );
+ }
+
+ async reconnect(timeoutMs = 3000): Promise<void> {
+ if (this.reconnectPromise) {
+ return this.reconnectPromise;
+ }
+ if (this.socket && !this.socket.destroyed) {
+ return;
+ }
+ const reconnectPromise = this.connect(timeoutMs);
+ this.reconnectPromise = reconnectPromise;
+ try {
+ await reconnectPromise;
+ } finally {
+ if (this.reconnectPromise === reconnectPromise) {
+ this.reconnectPromise = undefined;
+ }
+ }
+ }
+
+ disconnectForReconnect(reason: DaemonClosingReason): void {
+ const socket = this.socket;
+ if (!socket || socket.destroyed) {
+ return;
+ }
+ this.daemonClosingReason = reason;
+ this.notifyClosed(socket, new DaemonSocketClosedError(this.socketPath, reason));
+ socket.end();
+ socket.destroy();
}
onMessage(listener: DaemonClientMessageListener): () => void {
@@ -128,7 +213,9 @@ export class DaemonClient {
options: DaemonClientRequestOptions = {},
): Promise<DaemonResponse> {
if (!this.socket || this.socket.destroyed) {
- throw new Error("Daemon client is not connected");
+ throw new Error(
+ `Cannot send daemon command "${command.type}" because the Prime Agent daemon is not connected. ${daemonEndpointDetails(this.socketPath)}`,
+ );
}
const id = `daemon_${++this.requestId}`;
@@ -137,7 +224,11 @@ export class DaemonClient {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
this.pendingRequests.delete(id);
- reject(new Error(`Timed out waiting for daemon response to ${command.type}`));
+ reject(
+ new Error(
+ `Timed out after ${timeoutMs}ms waiting for the Prime Agent daemon response to "${command.type}". ${daemonEndpointDetails(this.socketPath)}`,
+ ),
+ );
}, timeoutMs);
this.pendingRequests.set(id, { resolve, reject, timeout, onProgress: options.onProgress });
@@ -148,7 +239,11 @@ export class DaemonClient {
close(): void {
this.detachReader?.();
this.detachReader = undefined;
- this.rejectAll(new Error("Daemon client closed"));
+ this.rejectAll(
+ new Error(
+ `Prime Agent daemon client closed before the operation completed. ${daemonEndpointDetails(this.socketPath)}`,
+ ),
+ );
this.socket?.end();
this.socket?.destroy();
this.socket = undefined;
@@ -179,6 +274,9 @@ export class DaemonClient {
waiter.resolve(message);
}
}
+ if (isDaemonClosing(message)) {
+ this.daemonClosingReason = message.reason;
+ }
if (isDaemonResponse(message) && message.id) {
const pending = this.pendingRequests.get(message.id);
@@ -227,6 +325,14 @@ export class DaemonClient {
}
}
+function isDaemonClosing(value: unknown): value is Extract<DaemonOutbound, { type: "daemon_closing" }> {
+ if (!value || typeof value !== "object") {
+ return false;
+ }
+ const candidate = value as { type?: unknown; reason?: unknown };
+ return candidate.type === "daemon_closing" && (candidate.reason === "shutdown" || candidate.reason === "update");
+}
+
function isDaemonHello(value: unknown): value is DaemonHello {
if (!value || typeof value !== "object") {
return false;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index a28aa0f227..9a8cc9e9a9 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -107,6 +107,7 @@ import {
DAEMON_PROTOCOL_INFO,
type DaemonAttachResult,
type DaemonClientCapability,
+ type DaemonClosingReason,
type DaemonCommand,
type DaemonOutbound,
type DaemonResponse,
@@ -128,7 +129,9 @@ import {
import { DaemonSessionSummarizer } from "./daemon-session-summarizer.js";
import {
cleanupDaemonSocketPath,
+ type DaemonSocketIdentity,
defaultDaemonSocketPath,
+ getDaemonSocketIdentity,
prepareDaemonSocketPath,
restrictDaemonSocketPath,
} from "./daemon-socket.js";
@@ -258,6 +261,7 @@ export class AgentDaemon {
private shuttingDown = false;
private updateRestartPreparing = false;
private ownsSocketPath = false;
+ private socketIdentity?: DaemonSocketIdentity;
private readonly clients = new Set<DaemonSocketClient>();
private readonly sessions = new Map<string, ActiveSessionState>();
private readonly openingSessions = new Map<string, Promise<ActiveSessionState>>();
@@ -351,6 +355,7 @@ export class AgentDaemon {
const onListening = () => {
this.server?.off("error", onError);
try {
+ this.socketIdentity = getDaemonSocketIdentity(this.socketPath);
this.ownsSocketPath = true;
if (process.platform !== "win32") {
restrictDaemonSocketPath(this.socketPath);
@@ -385,7 +390,9 @@ export class AgentDaemon {
return;
}
this.ownsSocketPath = false;
- cleanupDaemonSocketPath(this.socketPath);
+ const socketIdentity = this.socketIdentity;
+ this.socketIdentity = undefined;
+ cleanupDaemonSocketPath(this.socketPath, socketIdentity);
}
/**
@@ -2998,6 +3005,10 @@ export class AgentDaemon {
}
this.shuttingDown = true;
this.log(`shutting down (exit ${exitCode}); closing ${this.sessions.size} active session(s)`);
+ const closingReason: DaemonClosingReason = this.updateRestartPreparing ? "update" : "shutdown";
+ for (const client of this.clients) {
+ this.write(client, { type: "daemon_closing", reason: closingReason });
+ }
this.summarizer.stop();
for (const cleanup of this.signalCleanupHandlers) {
@@ -3005,7 +3016,7 @@ export class AgentDaemon {
}
this.cronScheduler.stop();
for (const state of [...this.sessions.values()]) {
- await this.closeSession(state, "shutdown");
+ await this.closeSession(state, closingReason);
}
for (const client of this.clients) {
client.detachInput();
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 72b5eb5b6a..a477f29dbe 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -435,6 +435,7 @@ export type DaemonErrorInfo =
| { code: "session_import_file_not_found"; filePath: string };
export type DaemonSessionClosedReason = "killed" | "shutdown" | "completed" | "replaced" | "update";
+export type DaemonClosingReason = "shutdown" | "update";
export type DaemonExtensionUIResponse = { value: string } | { confirmed: boolean } | { cancelled: true };
@@ -502,6 +503,7 @@ export type DaemonOutbound =
clientId: DaemonClientId;
serverCapabilities: readonly DaemonClientCapability[];
}
+ | { type: "daemon_closing"; reason: DaemonClosingReason }
| { type: "session_event"; activeSessionId: string; event: AgentConnectionSessionEvent; meta?: DaemonEventMeta }
| { type: "side_question_event"; activeSessionId: string; event: AgentConnectionSideQuestionEvent }
| { type: "session_status"; activeSessionId: string; recap?: string; meta?: DaemonEventMeta }
diff --git a/packages/coding-agent/src/modes/daemon/daemon-socket.ts b/packages/coding-agent/src/modes/daemon/daemon-socket.ts
index 745f994561..8a79157295 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-socket.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-socket.ts
@@ -2,9 +2,19 @@ import { chmodSync, existsSync, lstatSync, mkdirSync, unlinkSync } from "node:fs
import { createConnection } from "node:net";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
+import lockfile from "proper-lockfile";
const DAEMON_SOCKET_MODE = 0o600;
const DAEMON_SOCKET_DIR_MODE = 0o700;
+const DAEMON_SOCKET_RELEASE_GRACE_MS = 1000;
+const DAEMON_SOCKET_RELEASE_POLL_MS = 25;
+const DAEMON_SOCKET_LOCK_STALE_MS = 5000;
+const DAEMON_SOCKET_LOCK_UPDATE_MS = 1000;
+
+export interface DaemonSocketIdentity {
+ dev: number;
+ ino: number;
+}
export function defaultDaemonSocketPath(): string {
if (process.platform === "win32") {
@@ -16,18 +26,77 @@ export function defaultDaemonSocketPath(): string {
export async function prepareDaemonSocketPath(socketPath: string): Promise<void> {
ensureDefaultDaemonSocketDir(socketPath);
- if (process.platform === "win32" || !existsSync(socketPath)) {
+ if (process.platform === "win32") {
+ return;
+ }
+ if (!existsSync(socketPath)) {
+ return;
+ }
+ if (await canConnectToUnixSocket(socketPath)) {
+ throw new Error(`Daemon socket already in use: ${socketPath}`);
+ }
+ const releaseLock = await lockfile.lock(socketPath, {
+ realpath: false,
+ stale: DAEMON_SOCKET_LOCK_STALE_MS,
+ update: DAEMON_SOCKET_LOCK_UPDATE_MS,
+ retries: {
+ retries: 600,
+ factor: 1,
+ minTimeout: DAEMON_SOCKET_RELEASE_POLL_MS,
+ maxTimeout: DAEMON_SOCKET_RELEASE_POLL_MS,
+ },
+ });
+ try {
+ await prepareUnixDaemonSocketPath(socketPath);
+ } finally {
+ await releaseLock();
+ }
+}
+
+async function prepareUnixDaemonSocketPath(socketPath: string): Promise<void> {
+ if (!existsSync(socketPath)) {
return;
}
- const stat = lstatSync(socketPath);
+ let stat: ReturnType<typeof lstatSync>;
+ try {
+ stat = lstatSync(socketPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ return;
+ }
+ throw error;
+ }
if (!stat.isSocket()) {
throw new Error(`Daemon socket path exists and is not a socket: ${socketPath}`);
}
+ const staleIdentity: DaemonSocketIdentity = { dev: stat.dev, ino: stat.ino };
if (await canConnectToUnixSocket(socketPath)) {
throw new Error(`Daemon socket already in use: ${socketPath}`);
}
+ const deadline = Date.now() + DAEMON_SOCKET_RELEASE_GRACE_MS;
+ while (Date.now() < deadline) {
+ await delay(DAEMON_SOCKET_RELEASE_POLL_MS);
+ if (!existsSync(socketPath)) {
+ return;
+ }
+ let currentIdentity: DaemonSocketIdentity | undefined;
+ try {
+ currentIdentity = getDaemonSocketIdentity(socketPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ return;
+ }
+ throw error;
+ }
+ if (!currentIdentity || currentIdentity.dev !== staleIdentity.dev || currentIdentity.ino !== staleIdentity.ino) {
+ throw new Error(`Daemon socket changed ownership while waiting for cleanup: ${socketPath}`);
+ }
+ if (await canConnectToUnixSocket(socketPath)) {
+ throw new Error(`Daemon socket already in use: ${socketPath}`);
+ }
+ }
unlinkSync(socketPath);
}
@@ -39,16 +108,52 @@ export function restrictDaemonSocketPath(socketPath: string): void {
chmodSync(socketPath, DAEMON_SOCKET_MODE);
}
-export function cleanupDaemonSocketPath(socketPath: string): void {
+export function getDaemonSocketIdentity(socketPath: string): DaemonSocketIdentity | undefined {
+ if (process.platform === "win32") {
+ return undefined;
+ }
+ const stat = lstatSync(socketPath);
+ return { dev: stat.dev, ino: stat.ino };
+}
+
+export function cleanupDaemonSocketPath(socketPath: string, expectedIdentity?: DaemonSocketIdentity): void {
if (process.platform === "win32") {
return;
}
+ let releaseLock: (() => void) | undefined;
try {
- if (existsSync(socketPath)) {
- unlinkSync(socketPath);
+ releaseLock = lockfile.lockSync(socketPath, {
+ realpath: false,
+ stale: DAEMON_SOCKET_LOCK_STALE_MS,
+ update: DAEMON_SOCKET_LOCK_UPDATE_MS,
+ retries: 0,
+ });
+ } catch {
+ return;
+ }
+ try {
+ if (!existsSync(socketPath)) {
+ return;
+ }
+ if (expectedIdentity) {
+ const currentIdentity = getDaemonSocketIdentity(socketPath);
+ if (
+ !currentIdentity ||
+ currentIdentity.dev !== expectedIdentity.dev ||
+ currentIdentity.ino !== expectedIdentity.ino
+ ) {
+ return;
+ }
}
+ unlinkSync(socketPath);
} catch {
// Best effort cleanup; shutdown should not be blocked by socket unlink failures.
+ } finally {
+ try {
+ releaseLock();
+ } catch {
+ // Best effort cleanup; a failed release is recoverable as a stale lock.
+ }
}
}
@@ -102,3 +207,7 @@ function canConnectToUnixSocket(socketPath: string): Promise<boolean> {
socket.once("error", () => finish(false));
});
}
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index be17b3eee9..0b903530aa 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -1,6 +1,6 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import { getModel } from "@earendil-works/pi-ai";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { MissingSessionCwdError } from "../src/core/session-cwd.js";
import { SessionImportFileNotFoundError } from "../src/core/session-import-errors.js";
import {
@@ -12,11 +12,13 @@ import type {
AgentConnectionSavedSessionInfo,
AgentConnectionState,
} from "../src/modes/agent-connection/types.js";
-import type {
- DaemonClient,
- DaemonClientCloseListener,
- DaemonClientMessageListener,
- DaemonClientRequestOptions,
+
+import {
+ type DaemonClient,
+ type DaemonClientCloseListener,
+ type DaemonClientMessageListener,
+ type DaemonClientRequestOptions,
+ DaemonSocketClosedError,
} from "../src/modes/daemon/daemon-client.js";
import {
DAEMON_PROTOCOL_INFO,
@@ -30,9 +32,16 @@ class FakeDaemonClient {
readonly requests: DaemonCommand[] = [];
readonly requestTimeouts: number[] = [];
attachResultFactory: ((command: Extract<DaemonCommand, { type: "attach" }>) => DaemonAttachResult) | undefined;
+ restoredAttachGate: Promise<void> | undefined;
+ restoredAttachCompleted = 0;
closeCount = 0;
+ emitCloseOnClose = false;
+ connected = true;
+ reconnectCount = 0;
+ reconnectError: Error | undefined;
abortBashUnknownCommand = false;
abortAndClearQueueUnknownCommand = false;
+ updateRestartSessions: Array<Record<string, unknown>> = [];
private readonly messageListeners = new Set<DaemonClientMessageListener>();
private readonly closeListeners = new Set<DaemonClientCloseListener>();
@@ -44,7 +53,18 @@ class FakeDaemonClient {
this.requests.push(command);
this.requestTimeouts.push(timeoutMs);
switch (command.type) {
+ case "list":
+ return {
+ type: "response",
+ command: command.type,
+ success: true,
+ data: { sessions: this.updateRestartSessions },
+ };
case "attach":
+ if (command.activeSessionId === "active-restored" && this.restoredAttachGate) {
+ await this.restoredAttachGate;
+ this.restoredAttachCompleted++;
+ }
if (command.activeSessionId === "missing") {
return {
type: "response",
@@ -356,6 +376,23 @@ class FakeDaemonClient {
}
}
+ emitClose(error: Error): void {
+ for (const listener of [...this.closeListeners]) {
+ listener(error);
+ }
+ }
+
+ async reconnect(): Promise<void> {
+ if (this.connected) {
+ return;
+ }
+ this.reconnectCount++;
+ if (this.reconnectError) {
+ throw this.reconnectError;
+ }
+ this.connected = true;
+ }
+
getMessageListenerCount(): number {
return this.messageListeners.size;
}
@@ -366,6 +403,16 @@ class FakeDaemonClient {
close(): void {
this.closeCount++;
+ this.connected = false;
+ if (this.emitCloseOnClose) {
+ this.emitClose(new Error("Daemon socket closed"));
+ }
+ }
+
+ disconnectForReconnect(reason: "shutdown" | "update"): void {
+ this.closeCount++;
+ this.connected = false;
+ this.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", reason));
}
}
@@ -503,6 +550,419 @@ function emitSequencedQueueUpdate(client: FakeDaemonClient, activeSessionId: str
}
describe("DaemonAgentConnection", () => {
+ it("reattaches an open window to its restored session after an update restart", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.emitCloseOnClose = true;
+ const restoredMessages: AgentMessage[] = [{ role: "user", content: "restored prompt", timestamp: 2 }];
+ fakeClient.updateRestartSessions = [
+ {
+ id: "active-restored",
+ activeSessionId: "active-restored",
+ sessionId: "session-current",
+ sessionFile: "/tmp/session-current.jsonl",
+ },
+ ];
+ fakeClient.attachResultFactory = (command) =>
+ createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 1, {
+ state: createConnectionState(command.activeSessionId, "session-current"),
+ messages: command.activeSessionId === "active-restored" ? restoredMessages : [],
+ });
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const events: AgentConnectionEvent[] = [];
+ const restored = new Promise<AgentConnectionEvent>((resolve) => {
+ connection.subscribe((event) => {
+ events.push(event);
+ if (event.type === "session_replaced") {
+ resolve(event);
+ }
+ });
+ });
+ await connection.attach();
+
+ fakeClient.emitMessage({
+ type: "session_closed",
+ activeSessionId: "active-original",
+ reason: "update",
+ });
+ await Promise.resolve();
+ expect(fakeClient.closeCount).toBe(1);
+ expect(fakeClient.reconnectCount).toBe(1);
+
+ await expect(restored).resolves.toMatchObject({
+ type: "session_replaced",
+ state: { activeSessionId: "active-restored", sessionId: "session-current" },
+ messages: restoredMessages,
+ });
+ expect(fakeClient.reconnectCount).toBe(1);
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["attach", "list", "attach"]);
+ expect(fakeClient.requests.at(-1)).toMatchObject({
+ type: "attach",
+ activeSessionId: "active-restored",
+ resumeCursor: undefined,
+ });
+ expect(events).toEqual([
+ expect.objectContaining({
+ type: "session_replaced",
+ state: expect.objectContaining({ activeSessionId: "active-restored" }),
+ }),
+ ]);
+ });
+
+ it("reattaches when an update socket close arrives before the session notice", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const restoredMessages: AgentMessage[] = [{ role: "user", content: "restored prompt", timestamp: 2 }];
+ fakeClient.updateRestartSessions = [
+ {
+ id: "active-restored",
+ activeSessionId: "active-restored",
+ sessionId: "session-current",
+ sessionFile: "/tmp/session-current.jsonl",
+ },
+ ];
+ fakeClient.attachResultFactory = (command) =>
+ createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 1, {
+ state: createConnectionState(command.activeSessionId, "session-current"),
+ messages: command.activeSessionId === "active-restored" ? restoredMessages : [],
+ });
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const restored = new Promise<AgentConnectionEvent>((resolve) => {
+ connection.subscribe((event) => {
+ if (event.type === "session_replaced") {
+ resolve(event);
+ }
+ });
+ });
+ await connection.attach();
+
+ fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "update"));
+
+ await expect(restored).resolves.toMatchObject({
+ type: "session_replaced",
+ state: { activeSessionId: "active-restored", sessionId: "session-current" },
+ messages: restoredMessages,
+ });
+ expect(fakeClient.reconnectCount).toBe(1);
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["attach", "list", "attach"]);
+ });
+
+ it("coordinates one transport reconnect across connections sharing a daemon client", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.emitCloseOnClose = true;
+ fakeClient.updateRestartSessions = [
+ {
+ id: "restored-a",
+ activeSessionId: "restored-a",
+ sessionId: "session-a",
+ sessionFile: "/tmp/session-a.jsonl",
+ },
+ {
+ id: "restored-b",
+ activeSessionId: "restored-b",
+ sessionId: "session-b",
+ sessionFile: "/tmp/session-b.jsonl",
+ },
+ ];
+ const sessionIds: Record<string, string> = {
+ "active-a": "session-a",
+ "active-b": "session-b",
+ "restored-a": "session-a",
+ "restored-b": "session-b",
+ };
+ fakeClient.attachResultFactory = (command) =>
+ createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 1, {
+ state: createConnectionState(command.activeSessionId, sessionIds[command.activeSessionId]!),
+ });
+ const connectionA = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-a");
+ const connectionB = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-b");
+ await connectionA.attach();
+ await connectionB.attach();
+ const restoredA = new Promise<AgentConnectionEvent>((resolve) => {
+ connectionA.subscribe((event) => {
+ if (event.type === "session_replaced") {
+ resolve(event);
+ }
+ });
+ });
+ const restoredB = new Promise<AgentConnectionEvent>((resolve) => {
+ connectionB.subscribe((event) => {
+ if (event.type === "session_replaced") {
+ resolve(event);
+ }
+ });
+ });
+
+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "active-a", reason: "update" });
+
+ await expect(Promise.all([restoredA, restoredB])).resolves.toEqual([
+ expect.objectContaining({
+ type: "session_replaced",
+ state: expect.objectContaining({ sessionId: "session-a" }),
+ }),
+ expect.objectContaining({
+ type: "session_replaced",
+ state: expect.objectContaining({ sessionId: "session-b" }),
+ }),
+ ]);
+ expect(fakeClient.closeCount).toBe(1);
+ expect(fakeClient.reconnectCount).toBe(1);
+ });
+
+ it("does not reconnect after an explicit shutdown session close", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const closedEvents: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ if (event.type === "closed") {
+ closedEvents.push(event);
+ }
+ });
+ await connection.attach();
+
+ fakeClient.emitMessage({
+ type: "session_closed",
+ activeSessionId: "active-original",
+ reason: "shutdown",
+ });
+ fakeClient.emitClose(new Error("Daemon socket closed"));
+ await Promise.resolve();
+
+ expect(fakeClient.reconnectCount).toBe(0);
+ expect(closedEvents).toHaveLength(1);
+ expect(closedEvents[0]).toMatchObject({
+ type: "closed",
+ error: expect.stringContaining("The Prime Agent daemon shut down while this window was attached."),
+ });
+ const closedError = closedEvents[0]?.type === "closed" ? closedEvents[0].error : undefined;
+ expect(closedError).toContain("Session ID: session-current.");
+ expect(closedError).toContain("Session file: /tmp/session-current.jsonl.");
+ expect(closedError).toContain("Diagnostic log:");
+ });
+
+ it("does not infer an update when shutdown closes the socket before the session notice", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const closedEvents: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ if (event.type === "closed") {
+ closedEvents.push(event);
+ }
+ });
+ await connection.attach();
+
+ fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "shutdown"));
+ await Promise.resolve();
+
+ expect(fakeClient.reconnectCount).toBe(0);
+ expect(closedEvents).toHaveLength(1);
+ const closedError = closedEvents[0]?.type === "closed" ? closedEvents[0].error : undefined;
+ expect(closedError).toContain("The Prime Agent daemon shut down while this window was attached.");
+ });
+
+ it.each([
+ ["killed", "The daemon stopped this agent session."],
+ ["completed", "The daemon closed this agent session after it completed."],
+ ["replaced", "The daemon replaced this agent session with another session."],
+ ] as const)("explains a %s session close instead of exposing the raw reason", async (reason, explanation) => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const closedEvents: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ if (event.type === "closed") {
+ closedEvents.push(event);
+ }
+ });
+ await connection.attach();
+
+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "active-original", reason });
+ await Promise.resolve();
+
+ expect(closedEvents).toHaveLength(1);
+ const closedError = closedEvents[0]?.type === "closed" ? closedEvents[0].error : undefined;
+ expect(closedError).toContain(explanation);
+ expect(closedError).not.toBe(reason);
+ expect(closedError).toContain("Session ID: session-current.");
+ });
+
+ it("adds recovery and diagnostic context to unexpected daemon disconnects", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const closedEvents: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ if (event.type === "closed") {
+ closedEvents.push(event);
+ }
+ });
+ await connection.attach();
+
+ fakeClient.emitClose(new Error("ECONNRESET"));
+ await Promise.resolve();
+
+ expect(closedEvents).toHaveLength(1);
+ const closedError = closedEvents[0]?.type === "closed" ? closedEvents[0].error : undefined;
+ expect(closedError).toContain("Lost connection to the Prime Agent daemon. Cause: ECONNRESET");
+ expect(closedError).toContain("restart Prime Agent or reopen the session from Agents View");
+ expect(closedError).toContain("Session file: /tmp/session-current.jsonl.");
+ expect(closedError).toContain("Diagnostic log:");
+ });
+
+ it("reports an unannounced clean socket close without treating it as an update", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const closedEvents: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ if (event.type === "closed") {
+ closedEvents.push(event);
+ }
+ });
+ await connection.attach();
+
+ fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock"));
+ await Promise.resolve();
+
+ expect(fakeClient.reconnectCount).toBe(0);
+ expect(closedEvents).toHaveLength(1);
+ const closedError = closedEvents[0]?.type === "closed" ? closedEvents[0].error : undefined;
+ expect(closedError).toContain("Lost connection to the Prime Agent daemon.");
+ });
+
+ it("does not emit a restored session after disposal begins", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.updateRestartSessions = [
+ {
+ id: "active-restored",
+ activeSessionId: "active-restored",
+ sessionId: "session-current",
+ sessionFile: "/tmp/session-current.jsonl",
+ },
+ ];
+ let releaseRestoredAttach: (() => void) | undefined;
+ fakeClient.restoredAttachGate = new Promise<void>((resolve) => {
+ releaseRestoredAttach = resolve;
+ });
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ events.push(event);
+ });
+ await connection.attach();
+
+ fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "update"));
+ await vi.waitFor(() => {
+ expect(
+ fakeClient.requests.some(
+ (request) => request.type === "attach" && request.activeSessionId === "active-restored",
+ ),
+ ).toBe(true);
+ });
+ await connection.dispose();
+ releaseRestoredAttach?.();
+ await vi.waitFor(() => {
+ expect(fakeClient.restoredAttachCompleted).toBe(1);
+ });
+ for (let flush = 0; flush < 5; flush++) {
+ await Promise.resolve();
+ }
+
+ expect(events).toEqual([]);
+ expect(fakeClient.requests.at(-1)).toMatchObject({ type: "detach", activeSessionId: "active-restored" });
+ });
+
+ it("returns to normal close handling after update restoration times out", async () => {
+ vi.useFakeTimers();
+ try {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.reconnectError = new Error("daemon unavailable");
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const closedEvents: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ if (event.type === "closed") {
+ closedEvents.push(event);
+ }
+ });
+ await connection.attach();
+
+ fakeClient.emitMessage({
+ type: "session_closed",
+ activeSessionId: "active-original",
+ reason: "update",
+ });
+ await vi.advanceTimersByTimeAsync(120100);
+
+ expect(closedEvents).toHaveLength(1);
+ const closedError = closedEvents[0]?.type === "closed" ? closedEvents[0].error : undefined;
+ expect(closedError).toContain(
+ "The Prime Agent daemon restarted for an update, but this window could not reconnect",
+ );
+ expect(closedError).toContain("Last error: daemon unavailable");
+ expect(closedError).toContain("restart Prime Agent and reopen it from Agents View");
+ expect(closedError).toContain("Session ID: session-current.");
+ expect(closedError).toContain("Session file: /tmp/session-current.jsonl.");
+ expect(closedError).toContain("Diagnostic log:");
+ const reconnectCountAfterFailure = fakeClient.reconnectCount;
+ fakeClient.emitClose(new Error("Daemon socket closed"));
+ await Promise.resolve();
+
+ expect(fakeClient.reconnectCount).toBe(reconnectCountAfterFailure);
+ expect(closedEvents).toHaveLength(1);
+ await connection.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("reattaches using the replacement session identity after a session switch", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const restoredMessages: AgentMessage[] = [{ role: "user", content: "switched prompt", timestamp: 3 }];
+ fakeClient.updateRestartSessions = [
+ {
+ id: "active-restored",
+ activeSessionId: "active-restored",
+ sessionId: "session-next",
+ sessionFile: "/tmp/session-next.jsonl",
+ },
+ ];
+ fakeClient.attachResultFactory = (command) => {
+ const sessionId = command.activeSessionId === "active-restored" ? "session-next" : "session-current";
+ return createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 1, {
+ state: createConnectionState(command.activeSessionId, sessionId),
+ messages: command.activeSessionId === "active-restored" ? restoredMessages : [],
+ });
+ };
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ await connection.attach();
+ fakeClient.emitMessage({
+ type: "session_replaced",
+ activeSessionId: "active-original",
+ state: createConnectionState("active-original", "session-next"),
+ messages: [{ role: "user", content: "switched prompt", timestamp: 2 }],
+ });
+
+ const restored = new Promise<AgentConnectionEvent>((resolve) => {
+ connection.subscribe((event) => {
+ if (event.type === "session_replaced") {
+ resolve(event);
+ }
+ });
+ });
+ fakeClient.emitMessage({
+ type: "session_closed",
+ activeSessionId: "active-original",
+ reason: "update",
+ });
+ fakeClient.emitClose(new Error("Daemon socket closed"));
+
+ await expect(restored).resolves.toMatchObject({
+ type: "session_replaced",
+ state: { activeSessionId: "active-restored", sessionId: "session-next" },
+ messages: restoredMessages,
+ });
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["attach", "list", "attach"]);
+ expect(fakeClient.requests.at(-1)).toMatchObject({
+ type: "attach",
+ activeSessionId: "active-restored",
+ });
+ });
+
it("loads connection state and forwards replacement snapshots through the daemon protocol", async () => {
const fakeClient = new FakeDaemonClient();
const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index d15d6e41ba..f333429cbc 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -17,6 +17,7 @@ import {
resolveAgentsViewOpenCwd,
resolveAgentsViewResumeSummary,
resolveAgentsViewSessionUiServices,
+ shouldReconnectAgentsViewDaemon,
} from "../src/modes/agents-view/agents-view-mode.js";
import {
buildAgentsViewRows,
@@ -609,6 +610,12 @@ describe("agents view state", () => {
expect(formatAgentsViewStatusLine("\n \r\n ")).toBe("");
});
+ test("reconnects daemon restarts and crashes but stops after an intentional shutdown", () => {
+ expect(shouldReconnectAgentsViewDaemon("update")).toBe(true);
+ expect(shouldReconnectAgentsViewDaemon(undefined)).toBe(true);
+ expect(shouldReconnectAgentsViewDaemon("shutdown")).toBe(false);
+ });
+
test("caps generated session names at the configured limit", () => {
expect(createAgentsViewSessionName("x".repeat(120))).toHaveLength(80);
expect(createAgentsViewSessionName("short")).toBe("short");
diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.ts
index c715bc03d7..507b95a874 100644
--- a/packages/coding-agent/test/daemon-client.test.ts
+++ b/packages/coding-agent/test/daemon-client.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { DaemonClient } from "../src/modes/daemon/daemon-client.js";
+import { DaemonClient, getDaemonSocketCloseReason } from "../src/modes/daemon/daemon-client.js";
const netMock = vi.hoisted(() => {
type Listener = (...args: unknown[]) => void;
@@ -106,7 +106,10 @@ describe("DaemonClient", () => {
firstSocket.emit("error", new Error("initial connect failed"));
- await expect(firstAttempt).resolves.toMatchObject({ message: "initial connect failed" });
+ const firstError = await firstAttempt;
+ expect(firstError.message).toContain("Failed to connect to the Prime Agent daemon: initial connect failed.");
+ expect(firstError.message).toContain("Socket: /tmp/prime-agent-missing.sock.");
+ expect(firstError.message).toContain("Daemon log:");
expect(firstSocket.listenerCount("data")).toBe(0);
expect(firstSocket.listenerCount("end")).toBe(0);
@@ -114,7 +117,9 @@ describe("DaemonClient", () => {
expect(netMock.sockets).toHaveLength(2);
netMock.sockets[1]!.emit("error", new Error("retry reached socket"));
- await expect(secondAttempt).resolves.toMatchObject({ message: "retry reached socket" });
+ await expect(secondAttempt).resolves.toMatchObject({
+ message: expect.stringContaining("Failed to connect to the Prime Agent daemon: retry reached socket."),
+ });
});
it("allows connect retry after the initial connection times out", async () => {
@@ -126,7 +131,7 @@ describe("DaemonClient", () => {
const firstSocket = netMock.sockets[0]!;
const timeoutRejection = expect(firstAttempt).resolves.toMatchObject({
- message: "Timed out connecting to daemon socket: /tmp/prime-agent-slow.sock",
+ message: expect.stringContaining("Timed out after 5ms connecting to the Prime Agent daemon."),
});
await vi.advanceTimersByTimeAsync(5);
await timeoutRejection;
@@ -139,7 +144,9 @@ describe("DaemonClient", () => {
expect(netMock.sockets).toHaveLength(2);
netMock.sockets[1]!.emit("error", new Error("retry reached socket"));
- await expect(secondAttempt).resolves.toMatchObject({ message: "retry reached socket" });
+ await expect(secondAttempt).resolves.toMatchObject({
+ message: expect.stringContaining("Failed to connect to the Prime Agent daemon: retry reached socket."),
+ });
});
it("captures the daemon hello greeting for version checks", async () => {
@@ -224,6 +231,24 @@ describe("DaemonClient", () => {
client.close();
});
+ it("includes command, socket, and log context when a request is made while disconnected", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+
+ const request = client.request({ type: "list", all: true });
+
+ await expect(request).rejects.toMatchObject({
+ message: expect.stringContaining(
+ 'Cannot send daemon command "list" because the Prime Agent daemon is not connected.',
+ ),
+ });
+ await expect(request).rejects.toMatchObject({
+ message: expect.stringContaining("Socket: /tmp/prime-agent.sock."),
+ });
+ await expect(request).rejects.toMatchObject({
+ message: expect.stringContaining("Daemon log:"),
+ });
+ });
+
it("routes request progress by response id without notifying general listeners", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
@@ -377,23 +402,68 @@ describe("DaemonClient", () => {
it("notifies listeners when a connected daemon socket closes", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
+ expect(client.isConnected).toBe(false);
const connect = client.connect();
expect(netMock.sockets).toHaveLength(1);
const socket = netMock.sockets[0]!;
socket.emit("connect");
await connect;
+ expect(client.isConnected).toBe(true);
const closed: Error[] = [];
const unsubscribe = client.onClose((error) => closed.push(error));
socket.emit("close");
- expect(closed.map((error) => error.message)).toEqual(["Daemon socket closed"]);
+ expect(closed).toHaveLength(1);
+ expect(closed[0]?.message).toContain("Connection to the Prime Agent daemon closed.");
+ expect(closed[0]?.message).toContain("Socket: /tmp/prime-agent.sock.");
+ expect(closed[0]?.message).toContain("Daemon log:");
+ expect(client.isConnected).toBe(false);
unsubscribe();
client.close();
});
+ it.each(["shutdown", "update"] as const)("preserves the daemon %s reason on socket close", async (reason) => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+
+ const closed: Error[] = [];
+ client.onClose((error) => closed.push(error));
+ socket.emit("data", `${JSON.stringify({ type: "daemon_closing", reason })}\n`);
+ socket.emit("close");
+
+ expect(closed).toHaveLength(1);
+ expect(getDaemonSocketCloseReason(closed[0]!)).toBe(reason);
+ expect(closed[0]?.message).toContain(`Reason: ${reason}.`);
+ client.close();
+ });
+
+ it("notifies every listener before disconnecting a shared client for update reconnect", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+
+ const firstClosed: Error[] = [];
+ const secondClosed: Error[] = [];
+ client.onClose((error) => firstClosed.push(error));
+ client.onClose((error) => secondClosed.push(error));
+
+ client.disconnectForReconnect("update");
+
+ expect(client.isConnected).toBe(false);
+ expect(firstClosed).toHaveLength(1);
+ expect(secondClosed).toHaveLength(1);
+ expect(getDaemonSocketCloseReason(firstClosed[0]!)).toBe("update");
+ expect(getDaemonSocketCloseReason(secondClosed[0]!)).toBe("update");
+ });
+
it("notifies listeners once when a socket error is followed by close", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
@@ -434,6 +504,25 @@ describe("DaemonClient", () => {
client.close();
});
+
+ it("shares one reconnect attempt across concurrent callers", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+
+ const firstConnect = client.connect();
+ const firstSocket = netMock.sockets[0]!;
+ firstSocket.emit("connect");
+ await firstConnect;
+ firstSocket.emit("close");
+
+ const reconnectA = client.reconnect();
+ const reconnectB = client.reconnect();
+ expect(netMock.sockets).toHaveLength(2);
+ const secondSocket = netMock.sockets[1]!;
+ secondSocket.emit("connect");
+
+ await expect(Promise.all([reconnectA, reconnectB])).resolves.toEqual([undefined, undefined]);
+ client.close();
+ });
});
async function captureRejection(promise: Promise<void>): Promise<Error> {
diff --git a/packages/coding-agent/test/daemon-launch.test.ts b/packages/coding-agent/test/daemon-launch.test.ts
index d7c9628a71..9b448d8fa0 100644
--- a/packages/coding-agent/test/daemon-launch.test.ts
+++ b/packages/coding-agent/test/daemon-launch.test.ts
@@ -1,4 +1,5 @@
-import { mkdtempSync, rmSync } from "node:fs";
+import { spawn } from "node:child_process";
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { createServer, type Server, type Socket } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -71,6 +72,51 @@ async function startFakeDaemon(options: FakeDaemonOptions = {}): Promise<FakeDae
};
}
+async function startCrashingDaemon(): Promise<FakeDaemon> {
+ const dir = mkdtempSync(join(tmpdir(), "pa-launch-crash-"));
+ const socketPath = join(dir, "d.sock");
+ const child = spawn(
+ process.execPath,
+ [
+ "-e",
+ `const { createServer } = require("node:net");
+const socketPath = process.argv[1];
+const send = (socket, message) => socket.write(JSON.stringify(message) + "\\n");
+const server = createServer((socket) => {
+ send(socket, { type: "daemon_hello", socketPath, protocol: { name: "prime-agent-daemon", version: 1 } });
+ let buffer = "";
+ socket.on("data", (chunk) => {
+ buffer += chunk.toString();
+ const newline = buffer.indexOf("\\n");
+ if (newline === -1) return;
+ const command = JSON.parse(buffer.slice(0, newline));
+ if (command.type !== "shutdown") return;
+ send(socket, { type: "response", command: "shutdown", id: command.id, success: true });
+ socket.end(() => process.kill(process.pid, "SIGKILL"));
+ });
+});
+server.listen(socketPath, () => process.stdout.write("ready\\n"));`,
+ socketPath,
+ ],
+ { stdio: ["ignore", "pipe", "ignore"] },
+ );
+ await new Promise<void>((resolve, reject) => {
+ child.stdout?.once("data", () => resolve());
+ child.once("error", reject);
+ child.once("exit", (code, signal) => reject(new Error(`Daemon exited before listening: ${code ?? signal}`)));
+ });
+ return {
+ socketPath,
+ close: async () => {
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill("SIGKILL");
+ await new Promise<void>((resolve) => child.once("close", () => resolve()));
+ }
+ rmSync(dir, { recursive: true, force: true });
+ },
+ };
+}
+
describe("probeRunningDaemonSessions", () => {
const cleanups: Array<() => Promise<void>> = [];
afterEach(async () => {
@@ -127,4 +173,15 @@ describe("shutdownDaemonAndWait", () => {
cleanups.push(daemon.close);
expect(await shutdownDaemonAndWait(daemon.socketPath)).toBe(true);
});
+
+ it("accepts an exited daemon that leaves a stale socket behind", async () => {
+ if (process.platform === "win32") {
+ return;
+ }
+
+ const daemon = await startCrashingDaemon();
+ cleanups.push(daemon.close);
+ expect(await shutdownDaemonAndWait(daemon.socketPath, 100)).toBe(true);
+ expect(existsSync(daemon.socketPath)).toBe(true);
+ });
});
diff --git a/packages/coding-agent/test/daemon-socket.test.ts b/packages/coding-agent/test/daemon-socket.test.ts
index cbb8cbeb09..e1c8e220d3 100644
--- a/packages/coding-agent/test/daemon-socket.test.ts
+++ b/packages/coding-agent/test/daemon-socket.test.ts
@@ -1,7 +1,16 @@
+import { spawn } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, unlinkSync } from "node:fs";
+import { createConnection, createServer } from "node:net";
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
+import lockfile from "proper-lockfile";
import { describe, expect, it } from "vitest";
-import { defaultDaemonSocketPath } from "../src/modes/daemon/daemon-socket.js";
+import {
+ cleanupDaemonSocketPath,
+ defaultDaemonSocketPath,
+ getDaemonSocketIdentity,
+ prepareDaemonSocketPath,
+} from "../src/modes/daemon/daemon-socket.js";
describe("defaultDaemonSocketPath", () => {
it("uses a fixed Windows named pipe path", () => {
@@ -23,4 +32,217 @@ describe("defaultDaemonSocketPath", () => {
expect(dirname(socketPath)).toBe(join(tmpdir(), `prime-agent-${suffix}`));
expect(basename(socketPath)).toBe("daemon.sock");
});
+
+ it("checks a live daemon before acquiring the socket path lock", async () => {
+ if (process.platform === "win32") {
+ return;
+ }
+
+ const dir = mkdtempSync(join(tmpdir(), "pa-socket-live-"));
+ const socketPath = join(dir, "daemon.sock");
+ let observedLock: boolean | undefined;
+ const server = createServer((socket) => {
+ observedLock = existsSync(`${socketPath}.lock`);
+ socket.destroy();
+ });
+ try {
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(socketPath, resolve);
+ });
+
+ await expect(prepareDaemonSocketPath(socketPath)).rejects.toThrow(/socket already in use/i);
+ expect(observedLock).toBe(false);
+ } finally {
+ if (server.listening) {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("does not wait on a stale lock when no socket path exists", async () => {
+ if (process.platform === "win32") {
+ return;
+ }
+
+ const dir = mkdtempSync(join(tmpdir(), "pa-socket-stale-lock-"));
+ const socketPath = join(dir, "daemon.sock");
+ mkdirSync(`${socketPath}.lock`);
+ let prepared = false;
+ try {
+ await Promise.race([
+ prepareDaemonSocketPath(socketPath).then(() => {
+ prepared = true;
+ }),
+ new Promise<void>((resolve) => setTimeout(resolve, 250)),
+ ]);
+ expect(prepared).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("does not unlink a replacement daemon's socket during delayed cleanup", async () => {
+ if (process.platform === "win32") {
+ return;
+ }
+
+ const dir = mkdtempSync(join(tmpdir(), "pa-socket-ownership-"));
+ const socketPath = join(dir, "daemon.sock");
+ const oldServer = createServer();
+ const replacementServer = createServer();
+ try {
+ await new Promise<void>((resolve, reject) => {
+ oldServer.once("error", reject);
+ oldServer.listen(socketPath, resolve);
+ });
+ const oldIdentity = getDaemonSocketIdentity(socketPath);
+ if (!oldIdentity) {
+ throw new Error("Expected a Unix daemon socket identity");
+ }
+
+ unlinkSync(socketPath);
+ await new Promise<void>((resolve, reject) => {
+ replacementServer.once("error", reject);
+ replacementServer.listen(socketPath, resolve);
+ });
+
+ cleanupDaemonSocketPath(socketPath, oldIdentity);
+
+ await expect(
+ new Promise<void>((resolve, reject) => {
+ const client = createConnection(socketPath);
+ client.once("connect", () => {
+ client.destroy();
+ resolve();
+ });
+ client.once("error", reject);
+ }),
+ ).resolves.toBeUndefined();
+ } finally {
+ await Promise.all(
+ [oldServer, replacementServer].map(
+ (server) =>
+ new Promise<void>((resolve) => {
+ server.close(() => resolve());
+ }),
+ ),
+ );
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("does not unlink a socket while another daemon owns the path lock", async () => {
+ if (process.platform === "win32") {
+ return;
+ }
+
+ const dir = mkdtempSync(join(tmpdir(), "pa-socket-lock-"));
+ const socketPath = join(dir, "daemon.sock");
+ const server = createServer();
+ let releaseLock: (() => Promise<void>) | undefined;
+ try {
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(socketPath, resolve);
+ });
+ const identity = getDaemonSocketIdentity(socketPath);
+ if (!identity) {
+ throw new Error("Expected a Unix daemon socket identity");
+ }
+ releaseLock = await lockfile.lock(socketPath, { realpath: false });
+
+ cleanupDaemonSocketPath(socketPath, identity);
+
+ await expect(
+ new Promise<void>((resolve, reject) => {
+ const client = createConnection(socketPath);
+ client.once("connect", () => {
+ client.destroy();
+ resolve();
+ });
+ client.once("error", reject);
+ }),
+ ).resolves.toBeUndefined();
+ } finally {
+ await releaseLock?.();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("does not remove a replacement socket that appears while stale cleanup is pending", async () => {
+ if (process.platform === "win32") {
+ return;
+ }
+
+ const dir = mkdtempSync(join(tmpdir(), "pa-socket-startup-"));
+ const socketPath = join(dir, "daemon.sock");
+ const staleOwner = spawn(
+ process.execPath,
+ [
+ "-e",
+ "const { createServer } = require('node:net'); const server = createServer(); server.listen(process.argv[1], () => process.stdout.write('ready'));",
+ socketPath,
+ ],
+ { stdio: ["ignore", "pipe", "ignore"] },
+ );
+ const replacementServer = createServer();
+ let replacementTimer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await new Promise<void>((resolve, reject) => {
+ staleOwner.stdout?.once("data", () => resolve());
+ staleOwner.once("error", reject);
+ staleOwner.once("exit", (code) => {
+ if (code !== null && code !== 0) {
+ reject(new Error(`Stale socket owner exited before listening: ${code}`));
+ }
+ });
+ });
+ staleOwner.kill("SIGKILL");
+ await new Promise<void>((resolve) => staleOwner.once("close", () => resolve()));
+ expect(existsSync(socketPath)).toBe(true);
+
+ const replacementListening = new Promise<void>((resolve, reject) => {
+ replacementTimer = setTimeout(() => {
+ try {
+ if (existsSync(socketPath)) {
+ unlinkSync(socketPath);
+ }
+ replacementServer.once("error", reject);
+ replacementServer.listen(socketPath, resolve);
+ } catch (error) {
+ reject(error);
+ }
+ }, 50);
+ });
+
+ await expect(prepareDaemonSocketPath(socketPath)).rejects.toThrow(
+ /socket (already in use|changed ownership)/i,
+ );
+ await replacementListening;
+ await expect(
+ new Promise<void>((resolve, reject) => {
+ const client = createConnection(socketPath);
+ client.once("connect", () => {
+ client.destroy();
+ resolve();
+ });
+ client.once("error", reject);
+ }),
+ ).resolves.toBeUndefined();
+ } finally {
+ if (replacementTimer) {
+ clearTimeout(replacementTimer);
+ }
+ if (staleOwner.exitCode === null && staleOwner.signalCode === null) {
+ staleOwner.kill("SIGKILL");
+ }
+ if (replacementServer.listening) {
+ await new Promise<void>((resolve) => replacementServer.close(() => resolve()));
+ }
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
});