Skip to content

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

Rust

fix(coding-agent): reconnect attached windows when the daemon restarts (#2458)

Seth Karten2e9ab77b87ab
diff --git a/packages/coding-agent/.changes/tui-daemon-reconnect.md b/packages/coding-agent/.changes/tui-daemon-reconnect.md
new file mode 100644
index 0000000000..f1c6d42c64
--- /dev/null
+++ b/packages/coding-agent/.changes/tui-daemon-reconnect.md
@@ -0,0 +1,3 @@
+- Attached TUI windows now recover automatically when the daemon restarts: a shutdown close polls the same socket path for the reconnect window (60s by default) and then re-attaches the session and refreshes the transcript instead of dying; if the daemon stays gone, the saved-transcript message remains.
+- Daemon update restarts now announce the update close reason on every attached window, so all windows (not just the one running /update) restore their sessions.
+- A one-line banner reports restart recoveries, and warns to restart the window when the restarted daemon is newer than this window's binary.
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 67c60fbbd8..a65ac61870 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
@@ -32,6 +32,7 @@ import {
collectDaemonClientEnv,
collectDaemonLaunchEnv,
type DaemonAttachResult,
+ type DaemonClosingReason,
type DaemonCommand,
type DaemonEventCursor,
type DaemonOutbound,
@@ -113,6 +114,22 @@ interface DaemonSnapshotAssembly {
timeout: ReturnType<typeof setTimeout>;
}
+interface DaemonRestartRestoreOptions {
+ /**
+ * Bound for reconnect and session discovery; the terminal close lands within
+ * it (discovery requests are capped to the remaining time). A found
+ * session's attach and snapshot may finish past it.
+ */
+ timeoutMs: number;
+ /** Poll delay between restore attempts. */
+ retryMs: number;
+ /**
+ * Update-restart recovery: an update close outranks a plain-shutdown
+ * recovery in flight, and the update flag clears on a restored session.
+ */
+ updateRestart?: boolean;
+}
+
export const DAEMON_REFINE_REQUEST_TIMEOUT_MS = 10 * 60 * 1000;
const DAEMON_LONG_RUNNING_REQUEST_TIMEOUT_MS = 24 * 60 * 60 * 1000;
export const DAEMON_RECONNECT_TIMEOUT_MS = 60_000;
@@ -123,6 +140,7 @@ const MAX_DEFERRED_SESSION_EVENTS = 1000;
const MAX_PENDING_EXTENSION_UI_REQUESTS = 128;
const UPDATE_RECONNECT_TIMEOUT_MS = 120000;
const UPDATE_RECONNECT_RETRY_MS = 100;
+const SHUTDOWN_RECONNECT_RETRY_MS = 100;
const MAX_COMPLETED_SNAPSHOTS = 128;
const OWNED_SESSION_DISPOSE_RECONNECT_WAIT_MS = 10_000;
const updateTransportReconnects = new WeakMap<DaemonTransportClient, Promise<void>>();
@@ -270,6 +288,10 @@ export class DaemonAgentConnection implements AgentConnection {
private updateReconnectFailed = false;
private terminalCloseEmitted = false;
private updateReconnectPromise?: Promise<void>;
+ private shutdownReconnectFailed = false;
+ private shutdownReconnectPromise?: Promise<void>;
+ /** Reason the daemon last announced itself closing; cleared once the connection is (re)established. */
+ private daemonClosingNotice?: DaemonClosingReason;
private readonly activeSideQuestionIds = new Set<string>();
private readonly snapshotAssemblies = new Map<string, DaemonSnapshotAssembly>();
private readonly completedSnapshots = new Map<string, DaemonSessionSnapshot>();
@@ -340,8 +362,19 @@ export class DaemonAgentConnection implements AgentConnection {
// An authoritative shutdown/update reason outranks the surviving direct link.
const closeReason = getDaemonSocketCloseReason(error);
if (closeReason === "shutdown") {
- this.terminalCloseEmitted = true;
- void this.emit({ type: "closed", error: this.formatDaemonSessionClosedError("shutdown") });
+ if (this.updateRestartPending) {
+ // An update-restart recovery already owns the transport; this close joins it.
+ void this.reconnectAfterUpdate();
+ return;
+ }
+ if (this.shutdownReconnectFailed) {
+ this.terminalCloseEmitted = true;
+ void this.emit({ type: "closed", error: this.formatDaemonSessionClosedError("shutdown") });
+ return;
+ }
+ // The daemon may come back (update coordinator, supervisor relaunch, manual
+ // restart): reconnect to the same socket path before declaring the window dead.
+ void this.reconnectAfterShutdown();
return;
}
if ((this.updateRestartPending || closeReason === "update") && !this.updateReconnectFailed) {
@@ -349,6 +382,11 @@ export class DaemonAgentConnection implements AgentConnection {
void this.reconnectAfterUpdate();
return;
}
+ if (this.shutdownReconnectPromise) {
+ // The shutdown recovery loop owns the transport; a transient close joins it
+ // instead of starting a second reconnect that would race the restore.
+ return;
+ }
// A direct-transport loss is never itself a session loss: fall back through a supervisor re-attach.
if (directSessionSurvives || error instanceof DaemonDirectTransportClosedError || this.options.recoverDaemon) {
void this.reconnect(error);
@@ -492,7 +530,9 @@ export class DaemonAgentConnection implements AgentConnection {
summary.sessionFile ?? ("snapshot" in result ? result.snapshot.state.sessionFile : undefined);
this.captureDaemonLogPath();
this.updateReconnectFailed = false;
+ this.shutdownReconnectFailed = false;
this.terminalCloseEmitted = false;
+ this.daemonClosingNotice = undefined;
// The roster bar is an accessory: its subscribe failure must never fail an
// otherwise-recovered session. The bar degrades; the next reconnect or rebind
// re-attaches through this same seam.
@@ -1796,7 +1836,16 @@ export class DaemonAgentConnection implements AgentConnection {
let deadline: number | undefined;
let attempt = 0;
let lastError: Error = cause;
- while (!this.disposed && !this.terminalCloseEmitted) {
+ // A shutdown-restart recovery outranks this loop: it owns the client, and
+ // this loop must not race its restore, neither while it runs (the promise)
+ // nor after it restored the session (the revision bump).
+ const startSessionRevision = this.sessionRevision;
+ while (
+ !this.disposed &&
+ !this.terminalCloseEmitted &&
+ !this.shutdownReconnectPromise &&
+ this.sessionRevision === startSessionRevision
+ ) {
// A held direct link owns session liveness: control-plane recovery retries unbounded,
// and the bounded session-plane deadline arms only once the direct link is gone.
const directSessionHeld = this.client instanceof DaemonRoutedClient && this.client.hasDirectTransport;
@@ -1864,7 +1913,12 @@ export class DaemonAgentConnection implements AgentConnection {
await new Promise((resolveDelay) => setTimeout(resolveDelay, delayMs));
}
}
- if (!this.disposed && !this.terminalCloseEmitted) {
+ if (
+ !this.disposed &&
+ !this.terminalCloseEmitted &&
+ !this.shutdownReconnectPromise &&
+ this.sessionRevision === startSessionRevision
+ ) {
this.sessionInputPauses.clear();
this.sessionInputPauseGeneration++;
this.client.close();
@@ -1907,6 +1961,12 @@ export class DaemonAgentConnection implements AgentConnection {
await this.emit({ type: "heartbeats_changed" });
return;
}
+ if (message.type === "daemon_closing") {
+ // An orderly daemon shutdown announces itself before it closes sessions: the
+ // notice distinguishes that shutdown from a bare session stop below.
+ this.daemonClosingNotice = message.reason;
+ return;
+ }
if (!this.isMessageForActiveSession(message)) {
return;
}
@@ -2076,6 +2136,17 @@ export class DaemonAgentConnection implements AgentConnection {
void this.reconnectAfterUpdate();
return;
}
+ const daemonShutdownClose =
+ this.daemonClosingNotice === "shutdown" && (message.reason === "shutdown" || message.reason === "killed");
+ if (daemonShutdownClose) {
+ // The daemon itself is going away (daemon_closing announced it): recover the
+ // window when it comes back. An orderly supervisor shutdown archive-stops its
+ // workers, so the relayed session_closed arrives with reason "killed"; the
+ // notice, not the close reason, separates this from a bare session stop.
+ this.captureDaemonLogPath();
+ void this.reconnectAfterShutdown();
+ return;
+ }
this.terminalCloseEmitted = true;
const error = this.formatDaemonSessionClosedError(message.reason);
this.rejectSnapshotAssemblies(new Error(error));
@@ -2139,9 +2210,14 @@ export class DaemonAgentConnection implements AgentConnection {
const reconnectPromise = reconnectDaemonTransportAfterUpdate(this.client)
.then(() => this.restoreConnectionAfterUpdate())
.then(() => {
- if (!this.disposed && !this.terminalCloseEmitted) {
- void this.emit({ type: "connection_status", status: "connected" });
+ if (this.disposed || this.terminalCloseEmitted) {
+ return;
}
+ void this.emit({
+ type: "connection_status",
+ status: "connected",
+ daemonVersion: this.client.hello?.appVersion,
+ });
})
.catch(async (error: unknown) => {
this.updateRestartPending = false;
@@ -2163,24 +2239,108 @@ export class DaemonAgentConnection implements AgentConnection {
return reconnectPromise;
}
- private async restoreConnectionAfterUpdate(): Promise<void> {
+ /**
+ * Recover a shutdown-closed window when the daemon comes back on the same
+ * socket path: re-handshake, re-attach the same session, and resync. Unlike
+ * update recovery this never relaunches the daemon (an explicit stop must
+ * stay stopped), so it only polls until the bound in options.reconnectTimeoutMs.
+ */
+ private reconnectAfterShutdown(): Promise<void> {
+ if (this.shutdownReconnectPromise) {
+ return this.shutdownReconnectPromise;
+ }
+ this.pendingExtensionUiRequests.length = 0;
+ void this.emit({
+ type: "connection_status",
+ status: "reconnecting",
+ error: "The Prime Agent daemon shut down; waiting for it to come back.",
+ });
+ const reconnectPromise = Promise.resolve()
+ .then(() => {
+ // Drop a direct link to a stopped worker so the restore routes over the supervisor.
+ this.client.disconnectForReconnect("shutdown");
+ })
+ .then(() =>
+ this.restoreConnectionAfterDaemonRestart({
+ timeoutMs: this.options.reconnectTimeoutMs ?? DAEMON_RECONNECT_TIMEOUT_MS,
+ retryMs: SHUTDOWN_RECONNECT_RETRY_MS,
+ }),
+ )
+ .then((restored) => {
+ // An update-restart recovery that took over owns the connected banner, even
+ // once its flag cleared: only a restore this loop performed reports one here.
+ if (!restored || this.disposed || this.terminalCloseEmitted || this.updateRestartPending) {
+ return;
+ }
+ void this.emit({
+ type: "connection_status",
+ status: "connected",
+ daemonVersion: this.client.hello?.appVersion,
+ });
+ })
+ .catch(async (_error: unknown) => {
+ this.shutdownReconnectFailed = true;
+ if (!this.disposed && !this.terminalCloseEmitted) {
+ this.terminalCloseEmitted = true;
+ await this.emit({ type: "closed", error: this.formatDaemonSessionClosedError("shutdown") });
+ }
+ })
+ .finally(() => {
+ if (this.shutdownReconnectPromise === reconnectPromise) {
+ this.shutdownReconnectPromise = undefined;
+ }
+ });
+ this.shutdownReconnectPromise = reconnectPromise;
+ return reconnectPromise;
+ }
+
+ private async restoreConnectionAfterUpdate(): Promise<boolean> {
+ return this.restoreConnectionAfterDaemonRestart({
+ timeoutMs: UPDATE_RECONNECT_TIMEOUT_MS,
+ retryMs: UPDATE_RECONNECT_RETRY_MS,
+ updateRestart: true,
+ });
+ }
+
+ private async restoreConnectionAfterDaemonRestart(options: DaemonRestartRestoreOptions): Promise<boolean> {
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;
+ // An update-restart recovery outranks a generic shutdown recovery even after it
+ // finished: it clears updateRestartPending as soon as it restores, but the
+ // sessionRevision bump it leaves behind stands. ownRevisionBumps counts this
+ // loop's own bumps, so a revision bumped by anyone else is the permanent signal
+ // that the update recovery restored the session and this loop yields.
+ const startSessionRevision = this.sessionRevision;
+ let ownRevisionBumps = 0;
+ const deadline = Date.now() + options.timeoutMs;
let lastError: unknown;
while (!this.disposed && !this.terminalCloseEmitted && Date.now() < deadline) {
+ // An update-restart recovery outranks a plain-shutdown recovery still polling:
+ // while it runs (its flag) and once it restored (its revision bump).
+ if (
+ !options.updateRestart &&
+ (this.updateRestartPending || this.sessionRevision !== startSessionRevision + ownRevisionBumps)
+ ) {
+ return false;
+ }
try {
- await this.client.reconnect(1000);
+ // Every attempt waits no longer than the bound: the terminal close must not slip past it.
+ await this.client.reconnect(Math.max(1, Math.min(1000, deadline - Date.now())));
if (this.disposed || this.terminalCloseEmitted) {
- return;
+ return false;
}
// This loop owns the retry: a socket close must reject these instead of parking them behind a hello it can never produce.
- const response = await this.client.request({ type: "list" }, 30000, { recoverable: false });
+ // The list waits no longer than the bound: the terminal close must not slip past it.
+ const response = await this.client.request(
+ { type: "list" },
+ Math.max(1, Math.min(30_000, deadline - Date.now())),
+ { recoverable: false },
+ );
if (this.disposed || this.terminalCloseEmitted) {
- return;
+ return false;
}
if (!response.success) {
throw deserializeDaemonError(response);
@@ -2194,33 +2354,44 @@ export class DaemonAgentConnection implements AgentConnection {
);
if (restored?.activeSessionId) {
if (this.disposed || this.terminalCloseEmitted) {
- return;
+ return false;
}
this.sessionRevision++;
+ ownRevisionBumps++;
this.activeSessionId = restored.activeSessionId;
this.lastEventSequence = undefined;
this.lastEventCursor = undefined;
this.retiredEventGenerations.clear();
await this.attach({ recoverable: false });
if (this.disposed || this.terminalCloseEmitted) {
- return;
+ return false;
}
const snapshot = await this.getInitialSnapshot({ recoverable: false });
if (this.disposed || this.terminalCloseEmitted) {
- return;
+ return false;
+ }
+ // An update-restart recovery that took over while this iteration was in
+ // flight owns the resync: this iteration must not emit a duplicate. It
+ // clears its flag once it restores, so the revision bump it left behind
+ // is the permanent marker this generic recovery yields to.
+ if (
+ !options.updateRestart &&
+ (this.updateRestartPending || this.sessionRevision !== startSessionRevision + ownRevisionBumps)
+ ) {
+ return false;
}
- this.updateRestartPending = false;
+ if (options.updateRestart) this.updateRestartPending = false;
void this.emit({ type: "session_resynced", snapshot });
- return;
+ return true;
}
} catch (error) {
lastError = error;
}
- if (this.disposed || this.terminalCloseEmitted) return;
- await delay(UPDATE_RECONNECT_RETRY_MS);
+ if (this.disposed || this.terminalCloseEmitted) return false;
+ await delay(options.retryMs);
}
if (this.disposed || this.terminalCloseEmitted) {
- return;
+ return false;
}
throw lastError ?? new Error("the restored session did not become available");
}
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 25edc233b2..fdd9beff22 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -647,7 +647,13 @@ export type AgentConnectionEvent =
| { type: "session_status"; recap?: string }
| { type: "extension_ui_request"; request: AgentConnectionExtensionUiRequest }
| { type: "extension_error"; extensionPath: string; event: string; error: string }
- | { type: "connection_status"; status: "reconnecting" | "connected"; error?: string }
+ | {
+ type: "connection_status";
+ status: "reconnecting" | "connected";
+ error?: string;
+ /** App version of the restarted daemon; set when recovery re-attached to it. */
+ daemonVersion?: string;
+ }
| { type: "heartbeats_changed" }
| { type: "closed"; error?: string };
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 4a5e16e5f8..88e7f55717 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
@@ -2629,10 +2629,16 @@ export class AgentsViewMode implements Component, Focusable {
private async reconnectClient(client: DaemonClient, initialError: unknown): Promise<void> {
const deadline = Date.now() + (this.options.reconnectTimeoutMs ?? RECONNECT_TIMEOUT_MS);
+ // An update restart owns the daemon relaunch: while its coordinator stops and
+ // restores the daemon, this loop only polls, so it never spawns a competing
+ // daemon from this window's (possibly outdated) binary.
+ const mayRelaunch = !(initialError instanceof Error && getDaemonSocketCloseReason(initialError) === "update");
let lastError = initialError;
while (!this.stopped && !this.daemonShutdownReceived && client === this.client && Date.now() < deadline) {
try {
- await this.options.recoverDaemon?.();
+ if (mayRelaunch) {
+ await this.options.recoverDaemon?.();
+ }
await client.reconnect(1000);
if (!this.rosterStore || !(await this.rosterStore.attach(client))) {
throw new Error("Daemon lost the agent_roster capability during reconnect");
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 2b8b34fc04..6f506571ea 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -2385,9 +2385,14 @@ export class DaemonSupervisor {
case "restart":
setImmediate(() => void this.shutdown(0, false, true, false, "update"));
return success(command.id, command.type);
- case "shutdown":
- setImmediate(() => void this.shutdown(0, true, false, command.force === true, "shutdown"));
+ case "shutdown": {
+ // An update-restart coordinator stops a prepared daemon with this command;
+ // attached windows need the "update" reason to recover instead of dying.
+ // Capture the reason now: a later phase change must not rewrite it.
+ const closingReason: DaemonClosingReason = this.updateRestartPhase === "prepared" ? "update" : "shutdown";
+ setImmediate(() => void this.shutdown(0, true, false, command.force === true, closingReason));
return success(command.id, "shutdown");
+ }
case "prepare_update_restart": {
const manifest = await this.prepareUpdateRestart();
return success(command.id, "prepare_update_restart", manifest);
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 370941241c..9b6f1a9047 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -908,6 +908,78 @@ function getPayloadWorkingIndicatorOptions(
};
}
+export interface DaemonReconnectBanner {
+ message: string;
+ tone: "dim" | "warning";
+}
+
+/**
+ * One-line banner for a recovered daemon connection. When the restarted daemon
+ * is NEWER than this window's binary, say so instead of pretending the window
+ * is updated; the user restarts the window to pick up the new version. An
+ * older or unorderable daemon version is reported without the advice (restarting
+ * this window would pick up nothing).
+ */
+export function formatDaemonReconnectBanner(
+ daemonVersion: string | undefined,
+ clientVersion: string,
+): DaemonReconnectBanner {
+ if (!daemonVersion) {
+ return { message: "Daemon reconnected", tone: "dim" };
+ }
+ if (daemonVersion === clientVersion) {
+ return { message: `Daemon restarted (v${daemonVersion}) - reconnected`, tone: "dim" };
+ }
+ if (isDaemonVersionNewer(daemonVersion, clientVersion)) {
+ return {
+ message: `Daemon restarted (v${daemonVersion}), this window still runs v${clientVersion} - restart the window to pick up the update.`,
+ tone: "warning",
+ };
+ }
+ return { message: `Daemon restarted (v${daemonVersion}), this window runs v${clientVersion}.`, tone: "dim" };
+}
+
+/**
+ * Numeric version-prefix comparison ("0.9.5-beta.7" orders by 0.9.5); unparseable segments
+ * end the comparison. A numeric-equal release outranks the same version's prereleases.
+ */
+function isDaemonVersionNewer(daemonVersion: string, clientVersion: string): boolean {
+ const daemon = parseNumericVersionPrefix(daemonVersion);
+ const client = parseNumericVersionPrefix(clientVersion);
+ for (let index = 0; index < Math.max(daemon.length, client.length); index++) {
+ const difference = (daemon[index] ?? 0) - (client[index] ?? 0);
+ if (difference !== 0) {
+ return difference > 0;
+ }
+ }
+ // Semver orders a release ahead of its own prereleases ("1.2.3" > "1.2.3-beta.1"),
+ // so a numeric-equal daemon without a prerelease suffix outranks a client with one.
+ return !hasPrereleaseSuffix(daemonVersion) && hasPrereleaseSuffix(clientVersion);
+}
+
+/** The dot- and dash-separated segments of a version: "1.2.3-beta.1" -> ["1", "2", "3", "beta", "1"]. */
+function splitVersionSegments(value: string): string[] {
+ return value.split(/[.-]/);
+}
+
+/** The leading numeric segments of a version string; the first unparseable segment ends the prefix. */
+function parseNumericVersionPrefix(value: string): number[] {
+ const segments: number[] = [];
+ for (const segment of splitVersionSegments(value)) {
+ const parsed = Number(segment);
+ if (!Number.isFinite(parsed)) break;
+ segments.push(parsed);
+ }
+ return segments;
+}
+
+/** Whether a version string continues past its numeric prefix with a prerelease suffix. */
+function hasPrereleaseSuffix(version: string): boolean {
+ const segments = splitVersionSegments(version);
+ const prefixLength = parseNumericVersionPrefix(version).length;
+ return prefixLength > 0 && prefixLength < segments.length;
+}
+
export function updateArgsIncludeSelf(args: readonly string[]): boolean {
let selfFlag = false;
let extensionsOnlyFlag = false;
@@ -5727,10 +5799,12 @@ export class InteractiveMode {
} else if (event.type === "extension_ui_request") {
await this.handleConnectionExtensionUiRequest(event.request);
} else if (event.type === "connection_status") {
- this.showStatus(
- event.status === "connected" ? "Daemon reconnected" : "Daemon connection lost; reconnecting…",
- event.status === "reconnecting" ? "warning" : "dim",
- );
+ if (event.status === "connected") {
+ const banner = formatDaemonReconnectBanner(event.daemonVersion, VERSION);
+ this.showStatus(banner.message, banner.tone);
+ } else {
+ this.showStatus("Daemon connection lost; reconnecting…", "warning");
+ }
if (event.status === "connected") {
await this.refreshHeartbeatCatalog();
}
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index cb21a9cfd2..4bc3697e52 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -1274,13 +1274,9 @@ describe("DaemonAgentConnection", () => {
const fakeClient = new FakeDaemonClient();
fakeClient.emitCloseOnClose = true;
const restoredMessages: AgentMessage[] = [{ role: "user", content: "restored prompt", timestamp: 2 }];
+ // The restarted daemon lists the same session under a new active id.
fakeClient.updateRestartSessions = [
- {
- id: "active-restored",
- activeSessionId: "active-restored",
- sessionId: "session-current",
- sessionFile: "/tmp/session-current.jsonl",
- },
+ { id: "r1", activeSessionId: "active-restored", sessionId: "session-current", sessionFile: "/tmp/f.jsonl" },
];
fakeClient.attachResultFactory = (command) =>
createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 1, {
@@ -1446,22 +1442,16 @@ describe("DaemonAgentConnection", () => {
expect(fakeClient.reconnectCount).toBe(1);
});
- it("does not reconnect after an explicit shutdown session close", async () => {
+ it("does not reconnect after a shutdown session stop that never announced the daemon closing", 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);
- }
+ if (event.type === "closed") closedEvents.push(event);
});
await connection.attach();
-
- fakeClient.emitMessage({
- type: "session_closed",
- activeSessionId: "active-original",
- reason: "shutdown",
- });
+ // No daemon_closing notice: an explicit session stop stays stopped.
+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "active-original", reason: "shutdown" });
fakeClient.emitClose(new Error("Daemon socket closed"));
await Promise.resolve();
@@ -1477,24 +1467,119 @@ describe("DaemonAgentConnection", () => {
expect(closedError).toContain("Diagnostic log:");
});
- it("does not infer an update when shutdown closes the socket before the session notice", async () => {
+ function announceClose(reason: "shutdown" | "killed", fakeClient: FakeDaemonClient) {
+ fakeClient.emitMessage({ type: "daemon_closing", reason: "shutdown" });
+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "active-original", reason });
+ }
+
+ it.each([
+ [
+ "shutdown socket close",
+ (fakeClient: FakeDaemonClient) =>
+ fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "shutdown")),
+ ],
+ // An orderly supervisor shutdown archive-stops its workers, so attached windows
+ // read the relayed close as "killed"; a direct worker link closes as "shutdown".
+ ["announced daemon shutdown", (fakeClient: FakeDaemonClient) => announceClose("shutdown", fakeClient)],
+ ["announced supervisor shutdown", (fakeClient: FakeDaemonClient) => announceClose("killed", fakeClient)],
+ ])("recovers a %s by reconnecting to the restarted daemon", async (_closeKind, triggerClose) => {
const fakeClient = new FakeDaemonClient();
+ fakeClient.hello = { ...fakeClient.hello!, appVersion: "test-daemon-version" };
+ // The restarted daemon lists the same session under a new active id.
+ fakeClient.updateRestartSessions = [{ id: "r1", activeSessionId: "restored", sessionId: "session-current" }];
const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
- const closedEvents: AgentConnectionEvent[] = [];
- connection.subscribe((event) => {
- if (event.type === "closed") {
- closedEvents.push(event);
- }
+ const events: AgentConnectionEvent[] = [];
+ const connected = new Promise<AgentConnectionEvent>((resolveConnected) => {
+ connection.subscribe((event) => {
+ events.push(event);
+ if (event.type === "connection_status" && event.status === "connected") resolveConnected(event);
+ });
});
await connection.attach();
- fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "shutdown"));
- await Promise.resolve();
+ triggerClose(fakeClient);
- 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.");
+ await expect(connected).resolves.toMatchObject({ daemonVersion: "test-daemon-version" });
+ expect(events.filter((event) => event.type === "closed")).toEqual([]);
+ expect(events.filter((event) => event.type === "session_resynced").length).toBeGreaterThan(0);
+ await connection.dispose();
+ });
+
+ it("a generic reconnect yields once a restart recovery restored the session", async () => {
+ vi.useFakeTimers();
+ try {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.updateRestartSessions = [{ id: "r1", activeSessionId: "restored", sessionId: "session-current" }];
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original", {
+ reconnectTimeoutMs: 1000,
+ recoverDaemon: async () => undefined,
+ });
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => {
+ events.push(event);
+ });
+ await connection.attach();
+
+ fakeClient.emitClose(new Error("Daemon socket closed"));
+ fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "shutdown"));
+ await vi.advanceTimersByTimeAsync(2_000);
+ // The restart recovery owns the outcome: one resync, no duplicate, no terminal close.
+ expect(events.filter((event) => event.type === "session_resynced")).toHaveLength(1);
+ expect(events.filter((event) => event.type === "closed")).toEqual([]);
+ await connection.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("a shutdown recovery does not duplicate an update recovery's resync", async () => {
+ vi.useFakeTimers();
+ try {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original");
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe((event) => void events.push(event));
+ await connection.attach();
+ fakeClient.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "shutdown"));
+ await vi.advanceTimersByTimeAsync(50); // parks the shutdown recovery on its retry delay
+ fakeClient.updateRestartSessions = [{ id: "r1", activeSessionId: "restored", sessionId: "session-current" }];
+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "active-original", reason: "update" });
+ await vi.advanceTimersByTimeAsync(150); // the update recovery restores before the shutdown loop wakes
+ const connected = events.filter((event) => event.type === "connection_status" && event.status === "connected");
+ expect(events.filter((event) => event.type === "session_resynced")).toHaveLength(1);
+ expect(connected).toHaveLength(1);
+ await connection.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("keeps the saved-transcript close after shutdown recovery times out", async () => {
+ vi.useFakeTimers();
+ try {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.reconnectError = new Error("daemon unavailable");
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-original", {
+ reconnectTimeoutMs: 5000,
+ });
+ 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 vi.advanceTimersByTimeAsync(5100);
+
+ 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.");
+ await connection.dispose();
+ } finally {
+ vi.useRealTimers();
+ }
});
it("does not emit a restored session after disposal begins", async () => {
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 7182ea8fe2..09b19bd538 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -24,6 +24,7 @@ import {
summaryForUnifiedRecord,
} from "../src/modes/agents-view/agents-view-state.js";
import * as agentRoster from "../src/modes/daemon/agent-roster.js";
+import { DaemonSocketClosedError } from "../src/modes/daemon/daemon-client.js";
import {
type AgentsViewScopeFrame,
aggregateSessionHeartbeats,
@@ -2182,6 +2183,34 @@ describe("#502 agents view catalog refresh races", () => {
}
});
+ test("an update-restart close polls without relaunching the daemon", async () => {
+ const recoverDaemon = vi.fn(async () => undefined);
+ const client = {
+ hello: { protocol: { version: 3 } },
+ supportsServerCapability: () => true,
+ reconnect: vi.fn(async () => {}),
+ };
+ const harness = {
+ ...refreshHarness(),
+ stopped: false,
+ client,
+ options: { reconnectTimeoutMs: 10_000, recoverDaemon },
+ requireClient: () => client,
+ rosterStore: { attach: vi.fn(async () => true), summaries: () => [] },
+ refreshHeartbeats: vi.fn(async () => true),
+ armSavedSearchFetch: vi.fn(),
+ };
+ const reconnectClient =
+ privateMethod<(this: typeof harness, reconnectingClient: unknown, initialError: unknown) => Promise<void>>(
+ "reconnectClient",
+ );
+ // The update-restart coordinator owns the relaunch: this loop only polls.
+ await reconnectClient.call(harness, client, new DaemonSocketClosedError("/tmp/prime-agent.sock", "update"));
+ expect(recoverDaemon).not.toHaveBeenCalled();
+ await reconnectClient.call(harness, client, new Error("Daemon socket closed"));
+ expect(recoverDaemon).toHaveBeenCalled();
+ });
+
test("a pending saved scan cannot overwrite daemon shutdown status", async () => {
const scan = createDeferred<void>();
const harness = savedScanHarness([], {
diff --git a/packages/coding-agent/test/daemon-supervisor-admission.test.ts b/packages/coding-agent/test/daemon-supervisor-admission.test.ts
index 98b5089ef5..fa449d5677 100644
--- a/packages/coding-agent/test/daemon-supervisor-admission.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-admission.test.ts
@@ -653,4 +653,33 @@ describe("daemon supervisor prompt admission ownership", () => {
expect(admissionFor(supervisor, owner)).toBeUndefined();
expect(forwarded.filter((command) => command.type === "prompt")).toHaveLength(1);
});
+
+ it("closes an update-restart shutdown as update and a plain shutdown as shutdown", async () => {
+ const shutdownCalls: Array<{ closingReason?: string; force: boolean }> = [];
+ const supervisor = createHarness({ updateRestartPhase: "prepared" });
+ (supervisor as unknown as Record<string, unknown>).shutdown = (
+ _exitCode: number,
+ _stopWorkers: boolean,
+ _relaunch: boolean,
+ forceWorkers: boolean,
+ closingReason?: string,
+ ) => {
+ shutdownCalls.push({ closingReason, force: forceWorkers });
+ // The real method never returns (process.exit); match that without exiting.
+ return new Promise<never>(() => undefined);
+ };
+ const owner = client("shutdown-requester");
+
+ // The coordinator stops a prepared daemon without force; a plain stop stays "shutdown".
+ await supervisor.handleLine(owner, commandLine({ id: "shutdown-1", type: "shutdown" }));
+ await new Promise((resolveImmediate) => setImmediate(resolveImmediate));
+ (supervisor as unknown as { updateRestartPhase: undefined }).updateRestartPhase = undefined;
+ await supervisor.handleLine(owner, commandLine({ id: "shutdown-2", type: "shutdown", force: true }));
+ await new Promise((resolveImmediate) => setImmediate(resolveImmediate));
+
+ expect(shutdownCalls).toEqual([
+ { closingReason: "update", force: false },
+ { closingReason: "shutdown", force: true },
+ ]);
+ });
});
diff --git a/packages/coding-agent/test/interactive-update-relaunch.test.ts b/packages/coding-agent/test/interactive-update-relaunch.test.ts
index 7b15fffb77..fea01e8327 100644
--- a/packages/coding-agent/test/interactive-update-relaunch.test.ts
+++ b/packages/coding-agent/test/interactive-update-relaunch.test.ts
@@ -33,6 +33,7 @@ vi.mock("../src/cli/daemon-update-restart.js", async (importOriginal) => ({
import { buildDaemonUpdateRestartReport } from "../src/cli/daemon-update-restart.js";
import {
buildUpdateRelaunchArgs,
+ formatDaemonReconnectBanner,
InteractiveMode,
tryExecUpdateRelaunch,
} from "../src/modes/interactive/interactive-mode.js";
@@ -241,6 +242,28 @@ describe("interactive self-update relaunch", () => {
);
});
+describe("formatDaemonReconnectBanner", () => {
+ it.each([
+ [undefined, "1.2.3", "Daemon reconnected", "dim"],
+ ["1.2.3", "1.2.3", "Daemon restarted (v1.2.3) - reconnected", "dim"],
+ [
+ "2.0.0",
+ "1.2.3",
+ "Daemon restarted (v2.0.0), this window still runs v1.2.3 - restart the window to pick up the update.",
+ "warning",
+ ],
+ [
+ "1.2.3",
+ "1.2.3-beta.1",
+ "Daemon restarted (v1.2.3), this window still runs v1.2.3-beta.1 - restart the window to pick up the update.",
+ "warning",
+ ],
+ ["1.2.3-beta.1", "1.2.3", "Daemon restarted (v1.2.3-beta.1), this window runs v1.2.3.", "dim"],
+ ])("maps daemon version %s vs client %s to banner", (daemonVersion, clientVersion, message, tone) => {
+ expect(formatDaemonReconnectBanner(daemonVersion, clientVersion)).toEqual({ message, tone });
+ });
+});
+
describe("buildDaemonUpdateRestartReport", () => {
it("reports recovery results when the daemon restart fails", () => {
const report = buildDaemonUpdateRestartReport({