A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI, bug] fix(daemon): let session opens wait through an update restart instead of failing (#2391)
Seth Karten54da82e97173
diff --git a/packages/coding-agent/.changes/fix-update-restart-open-wait.md b/packages/coding-agent/.changes/fix-update-restart-open-wait.mdnew file mode 100644index 0000000000..74ecb7923b--- /dev/null+++ b/packages/coding-agent/.changes/fix-update-restart-open-wait.md@@ -0,0 +1 @@+- Fixed opening an agent from Agents View during a daemon auto-update failing with "Daemon is preparing an update restart": the open now waits through the update restart (bounded) and reconnects once the daemon returns, with a notice that it waited instead of a hard failure.diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.tsindex 06a21edb4c..4a5e16e5f8 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@@ -29,7 +29,7 @@ import { ensureTool } from "../../utils/tools-manager.js";import { DaemonAgentConnection } from "../agent-connection/daemon-agent-connection.js";import type { AgentConnectionHeartbeat, AgentConnectionSavedSessionInfo } from "../agent-connection/types.js";import { DaemonClient, getDaemonSocketCloseReason } from "../daemon/daemon-client.js";-import { DaemonSessionRecoveringError } from "../daemon/daemon-errors.js";+import { DaemonSessionRecoveringError, isDaemonUpdateRestartingError } from "../daemon/daemon-errors.js";import {collectDaemonClientEnv,type DaemonClosingReason,@@ -37,6 +37,7 @@ import {type DaemonResponse,isUnknownDaemonCommandError,} from "../daemon/daemon-protocol.js";+import { DaemonControlPlaneTransportError } from "../daemon/daemon-routed-client.js";import { resolveAttachModelFallbackMessage, type SessionSummary } from "../daemon/daemon-session-list.js";import { listDaemonHeartbeats } from "../daemon/heartbeat-catalog.js";import {@@ -316,6 +317,157 @@ interface OpenedAgentsViewSession {connection: DaemonAgentConnection;summary: SessionSummary;cwdFallbackNotice?: string;+ updateRestartWaitNotice?: string;+}++/**+ * Bounded wait budget for an open that arrives while the daemon is preparing+ * an update restart. Mirrors the update coordinator's worst case (100s+ * prepare + supervisor stop + 60s successor startup + session restore), the+ * same budget attached sessions get to reconnect after an update.+ */+export const DAEMON_UPDATE_RESTART_OPEN_WAIT_MS = 240_000;+const DAEMON_UPDATE_RESTART_OPEN_RETRY_MS = 500;++export interface DaemonUpdateRestartWaitResult<T> {+ result: T;+ waitedForUpdateRestart: boolean;+}++/**+ * Transport-level error codes that mean the socket was down while the daemon+ * exited or its successor had not finished booting.+ */+const DAEMON_UPDATE_RESTART_TRANSIENT_ERROR_CODES = new Set([+ "ECONNREFUSED",+ "ECONNRESET",+ "EPIPE",+ "ENOENT",+ "ETIMEDOUT",+ "ECONNABORTED",+]);++/**+ * True when an open failure is part of the normal update-restart window+ * rather than a permanent failure: the preparing-restart rejection itself,+ * transport failures while the daemon exits and its successor boots (socket+ * close, connect/handshake/request timeouts, routed control-plane transport+ * failures), and session-not-restored-yet misses ("Unknown active session", a+ * session still recovering). Permanent create and attach failures (e.g. a+ * missing session import file) return false so the open fails immediately+ * instead of hiding behind the bounded update wait.+ */+function isDaemonUpdateRestartTransientError(error: unknown): boolean {+ if (isDaemonUpdateRestartingError(error)) return true;+ if (!(error instanceof Error)) return false;+ if (isUnknownActiveSessionError(error)) return true;+ if (error instanceof DaemonSessionRecoveringError) return true;+ // A routed session transport wraps any control-plane transport failure+ // (socket close, connect, timeouts — the restart-window shapes above);+ // capability errors stay unwrapped and permanent.+ if (error instanceof DaemonControlPlaneTransportError) return true;+ const code = (error as NodeJS.ErrnoException).code;+ if (typeof code === "string" && DAEMON_UPDATE_RESTART_TRANSIENT_ERROR_CODES.has(code)) return true;+ return (+ // Socket closed while the daemon exits for the restart.+ error.message.startsWith("Connection to the Prime Agent daemon closed.") ||+ // Connect failures while the successor socket is not listening yet.+ error.message.startsWith("Failed to connect to the Prime Agent daemon:") ||+ // A request attempted while the transport is down between daemon processes.+ error.message.startsWith("Cannot send daemon command") ||+ // Transport timeouts while the daemon exits and its successor boots:+ // connect, handshake, and in-flight requests (e.g. create) that cannot+ // get a response until the successor is ready.+ /^Timed out after \d+ms (connecting to the Prime Agent daemon|waiting for the Prime Agent daemon handshake|waiting for the Prime Agent daemon response to)/.test(+ error.message,+ )+ );+}++function daemonUpdateRestartDeadlineError(waitMs: number, lastError: unknown): Error {+ const lastErrorText =+ lastError === undefined ? "none yet" : lastError instanceof Error ? lastError.message : String(lastError);+ return new Error(+ `The Prime Agent daemon did not finish its update restart within ${Math.round(waitMs / 1000)} seconds. Try opening this agent again once the update finishes. Last error: ${lastErrorText}`,+ );+}++/**+ * Run an open attempt, retrying while the daemon is in the update-restart+ * transient state instead of failing the open. The first+ * "preparing an update restart" rejection arms the wait; once armed, only+ * restart-transient failures of the restart itself (socket close while the+ * daemon exits, connect errors while the successor boots, session-not-yet-+ * restored misses) stay inside the same bounded loop, because they are all part+ * of the same normal update restart, while permanent failures (e.g. a missing+ * session file) propagate immediately instead of hiding behind the wait. A+ * non-update error before any update-restart signal propagates unchanged. The+ * wait budget bounds the whole wait: each attempt is raced against the+ * remaining budget, so an in-flight attempt (e.g. a create request with its own+ * 30-second timeout) cannot hold the open past the deadline, which fails with a+ * clear actionable message that includes the last error. A losing attempt that+ * still settles afterwards is not abandoned silently: its result goes to+ * onAbandoned for disposal and its failure is swallowed.+ */+export async function waitThroughDaemonUpdateRestart<T>(+ attempt: () => Promise<T>,+ options: {+ waitMs?: number;+ retryMs?: number;+ onWait?: (error: unknown) => void;+ /** Called with the result of an attempt that resolves after the deadline already failed the open, so resources nobody receives can be disposed. */+ onAbandoned?: (result: T) => void;+ } = {},+): Promise<DaemonUpdateRestartWaitResult<T>> {+ const waitMs = options.waitMs ?? DAEMON_UPDATE_RESTART_OPEN_WAIT_MS;+ const retryMs = options.retryMs ?? DAEMON_UPDATE_RESTART_OPEN_RETRY_MS;+ const deadline = Date.now() + waitMs;+ let sawUpdateRestart = false;+ let lastError: unknown;+ let attemptAbandoned = false;+ while (true) {+ const deadlineError = daemonUpdateRestartDeadlineError(waitMs, lastError);+ // An in-flight attempt (e.g. a create request with its own 30-second+ // timeout) must not push the open past the deadline: race every attempt+ // against the remaining budget so the bound holds.+ let deadlineTimer: ReturnType<typeof setTimeout> | undefined;+ const deadlineHit = new Promise<never>((_, reject) => {+ deadlineTimer = setTimeout(() => reject(deadlineError), Math.max(0, deadline - Date.now()));+ });+ const attemptPromise = attempt();+ // The race cannot cancel the losing attempt: when the deadline wins, a+ // late success must still be disposed (nobody receives its result), and+ // a late failure is expected and must not surface as unhandled.+ void attemptPromise.then(+ (result) => {+ if (attemptAbandoned) options.onAbandoned?.(result);+ },+ () => undefined,+ );+ try {+ const result = await Promise.race([attemptPromise, deadlineHit]);+ clearTimeout(deadlineTimer);+ return { result, waitedForUpdateRestart: sawUpdateRestart };+ } catch (error) {+ clearTimeout(deadlineTimer);+ if (error === deadlineError) {+ attemptAbandoned = true;+ throw deadlineError;+ }+ if (!sawUpdateRestart) {+ if (!isDaemonUpdateRestartingError(error)) throw error;+ sawUpdateRestart = true;+ options.onWait?.(error);+ } else if (!isDaemonUpdateRestartTransientError(error)) {+ throw error;+ }+ lastError = error;+ if (Date.now() + retryMs > deadline) {+ throw daemonUpdateRestartDeadlineError(waitMs, lastError);+ }+ await new Promise((resolve) => setTimeout(resolve, retryMs));+ }+ }}export function resolveAgentsViewOpenCwd(@@ -478,13 +630,36 @@ async function runAgentsViewLoop(let opened: OpenedAgentsViewSession | undefined;try {- opened = await openAgentsViewSession(options, result.summary);+ // An auto-update can fence session opens as "preparing an update+ // restart" at the exact moment the user hits enter; the restart is a+ // normal transient state, so wait through it instead of failing.+ const openedThroughUpdate = await waitThroughDaemonUpdateRestart(+ () => openAgentsViewSession(options, result.summary),+ {+ onWait: (error) => logClientError("Waiting for daemon update restart to finish before opening", error),+ // An open that resolves after the deadline already failed the+ // wait: dispose the connection nobody received instead of+ // leaking it.+ onAbandoned: (abandoned) => {+ void abandoned.connection.dispose().catch(() => undefined);+ },+ },+ );+ opened = openedThroughUpdate.result;persistentState.backSession = opened.summary;- if (opened.cwdFallbackNotice) {- persistentState.statusMessage = combineAgentsViewStartupNotices(- result.statusMessage,- opened.cwdFallbackNotice,- );+ if (openedThroughUpdate.waitedForUpdateRestart) {+ opened = {+ ...opened,+ updateRestartWaitNotice:+ "Waited for the Prime Agent daemon update restart to finish before opening this agent",+ };+ }+ const openStartupNotice = combineAgentsViewStartupNotices(+ opened.cwdFallbackNotice,+ opened.updateRestartWaitNotice,+ );+ if (openStartupNotice) {+ persistentState.statusMessage = combineAgentsViewStartupNotices(result.statusMessage, openStartupNotice);}const uiServices = await resolveAgentsViewSessionUiServices(options, opened.summary);const interactiveMode = new InteractiveMode({@@ -496,7 +671,7 @@ async function runAgentsViewLoop(bindLocalSessionExtensions: false,migratedProviders: options.migratedProviders,modelFallbackMessage: resolveAttachModelFallbackMessage(opened.summary, options.modelFallbackMessage),- startupNotice: combineAgentsViewStartupNotices(result.statusMessage, opened.cwdFallbackNotice),+ startupNotice: combineAgentsViewStartupNotices(result.statusMessage, openStartupNotice),verbose: options.verbose,returnToAgentsView: true,forceFullscreen: true,diff --git a/packages/coding-agent/src/modes/daemon/daemon-errors.ts b/packages/coding-agent/src/modes/daemon/daemon-errors.tsindex 760ed0b333..b85429d583 100644--- a/packages/coding-agent/src/modes/daemon/daemon-errors.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-errors.ts@@ -3,6 +3,12 @@ import { SessionImportFileNotFoundError } from "../../core/session-import-errorsimport { SessionAlreadyActiveError } from "../../core/session-lease.js";import type { DaemonErrorInfo, DaemonResponse } from "./daemon-protocol.js";+/** Rejection message for commands fenced out while the daemon prepares an update restart. */+export const UPDATE_RESTART_PREPARING_MESSAGE = "Daemon is preparing an update restart";++/** Machine-readable companion for {@link UPDATE_RESTART_PREPARING_MESSAGE} rejections. */+export const UPDATE_RESTART_PREPARING_ERROR_INFO: DaemonErrorInfo = { code: "update_restarting" };+/** A known session (a persisted descriptor names it) that cannot be routed to yet; retryable, unlike "Unknown active session". */export class DaemonSessionRecoveringError extends Error {readonly code = "session_recovering" as const;@@ -13,6 +19,33 @@ export class DaemonSessionRecoveringError extends Error {}}+/**+ * The daemon is preparing an update restart: mutations (including session+ * opens) are rejected while the restart coordinator drains and checkpoints.+ * This is a normal transient state, so clients should wait through it and+ * retry, not surface it as a hard failure.+ */+export class DaemonUpdateRestartingError extends Error {+ readonly code = "update_restarting" as const;++ constructor(message = "Daemon is preparing an update restart") {+ super(message);+ this.name = "DaemonUpdateRestartingError";+ }+}++/**+ * True when an open failure is the update-restart transient state. Typed+ * errors come from current daemons; the exact-message fallback also recognizes+ * older daemons that reject with the same plain string.+ */+export function isDaemonUpdateRestartingError(error: unknown): boolean {+ return (+ error instanceof DaemonUpdateRestartingError ||+ (error instanceof Error && error.message === "Daemon is preparing an update restart")+ );+}+export function serializeDaemonError(error: unknown): DaemonErrorInfo | undefined {if (error instanceof MissingSessionCwdError) {return { code: "missing_session_cwd", issue: error.issue };@@ -30,6 +63,9 @@ export function serializeDaemonError(error: unknown): DaemonErrorInfo | undefineif (error instanceof DaemonSessionRecoveringError) {return { code: "session_recovering", activeSessionId: error.activeSessionId };}+ if (error instanceof DaemonUpdateRestartingError) {+ return { code: "update_restarting" };+ }return undefined;}@@ -61,5 +97,8 @@ export function deserializeDaemonError(response: Extract<DaemonResponse, { succeif (errorInfo?.code === "session_recovering") {return new DaemonSessionRecoveringError(errorInfo.activeSessionId);}+ if (errorInfo?.code === "update_restarting") {+ return new DaemonUpdateRestartingError();+ }return new Error(response.error);}diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 0f0ba4818d..a8123dbd35 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -144,7 +144,12 @@ import {} from "./agent-roster.js";import { createCompactAssistantDelta } from "./compact-session-stream.js";import { filterClientEnv, withClientEnv } from "./daemon-client-env.js";-import { deserializeDaemonError, serializeDaemonError } from "./daemon-errors.js";+import {+ deserializeDaemonError,+ serializeDaemonError,+ UPDATE_RESTART_PREPARING_ERROR_INFO,+ UPDATE_RESTART_PREPARING_MESSAGE,+} from "./daemon-errors.js";import { bindActiveSessionState } from "./daemon-extension-binding.js";import {collectDaemonLaunchEnv,@@ -3961,7 +3966,12 @@ export class AgentDaemon {if (this.updateRestart && !updateLifecycle) {this.write(client,- failure(workerCommand.id, workerCommand.type, "Daemon is preparing an update restart"),+ failure(+ workerCommand.id,+ workerCommand.type,+ UPDATE_RESTART_PREPARING_MESSAGE,+ UPDATE_RESTART_PREPARING_ERROR_INFO,+ ),);return;}@@ -3997,7 +4007,10 @@ export class AgentDaemon {: restartPhase !== undefined && command.type !== "shutdown";if (mutation && restartRejected) {clearParsedAdmission();- this.write(client, failure(command.id, command.type, "Daemon is preparing an update restart"));+ this.write(+ client,+ failure(command.id, command.type, UPDATE_RESTART_PREPARING_MESSAGE, UPDATE_RESTART_PREPARING_ERROR_INFO),+ );return;}if (mutation) this.mutationDrain.begin();diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex 9dd27f85ea..abc8613451 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -1035,6 +1035,7 @@ export type DaemonErrorInfo =| { code: "session_import_file_not_found"; filePath: string }| { code: "session_already_active"; sessionPath: string; activeSessionId?: string }| { code: "session_recovering"; activeSessionId: string }+ | { code: "update_restarting" }| { code: "command_result_uncertain"; clientId: DaemonClientId; commandId: DaemonCommandId };export type DaemonSessionClosedReason = "killed" | "shutdown" | "completed" | "replaced" | "update";diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex ab57860ec4..e1a76ea24e 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -76,7 +76,13 @@ import {import { CommandRecoveryJournal, createCommandIdempotencyKey } from "./command-recovery-journal.js";import { CompactAssistantStreamReconstructor, isCompactAssistantDelta } from "./compact-session-stream.js";import { DAEMON_CATALOG_ROLE_ENV, DaemonCatalogClient } from "./daemon-catalog-process.js";-import { DaemonSessionRecoveringError, deserializeDaemonError, serializeDaemonError } from "./daemon-errors.js";+import {+ DaemonSessionRecoveringError,+ deserializeDaemonError,+ serializeDaemonError,+ UPDATE_RESTART_PREPARING_ERROR_INFO,+ UPDATE_RESTART_PREPARING_MESSAGE,+} from "./daemon-errors.js";import {collectDaemonClientEnv,createDaemonEventMeta,@@ -1774,7 +1780,10 @@ export class DaemonSupervisor {const command = preParsed.command;const parsedAdmission = preParsed.admission;if (command.type === "cancel_prompt_admission" && this.updateRestartPhase !== undefined) {- this.write(client, failure(command.id, command.type, "Daemon is preparing an update restart"));+ this.write(+ client,+ failure(command.id, command.type, UPDATE_RESTART_PREPARING_MESSAGE, UPDATE_RESTART_PREPARING_ERROR_INFO),+ );return;}const cancellationAdmission =@@ -1855,7 +1864,10 @@ export class DaemonSupervisor {: phase !== undefined && !(phase === "prepared" && command.type === "shutdown");if (restartRejected && mutation) {if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);- this.write(client, failure(command.id, command.type, "Daemon is preparing an update restart"));+ this.write(+ client,+ failure(command.id, command.type, UPDATE_RESTART_PREPARING_MESSAGE, UPDATE_RESTART_PREPARING_ERROR_INFO),+ );return;}if (mutation && !UPDATE_RESTART_DRAIN_COMMANDS.has(command.type)) {diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.tsindex a82ed24411..88e4c17e14 100644--- a/packages/coding-agent/test/agents-view-mode.test.ts+++ b/packages/coding-agent/test/agents-view-mode.test.ts@@ -11,6 +11,7 @@ import {type AgentsViewPersistentState,createInitialAgentsViewPersistentState,runAgentsViewMode,+ waitThroughDaemonUpdateRestart,} from "../src/modes/agents-view/agents-view-mode.js";import * as agentsViewState from "../src/modes/agents-view/agents-view-state.js";import {@@ -19,6 +20,8 @@ import {resolveAgentsViewLeftResult,type UnifiedSessionRecord,} from "../src/modes/agents-view/agents-view-state.js";+import { DaemonSessionRecoveringError, DaemonUpdateRestartingError } from "../src/modes/daemon/daemon-errors.js";+import { DaemonControlPlaneTransportError } from "../src/modes/daemon/daemon-routed-client.js";import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";import * as savedSessionCatalog from "../src/modes/daemon/saved-session-catalog.js";import type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";@@ -38,14 +41,17 @@ vi.mock("../src/config.js", async (importOriginal) => {return { ...actual, appendRotatingLog: vi.fn() };});-vi.mock("../src/modes/daemon/daemon-client.js", () => ({- DaemonClient: class {- connect = vi.fn(async () => undefined);- close = vi.fn();- request = modeMocks.clientRequest;- },- getDaemonSocketCloseReason: vi.fn(),-}));+vi.mock("../src/modes/daemon/daemon-client.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../src/modes/daemon/daemon-client.js")>();+ return {+ ...actual,+ DaemonClient: class {+ connect = vi.fn(async () => undefined);+ close = vi.fn();+ request = modeMocks.clientRequest;+ },+ };+});vi.mock("../src/modes/agent-connection/daemon-agent-connection.js", () => ({DaemonAgentConnection: Object.assign(function DaemonAgentConnection() {}, {@@ -1264,27 +1270,49 @@ describe("agents view reply delivery on inactive sessions", () => {expect(submit).toHaveBeenCalledWith("expanded paste body", "followUp");});- it("creates a new daemon session over a dedicated connection and opens it", async () => {- const created = replySummary({ id: "active-new", activeSessionId: "active-new", lifecycle: "live" });- const request = vi.fn(async () => ({ success: true, data: created }));- const close = vi.fn();- const self: Record<string, unknown> = {- creatingNewSession: false,- stopped: false,- options: { config: { cwd: process.cwd() } },- connectDedicatedClient: vi.fn(async () => ({ request, close })),- setStatusMessage: vi.fn(),- selectSummary: vi.fn(),- finish: vi.fn(),- };+ // [the view finishes mid-create, the requests the dedicated connection carries]+ it.each([+ ["opens it", false, ["create"]],+ ["kills a session created after the view already finished", true, ["create", "kill"]],+ ] as const)(+ "creates a new daemon session over a dedicated connection and %s",+ async (_name, stopsDuringCreate, requestTypes) => {+ const created = replySummary({ id: "active-new", activeSessionId: "active-new", lifecycle: "live" });+ const requests: { type: string }[] = [];+ const close = vi.fn();+ const self: Record<string, unknown> = {+ creatingNewSession: false,+ stopped: false,+ options: { config: {} },+ connectDedicatedClient: vi.fn(async () => ({+ close,+ request: vi.fn(async (command: { type: string }) => {+ requests.push(command);+ // The view finishes while create is in flight.+ if (stopsDuringCreate) self.stopped = true;+ return { success: true, data: created };+ }),+ })),+ setStatusMessage: vi.fn(),+ selectSummary: vi.fn(),+ finish: vi.fn(),+ };- await expect(invoke("createNewSession", self)).resolves.toBe(true);- expect(request).toHaveBeenCalledWith(expect.objectContaining({ type: "create" }));- expect(self.selectSummary).toHaveBeenCalledWith(created);- expect(self.finish).toHaveBeenCalledWith({ type: "open", summary: created });- expect(close).toHaveBeenCalledOnce();- expect(self.creatingNewSession).toBe(false);- });+ const result = await invoke("createNewSession", self);++ expect(requests.map((r) => r.type)).toEqual(requestTypes);+ if (stopsDuringCreate) {+ expect(self.finish).not.toHaveBeenCalled();+ expect(self.selectSummary).not.toHaveBeenCalled();+ } else {+ expect(result).toBe(true);+ expect(self.selectSummary).toHaveBeenCalledWith(created);+ expect(self.finish).toHaveBeenCalledWith({ type: "open", summary: created });+ expect(close).toHaveBeenCalledOnce();+ expect(self.creatingNewSession).toBe(false);+ }+ },+ );it("resumes a saved session before delivering the reply", async () => {const request = vi.fn(async (command: { type: string }) => {@@ -1369,7 +1397,11 @@ describe("agents view reply delivery on inactive sessions", () => {expect(self.inactiveAgentIdentities).not.toContain("file:/tmp/sessions/saved-1.jsonl");});- it("preserves a replacement composer when an older reply succeeds", async () => {+ // [re-armed target survives, text entered mid-send survives]+ it.each([+ ["preserves a replacement composer when an older reply succeeds", true],+ ["preserves new text entered while the same reply succeeds", false],+ ] as const)("%s", async (_name, rearmed) => {const editor = editorWithText("old reply");const oldTarget = { key: "saved-1", summary: savedSummary };const newTarget = {@@ -1383,40 +1415,18 @@ describe("agents view reply delivery on inactive sessions", () => {setReplyTarget: vi.fn(),refreshSessions: vi.fn(async () => true),sendReply: vi.fn(async () => {- self.replyTarget = newTarget;- editor.setText("new reply");- return true;- }),- };-- await invoke("submit", self, "old reply");-- expect(self.replyTarget).toBe(newTarget);- expect(editor.getText()).toBe("new reply");- expect(self.setReplyTarget).not.toHaveBeenCalled();- expect(self.refreshSessions).toHaveBeenCalledWith();- });-- it("preserves new text entered while the same reply succeeds", async () => {- const editor = editorWithText("first reply");- const target = { key: "saved-1", summary: savedSummary };- const self: Record<string, unknown> = {- replyTarget: target,- options: {},- editor,- setReplyTarget: vi.fn(),- refreshSessions: vi.fn(async () => true),- sendReply: vi.fn(async () => {+ if (rearmed) self.replyTarget = newTarget;editor.setText("next reply");return true;}),};- await invoke("submit", self, "first reply");+ await invoke("submit", self, "old reply");- expect(self.replyTarget).toBe(target);+ expect(self.replyTarget).toBe(rearmed ? newTarget : oldTarget);expect(editor.getText()).toBe("next reply");expect(self.setReplyTarget).not.toHaveBeenCalled();+ if (rearmed) expect(self.refreshSessions).toHaveBeenCalledWith();});it.each([@@ -1545,34 +1555,6 @@ describe("agents view reply delivery on inactive sessions", () => {expect(self.selectSummary).not.toHaveBeenCalled();});- it("kills a session created after the view already finished", async () => {- const created = replySummary({ id: "active-new", activeSessionId: "active-new", lifecycle: "live" });- const requests: { type: string }[] = [];- const self: Record<string, unknown> = {- creatingNewSession: false,- stopped: false,- options: { config: {} },- connectDedicatedClient: vi.fn(async () => ({- close: vi.fn(),- request: vi.fn(async (command: { type: string }) => {- requests.push(command);- // The view finishes while create is in flight.- self.stopped = true;- return { success: true, data: created };- }),- })),- setStatusMessage: vi.fn(),- selectSummary: vi.fn(),- finish: vi.fn(),- };-- await invoke("createNewSession", self);-- expect(requests.map((r) => r.type)).toEqual(["create", "kill"]);- expect(self.finish).not.toHaveBeenCalled();- expect(self.selectSummary).not.toHaveBeenCalled();- });-it("does not disarm a composer that was re-armed during the command", async () => {const live = replySummary({ activeSessionId: "active-1", lifecycle: "live" });const originalTarget = { key: "active-1", summary: live };@@ -1631,3 +1613,119 @@ describe("agents view reply delivery on inactive sessions", () => {);});});++describe("agents view open during a daemon update restart", () => {+ beforeEach(() => vi.clearAllMocks());++ it.each([+ [+ "waits through the update restart and surfaces the wait notice",+ true,+ "Waited for the Prime Agent daemon update restart to finish",+ ],+ [+ "surfaces a permanent create failure unmasked by the wait",+ false,+ "Failed to open agent: File not found: /tmp/scope.jsonl",+ ],+ ] as const)("%s", async (_name, reachesSession, expectedMessage) => {+ const saved = summary({ activeSessionId: undefined, lifecycle: "archived" });+ let runs = 0;+ vi.spyOn(AgentsViewMode.prototype, "run").mockImplementation(async function (this: AgentsViewMode) {+ runs += 1;+ if (runs === 1) return { type: "open", summary: saved, hasChildren: false };+ expect(String(Reflect.get(this, "persistentState").statusMessage)).toContain(expectedMessage);+ return { type: "exit" };+ });+ modeMocks.clientRequest+ .mockResolvedValueOnce({+ success: false,+ error: "Daemon is preparing an update restart",+ })+ .mockResolvedValueOnce(+ reachesSession+ ? { success: true, data: { ...saved, activeSessionId: "resumed-after-update", lifecycle: "live" } }+ : { success: false, error: "File not found: /tmp/scope.jsonl" },+ );+ modeMocks.interactiveRun.mockResolvedValue({+ type: "agents_view",+ source: { activeSessionId: "resumed-after-update", sessionId: saved.sessionId, cwd: saved.cwd },+ } as never);++ await runAgentsViewMode({+ config: { cwd: process.cwd() },+ socketPath: "/tmp/agents-view-test.sock",+ uiServices: createUiServices(),+ });++ expect(modeMocks.clientRequest).toHaveBeenCalledTimes(2);+ expect(modeMocks.interactiveRun).toHaveBeenCalledTimes(reachesSession ? 1 : 0);+ expect(runs).toBe(2);+ });+});++describe("waitThroughDaemonUpdateRestart", () => {+ const updateRestartDeadline =+ /The Prime Agent daemon did not finish its update restart within \d+ seconds\. Try opening this agent again once the update finishes\. Last error: Daemon is preparing an update restart/;++ // Post-arm transient shapes only; arming is pinned at the loop/deadline layers.+ it("retries every restart-transient failure and reports that it waited", async () => {+ const transientFailures = [+ () => new Error("Failed to connect to the Prime Agent daemon: connect ENOENT"),+ () => Object.assign(new Error("connect ECONNREFUSED"), { code: "ECONNREFUSED" }),+ () => new Error("Connection to the Prime Agent daemon closed."),+ () => new Error('Timed out after 30000ms waiting for the Prime Agent daemon response to "create".'),+ () => new DaemonControlPlaneTransportError(new Error("Connection to the Prime Agent daemon closed.")),+ () => new Error("Unknown active session: update-restart-session"),+ () => new DaemonSessionRecoveringError("update-restart-session"),+ ];+ let attempts = 0;+ const outcome = await waitThroughDaemonUpdateRestart(+ async () => {+ attempts += 1;+ if (attempts === 1) throw new DaemonUpdateRestartingError();+ const failure = transientFailures[attempts - 2];+ if (failure) throw failure();+ return "opened";+ },+ { waitMs: 5_000, retryMs: 1 },+ );+ expect(outcome).toEqual({ result: "opened", waitedForUpdateRestart: true });+ });++ it("propagates a non-update failure before any update-restart signal", async () => {+ let attempts = 0;+ await expect(+ waitThroughDaemonUpdateRestart(async () => {+ attempts += 1;+ throw new Error("spawn EMFILE");+ }),+ ).rejects.toThrow("spawn EMFILE");+ expect(attempts).toBe(1);+ });++ // The deadline races every attempt so an in-flight create cannot hold the open past the budget.+ it("fails at the deadline even when an in-flight attempt would block past it", async () => {+ vi.useFakeTimers();+ const inFlight = new Promise<string>(() => {});+ let attempts = 0;+ try {+ const opening = waitThroughDaemonUpdateRestart(+ async () => {+ attempts += 1;+ if (attempts === 1) throw new DaemonUpdateRestartingError();+ return inFlight;+ },+ { waitMs: 60, retryMs: 5 },+ ).then(+ () => "unexpectedly opened",+ (error: Error) => error.message,+ );+ await vi.advanceTimersByTimeAsync(60);+ expect(await opening).toMatch(updateRestartDeadline);+ expect(attempts).toBe(2);+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/packages/coding-agent/test/daemon-errors.test.ts b/packages/coding-agent/test/daemon-errors.test.tsindex e1c17942f2..c148c891d5 100644--- a/packages/coding-agent/test/daemon-errors.test.ts+++ b/packages/coding-agent/test/daemon-errors.test.ts@@ -3,8 +3,10 @@ import { SessionAlreadyActiveError } from "../src/core/session-lease.js";import {DaemonSessionCreateError,DaemonSessionRecoveringError,+ DaemonUpdateRestartingError,deserializeDaemonCreateError,deserializeDaemonError,+ isDaemonUpdateRestartingError,serializeDaemonError,} from "../src/modes/daemon/daemon-errors.js";@@ -58,3 +60,29 @@ describe("session_recovering wire round-trip", () => {expect(legacy).not.toBeInstanceOf(DaemonSessionRecoveringError);});});++describe("update_restarting wire round-trip", () => {+ it("serializes for old clients (readable message) and deserializes for new clients (typed, retryable)", () => {+ const error = new DaemonUpdateRestartingError();+ const errorInfo = serializeDaemonError(error);+ expect(errorInfo).toEqual({ code: "update_restarting" });+ expect(error.message).toBe("Daemon is preparing an update restart");+ const roundTripped = deserializeDaemonError({+ type: "response",+ command: "create",+ success: false,+ error: error.message,+ errorInfo,+ });+ expect(roundTripped).toBeInstanceOf(DaemonUpdateRestartingError);+ const legacy = deserializeDaemonError({+ type: "response",+ command: "create",+ success: false,+ error: "Daemon is preparing an update restart",+ });+ expect(legacy).not.toBeInstanceOf(DaemonUpdateRestartingError);+ expect(isDaemonUpdateRestartingError(legacy)).toBe(true);+ expect(isDaemonUpdateRestartingError(new Error("Unknown active session: active-gap"))).toBe(false);+ });+});diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.tsindex b5c55e3ec0..e900df4a4f 100644--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts@@ -4583,6 +4583,7 @@ describe("daemon worker supervisor monitoring", () => {await prepare;await expect(client.request({ type: "abort", activeSessionId: "missing" })).resolves.toMatchObject({error: "Daemon is preparing an update restart",+ errorInfo: { code: "update_restarting" },});} finally {client.close();