A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
resume sessions after self-update (#326)
kt9039605b934e
diff --git a/packages/agent/src/agent.ts b/packages/agent/src/agent.tsindex 141eca0e9c..dbf6636a0e 100644--- a/packages/agent/src/agent.ts+++ b/packages/agent/src/agent.ts@@ -359,25 +359,48 @@ export class Agent {throw new Error("Agent is already processing. Wait for completion before continuing.");}+ const runQueuedMessages = (): Promise<void> | undefined => {+ const queuedSteering = this.steeringQueue.drain();+ if (queuedSteering.length > 0) {+ return this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });+ }++ const queuedFollowUps = this.followUpQueue.drain();+ if (queuedFollowUps.length > 0) {+ return this.runPromptMessages(queuedFollowUps);+ }++ return undefined;+ };+const lastMessage = this._state.messages[this._state.messages.length - 1];if (!lastMessage) {+ const queuedRun = runQueuedMessages();+ if (queuedRun) {+ await queuedRun;+ return;+ }+throw new Error("No messages to continue from");}if (lastMessage.role === "assistant") {- const queuedSteering = this.steeringQueue.drain();- if (queuedSteering.length > 0) {- await this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });+ const queuedRun = runQueuedMessages();+ if (queuedRun) {+ await queuedRun;return;}- const queuedFollowUps = this.followUpQueue.drain();- if (queuedFollowUps.length > 0) {- await this.runPromptMessages(queuedFollowUps);+ throw new Error("Cannot continue from message role: assistant");+ }++ const lastMessageRole: string = lastMessage.role;+ if (lastMessageRole === "custom") {+ const queuedRun = runQueuedMessages();+ if (queuedRun) {+ await queuedRun;return;}-- throw new Error("Cannot continue from message role: assistant");}await this.runContinuation();diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex a59b23f22e..ca5c81ffe3 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -10,6 +10,7 @@- Fixed provider auth failures leaving stale credentials shown as connected in `/login` ([ENG-4491](https://linear.app/primeintellect/issue/ENG-4491/mark-provider-stale-after-repeated-401s)).- Fixed typing into the prompt after highlighting an inline subagent ([ENG-4494](https://linear.app/primeintellect/issue/ENG-4494/allow-typing-after-highlighting-a-subagent)).- Fixed session-targeted heartbeat jobs staying scheduled after sessions are killed or saved sessions are deleted ([#332](https://github.com/PrimeIntellect-ai/prime-agent/pull/332)).+- Fixed self-updates interrupting and automatically resuming daemon sessions instead of waiting for long-running work to finish.- Fixed provider errors being surfaced instead of retried within the retry budget ([ENG-4503](https://linear.app/primeintellect/issue/ENG-4503/restarting-old-session-returns-empty-model-response)).## [0.2.6] - 2026-07-06diff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.tsindex 785e3d9a2b..394e477540 100644--- a/packages/coding-agent/src/cli/daemon-launch.ts+++ b/packages/coding-agent/src/cli/daemon-launch.ts@@ -138,7 +138,13 @@ export type RunningDaemonProbe = { reachable: false } | { reachable: true; activexport function isSessionBusy(summary: SessionSummary): boolean {// pendingMessageCount covers queued steering/follow-ups, which live only in// memory and would be lost if the daemon were stopped.- return summary.isStreaming || summary.isCompacting || summary.pendingMessageCount > 0;+ return (+ summary.isStreaming ||+ summary.isCompacting ||+ summary.isBashRunning === true ||+ summary.hasRunningRlmChildren === true ||+ summary.pendingMessageCount > 0+ );}export async function probeRunningDaemonSessions(socketPath: string): Promise<RunningDaemonProbe> {diff --git a/packages/coding-agent/src/cli/daemon-stop-confirm.ts b/packages/coding-agent/src/cli/daemon-stop-confirm.tsindex 250e2523ff..9b6d88f19a 100644--- a/packages/coding-agent/src/cli/daemon-stop-confirm.ts+++ b/packages/coding-agent/src/cli/daemon-stop-confirm.ts@@ -45,8 +45,8 @@ export interface DaemonSessionLossCopy {* Returns true when it is safe to proceed with stopping the daemon: it is not* reachable, `force` is set, no sessions are busy, or the user confirmed at a* TTY. Returns false to abort (busy/unlistable and either declined or non-TTY).- * Only busy sessions (streaming, compacting, or pending messages) lose work;- * idle loaded sessions reload from disk on the fresh daemon.+ * Only busy sessions (streaming, compacting, running bash, or pending messages)+ * require confirmation; idle loaded sessions are restored from disk.*/export async function confirmDaemonSessionLoss(probe: RunningDaemonProbe,diff --git a/packages/coding-agent/src/config.ts b/packages/coding-agent/src/config.tsindex 0ac702afc2..8eb03159ae 100644--- a/packages/coding-agent/src/config.ts+++ b/packages/coding-agent/src/config.ts@@ -34,6 +34,9 @@ export const isBunBinary =/** Detect if Bun is the runtime (compiled binary or bun run) */export const isBunRuntime = !!process.versions.bun;+export const SELF_UPDATE_INTERACTIVE_CHILD_ENV = "PRIME_AGENT_INTERACTIVE_SELF_UPDATE";+export const SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE = 75;+// =============================================================================// Install Method Detection// =============================================================================@@ -557,6 +560,10 @@ export function getDaemonLogPath(socketPath: string): string {return join(getLogsDir(), `${basename(socketPath)}.${hash}.log`);}+export function getDaemonUpdateRestartManifestPath(agentDir: string = getAgentDir()): string {+ return join(agentDir, "daemon-update-restart.json");+}+const MAX_LOG_BYTES = 5 * 1024 * 1024;/**diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 37d03ecbf6..65da448870 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -28,7 +28,7 @@ import {type ShouldStopAfterTurnContext,type ThinkingLevel,} from "@earendil-works/pi-agent-core";-import type { AssistantMessage, ImageContent, Model, TextContent, Usage } from "@earendil-works/pi-ai";+import type { AssistantMessage, ImageContent, Model, TextContent, Usage, UserMessage } from "@earendil-works/pi-ai";import {clampThinkingLevel,cleanupSessionResources,@@ -398,20 +398,25 @@ export interface PromptOptions {preflightResult?: (success: boolean, queued?: boolean) => void;/** Queue instead of starting immediately when the session is idle but already has queued work. */queueIfBusy?: boolean;+ /** Skip extension input handlers for replaying already-accepted input. */+ skipInputHandlers?: boolean;+ agentMessageId?: string;+ content?: (TextContent | ImageContent)[];}interface InternalPromptOptions extends PromptOptions {skipPrePromptWork?: boolean;- skipInputHandlers?: boolean;returnAfterAccepted?: boolean;agentMessageId?: string;}+type QueuedAgentMessage = UserMessage | CustomMessage;+interface QueuedSteeringMessage {text: string;previewLabel?: string;agentMessageId?: string;- message: AgentMessage;+ message: QueuedAgentMessage;}interface QueuedFollowUpMessage {@@ -419,7 +424,54 @@ interface QueuedFollowUpMessage {previewLabel?: string;queueKey?: string;agentMessageId?: string;- message: AgentMessage;+ message: QueuedAgentMessage;+}++export interface QueuedAgentInputSnapshot {+ text: string;+ content?: (TextContent | ImageContent)[];+ images?: ImageContent[];+ queueKey?: string;+ agentMessageId?: string;+ customMessage?: CustomMessage;+}++export interface AcceptedAgentInputSnapshot extends QueuedAgentInputSnapshot {+ nextTurn: CustomMessage[];+}++function cloneCustomMessage(message: CustomMessage): CustomMessage {+ return {+ ...message,+ content: Array.isArray(message.content) ? message.content.map((block) => ({ ...block })) : message.content,+ };+}++function createQueuedAgentInputSnapshotFromUserMessage(+ text: string,+ message: QueuedAgentMessage,+): QueuedAgentInputSnapshot {+ if (message.role === "custom") {+ return { text, customMessage: cloneCustomMessage(message) };+ }+ const messageContent = message.content;+ if (!Array.isArray(messageContent)) {+ return { text };+ }+ const content = messageContent.map((block) => ({ ...block }));+ const images = content.filter((block): block is ImageContent => block.type === "image");+ return { text, content, ...(images.length > 0 ? { images } : {}) };+}++function createQueuedAgentInputSnapshot(+ message: QueuedSteeringMessage | QueuedFollowUpMessage,+): QueuedAgentInputSnapshot {+ const snapshot = createQueuedAgentInputSnapshotFromUserMessage(message.text, message.message);+ return {+ ...snapshot,+ ...(message.agentMessageId ? { agentMessageId: message.agentMessageId } : {}),+ ...("queueKey" in message && message.queueKey ? { queueKey: message.queueKey } : {}),+ };}function queuedMessagePreview(message: { text: string; previewLabel?: string }): string {@@ -440,10 +492,11 @@ function injectedMessagePreviewLabel(message: CustomMessage): string | undefinedinterface AcceptedAgentMessagePrompt {text: string;agentMessageId: string;- message: AgentMessage;+ message: UserMessage;messages: Set<AgentMessage>;/** Pending nextTurn messages drained into this prompt; restored to the queue if the prompt is cleared. */pendingNextTurnMessages: CustomMessage[];+ deliveredPendingNextTurnMessages: Set<CustomMessage>;accepted: Promise<void>;resolveAccepted: () => void;rejectAccepted: (error: Error) => void;@@ -451,6 +504,10 @@ interface AcceptedAgentMessagePrompt {cleared: boolean;}+function undeliveredPendingNextTurnMessages(accepted: AcceptedAgentMessagePrompt): CustomMessage[] {+ return accepted.pendingNextTurnMessages.filter((message) => !accepted.deliveredPendingNextTurnMessages.has(message));+}+interface AgentMessageDeliveryWaiter {promise: Promise<void>;resolve: () => void;@@ -1739,6 +1796,13 @@ export class AgentSession {} else if (acceptedPrompt.turnStarted) {acceptedPrompt.messages.add(event.message);}+ if (+ event.type === "message_end" &&+ event.message.role === "custom" &&+ acceptedPrompt.pendingNextTurnMessages.includes(event.message)+ ) {+ acceptedPrompt.deliveredPendingNextTurnMessages.add(event.message);+ }if (acceptedPrompt.cleared && acceptedPrompt.messages.has(event.message)) {// Membership filter, not a positional slice: newer prompts or compaction may// have rewritten state.messages since the clear.@@ -2366,7 +2430,7 @@ export class AgentSession {skipInputHandlers: true,skipPrePromptWork: true,returnAfterAccepted: true,- agentMessageId: parseAgentSessionMessagePromptId(text),+ agentMessageId: options?.agentMessageId ?? parseAgentSessionMessagePromptId(text),});}@@ -2658,8 +2722,10 @@ export class AgentSession {messages.push(msg);}this._pendingNextTurnMessages = [];- const userContent: (TextContent | ImageContent)[] = [{ type: "text", text: expandedText }];- if (currentImages) {+ const userContent: (TextContent | ImageContent)[] = options?.content+ ? options.content.map((block) => ({ ...block }))+ : [{ type: "text", text: expandedText }];+ if (!options?.content && currentImages) {userContent.push(...currentImages);}const userMessage: AgentMessage = {@@ -2681,6 +2747,7 @@ export class AgentSession {message: userMessage,messages: new Set<AgentMessage>([...drainedNextTurnMessages, userMessage]),pendingNextTurnMessages: drainedNextTurnMessages,+ deliveredPendingNextTurnMessages: new Set(),accepted,resolveAccepted,rejectAccepted,@@ -2706,8 +2773,10 @@ export class AgentSession {this._pendingNextTurnMessages = [];// Add user message- const userContent: (TextContent | ImageContent)[] = [{ type: "text", text: expandedText }];- if (currentImages) {+ const userContent: (TextContent | ImageContent)[] = options?.content+ ? options.content.map((block) => ({ ...block }))+ : [{ type: "text", text: expandedText }];+ if (!options?.content && currentImages) {userContent.push(...currentImages);}const userMessage: AgentMessage = {@@ -2837,7 +2906,9 @@ export class AgentSession {// The prompt was never accepted, so next-turn context drained for it// was not consumed by the model and must remain available to retry.this._pendingNextTurnMessages.unshift(- ...acceptedAgentMessagePrompt.pendingNextTurnMessages.map((message) => ({ ...message })),+ ...undeliveredPendingNextTurnMessages(acceptedAgentMessagePrompt).map((message) => ({+ ...message,+ })),);}reportPreflight(false);@@ -2961,7 +3032,11 @@ export class AgentSession {* @param images Optional image attachments to include with the message* @throws Error if text is an extension command*/- async followUp(text: string, images?: ImageContent[], options: { queueKey?: string } = {}): Promise<boolean> {+ async followUp(+ text: string,+ images?: ImageContent[],+ options: { queueKey?: string; agentMessageId?: string } = {},+ ): Promise<boolean> {// Check for extension commands (cannot be queued)if (text.startsWith("/")) {this._throwIfExtensionCommand(text);@@ -2971,7 +3046,44 @@ export class AgentSession {let expandedText = this._expandSkillCommand(text);expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);- return this._queueFollowUp(expandedText, images, { queueKey: options.queueKey });+ return this._queueFollowUp(expandedText, images, {+ queueKey: options.queueKey,+ agentMessageId: options.agentMessageId,+ });+ }++ async restoreSteeringMessage(+ text: string,+ images?: ImageContent[],+ options: {+ agentMessageId?: string;+ content?: (TextContent | ImageContent)[];+ customMessage?: CustomMessage;+ } = {},+ ): Promise<void> {+ await this._queueSteer(text, images, {+ agentMessageId: options.agentMessageId,+ content: options.content,+ message: options.customMessage,+ });+ }++ async restoreFollowUpMessage(+ text: string,+ images?: ImageContent[],+ options: {+ queueKey?: string;+ agentMessageId?: string;+ content?: (TextContent | ImageContent)[];+ customMessage?: CustomMessage;+ } = {},+ ): Promise<boolean> {+ return this._queueFollowUp(text, images, {+ queueKey: options.queueKey,+ agentMessageId: options.agentMessageId,+ content: options.content,+ message: options.customMessage,+ });}private _buildPromptContent(@@ -3060,18 +3172,18 @@ export class AgentSession {options: {agentMessageId?: string;content?: (TextContent | ImageContent)[];- message?: AgentMessage;+ message?: QueuedAgentMessage;previewLabel?: string;} = {},): Promise<void> {const content = options.content ?? this._buildPromptContent(text, images);- const message: AgentMessage =+ const message: QueuedAgentMessage =options.message ??({role: "user",content,timestamp: Date.now(),- } satisfies AgentMessage);+ } satisfies UserMessage);this._steeringMessages.push({text,previewLabel: options.previewLabel,@@ -3092,7 +3204,7 @@ export class AgentSession {queueKey?: string;agentMessageId?: string;content?: (TextContent | ImageContent)[];- message?: AgentMessage;+ message?: QueuedAgentMessage;previewLabel?: string;} = {},): Promise<boolean> {@@ -3100,13 +3212,13 @@ export class AgentSession {return false;}const content = options.content ?? this._buildPromptContent(text, images);- const message: AgentMessage =+ const message: QueuedAgentMessage =options.message ??({role: "user",content,timestamp: Date.now(),- } satisfies AgentMessage);+ } satisfies UserMessage);this._followUpMessages.push({text,previewLabel: options.previewLabel,@@ -3286,7 +3398,9 @@ export class AgentSession {this.agent.state.messages = this.agent.state.messages.filter((message) => !accepted.messages.has(message));// Restore drained nextTurn messages the model never saw. Clones, so the cleared// run's late-event cleanup cannot strip the restored copies from a newer run.- this._pendingNextTurnMessages.unshift(...accepted.pendingNextTurnMessages.map((message) => ({ ...message })));+ this._pendingNextTurnMessages.unshift(+ ...undeliveredPendingNextTurnMessages(accepted).map((message) => ({ ...message })),+ );const error = new Error("Accepted agent message was cleared before delivery.");this._rejectAgentMessageDelivery(accepted.agentMessageId, error);accepted.rejectAccepted(error);@@ -3320,6 +3434,39 @@ export class AgentSession {return this._followUpMessages.map(queuedMessagePreview);}+ getSteeringQueueSnapshots(): readonly QueuedAgentInputSnapshot[] {+ return this._steeringMessages.map((message) => createQueuedAgentInputSnapshot(message));+ }++ getFollowUpQueueSnapshots(): readonly QueuedAgentInputSnapshot[] {+ return this._followUpMessages.map((message) => createQueuedAgentInputSnapshot(message));+ }++ getPendingNextTurnMessageSnapshots(): readonly CustomMessage[] {+ const messages = this._pendingNextTurnMessages.map((message) => cloneCustomMessage(message));+ const accepted = this._acceptedAgentMessagePrompt;+ if (accepted && !accepted.cleared && accepted.turnStarted) {+ messages.push(...undeliveredPendingNextTurnMessages(accepted).map((message) => cloneCustomMessage(message)));+ }+ return messages;+ }++ getAcceptedPromptSnapshot(): AcceptedAgentInputSnapshot | undefined {+ const accepted = this._acceptedAgentMessagePrompt;+ if (!accepted || accepted.cleared || accepted.turnStarted) {+ return undefined;+ }+ return {+ ...createQueuedAgentInputSnapshotFromUserMessage(accepted.text, accepted.message),+ agentMessageId: accepted.agentMessageId,+ nextTurn: undeliveredPendingNextTurnMessages(accepted).map((message) => cloneCustomMessage(message)),+ };+ }++ restorePendingNextTurnMessages(messages: readonly CustomMessage[]): void {+ this._pendingNextTurnMessages.push(...messages.map((message) => cloneCustomMessage(message)));+ }+hasQueuedFollowUp(queueKey: string): boolean {return this._followUpMessages.some((message) => message.queueKey === queueKey);}@@ -3330,7 +3477,7 @@ export class AgentSession {return false;}this._followUpMessages = this._followUpMessages.filter((message) => message.queueKey !== queueKey);- const removedMessages = new Set(removed.map((message) => message.message));+ const removedMessages = new Set<AgentMessage>(removed.map((message) => message.message));for (const message of removed) {this._rejectAgentMessageDelivery(message.agentMessageId,@@ -3362,6 +3509,22 @@ export class AgentSession {}}+ abortForUpdateRestart(): void {+ this.abortRetry();+ this._cancelActiveRlmChildRuns("Parent session aborted for update restart");+ this._goalAbortInProgress = this._goalState.status === "active";+ this.agent.abort();+ if (this._goalAbortInProgress) {+ void this.agent+ .waitForIdle()+ .then(() => this._agentEventQueue)+ .catch(() => undefined)+ .finally(() => {+ this._goalAbortInProgress = false;+ });+ }+ }+// =========================================================================// Model Management// =========================================================================diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.tsindex d6d28a7c85..d7606dcc7b 100644--- a/packages/coding-agent/src/core/session-manager.ts+++ b/packages/coding-agent/src/core/session-manager.ts@@ -1222,6 +1222,35 @@ export class SessionManager {return this.sessionFile;}+ materializeSessionFile(sessionDir?: string): string {+ if (this.sessionFile) {+ return this.sessionFile;+ }+ const dir = sessionDir ?? (this.sessionDir || getDefaultSessionDir(this.cwd));+ if (!existsSync(dir)) {+ mkdirSync(dir, { recursive: true });+ }+ const target = createUniqueSessionFileTarget(dir);+ this.sessionDir = dir;+ this.sessionId = target.sessionId;+ this.sessionFile = target.sessionFile;+ this.persist = true;+ const timestamp = new Date().toISOString();+ const git = captureGitContext(this.cwd) ?? undefined;+ const header: SessionHeader = {+ type: "session",+ version: CURRENT_SESSION_VERSION,+ id: this.sessionId,+ timestamp,+ cwd: this.cwd,+ git,+ };+ this.fileEntries = [header, ...this.getEntries()];+ this._rewriteFile();+ this.flushed = true;+ return this.sessionFile;+ }+getSessionArtifactDir(): string | undefined {return this.persist ? getSessionArtifactPath(this.sessionDir, this.sessionId) : undefined;}diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.tsindex fe24cdd749..400bbc169b 100644--- a/packages/coding-agent/src/core/slash-commands.ts+++ b/packages/coding-agent/src/core/slash-commands.ts@@ -55,6 +55,12 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [},{ name: "context", description: "Show token, cost, and context usage for agent and sub-agents" },{ name: "changelog", description: "Show changelog entries" },+ {+ name: "update",+ description: `Update ${APP_NAME} and installed packages`,+ argumentHint: "[source|--self|--extensions]",+ takesArgument: true,+ },{ name: "hotkeys", description: "Show all keyboard shortcuts" },{ name: "fork", description: "Create a new fork from a previous user message" },{ name: "clone", description: "Duplicate the current session at the current position" },diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 8fa0c5219a..91fde593ed 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -6,10 +6,17 @@* disposing the underlying agent loop.*/+import { mkdirSync, writeFileSync } from "node:fs";import { createServer, type Server, type Socket } from "node:net";-import { resolve } from "node:path";+import { dirname, resolve } from "node:path";import { getLogger } from "@earendil-works/pi-ai";-import { appendRotatingLog, getCronJobsPath, getDaemonLogPath, VERSION } from "../../config.js";+import {+ appendRotatingLog,+ getCronJobsPath,+ getDaemonLogPath,+ getDaemonUpdateRestartManifestPath,+ VERSION,+} from "../../config.js";import {AGENT_MESSAGE_SOURCE,type AgentSessionMessageAgentSummary,@@ -48,6 +55,7 @@ import type { AgentSession, PromptOptions } from "../../core/agent-session.js";import { type AgentSessionRuntimeConfig, mergeAgentSessionRuntimeConfig } from "../../core/agent-session-config.js";import {AgentSessionRuntime,+ type AgentSessionRuntimeMetadata,type CreateAgentSessionRuntimeFactory,createAgentSessionRuntime,} from "../../core/agent-session-runtime.js";@@ -101,6 +109,8 @@ import {type DaemonSavedSessionInfo,type DaemonSessionClosedReason,type DaemonSessionSnapshot,+ type DaemonUpdateRestartManifest,+ type DaemonUpdateRestartSession,failure,isDaemonDialogExtensionUiRequest,success,@@ -142,6 +152,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["prompt","steer","follow_up",+ "restore_next_turn",+ "resume_queue","send_message","agent_messages_status","agent_messages_pause",@@ -201,6 +213,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["get_tool_definition","set_session_entry_label","extension_ui_response",+ "prepare_update_restart","shutdown",]);@@ -212,6 +225,15 @@ const DAEMON_SERVER_CAPABILITIES: readonly DaemonClientCapability[] = [];const DAEMON_CLIENT_CAPABILITY_SET: ReadonlySet<string> = new Set(DAEMON_SERVER_CAPABILITIES);+const UPDATE_RESTART_ABORT_BASH_TIMEOUT_MS = 5000;+const UPDATE_RESTART_MARKER =+ "<prime_agent_update_interrupted>\n" ++ "Prime Agent was updated and intentionally interrupted this session. Continue from the saved transcript and restored tool/kernel state. Any running model, tool, bash, or child-agent work may have been partially completed.\n" ++ "</prime_agent_update_interrupted>";++function delay(ms: number): Promise<void> {+ return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));+}export async function runDaemonMode(options: DaemonModeOptions): Promise<never> {const socketPath = options.socketPath ?? defaultDaemonSocketPath();@@ -223,6 +245,7 @@ export async function runDaemonMode(options: DaemonModeOptions): Promise<never>export class AgentDaemon {private server?: Server;private shuttingDown = false;+ private updateRestartPreparing = false;private ownsSocketPath = false;private readonly clients = new Set<DaemonSocketClient>();private readonly sessions = new Map<string, ActiveSessionState>();@@ -481,6 +504,7 @@ export class AgentDaemon {agentDir,sessionManager,sessionConfig: config,+ runtimeMetadata: command.runtimeMetadata,sessionOptions: {customTools: [...createAgentHeartbeatToolDefinitions({@@ -576,8 +600,11 @@ export class AgentDaemon {}private async runCronJob(job: AgentCronJob): Promise<"skipped" | undefined> {+ if (this.updateRestartPreparing) {+ return "skipped";+ }const state = await this.getOrCreateCronJobSession(job);- if (!state) {+ if (!state || this.updateRestartPreparing) {return "skipped";}const session = state.runtime.session;@@ -625,14 +652,18 @@ export class AgentDaemon {message: string,options?: PromptOptions,): Promise<void> {- await this.withAgentMessagePreparingGuard(state, (session) =>- session.prompt(message, {+ await this.withAgentMessagePreparingGuard(state, (session) => {+ const prompt =+ options?.agentMessageId === undefined+ ? session.prompt.bind(session)+ : session.acceptAgentMessagePrompt.bind(session);+ return prompt(message, {...options,preflightResult: (didSucceed) => {options?.preflightResult?.(didSucceed);},- }),- );+ });+ });}private async promptHeartbeatWithAgentMessagePreparingGuard(@@ -862,6 +893,9 @@ export class AgentDaemon {}private async getOrCreateCronJobSession(job: AgentCronJob): Promise<ActiveSessionState | undefined> {+ if (this.updateRestartPreparing) {+ return undefined;+ }const current = this.sessions.get(job.activeSessionId) ?? this.findSessionBySessionFile(job.sessionFile);// A half-bound match falls through to createRuntime, which awaits the// pending create for the same session file instead of prompting mid-bind.@@ -1206,6 +1240,9 @@ export class AgentDaemon {client: DaemonSocketClient,command: DaemonCommand,): Promise<DaemonResponse | undefined> {+ if (this.updateRestartPreparing && command.type !== "shutdown") {+ throw new Error("Daemon is preparing an update restart");+ }switch (command.type) {case "list": {const activeSessions = Array.from(this.sessions.values());@@ -1355,8 +1392,12 @@ export class AgentDaemon {this.write(client, success(command.id, "prompt"));};void this.promptWithAgentMessagePreparingGuard(state, command.message, {+ content: command.content,images: command.images,streamingBehavior: command.streamingBehavior,+ expandPromptTemplates: command.expandPromptTemplates,+ agentMessageId: command.agentMessageId,+ skipInputHandlers: command.expandPromptTemplates === false ? true : undefined,source: "rpc",preflightResult: (didSucceed) => {if (didSucceed) {@@ -1379,14 +1420,64 @@ export class AgentDaemon {case "steer": {const state = this.getSessionState(command.activeSessionId);- await state.runtime.session.steer(command.message, command.images);+ if (command.expandPromptTemplates === false) {+ await state.runtime.session.restoreSteeringMessage(command.message, command.images, {+ agentMessageId: command.agentMessageId,+ content: command.content,+ customMessage: command.customMessage,+ });+ } else {+ await state.runtime.session.steer(command.message, command.images);+ }return success(command.id, "steer");}case "follow_up": {const state = this.getSessionState(command.activeSessionId);- await state.runtime.session.followUp(command.message, command.images);- return success(command.id, "follow_up");+ let queued: boolean;+ if (command.expandPromptTemplates === false) {+ queued = await state.runtime.session.restoreFollowUpMessage(command.message, command.images, {+ queueKey: command.queueKey,+ agentMessageId: command.agentMessageId,+ content: command.content,+ customMessage: command.customMessage,+ });+ } else {+ queued = await state.runtime.session.followUp(command.message, command.images, {+ queueKey: command.queueKey,+ agentMessageId: command.agentMessageId,+ });+ }+ return success(command.id, "follow_up", { queued });+ }++ case "restore_next_turn": {+ const state = this.getSessionState(command.activeSessionId);+ state.runtime.session.restorePendingNextTurnMessages(command.messages);+ return success(command.id, "restore_next_turn");+ }++ case "resume_queue": {+ const state = this.getSessionState(command.activeSessionId);+ let checkedStart = false;+ let startError: unknown;+ void state.runtime.session.agent.continue().then(undefined, (error: unknown) => {+ if (checkedStart) {+ this.broadcastToSession(+ state,+ failure(undefined, "resume_queue", error, serializeDaemonError(error)),+ );+ } else {+ startError = error;+ }+ });+ // Self-update restore must acknowledge that queued work restarted without waiting for it to finish.+ await Promise.resolve();+ checkedStart = true;+ if (startError !== undefined) {+ return failure(command.id, "resume_queue", startError, serializeDaemonError(startError));+ }+ return success(command.id, "resume_queue");}case "send_message": {@@ -1817,6 +1908,12 @@ export class AgentDaemon {return success(command.id, "extension_ui_response");}+ case "prepare_update_restart":+ this.log(+ `prepare_update_restart command received over socket; ${this.sessions.size} active session(s) will be closed`,+ );+ return success(command.id, "prepare_update_restart", await this.prepareUpdateRestart());+case "shutdown":this.log(`shutdown command received over socket; ${this.sessions.size} active session(s) will be closed`);setImmediate(() => {@@ -2187,6 +2284,186 @@ export class AgentDaemon {return !this.hasScheduledJobsForSession(state.activeSessionId);}+ private createUpdateRestartSession(state: ActiveSessionState): DaemonUpdateRestartSession | undefined {+ const session = state.runtime.session;+ const queue = {+ steering: [...session.getSteeringQueueSnapshots()].map((message) => ({+ message: message.text,+ ...(message.content ? { content: message.content } : {}),+ ...(message.images ? { images: message.images } : {}),+ ...(message.agentMessageId ? { agentMessageId: message.agentMessageId } : {}),+ ...(message.customMessage ? { customMessage: message.customMessage } : {}),+ })),+ followUp: [...session.getFollowUpQueueSnapshots()].map((message) => ({+ message: message.text,+ ...(message.content ? { content: message.content } : {}),+ ...(message.images ? { images: message.images } : {}),+ ...(message.queueKey ? { queueKey: message.queueKey } : {}),+ ...(message.agentMessageId ? { agentMessageId: message.agentMessageId } : {}),+ ...(message.customMessage ? { customMessage: message.customMessage } : {}),+ })),+ nextTurn: [...session.getPendingNextTurnMessageSnapshots()],+ };+ const acceptedPrompt = session.getAcceptedPromptSnapshot();+ const restartQueue = {+ ...queue,+ ...(acceptedPrompt+ ? {+ acceptedPrompt: {+ message: acceptedPrompt.text,+ ...(acceptedPrompt.content ? { content: acceptedPrompt.content } : {}),+ ...(acceptedPrompt.images ? { images: acceptedPrompt.images } : {}),+ agentMessageId: acceptedPrompt.agentMessageId,+ nextTurn: acceptedPrompt.nextTurn,+ },+ }+ : {}),+ };+ const hasQueuedMessages =+ restartQueue.steering.length > 0 ||+ restartQueue.followUp.length > 0 ||+ restartQueue.nextTurn.length > 0 ||+ restartQueue.acceptedPrompt !== undefined;+ const wasStreaming = session.isStreaming;+ const wasCompacting = session.isCompacting;+ const wasBashRunning = session.isBashRunning;+ const hadRunningRlmChildren = session.hasRunningRlmChildren();+ const wasRetrying = session.isRetrying;+ const hadAcceptedPromptInFlight = session.hasAcceptedPromptInFlight;+ const shouldResume =+ wasStreaming ||+ wasCompacting ||+ wasBashRunning ||+ hadRunningRlmChildren ||+ wasRetrying ||+ hadAcceptedPromptInFlight ||+ restartQueue.steering.length > 0 ||+ restartQueue.followUp.length > 0 ||+ restartQueue.acceptedPrompt !== undefined;+ const sessionFile =+ session.sessionFile ??+ (hasQueuedMessages || shouldResume+ ? session.sessionManager.materializeSessionFile(+ state.runtime.runtimeConfig?.sessionDir ?? this.options.defaultSessionConfig.sessionDir,+ )+ : undefined);+ if (!sessionFile || (this.isEmptyDraftContent(state) && !hasQueuedMessages && !shouldResume)) {+ return undefined;+ }+ return {+ activeSessionId: state.activeSessionId,+ sessionId: session.sessionId,+ sessionFile,+ cwd: session.sessionManager.getCwd(),+ config: {+ ...state.runtime.runtimeConfig,+ cwd: session.sessionManager.getCwd(),+ },+ runtimeMetadata: state.runtime.metadata,+ ...(state.clientEnv ? { clientEnv: { ...state.clientEnv } } : {}),+ queue: restartQueue,+ shouldResume,+ wasStreaming,+ wasCompacting,+ wasBashRunning,+ hadRunningRlmChildren,+ wasRetrying,+ hadAcceptedPromptInFlight,+ };+ }++ private appendUpdateRestartMarker(state: ActiveSessionState, restartSession: DaemonUpdateRestartSession): void {+ if (!restartSession.shouldResume) {+ return;+ }+ state.runtime.session.sessionManager.appendCustomMessageEntry(+ "prime-agent.update_restart",+ UPDATE_RESTART_MARKER,+ false,+ {+ activeSessionId: restartSession.activeSessionId,+ wasStreaming: restartSession.wasStreaming,+ wasCompacting: restartSession.wasCompacting,+ wasBashRunning: restartSession.wasBashRunning,+ hadRunningRlmChildren: restartSession.hadRunningRlmChildren,+ wasRetrying: restartSession.wasRetrying,+ hadAcceptedPromptInFlight: restartSession.hadAcceptedPromptInFlight,+ },+ );+ }++ private writeUpdateRestartManifest(manifest: DaemonUpdateRestartManifest): void {+ const path = getDaemonUpdateRestartManifestPath(this.options.defaultSessionConfig.agentDir);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, `${JSON.stringify(manifest)}\n`);+ }++ private getUpdateRestartSessionDepth(state: ActiveSessionState): number {+ let depth = 0;+ let metadata: AgentSessionRuntimeMetadata = state.runtime.metadata;+ const seen = new Set<string>([state.activeSessionId]);+ while (metadata.parentActiveSessionId && !seen.has(metadata.parentActiveSessionId)) {+ const parent = this.sessions.get(metadata.parentActiveSessionId);+ if (!parent) {+ break;+ }+ seen.add(parent.activeSessionId);+ depth++;+ metadata = parent.runtime.metadata;+ }+ return depth;+ }++ private async prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest> {+ if (this.updateRestartPreparing) {+ throw new Error("Daemon is already preparing an update restart");+ }+ this.updateRestartPreparing = true;+ // Keep persisted jobs for the replacement daemon, but stop this daemon from firing them after sessions detach.+ this.cronScheduler.stop();+ try {+ const states = [...this.sessions.values()];+ const restartSessions = states+ .map((state) => [state, this.createUpdateRestartSession(state)] as const)+ .filter(+ (entry): entry is readonly [ActiveSessionState, DaemonUpdateRestartSession] => entry[1] !== undefined,+ )+ .sort(+ ([left], [right]) => this.getUpdateRestartSessionDepth(left) - this.getUpdateRestartSessionDepth(right),+ );+ const manifest = {+ createdAt: new Date().toISOString(),+ sessions: restartSessions.map(([, restartSession]) => restartSession),+ };++ this.writeUpdateRestartManifest(manifest);++ for (const [state, restartSession] of restartSessions) {+ this.appendUpdateRestartMarker(state, restartSession);+ }+ const restoredActiveSessionIds = new Set(restartSessions.map(([state]) => state.activeSessionId));+ const closeStates = [...states].sort(+ (left, right) => this.getUpdateRestartSessionDepth(right) - this.getUpdateRestartSessionDepth(left),+ );+ for (const state of closeStates) {+ if (this.sessions.has(state.activeSessionId)) {+ await this.closeSession(+ state,+ restoredActiveSessionIds.has(state.activeSessionId) ? "update" : "killed",+ );+ }+ }+ for (const state of [...this.sessions.values()]) {+ await this.closeSession(state, "killed");+ }++ return manifest;+ } catch (error) {+ this.updateRestartPreparing = false;+ throw error;+ }+ }+private hasScheduledJobsForSession(activeSessionId: string): boolean {return this.cronStore.list()@@ -2231,6 +2508,17 @@ export class AgentDaemon {}}+ private async abortBashForClose(state: ActiveSessionState): Promise<void> {+ if (!state.runtime.session.isBashRunning) {+ return;+ }+ state.runtime.session.abortBash();+ const deadline = Date.now() + UPDATE_RESTART_ABORT_BASH_TIMEOUT_MS;+ while (state.runtime.session.isBashRunning && Date.now() < deadline) {+ await delay(50);+ }+ }+private async closeSessionOnce(state: ActiveSessionState, reason: DaemonSessionClosedReason): Promise<void> {if (!this.sessions.has(state.activeSessionId)) {return;@@ -2247,10 +2535,11 @@ export class AgentDaemon {// Empty draft (no messages, config, or jobs): discard rather than persist an// empty session file. Mirrors the detach-time discard so a config-bearing// draft closed via kill/completed is never wiped.- const isEmptyDraftSession = reason !== "shutdown" && this.isEmptyDraftContent(state);+ const keepsResumeEntry = reason === "shutdown" || reason === "update";+ const isEmptyDraftSession = !keepsResumeEntry && this.isEmptyDraftContent(state);let persistError: unknown;// Clean shutdown leaves the session un-archived so it stays in the resume list.- if (reason !== "shutdown" && !isEmptyDraftSession) {+ if (!keepsResumeEntry && !isEmptyDraftSession) {try {state.runtime.session.sessionManager.appendSessionState({ status: "archived" });} catch (error) {@@ -2258,6 +2547,12 @@ export class AgentDaemon {}}cancelPendingExtensionUiRequests(state);+ if (reason === "killed" || reason === "shutdown" || reason === "replaced" || reason === "update") {+ await this.abortBashForClose(state);+ }+ if (reason === "update") {+ state.runtime.session.abortForUpdateRestart();+ }if (reason === "killed" || reason === "shutdown" || reason === "replaced") {await state.runtime.session.abort().catch(() => undefined);}@@ -2275,10 +2570,10 @@ export class AgentDaemon {await deleteSessionFile(sessionFile).catch(() => undefined);}}- if (persistError && reason !== "shutdown" && reason !== "completed") {+ if (persistError && !keepsResumeEntry && reason !== "completed") {throw persistError;}- if (cascadeError && reason !== "shutdown" && reason !== "completed") {+ if (cascadeError && !keepsResumeEntry && reason !== "completed") {throw cascadeError;}}diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex febfe15887..442a71f271 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -1,12 +1,14 @@import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";-import type { ImageContent, Transport } from "@earendil-works/pi-ai";+import type { ImageContent, TextContent, Transport } from "@earendil-works/pi-ai";import type {AgentSessionMessageDeliveryMode,AgentSessionMessageReceipt,AgentSessionMessageSafetyStatus,} from "../../core/agent-messages.js";import type { AgentSessionRuntimeConfig } from "../../core/agent-session-config.js";+import type { AgentSessionRuntimeMetadata } from "../../core/agent-session-runtime.js";import type { AgentCronJob, AgentHeartbeatUpdateAction } from "../../core/cron-jobs.js";+import type { CustomMessage } from "../../core/messages.js";import type { SessionCwdIssue } from "../../core/session-cwd.js";import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";import type {@@ -185,6 +187,49 @@ export interface DaemonAttachResult {};}+export interface DaemonUpdateRestartQueuedMessage {+ message: string;+ content?: (TextContent | ImageContent)[];+ images?: ImageContent[];+ queueKey?: string;+ agentMessageId?: string;+ customMessage?: CustomMessage;+}++export interface DaemonUpdateRestartAcceptedPrompt extends DaemonUpdateRestartQueuedMessage {+ nextTurn: CustomMessage[];+}++export interface DaemonUpdateRestartQueue {+ steering: DaemonUpdateRestartQueuedMessage[];+ followUp: DaemonUpdateRestartQueuedMessage[];+ nextTurn: CustomMessage[];+ acceptedPrompt?: DaemonUpdateRestartAcceptedPrompt;+}++export interface DaemonUpdateRestartSession {+ activeSessionId: string;+ sessionId: string;+ sessionFile: string;+ cwd: string;+ config: AgentSessionRuntimeConfig;+ runtimeMetadata?: AgentSessionRuntimeMetadata;+ clientEnv?: Record<string, string>;+ queue: DaemonUpdateRestartQueue;+ shouldResume: boolean;+ wasStreaming: boolean;+ wasCompacting: boolean;+ wasBashRunning: boolean;+ hadRunningRlmChildren: boolean;+ wasRetrying: boolean;+ hadAcceptedPromptInFlight: boolean;+}++export interface DaemonUpdateRestartManifest {+ createdAt: string;+ sessions: DaemonUpdateRestartSession[];+}+export type DaemonCommand =| { id?: string; type: "list"; all?: boolean; cwd?: string; sessionDir?: string }| { id?: string; type: "list_saved_sessions"; activeSessionId: string; scope: AgentConnectionSavedSessionScope }@@ -195,6 +240,7 @@ export type DaemonCommand =continueRecent?: boolean;name?: string;config?: AgentSessionRuntimeConfig;+ runtimeMetadata?: AgentSessionRuntimeMetadata;} & DaemonClientEnv)// Attach env is adopt-if-absent only: it fills identity for env-less// sessions (e.g. cron-created) but never rebinds one, since watchers@@ -214,11 +260,37 @@ export type DaemonCommand =type: "prompt";activeSessionId: string;message: string;+ content?: (TextContent | ImageContent)[];images?: ImageContent[];streamingBehavior?: "steer" | "followUp";+ expandPromptTemplates?: boolean;+ agentMessageId?: string;+ }+ | {+ id?: string;+ type: "steer";+ activeSessionId: string;+ message: string;+ content?: (TextContent | ImageContent)[];+ images?: ImageContent[];+ expandPromptTemplates?: boolean;+ agentMessageId?: string;+ customMessage?: CustomMessage;+ }+ | {+ id?: string;+ type: "follow_up";+ activeSessionId: string;+ message: string;+ content?: (TextContent | ImageContent)[];+ images?: ImageContent[];+ queueKey?: string;+ expandPromptTemplates?: boolean;+ agentMessageId?: string;+ customMessage?: CustomMessage;}- | { id?: string; type: "steer"; activeSessionId: string; message: string; images?: ImageContent[] }- | { id?: string; type: "follow_up"; activeSessionId: string; message: string; images?: ImageContent[] }+ | { id?: string; type: "restore_next_turn"; activeSessionId: string; messages: CustomMessage[] }+ | { id?: string; type: "resume_queue"; activeSessionId: string }| {id?: string;type: "send_message";@@ -313,6 +385,7 @@ export type DaemonCommand =requestId: string;response: DaemonExtensionUIResponse;}+ | { id?: string; type: "prepare_update_restart" }| { id?: string; type: "shutdown" };type DaemonCommandName = DaemonCommand["type"];@@ -332,7 +405,7 @@ export type DaemonErrorInfo =| { code: "missing_session_cwd"; issue: SessionCwdIssue }| { code: "session_import_file_not_found"; filePath: string };-export type DaemonSessionClosedReason = "killed" | "shutdown" | "completed" | "replaced";+export type DaemonSessionClosedReason = "killed" | "shutdown" | "completed" | "replaced" | "update";export type DaemonExtensionUIResponse = { value: string } | { confirmed: boolean } | { cancelled: true };diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.tsindex 63f7c4b5b9..beafb8f5be 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -38,6 +38,7 @@ export interface SessionSummary {isStreaming: boolean;isCompacting: boolean;isBashRunning?: boolean;+ hasRunningRlmChildren?: boolean;/** True while the agent is streaming with tool calls pending; drives the "running tools" label. */isRunningTools?: boolean;attachedClients: number;@@ -146,6 +147,7 @@ export function summaryForActiveSession(activeSession: ActiveSessionState, savedisStreaming: session.isStreaming,isCompacting: session.isCompacting,isBashRunning: session.isBashRunning,+ hasRunningRlmChildren: session.hasRunningRlmChildren(),isRunningTools: session.isStreaming && session.state.pendingToolCalls.size > 0,attachedClients: activeSession.clients.size,messageCount: session.messages.length,@@ -324,6 +326,7 @@ export function isActiveSessionBusy(activeSession: ActiveSessionState): booleanreturn (session.isStreaming ||session.isCompacting ||+ session.isBashRunning ||effectivePendingMessageCount(session) > 0 ||session.hasRunningRlmChildren());diff --git a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.tsindex fdb85e2d63..c134fa1d0c 100644--- a/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts+++ b/packages/coding-agent/src/modes/interactive/components/child-agent-inspector.ts@@ -208,8 +208,7 @@ export class ChildAgentSummaryComponent implements Component, Focusable {onExit?: () => void;onOpenDetail?: (nodeId: string) => void;// Chat actions that should still work while the list holds focus.- onChatAction?: (data: string) => boolean | undefined;- onUnhandledInput?: (data: string) => void;+ onChatAction?: (data: string) => void;constructor(private readonly getLocationLabel: () => string | undefined = () => undefined,@@ -287,10 +286,8 @@ export class ChildAgentSummaryComponent implements Component, Focusable {this.onCancel?.();return;}- if (this.onChatAction?.(data)) {- return;- }- this.onUnhandledInput?.(data);+ // Keys the list doesn't own fall through to chat actions (expand tools, etc.).+ this.onChatAction?.(data);}private isAtFirstRow(flat: readonly FlatChildAgentNode[]): boolean {diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex ddf5398615..63adab678b 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -49,12 +49,15 @@ import {} from "@earendil-works/pi-tui";import { spawn, spawnSync } from "child_process";import {+ APP_NAME,APP_TITLE,getAgentDir,getAgentTracesLogPath,getDebugLogPath,getLogsDir,getShareViewerUrl,+ SELF_UPDATE_INTERACTIVE_CHILD_ENV,+ SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE,VERSION,} from "../../config.js";import {@@ -86,6 +89,7 @@ import {} from "../../core/messages.js";import { findExactModelReferenceMatch, resolveModelScopeFromModels } from "../../core/model-resolver.js";import { resolvePrimeAgentTracesBaseUrl } from "../../core/prime-inference-auth.js";+import { parseCommandArgs } from "../../core/prompt-templates.js";import { formatMissingSessionCwdPrompt, MissingSessionCwdError } from "../../core/session-cwd.js";import { SessionImportFileNotFoundError } from "../../core/session-import-errors.js";import { parseSkillBlock } from "../../core/skill-blocks.js";@@ -472,6 +476,51 @@ function getPayloadWorkingIndicatorOptions(};}+function updateArgsIncludeSelf(args: readonly string[]): boolean {+ let selfFlag = false;+ let extensionsOnlyFlag = false;+ for (let index = 0; index < args.length; index++) {+ const arg = args[index];+ if (arg === "--self") {+ selfFlag = true;+ } else if (arg === "--extensions") {+ extensionsOnlyFlag = true;+ } else if (arg === "--extension") {+ extensionsOnlyFlag = true;+ index++;+ }+ }+ if (selfFlag) {+ return true;+ }+ if (extensionsOnlyFlag) {+ return false;+ }+ const positional = args.find((arg) => !arg.startsWith("-"));+ if (!positional) {+ return true;+ }+ const normalized = positional.toLowerCase();+ return normalized === "self" || normalized === "pi" || normalized === APP_NAME.toLowerCase();+}++function argsIncludeSessionSelection(args: readonly string[]): boolean {+ for (const arg of args) {+ if (arg === "--resume" || arg === "-r" || arg === "--continue" || arg === "-c" || arg === "--fork") {+ return true;+ }+ }+ return false;+}++export function buildUpdateRelaunchArgs(args: readonly string[], sessionFile: string | undefined): string[] {+ const relaunchArgs = [...args];+ if (sessionFile && !argsIncludeSessionSelection(relaunchArgs)) {+ relaunchArgs.push("--resume", sessionFile);+ }+ return relaunchArgs;+}+/*** Options for InteractiveMode initialization.*/@@ -770,7 +819,6 @@ export class InteractiveMode {this.childAgentSummary.onCancel = () => this.focusEditor();this.childAgentSummary.onExit = () => this.handleSubagentSummaryExit();this.childAgentSummary.onChatAction = (data) => this.handleSubagentSummaryChatAction(data);- this.childAgentSummary.onUnhandledInput = (data) => this.handleSubagentSummaryUnhandledInput(data);this.footerDataProvider = new FooterDataProvider(this.uiServices.getInitialCwd());this.footer = new FooterComponent(this.footerDataProvider);this.footer.setAutoCompactEnabled(this.settingsManager.getCompactionEnabled());@@ -3603,6 +3651,7 @@ export class InteractiveMode {text = text.trim();if (!text) return;const promptStashToRestore = this.promptStash;+ let restorePromptStashAfterSubmit = true;try {const slashCommand = parseSlashCommand(text);@@ -3721,6 +3770,7 @@ export class InteractiveMode {}if (commandName === "tree" && !commandArgs) {this.editor.setText("");+ restorePromptStashAfterSubmit = false;await this.showTreeSelector();return;}@@ -3761,6 +3811,19 @@ export class InteractiveMode {await this.handleReloadCommand();return;}+ if (commandName === "update") {+ this.editor.setText("");+ const updateArgs = parseCommandArgs(commandArgs);+ if (+ !updateArgsIncludeSelf(updateArgs) &&+ (this.isAgentCompacting() || this.isAgentStreaming() || this.isBashRunning())+ ) {+ this.showWarning("Wait for the current work to finish before updating.");+ return;+ }+ await this.handleUpdateCommand(commandArgs);+ return;+ }if (commandName === "fullscreen") {this.editor.setText("");const arg = commandArgs?.trim().toLowerCase();@@ -3866,7 +3929,7 @@ export class InteractiveMode {}this.editor.addToHistory?.(text);} finally {- if (promptStashToRestore !== undefined) {+ if (restorePromptStashAfterSubmit && promptStashToRestore !== undefined) {this.restorePromptStashIfEditorEmpty(promptStashToRestore);}}@@ -4707,23 +4770,19 @@ export class InteractiveMode {this.focusEditor();}- private handleSubagentSummaryUnhandledInput(data: string): void {- this.focusEditor();- this.editor.handleInput(data);- }-// Chat actions stay live while the subagent list holds focus; the editor's// own handlers are bypassed because input routes only to the focused list.- private handleSubagentSummaryChatAction(data: string): boolean {+ private handleSubagentSummaryChatAction(data: string): void {if (this.keybindings.matches(data, "app.tools.expand")) {this.toggleToolOutputExpansion();- return true;+ return;}if (this.keybindings.matches(data, "app.thinking.toggle")) {this.toggleThinkingBlockVisibility();- return true;+ return;}- return false;+ this.focusEditor();+ this.editor.handleInput(data);}private getTrayOverrideLabel(): string | undefined {@@ -7157,6 +7216,89 @@ export class InteractiveMode {// Command handlers// =========================================================================+ private async handleUpdateCommand(args: string): Promise<void> {+ const entrypoint = process.argv[1];+ if (!entrypoint) {+ this.showError("Cannot determine current CLI entrypoint for update");+ return;+ }++ const updateArgs = parseCommandArgs(args);+ const includesSelf = updateArgsIncludeSelf(updateArgs);+ const updateCwd = this.getCurrentCwd();+ this.stopWorkingLoader();+ await this.ui.terminal.drainInput(1000).catch(() => undefined);+ this.ui.stop();++ const updateEnv = includesSelf ? { ...process.env, [SELF_UPDATE_INTERACTIVE_CHILD_ENV]: "1" } : process.env;+ const updateResult = spawnSync(process.execPath, [...process.execArgv, entrypoint, "update", ...updateArgs], {+ stdio: "inherit",+ cwd: updateCwd,+ env: updateEnv,+ });+ const updateExitCode = updateResult.status ?? (updateResult.signal ? 1 : 0);+ const selfUpdateNotAttempted =+ includesSelf && !updateResult.error && updateExitCode === SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE;++ if (includesSelf && !selfUpdateNotAttempted) {+ const relaunchArgs = buildUpdateRelaunchArgs(process.argv.slice(2), this.connectionState?.sessionFile);+ if (updateResult.error) {+ console.error(`Update failed: ${updateResult.error.message}`);+ console.error(`Relaunching ${APP_NAME}...`);+ } else if (updateExitCode !== 0) {+ console.error(+ updateResult.signal+ ? `Update terminated by signal ${updateResult.signal}`+ : `Update exited with code ${updateExitCode}`,+ );+ console.error(`Relaunching ${APP_NAME}...`);+ }+ this.stop();+ await this.agentConnection.dispose().catch(() => undefined);+ try {+ await this.options.onShutdown?.();+ } catch {+ // The update already completed; do not block relaunch on local teardown.+ }+ const relaunchResult = spawnSync(process.execPath, [...process.execArgv, entrypoint, ...relaunchArgs], {+ stdio: "inherit",+ cwd: updateCwd,+ env: process.env,+ });+ if (relaunchResult.error) {+ console.error(`Failed to relaunch ${APP_NAME}: ${relaunchResult.error.message}`);+ process.exit(1);+ }+ process.exit(relaunchResult.status ?? (relaunchResult.signal ? 1 : 0));+ }++ this.ui.start();+ if (this.fullscreenEnabled) {+ this.applyFullscreen(true);+ }+ this.ui.requestRender(true);++ if (selfUpdateNotAttempted) {+ this.showStatus(`Update did not change ${APP_NAME}. Reloading resources...`);+ await this.handleReloadCommand();+ return;+ }+ if (updateResult.error) {+ this.showError(`Update failed: ${updateResult.error.message}`);+ return;+ }+ if (updateExitCode !== 0) {+ this.showError(+ updateResult.signal+ ? `Update terminated by signal ${updateResult.signal}`+ : `Update exited with code ${updateExitCode}`,+ );+ return;+ }+ this.showStatus("Packages updated. Reloading resources...");+ await this.handleReloadCommand();+ }+private async handleReloadCommand(): Promise<void> {if (this.isAgentStreaming()) {this.showWarning("Wait for the current response to finish before reloading.");diff --git a/packages/coding-agent/src/modes/shared/startup-notices.ts b/packages/coding-agent/src/modes/shared/startup-notices.tsindex 0624aa4094..1fe9ea1ad8 100644--- a/packages/coding-agent/src/modes/shared/startup-notices.ts+++ b/packages/coding-agent/src/modes/shared/startup-notices.ts@@ -111,7 +111,7 @@ export async function checkTmuxKeyboardSetup(): Promise<string | undefined> {export function formatUpdateAvailableNotice(newVersion: string): string {return (`${theme.bold(theme.fg("accent", "Update available:"))} ` +- `${theme.fg("muted", `v${newVersion}. Run `)}${theme.fg("accent", "prime-agent update")}`+ `${theme.fg("muted", `v${newVersion}. Run `)}${theme.fg("accent", "/update")}`);}@@ -119,7 +119,7 @@ export function formatPackageUpdateNotice(packages: string[]): string {const packageList = packages.join(", ");return (`${theme.bold(theme.fg("warning", "Package updates available:"))} ` +- `${theme.fg("muted", `${packageList}. Run `)}${theme.fg("accent", "prime-agent update --extensions")}`+ `${theme.fg("muted", `${packageList}. Run `)}${theme.fg("accent", "/update --extensions")}`);}diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.tsindex aff93faf67..db9574e658 100644--- a/packages/coding-agent/src/package-manager-cli.ts+++ b/packages/coding-agent/src/package-manager-cli.ts@@ -1,8 +1,11 @@import chalk from "chalk";import { spawn } from "child_process";+import { readFileSync, rmSync, statSync } from "fs";import { selectConfig } from "./cli/config-selector.js";import {ensureInteractiveDaemonRunning,+ isDaemonSessionSummary,+ isSessionBusy,probeRunningDaemonSessions,type RunningDaemonProbe,shutdownDaemonAndWait,@@ -12,14 +15,27 @@ import {APP_NAME,CONFIG_DIR_NAME,getAgentDir,+ getDaemonUpdateRestartManifestPath,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,PACKAGE_NAME,+ SELF_UPDATE_INTERACTIVE_CHILD_ENV,+ SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE,type SelfUpdateCommand,VERSION,} from "./config.js";+import { parseAgentSessionMessagePromptId } from "./core/agent-messages.js";+import type { AgentSessionRuntimeMetadata } from "./core/agent-session-runtime.js";+import type { CustomMessage } from "./core/messages.js";import { DefaultPackageManager } from "./core/package-manager.js";import { SettingsManager } from "./core/settings-manager.js";+import { DaemonClient } from "./modes/daemon/daemon-client.js";+import {+ type DaemonUpdateRestartManifest,+ type DaemonUpdateRestartQueuedMessage,+ type DaemonUpdateRestartSession,+ isUnknownDaemonCommandError,+} from "./modes/daemon/daemon-protocol.js";import { defaultDaemonSocketPath } from "./modes/daemon/daemon-socket.js";import { shouldUseWindowsShell } from "./utils/child-process.js";import { getLatestPiRelease, isNewerPackageVersion } from "./utils/version-check.js";@@ -307,6 +323,11 @@ interface SelfUpdatePlan {shouldRun: boolean;}+function setSelfUpdateNoChangeExitCode(): void {+ process.exitCode =+ process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] === "1" ? SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE : undefined;+}+async function getSelfUpdatePlan(force: boolean): Promise<SelfUpdatePlan> {try {const latestRelease = await getLatestPiRelease(VERSION);@@ -354,15 +375,16 @@ async function runSelfUpdate(command: SelfUpdateCommand): Promise<void> {}}-// Only busy sessions (streaming, compacting, or pending messages) would lose work;-// idle loaded sessions reload from disk on the fresh daemon.+const UPDATE_RESTART_CONTINUATION_PROMPT =+ "Prime Agent restarted after an update. Continue the interrupted task from the saved transcript and restored tool/kernel state. Inspect current state before retrying commands when needed.";+const UPDATE_SESSION_LOSS_COPY: DaemonSessionLossCopy = {busyDetail(count) {const { noun, pronoun } = pluralizeSessions(count);- return `The running daemon has ${count} busy ${noun}. Updating will stop the daemon and terminate ${pronoun}.`;+ return `The running daemon has ${count} busy ${noun}. After the update installs, Prime Agent will stop ${pronoun}, restart the daemon, and resume interrupted work.`;},unlistableDetail:- "A running daemon's sessions could not be listed. Updating will stop the daemon and may terminate active sessions.",+ "A running daemon's sessions could not be listed. After the update installs, Prime Agent will stop resident sessions, restart the daemon, and resume interrupted work where possible.",question: "Continue?",nonTtyHint: "Re-run with --force to proceed.",};@@ -372,26 +394,648 @@ function confirmDaemonSessionLossBeforeUpdate(probe: RunningDaemonProbe, force:return confirmDaemonSessionLoss(probe, { force, copy: UPDATE_SESSION_LOSS_COPY });}-async function restartDaemonAfterSelfUpdate(socketPath: string, daemonWasRunning: boolean): Promise<void> {- if (!daemonWasRunning) {+function daemonProbeMayHaveBusySessions(probe: RunningDaemonProbe): boolean {+ return probe.reachable && (probe.activeSessions === undefined || probe.activeSessions.some(isSessionBusy));+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function readString(value: unknown, fieldName: string): string {+ if (typeof value !== "string") {+ throw new Error(`Daemon update restart response is missing ${fieldName}`);+ }+ return value;+}++function readOptionalString(value: unknown, fieldName: string): string | undefined {+ if (value === undefined) {+ return undefined;+ }+ if (typeof value !== "string") {+ throw new Error(`Daemon update restart response is missing ${fieldName}`);+ }+ return value;+}++function readBoolean(value: unknown, fieldName: string): boolean {+ if (typeof value !== "boolean") {+ throw new Error(`Daemon update restart response is missing ${fieldName}`);+ }+ return value;+}++function readNumber(value: unknown, fieldName: string): number {+ if (typeof value !== "number") {+ throw new Error(`Daemon update restart response is missing ${fieldName}`);+ }+ return value;+}++function readOptionalStringRecord(value: unknown, fieldName: string): Record<string, string> | undefined {+ if (value === undefined) {+ return undefined;+ }+ if (!isRecord(value) || !Object.values(value).every((entry): entry is string => typeof entry === "string")) {+ throw new Error(`Daemon update restart response is missing ${fieldName}`);+ }+ return value as Record<string, string>;+}++function readOptionalImages(value: unknown, fieldName: string): DaemonUpdateRestartQueuedMessage["images"] {+ if (value === undefined) {+ return undefined;+ }+ if (!Array.isArray(value) || !value.every(isImageContent)) {+ throw new Error(`Daemon update restart response is missing ${fieldName}`);+ }+ return value;+}++function readOptionalMessageContent(value: unknown, fieldName: string): DaemonUpdateRestartQueuedMessage["content"] {+ if (value === undefined) {+ return undefined;+ }+ if (!Array.isArray(value) || !value.every(isCustomMessageContentBlock)) {+ throw new Error(`Daemon update restart response is missing ${fieldName}`);+ }+ return value;+}++function isImageContent(value: unknown): value is NonNullable<DaemonUpdateRestartQueuedMessage["images"]>[number] {+ return (+ isRecord(value) && value.type === "image" && typeof value.data === "string" && typeof value.mimeType === "string"+ );+}++function isCustomMessageContentBlock(+ value: unknown,+): value is NonNullable<DaemonUpdateRestartQueuedMessage["content"]>[number] {+ return (isRecord(value) && value.type === "text" && typeof value.text === "string") || isImageContent(value);+}++function isCustomMessage(value: unknown): value is CustomMessage {+ return (+ isRecord(value) &&+ value.role === "custom" &&+ typeof value.customType === "string" &&+ (typeof value.content === "string" ||+ (Array.isArray(value.content) && value.content.every(isCustomMessageContentBlock))) &&+ typeof value.display === "boolean" &&+ typeof value.timestamp === "number"+ );+}++function readCustomMessages(value: unknown, fieldName: string): CustomMessage[] {+ if (value === undefined) {+ return [];+ }+ if (!Array.isArray(value) || !value.every(isCustomMessage)) {+ throw new Error(`Daemon update restart response is missing ${fieldName}`);+ }+ return value;+}++function parseDaemonUpdateRestartQueuedMessage(value: unknown): DaemonUpdateRestartQueuedMessage {+ if (!isRecord(value)) {+ throw new Error("Daemon update restart response contains an invalid queued message");+ }+ const message = readString(value.message, "queue.message");+ const content = readOptionalMessageContent(value.content, "queue.content");+ const images = readOptionalImages(value.images, "queue.images");+ const queueKey = readOptionalString(value.queueKey, "queue.queueKey");+ const customMessage =+ value.customMessage === undefined+ ? undefined+ : isCustomMessage(value.customMessage)+ ? value.customMessage+ : undefined;+ if (value.customMessage !== undefined && !customMessage) {+ throw new Error("Daemon update restart response contains an invalid custom queued message");+ }+ const agentMessageId =+ readOptionalString(value.agentMessageId, "queue.agentMessageId") ?? parseAgentSessionMessagePromptId(message);+ return {+ message,+ ...(content ? { content } : {}),+ ...(images ? { images } : {}),+ ...(queueKey ? { queueKey } : {}),+ ...(agentMessageId ? { agentMessageId } : {}),+ ...(customMessage ? { customMessage } : {}),+ };+}++function parseDaemonUpdateRestartAcceptedPrompt(+ value: unknown,+): NonNullable<DaemonUpdateRestartSession["queue"]["acceptedPrompt"]> {+ if (!isRecord(value)) {+ throw new Error("Daemon update restart response contains an invalid accepted prompt");+ }+ return {+ ...parseDaemonUpdateRestartQueuedMessage(value),+ nextTurn: readCustomMessages(value.nextTurn, "queue.acceptedPrompt.nextTurn"),+ };+}++function readOptionalAcceptedPrompt(value: unknown): DaemonUpdateRestartSession["queue"]["acceptedPrompt"] | undefined {+ if (value === undefined) {+ return undefined;+ }+ return parseDaemonUpdateRestartAcceptedPrompt(value);+}++function readQueuedMessages(value: unknown, fieldName: string): DaemonUpdateRestartQueuedMessage[] {+ if (!Array.isArray(value)) {+ throw new Error(`Daemon update restart response is missing ${fieldName}`);+ }+ return value.map(parseDaemonUpdateRestartQueuedMessage);+}++function parseDaemonUpdateRestartRuntimeMetadata(value: unknown): AgentSessionRuntimeMetadata | undefined {+ if (value === undefined) {+ return undefined;+ }+ if (!isRecord(value)) {+ throw new Error("Daemon update restart response contains invalid runtime metadata");+ }+ const kind = readString(value.kind, "runtimeMetadata.kind");+ if (kind !== "top-level" && kind !== "subagent") {+ throw new Error("Daemon update restart response contains invalid runtime metadata kind");+ }+ const parentActiveSessionId = readOptionalString(+ value.parentActiveSessionId,+ "runtimeMetadata.parentActiveSessionId",+ );+ const parentSessionId = readOptionalString(value.parentSessionId, "runtimeMetadata.parentSessionId");+ const parentSessionFile = readOptionalString(value.parentSessionFile, "runtimeMetadata.parentSessionFile");+ const rlmChildId = readOptionalString(value.rlmChildId, "runtimeMetadata.rlmChildId");+ const rlmParentNodeId = readOptionalString(value.rlmParentNodeId, "runtimeMetadata.rlmParentNodeId");+ const prompt = readOptionalString(value.prompt, "runtimeMetadata.prompt");+ const spawnCode = readOptionalString(value.spawnCode, "runtimeMetadata.spawnCode");+ const sessionDir = readOptionalString(value.sessionDir, "runtimeMetadata.sessionDir");+ return {+ kind,+ createdAt: readNumber(value.createdAt, "runtimeMetadata.createdAt"),+ ...(parentActiveSessionId ? { parentActiveSessionId } : {}),+ ...(parentSessionId ? { parentSessionId } : {}),+ ...(parentSessionFile ? { parentSessionFile } : {}),+ ...(rlmChildId ? { rlmChildId } : {}),+ ...(rlmParentNodeId ? { rlmParentNodeId } : {}),+ ...(prompt ? { prompt } : {}),+ ...(spawnCode ? { spawnCode } : {}),+ ...(sessionDir ? { sessionDir } : {}),+ };+}++function wasFollowUpQueued(response: { success: true; data?: unknown }): boolean {+ return !isRecord(response.data) || response.data.queued !== false;+}++function parseDaemonUpdateRestartSession(value: unknown): DaemonUpdateRestartSession {+ if (!isRecord(value)) {+ throw new Error("Daemon update restart response contains an invalid session");+ }+ const queue = value.queue;+ if (!isRecord(queue)) {+ throw new Error("Daemon update restart response contains an invalid queue");+ }+ const config = value.config;+ if (!isRecord(config)) {+ throw new Error("Daemon update restart response contains an invalid session config");+ }+ const clientEnv = readOptionalStringRecord(value.clientEnv, "clientEnv");+ const runtimeMetadata = parseDaemonUpdateRestartRuntimeMetadata(value.runtimeMetadata);+ return {+ activeSessionId: readString(value.activeSessionId, "activeSessionId"),+ sessionId: readString(value.sessionId, "sessionId"),+ sessionFile: readString(value.sessionFile, "sessionFile"),+ cwd: readString(value.cwd, "cwd"),+ config: config as DaemonUpdateRestartSession["config"],+ ...(runtimeMetadata ? { runtimeMetadata } : {}),+ ...(clientEnv ? { clientEnv } : {}),+ queue: {+ steering: readQueuedMessages(queue.steering, "queue.steering"),+ followUp: readQueuedMessages(queue.followUp, "queue.followUp"),+ nextTurn: readCustomMessages(queue.nextTurn, "queue.nextTurn"),+ ...(queue.acceptedPrompt !== undefined+ ? { acceptedPrompt: readOptionalAcceptedPrompt(queue.acceptedPrompt) }+ : {}),+ },+ shouldResume: readBoolean(value.shouldResume, "shouldResume"),+ wasStreaming: readBoolean(value.wasStreaming, "wasStreaming"),+ wasCompacting: readBoolean(value.wasCompacting, "wasCompacting"),+ wasBashRunning: readBoolean(value.wasBashRunning, "wasBashRunning"),+ hadRunningRlmChildren: readBoolean(value.hadRunningRlmChildren, "hadRunningRlmChildren"),+ wasRetrying: readBoolean(value.wasRetrying, "wasRetrying"),+ hadAcceptedPromptInFlight: readBoolean(value.hadAcceptedPromptInFlight, "hadAcceptedPromptInFlight"),+ };+}++function parseDaemonUpdateRestartManifest(value: unknown): DaemonUpdateRestartManifest {+ if (!isRecord(value)) {+ throw new Error("Daemon update restart response is invalid");+ }+ const sessions = value.sessions;+ if (!Array.isArray(sessions)) {+ throw new Error("Daemon update restart response is missing sessions");+ }+ return {+ createdAt: readString(value.createdAt, "createdAt"),+ sessions: sessions.map(parseDaemonUpdateRestartSession),+ };+}++function clearPreparedDaemonUpdateRestartManifest(agentDir: string): void {+ try {+ rmSync(getDaemonUpdateRestartManifestPath(agentDir), { force: true });+ } catch {+ // Best effort only; the mtime guard below prevents stale fallback use.+ }+}++function readPreparedDaemonUpdateRestartManifest(+ agentDir: string,+ notBeforeMs?: number,+): DaemonUpdateRestartManifest | undefined {+ const manifestPath = getDaemonUpdateRestartManifestPath(agentDir);+ let modifiedAt: number;+ try {+ modifiedAt = statSync(manifestPath).mtimeMs;+ } catch {+ return undefined;+ }+ if (notBeforeMs !== undefined && modifiedAt < notBeforeMs - 1000) {+ return undefined;+ }+ const parsed = JSON.parse(readFileSync(manifestPath, "utf-8")) as unknown;+ return parseDaemonUpdateRestartManifest(parsed);+}++function tryReadPreparedDaemonUpdateRestartManifest(agentDir: string): DaemonUpdateRestartManifest | undefined {+ try {+ return readPreparedDaemonUpdateRestartManifest(agentDir);+ } catch {+ return undefined;+ }+}++function hasRestorableDaemonUpdateRestart(manifest: DaemonUpdateRestartManifest | undefined): boolean {+ return manifest !== undefined && manifest.sessions.length > 0;+}++function responseHasActiveDaemonSessions(data: unknown): boolean {+ if (!isRecord(data) || !Array.isArray(data.sessions)) {+ return true;+ }+ return data.sessions.length > 0;+}++export async function prepareDaemonUpdateRestart(+ socketPath: string,+ agentDir: string,+): Promise<DaemonUpdateRestartManifest> {+ const pendingManifest = tryReadPreparedDaemonUpdateRestartManifest(agentDir);+ const client = new DaemonClient(socketPath);+ let connected = false;+ let startedAt: number | undefined;+ try {+ await client.connect(1000);+ connected = true;+ if (pendingManifest && pendingManifest.sessions.length > 0) {+ const listResponse = await client.request({ type: "list" }, 30000);+ if (listResponse.success && !responseHasActiveDaemonSessions(listResponse.data)) {+ return pendingManifest;+ }+ }+ clearPreparedDaemonUpdateRestartManifest(agentDir);+ startedAt = Date.now();+ const response = await client.request({ type: "prepare_update_restart" }, 120000);+ if (!response.success) {+ throw new Error(response.error);+ }+ return parseDaemonUpdateRestartManifest(response.data);+ } catch (error) {+ if (startedAt !== undefined) {+ const fallback = readPreparedDaemonUpdateRestartManifest(agentDir, startedAt);+ if (fallback) {+ return fallback;+ }+ }+ if (!connected && pendingManifest && pendingManifest.sessions.length > 0) {+ return pendingManifest;+ }+ throw error;+ } finally {+ client.close();+ }+}++function readCreatedActiveSessionId(value: unknown): string {+ if (!isDaemonSessionSummary(value) || typeof value.activeSessionId !== "string") {+ throw new Error("Daemon returned an invalid session create response");+ }+ return value.activeSessionId;+}++async function restoreNextTurnMessages(+ client: DaemonClient,+ activeSessionId: string,+ sessionFile: string,+ messages: readonly CustomMessage[],+): Promise<boolean> {+ if (messages.length === 0) {+ return true;+ }+ const response = await client.request(+ { type: "restore_next_turn", activeSessionId, messages: [...messages] },+ 30000,+ );+ if (!response.success) {+ console.error(chalk.yellow(`Warning: could not restore pending context for ${sessionFile}: ${response.error}`));+ return false;+ }+ return true;+}++interface RestoreDaemonUpdateRestartSessionResult {+ restored: boolean;+ resumed: boolean;+}++function remapDaemonUpdateRestartRuntimeMetadata(+ session: DaemonUpdateRestartSession,+ restoredActiveSessionIds: ReadonlyMap<string, string>,+): AgentSessionRuntimeMetadata | undefined {+ const metadata = session.runtimeMetadata;+ if (!metadata) {+ return undefined;+ }+ if (metadata.kind !== "subagent") {+ return metadata;+ }+ const { parentActiveSessionId: oldParentActiveSessionId, ...runtimeMetadata } = metadata;+ const parentActiveSessionId = oldParentActiveSessionId+ ? restoredActiveSessionIds.get(oldParentActiveSessionId)+ : undefined;+ return {+ ...runtimeMetadata,+ ...(parentActiveSessionId ? { parentActiveSessionId } : {}),+ };+}++async function restoreDaemonUpdateRestartSession(+ client: DaemonClient,+ session: DaemonUpdateRestartSession,+ restoredActiveSessionIds: Map<string, string>,+): Promise<RestoreDaemonUpdateRestartSessionResult> {+ const runtimeMetadata = remapDaemonUpdateRestartRuntimeMetadata(session, restoredActiveSessionIds);+ const createResponse = await client.request(+ {+ type: "create",+ sessionPath: session.sessionFile,+ config: session.config,+ ...(runtimeMetadata ? { runtimeMetadata } : {}),+ ...(session.clientEnv ? { env: session.clientEnv } : {}),+ },+ 120000,+ );+ if (!createResponse.success) {+ console.error(chalk.yellow(`Warning: could not restore ${session.sessionFile}: ${createResponse.error}`));+ return { restored: false, resumed: false };+ }+ const activeSessionId = readCreatedActiveSessionId(createResponse.data);+ restoredActiveSessionIds.set(session.activeSessionId, activeSessionId);+ const acceptedPrompt = session.queue.acceptedPrompt;+ if (!session.shouldResume) {+ await restoreNextTurnMessages(client, activeSessionId, session.sessionFile, session.queue.nextTurn);+ return { restored: true, resumed: false };+ }+ const needsContinuationPrompt =+ session.wasStreaming ||+ session.wasCompacting ||+ session.wasBashRunning ||+ session.hadRunningRlmChildren ||+ session.wasRetrying ||+ session.hadAcceptedPromptInFlight;+ const steeringQueue = [...session.queue.steering];+ const followUpQueue = [...session.queue.followUp];+ let resumedSession = false;+ let restoredQueuedWork = false;+ if (acceptedPrompt) {+ await restoreNextTurnMessages(client, activeSessionId, session.sessionFile, acceptedPrompt.nextTurn);+ } else {+ await restoreNextTurnMessages(client, activeSessionId, session.sessionFile, session.queue.nextTurn);+ }+ for (const queued of steeringQueue) {+ const response = await client.request(+ {+ type: "steer",+ activeSessionId,+ message: queued.message,+ content: queued.content,+ images: queued.images,+ expandPromptTemplates: false,+ agentMessageId: queued.agentMessageId,+ customMessage: queued.customMessage,+ },+ 30000,+ );+ if (response.success) {+ restoredQueuedWork = true;+ } else {+ console.error(+ chalk.yellow(+ `Warning: could not restore queued steering message for ${session.sessionFile}: ${response.error}`,+ ),+ );+ }+ }+ for (const queued of followUpQueue) {+ const response = await client.request(+ {+ type: "follow_up",+ activeSessionId,+ message: queued.message,+ content: queued.content,+ images: queued.images,+ queueKey: queued.queueKey,+ expandPromptTemplates: false,+ agentMessageId: queued.agentMessageId,+ customMessage: queued.customMessage,+ },+ 30000,+ );+ if (response.success && wasFollowUpQueued(response)) {+ restoredQueuedWork = true;+ } else if (!response.success) {+ console.error(+ chalk.yellow(+ `Warning: could not restore queued follow-up message for ${session.sessionFile}: ${response.error}`,+ ),+ );+ }+ }+ if (acceptedPrompt) {+ const promptResponse = await client.request(+ {+ type: "prompt",+ activeSessionId,+ message: acceptedPrompt.message,+ content: acceptedPrompt.content,+ images: acceptedPrompt.images,+ expandPromptTemplates: false,+ agentMessageId: acceptedPrompt.agentMessageId,+ },+ 120000,+ );+ if (!promptResponse.success) {+ console.error(chalk.yellow(`Warning: could not resume ${session.sessionFile}: ${promptResponse.error}`));+ } else {+ resumedSession = true;+ }+ await restoreNextTurnMessages(client, activeSessionId, session.sessionFile, session.queue.nextTurn);+ } else if (needsContinuationPrompt) {+ const promptResponse = await client.request(+ {+ type: "prompt",+ activeSessionId,+ message: UPDATE_RESTART_CONTINUATION_PROMPT,+ expandPromptTemplates: false,+ },+ 120000,+ );+ if (!promptResponse.success) {+ console.error(chalk.yellow(`Warning: could not resume ${session.sessionFile}: ${promptResponse.error}`));+ } else {+ resumedSession = true;+ }+ }+ if (!resumedSession && restoredQueuedWork && !acceptedPrompt) {+ const response = await client.request({ type: "resume_queue", activeSessionId }, 30000);+ if (response.success) {+ resumedSession = true;+ } else {+ console.error(+ chalk.yellow(`Warning: could not resume queued work for ${session.sessionFile}: ${response.error}`),+ );+ }+ }+ return { restored: true, resumed: resumedSession };+}++async function restoreDaemonUpdateRestart(socketPath: string, manifest: DaemonUpdateRestartManifest): Promise<void> {+ if (manifest.sessions.length === 0) {+ return;+ }+ const client = new DaemonClient(socketPath);+ let restored = 0;+ let resumed = 0;+ const restoredActiveSessionIds = new Map<string, string>();+ try {+ await client.connect(10000);+ for (const session of manifest.sessions) {+ try {+ const result = await restoreDaemonUpdateRestartSession(client, session, restoredActiveSessionIds);+ if (result.restored) {+ restored++;+ }+ if (result.resumed) {+ resumed++;+ }+ } catch (error: unknown) {+ console.error(+ chalk.yellow(`Warning: could not restore ${session.sessionFile}: ${formatUnknownError(error)}`),+ );+ }+ }+ } finally {+ client.close();+ }+ console.log(chalk.green(`Restored ${restored} daemon session${restored === 1 ? "" : "s"}`));+ if (resumed > 0) {+ console.log(chalk.green(`Resumed ${resumed} interrupted session${resumed === 1 ? "" : "s"}`));+ }+}++function formatUnknownError(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++async function tryRestoreDaemonUpdateRestart(+ socketPath: string,+ agentDir: string,+ manifest: DaemonUpdateRestartManifest | undefined,+ failureContext: string,+): Promise<boolean> {+ if (!manifest) {+ return false;+ }+ try {+ await restoreDaemonUpdateRestart(socketPath, manifest);+ clearPreparedDaemonUpdateRestartManifest(agentDir);+ return true;+ } catch (error: unknown) {+ console.error(+ chalk.yellow(`Warning: could not restore daemon sessions ${failureContext}: ${formatUnknownError(error)}`),+ );+ return false;+ }+}++async function restartDaemonAfterSelfUpdate(socketPath: string, agentDir: string): Promise<void> {+ const daemonProbe = await probeRunningDaemonSessions(socketPath);+ let manifest: DaemonUpdateRestartManifest | undefined;+ let oldDaemonAlreadyStopped = false;+ if (daemonProbe.reachable) {+ try {+ manifest = await prepareDaemonUpdateRestart(socketPath, agentDir);+ } catch (error: unknown) {+ const message = formatUnknownError(error);+ const daemonLacksPrepareCommand = isUnknownDaemonCommandError(error, "prepare_update_restart");+ if (daemonProbeMayHaveBusySessions(daemonProbe) || !daemonLacksPrepareCommand) {+ console.error(+ chalk.yellow(+ `Warning: updated, but could not prepare daemon sessions for automatic resume (${message}); leaving the running daemon on the previous version.`,+ ),+ );+ return;+ }+ console.error(+ chalk.yellow(+ `Warning: the old daemon cannot prepare idle sessions for automatic resume (${message}); restarting the daemon without restored sessions.`,+ ),+ );+ }+ } else {+ manifest = tryReadPreparedDaemonUpdateRestartManifest(agentDir);+ oldDaemonAlreadyStopped = hasRestorableDaemonUpdateRestart(manifest);+ }+ if (!daemonProbe.reachable && !hasRestorableDaemonUpdateRestart(manifest)) {return;}- const stopped = await shutdownDaemonAndWait(socketPath);+ const stopped = oldDaemonAlreadyStopped || (await shutdownDaemonAndWait(socketPath));if (!stopped) {console.error(chalk.yellow(`Warning: could not stop the old daemon on ${socketPath}; it will be replaced on next launch.`),);+ await tryRestoreDaemonUpdateRestart(socketPath, agentDir, manifest, "after daemon stop failed");return;}try {await ensureInteractiveDaemonRunning(socketPath);} catch (error: unknown) {- const message = error instanceof Error ? error.message : String(error);+ const message = formatUnknownError(error);console.error(chalk.yellow(`Warning: updated, but could not relaunch the daemon (${message}); it will start on next launch.`,),);+ await tryRestoreDaemonUpdateRestart(socketPath, agentDir, manifest, "after relaunch failed");+ return;+ }+ if (manifest) {+ await tryRestoreDaemonUpdateRestart(socketPath, agentDir, manifest, "after relaunch");}}@@ -546,6 +1190,7 @@ export async function handlePackageCommand(args: string[]): Promise<boolean> {if (updateTargetIncludesSelf(target)) {const selfUpdatePlan = await getSelfUpdatePlan(options.force);if (!selfUpdatePlan.shouldRun) {+ setSelfUpdateNoChangeExitCode();return true;}const selfUpdateCommand = getSelfUpdateCommand(@@ -563,7 +1208,7 @@ export async function handlePackageCommand(args: string[]): Promise<boolean> {process.exitCode = 1;return true;}- // Confirm before the install, since upgrading the daemon afterward stops it.+ // Confirm before the install, since upgrading the daemon afterward stops and resumes busy work.const daemonSocketPath = defaultDaemonSocketPath();const daemonProbe = await probeRunningDaemonSessions(daemonSocketPath);if (!(await confirmDaemonSessionLossBeforeUpdate(daemonProbe, options.force))) {@@ -583,7 +1228,7 @@ export async function handlePackageCommand(args: string[]): Promise<boolean> {return true;}console.log(chalk.green(`Updated ${APP_NAME}`));- await restartDaemonAfterSelfUpdate(daemonSocketPath, daemonProbe.reachable);+ await restartDaemonAfterSelfUpdate(daemonSocketPath, agentDir);}return true;}diff --git a/packages/coding-agent/test/child-agent-summary-list.test.ts b/packages/coding-agent/test/child-agent-summary-list.test.tsindex 2b4e9c9f96..215c6a41f3 100644--- a/packages/coding-agent/test/child-agent-summary-list.test.ts+++ b/packages/coding-agent/test/child-agent-summary-list.test.ts@@ -1,6 +1,5 @@-import { setKeybindings, visibleWidth } from "@earendil-works/pi-tui";+import { visibleWidth } from "@earendil-works/pi-tui";import { beforeAll, describe, expect, it } from "vitest";-import { KeybindingsManager } from "../src/core/keybindings.js";import {type ChildAgentInspectorNode,ChildAgentSummaryComponent,@@ -18,7 +17,6 @@ function node(id: string, status: ChildAgentInspectorNode["status"] = "running")describe("ChildAgentSummaryComponent inline list", () => {beforeAll(() => {- setKeybindings(new KeybindingsManager());initTheme("dark");});@@ -145,55 +143,12 @@ describe("ChildAgentSummaryComponent inline list", () => {let forwarded: string | undefined;summary.onChatAction = (data) => {forwarded = data;- return undefined;};// Ctrl+O isn't a list key, so it should bubble to the chat action handler.summary.handleInput("\x0f");expect(forwarded).toBe("\x0f");});- it("forwards text input to the unhandled input callback", () => {- const summary = new ChildAgentSummaryComponent();- summary.focused = true;- summary.setNodes([node("a")]);- let forwarded: string | undefined;- summary.onUnhandledInput = (data) => {- forwarded = data;- };- summary.handleInput("h");- expect(forwarded).toBe("h");- });-- it("does not forward handled chat actions as unhandled input", () => {- const summary = new ChildAgentSummaryComponent();- summary.focused = true;- summary.setNodes([node("a")]);- let unhandled: string | undefined;- summary.onChatAction = () => true;- summary.onUnhandledInput = (data) => {- unhandled = data;- };- summary.handleInput("\x0f");- expect(unhandled).toBeUndefined();- });-- it("routes back through onExit without forwarding input", () => {- const summary = new ChildAgentSummaryComponent();- summary.focused = true;- summary.setNodes([node("a")]);- let exited = false;- let unhandled: string | undefined;- summary.onExit = () => {- exited = true;- };- summary.onUnhandledInput = (data) => {- unhandled = data;- };- summary.handleInput("\x1b[D");- expect(exited).toBe(true);- expect(unhandled).toBeUndefined();- });-it("opens the selected subagent's detail on confirm", () => {const summary = new ChildAgentSummaryComponent();summary.focused = true;diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.tsindex 2ba851170b..c747d91c9d 100644--- a/packages/coding-agent/test/daemon-session-list.test.ts+++ b/packages/coding-agent/test/daemon-session-list.test.ts@@ -71,6 +71,7 @@ describe("buildSessionList", () => {[],);expect(entries[0]?.activity).toBe("working");+ expect(entries[0]?.hasRunningRlmChildren).toBe(true);});it("counts accepted in-flight agent prompts as pending work", () => {diff --git a/packages/coding-agent/test/daemon-stop-confirm.test.ts b/packages/coding-agent/test/daemon-stop-confirm.test.tsindex 2660309ce8..37ca05bc16 100644--- a/packages/coding-agent/test/daemon-stop-confirm.test.ts+++ b/packages/coding-agent/test/daemon-stop-confirm.test.ts@@ -77,7 +77,13 @@ describe("confirmDaemonSessionLoss", () => {it("treats compacting and pending-message sessions as busy", async () => {setTTY(false);- for (const overrides of [{ isCompacting: true }, { pendingMessageCount: 1 }, { isStreaming: true }]) {+ for (const overrides of [+ { isCompacting: true },+ { pendingMessageCount: 1 },+ { isStreaming: true },+ { isBashRunning: true },+ { hasRunningRlmChildren: true },+ ]) {vi.mocked(console.error).mockClear();const probe: RunningDaemonProbe = { reachable: true, activeSessions: [session(overrides)] };expect(await confirmDaemonSessionLoss(probe, { force: false, copy: COPY })).toBe(false);diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.tsindex 08ec6b0a81..51c6310e6f 100644--- a/packages/coding-agent/test/interactive-mode-status.test.ts+++ b/packages/coding-agent/test/interactive-mode-status.test.ts@@ -82,7 +82,7 @@ describe("InteractiveMode update notifications", () => {initTheme("dark");});- test("shows the Prime Agent update command in one compact line", () => {+ test("shows the slash update command in one compact line", () => {const chatContainer = new Container();const fakeThis = {chatContainer,@@ -96,7 +96,8 @@ describe("InteractiveMode update notifications", () => {expect(output.split("\n")).toHaveLength(1);expect(output).toContain("Update available:");expect(output).toContain("v1.2.3");- expect(output).toContain("prime-agent update");+ expect(output).toContain("/update");+ expect(output).not.toContain("prime-agent update");expect(output).not.toContain("pi update");expect(output).not.toContain("Changelog:");});@@ -115,7 +116,8 @@ describe("InteractiveMode update notifications", () => {expect(output.split("\n")).toHaveLength(1);expect(output).toContain("Package updates available:");expect(output).toContain("npm:@foo/bar");- expect(output).toContain("prime-agent update --extensions");+ expect(output).toContain("/update --extensions");+ expect(output).not.toContain("prime-agent update");expect(output).not.toContain("pi update");});});diff --git a/packages/coding-agent/test/interactive-mode-streaming.test.ts b/packages/coding-agent/test/interactive-mode-streaming.test.tsindex ed2ee69927..ebe4e5da02 100644--- a/packages/coding-agent/test/interactive-mode-streaming.test.ts+++ b/packages/coding-agent/test/interactive-mode-streaming.test.ts@@ -49,6 +49,16 @@ type GetUserInput = (this: {returnToAgentsViewRequested: boolean;onInputCallback?: (text: string | undefined) => void;}) => Promise<string | undefined>;+type HandleSubagentSummaryChatAction = (+ this: {+ keybindings: { matches(data: string, action: string): boolean };+ editor: { handleInput(data: string): void };+ focusEditor(): void;+ toggleToolOutputExpansion(): void;+ toggleThinkingBlockVisibility(): void;+ },+ data: string,+) => void;function createFakeInteractiveModeThis(): HandleEventThis {const fakeThis = {@@ -166,4 +176,43 @@ describe("InteractiveMode streaming events", () => {await expect(getUserInput.call({ returnToAgentsViewRequested: true })).resolves.toBeUndefined();});++ test("forwards typed keys from focused subagent summary back to the editor", () => {+ const handleSubagentSummaryChatAction = (+ InteractiveMode.prototype as unknown as { handleSubagentSummaryChatAction: HandleSubagentSummaryChatAction }+ ).handleSubagentSummaryChatAction;+ const fakeThis = {+ keybindings: { matches: vi.fn(() => false) },+ editor: { handleInput: vi.fn() },+ focusEditor: vi.fn(),+ toggleToolOutputExpansion: vi.fn(),+ toggleThinkingBlockVisibility: vi.fn(),+ };++ handleSubagentSummaryChatAction.call(fakeThis, "x");++ expect(fakeThis.focusEditor).toHaveBeenCalledOnce();+ expect(fakeThis.editor.handleInput).toHaveBeenCalledWith("x");+ expect(fakeThis.toggleToolOutputExpansion).not.toHaveBeenCalled();+ expect(fakeThis.toggleThinkingBlockVisibility).not.toHaveBeenCalled();+ });++ test("keeps focused subagent summary shortcuts in the chat surface", () => {+ const handleSubagentSummaryChatAction = (+ InteractiveMode.prototype as unknown as { handleSubagentSummaryChatAction: HandleSubagentSummaryChatAction }+ ).handleSubagentSummaryChatAction;+ const fakeThis = {+ keybindings: { matches: vi.fn((_data: string, action: string) => action === "app.tools.expand") },+ editor: { handleInput: vi.fn() },+ focusEditor: vi.fn(),+ toggleToolOutputExpansion: vi.fn(),+ toggleThinkingBlockVisibility: vi.fn(),+ };++ handleSubagentSummaryChatAction.call(fakeThis, "\x0f");++ expect(fakeThis.toggleToolOutputExpansion).toHaveBeenCalledOnce();+ expect(fakeThis.focusEditor).not.toHaveBeenCalled();+ expect(fakeThis.editor.handleInput).not.toHaveBeenCalled();+ });});diff --git a/packages/coding-agent/test/interactive-update-relaunch.test.ts b/packages/coding-agent/test/interactive-update-relaunch.test.tsnew file mode 100644index 0000000000..ceb690303f--- /dev/null+++ b/packages/coding-agent/test/interactive-update-relaunch.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { buildUpdateRelaunchArgs } from "../src/modes/interactive/interactive-mode.js";++describe("buildUpdateRelaunchArgs", () => {+ it("relaunches the current session with the supported resume flag", () => {+ expect(buildUpdateRelaunchArgs(["--model", "gpt-5"], "/tmp/session.jsonl")).toEqual([+ "--model",+ "gpt-5",+ "--resume",+ "/tmp/session.jsonl",+ ]);+ });++ it("keeps an existing resume selection", () => {+ expect(buildUpdateRelaunchArgs(["--resume", "/tmp/other.jsonl"], "/tmp/session.jsonl")).toEqual([+ "--resume",+ "/tmp/other.jsonl",+ ]);+ });++ it("does not treat the unsupported session flag as an existing selection", () => {+ expect(buildUpdateRelaunchArgs(["--session", "/tmp/old.jsonl"], "/tmp/session.jsonl")).toEqual([+ "--session",+ "/tmp/old.jsonl",+ "--resume",+ "/tmp/session.jsonl",+ ]);+ });+});diff --git a/packages/coding-agent/test/package-self-update-daemon.test.ts b/packages/coding-agent/test/package-self-update-daemon.test.tsnew file mode 100644index 0000000000..e7eaa0f6cd--- /dev/null+++ b/packages/coding-agent/test/package-self-update-daemon.test.ts@@ -0,0 +1,660 @@+import { mkdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ ENV_AGENT_DIR,+ PACKAGE_NAME,+ SELF_UPDATE_INTERACTIVE_CHILD_ENV,+ SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE,+} from "../src/config.js";+import type { AgentSessionRuntimeMetadata } from "../src/core/agent-session-runtime.js";+import { handlePackageCommand } from "../src/package-manager-cli.js";++interface MockSessionSummary {+ id: string;+ activeSessionId?: string;+ isStreaming: boolean;+ isCompacting: boolean;+ isBashRunning?: boolean;+ hasRunningRlmChildren?: boolean;+ pendingMessageCount: number;+}++type MockRunningDaemonProbe = { reachable: false } | { reachable: true; activeSessions?: MockSessionSummary[] };++interface MockCustomMessage {+ role: "custom";+ customType: string;+ content: string;+ display: boolean;+ timestamp: number;+}++interface MockQueuedMessage {+ message: string;+ content?: Array<{ type: "text"; text: string }>;+ agentMessageId?: string;+ queueKey?: string;+ customMessage?: MockCustomMessage;+}++interface MockUpdateRestartSession {+ activeSessionId: string;+ sessionId: string;+ sessionFile: string;+ cwd: string;+ config: Record<string, unknown>;+ runtimeMetadata?: AgentSessionRuntimeMetadata;+ queue: {+ steering: MockQueuedMessage[];+ followUp: MockQueuedMessage[];+ nextTurn: MockCustomMessage[];+ acceptedPrompt?: MockQueuedMessage & { nextTurn: MockCustomMessage[] };+ };+ shouldResume: boolean;+ wasStreaming: boolean;+ wasCompacting: boolean;+ wasBashRunning: boolean;+ hadRunningRlmChildren: boolean;+ wasRetrying: boolean;+ hadAcceptedPromptInFlight: boolean;+}++interface MockUpdateRestartManifest {+ createdAt: string;+ sessions: MockUpdateRestartSession[];+}++interface MockDaemonRequest {+ type: string;+ activeSessionId?: string;+ message?: string;+ agentMessageId?: string;+ customMessage?: MockCustomMessage;+ content?: unknown;+ messages?: MockCustomMessage[];+ queueKey?: string;+ sessionPath?: string;+ runtimeMetadata?: AgentSessionRuntimeMetadata;+}++type MockDaemonResponse = { success: true; data?: unknown } | { success: false; error: string };++const mockState = vi.hoisted(() => ({+ calls: [] as string[],+ createActiveSessionIds: [] as string[],+ createThrowSessionPaths: [] as string[],+ daemonProbe: { reachable: true, activeSessions: [] } as MockRunningDaemonProbe,+ globalPackageRoot: "",+ prepareManifest: { createdAt: "2026-07-07T00:00:00.000Z", sessions: [] } as MockUpdateRestartManifest,+ promptFailures: 0,+ requestPayloads: [] as MockDaemonRequest[],+ restoreNextTurnFailures: 0,+ socketPath: "",+ spawnExitCodes: [] as number[],+ shutdownResult: true,+}));++vi.mock("child_process", () => ({+ spawn: vi.fn((command: string, args: string[]) => {+ mockState.calls.push(`spawn:${command} ${args.join(" ")}`);+ const exitCode = mockState.spawnExitCodes.shift() ?? 0;+ const child = {+ on(event: string, listener: unknown) {+ if (event === "close") {+ queueMicrotask(() => {+ (listener as (code: number | null, signal: string | null) => void)(exitCode, null);+ });+ }+ return child;+ },+ };+ return child;+ }),+ spawnSync: vi.fn(() => ({+ status: 0,+ stdout: `${mockState.globalPackageRoot}\n`,+ stderr: "",+ })),+}));++vi.mock("../src/modes/daemon/daemon-socket.js", () => ({+ defaultDaemonSocketPath: () => mockState.socketPath,+}));++vi.mock("../src/cli/daemon-launch.js", () => ({+ ensureInteractiveDaemonRunning: vi.fn(async () => {+ mockState.calls.push("ensure-daemon");+ }),+ isDaemonSessionSummary: (value: unknown) => {+ if (!value || typeof value !== "object") {+ return false;+ }+ const summary = value as { activeSessionId?: unknown; id?: unknown };+ return typeof summary.activeSessionId === "string" || typeof summary.id === "string";+ },+ isSessionBusy: (summary: MockSessionSummary) =>+ summary.isStreaming ||+ summary.isCompacting ||+ summary.isBashRunning === true ||+ summary.hasRunningRlmChildren === true ||+ summary.pendingMessageCount > 0,+ probeRunningDaemonSessions: vi.fn(async () => {+ mockState.calls.push("probe-daemon");+ return mockState.daemonProbe;+ }),+ shutdownDaemonAndWait: vi.fn(async () => {+ mockState.calls.push("shutdown-daemon");+ return mockState.shutdownResult;+ }),+}));++vi.mock("../src/modes/daemon/daemon-client.js", () => ({+ DaemonClient: class {+ constructor(readonly socketPath: string) {}++ async connect(): Promise<void> {+ mockState.calls.push(`daemon-connect:${this.socketPath}`);+ }++ async request(request: MockDaemonRequest): Promise<MockDaemonResponse> {+ mockState.calls.push(`daemon-request:${request.type}`);+ mockState.requestPayloads.push(request);+ if (request.type === "prepare_update_restart") {+ return { success: true, data: mockState.prepareManifest };+ }+ if (request.type === "create") {+ if (request.sessionPath && mockState.createThrowSessionPaths.includes(request.sessionPath)) {+ throw new Error("create failed");+ }+ const activeSessionId = mockState.createActiveSessionIds.shift() ?? "restored-active";+ return { success: true, data: { id: activeSessionId, activeSessionId } };+ }+ if (request.type === "restore_next_turn" && mockState.restoreNextTurnFailures > 0) {+ mockState.restoreNextTurnFailures--;+ return { success: false, error: "restore failed" };+ }+ if (request.type === "prompt" && mockState.promptFailures > 0) {+ mockState.promptFailures--;+ return { success: false, error: "prompt failed" };+ }+ return { success: true };+ }++ close(): void {}+ },+}));++describe("self-update daemon restart", () => {+ let tempDir: string;+ let agentDir: string;+ let projectDir: string;+ let packageDir: string;+ let originalAgentDir: string | undefined;+ let originalPiPackageDir: string | undefined;+ let originalCwd: string;+ let originalExecPath: string;+ let originalExitCode: typeof process.exitCode;++ beforeEach(() => {+ tempDir = join(tmpdir(), `pi-self-update-daemon-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ agentDir = join(tempDir, "agent");+ projectDir = join(tempDir, "project");+ packageDir = join(tempDir, "global-prefix", "lib", "node_modules", PACKAGE_NAME);+ mockState.globalPackageRoot = join(tempDir, "global-prefix", "lib", "node_modules");+ mockState.socketPath = join(tempDir, "daemon.sock");+ mockState.calls = [];+ mockState.createActiveSessionIds = [];+ mockState.createThrowSessionPaths = [];+ mockState.daemonProbe = { reachable: true, activeSessions: [] };+ mockState.prepareManifest = { createdAt: "2026-07-07T00:00:00.000Z", sessions: [] };+ mockState.promptFailures = 0;+ mockState.requestPayloads = [];+ mockState.restoreNextTurnFailures = 0;+ mockState.spawnExitCodes = [];+ mockState.shutdownResult = true;+ mkdirSync(agentDir, { recursive: true });+ mkdirSync(projectDir, { recursive: true });+ mkdirSync(packageDir, { recursive: true });++ originalAgentDir = process.env[ENV_AGENT_DIR];+ originalPiPackageDir = process.env.PI_PACKAGE_DIR;+ originalCwd = process.cwd();+ originalExecPath = process.execPath;+ originalExitCode = process.exitCode;+ process.exitCode = undefined;+ process.env[ENV_AGENT_DIR] = agentDir;+ process.env.PI_PACKAGE_DIR = packageDir;+ process.chdir(projectDir);+ Object.defineProperty(process, "execPath", {+ value: join(packageDir, "dist", "cli.js"),+ configurable: true,+ });+ writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ npmCommand: ["npm"] }, null, 2));+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => Response.json({ version: "999.0.0" })),+ );+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ process.chdir(originalCwd);+ process.exitCode = originalExitCode;+ if (originalAgentDir === undefined) {+ delete process.env[ENV_AGENT_DIR];+ } else {+ process.env[ENV_AGENT_DIR] = originalAgentDir;+ }+ if (originalPiPackageDir === undefined) {+ delete process.env.PI_PACKAGE_DIR;+ } else {+ process.env.PI_PACKAGE_DIR = originalPiPackageDir;+ }+ delete process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV];+ Object.defineProperty(process, "execPath", { value: originalExecPath, configurable: true });+ rmSync(tempDir, { recursive: true, force: true });+ });++ it("uses the interactive no-change sentinel only when self-update is unchanged", async () => {+ process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = "1";+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => Response.json({ version: "0.2.6" })),+ );++ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ expect(process.exitCode).toBe(SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE);+ expect(mockState.calls.some((call) => call.startsWith("spawn:npm "))).toBe(false);+ });++ it("does not use the no-change sentinel when interactive self-update is cancelled", async () => {+ process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = "1";+ mockState.daemonProbe = {+ reachable: true,+ activeSessions: [+ {+ id: "busy",+ activeSessionId: "busy",+ isStreaming: true,+ isCompacting: false,+ pendingMessageCount: 0,+ },+ ],+ };+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});++ try {+ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ expect(process.exitCode).toBe(1);+ expect(mockState.calls.some((call) => call.startsWith("spawn:npm "))).toBe(false);+ } finally {+ errorSpy.mockRestore();+ }+ });++ it("does not prepare or stop the daemon when the package update fails", async () => {+ mockState.spawnExitCodes = [23];+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});++ try {+ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ expect(process.exitCode).toBe(1);+ expect(mockState.calls).toContain("probe-daemon");+ expect(mockState.calls.some((call) => call === "daemon-request:prepare_update_restart")).toBe(false);+ expect(mockState.calls.some((call) => call === "shutdown-daemon")).toBe(false);+ } finally {+ errorSpy.mockRestore();+ logSpy.mockRestore();+ }+ });++ it("restarts the daemon only after the package update succeeds", async () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});++ try {+ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ expect(process.exitCode).toBeUndefined();+ const spawnIndex = mockState.calls.findIndex((call) => call.startsWith("spawn:npm "));+ const prepareIndex = mockState.calls.indexOf("daemon-request:prepare_update_restart");+ const shutdownIndex = mockState.calls.indexOf("shutdown-daemon");+ const ensureIndex = mockState.calls.indexOf("ensure-daemon");+ expect(spawnIndex).toBeGreaterThanOrEqual(0);+ expect(prepareIndex).toBeGreaterThan(spawnIndex);+ expect(shutdownIndex).toBeGreaterThan(prepareIndex);+ expect(ensureIndex).toBeGreaterThan(shutdownIndex);+ } finally {+ errorSpy.mockRestore();+ logSpy.mockRestore();+ }+ });++ it("still resumes accepted prompts when accepted context restore fails", async () => {+ mockState.restoreNextTurnFailures = 1;+ mockState.prepareManifest = {+ createdAt: "2026-07-07T00:00:00.000Z",+ sessions: [+ {+ activeSessionId: "old-active",+ sessionId: "session-1",+ sessionFile: join(projectDir, "session.jsonl"),+ cwd: projectDir,+ config: { cwd: projectDir, agentDir },+ queue: {+ steering: [],+ followUp: [],+ nextTurn: [+ {+ role: "custom",+ customType: "prime-agent.test",+ content: "subsequent turn context",+ display: false,+ timestamp: Date.now(),+ },+ ],+ acceptedPrompt: {+ message: "accepted work",+ content: [{ type: "text", text: "accepted work" }],+ agentMessageId: "agentmsg_accepted",+ nextTurn: [+ {+ role: "custom",+ customType: "prime-agent.test",+ content: "accepted prompt context",+ display: false,+ timestamp: Date.now(),+ },+ ],+ },+ },+ shouldResume: true,+ wasStreaming: false,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: true,+ },+ ],+ };+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});++ try {+ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ const promptRequests = mockState.requestPayloads.filter((request) => request.type === "prompt");+ expect(promptRequests).toEqual([+ expect.objectContaining({+ activeSessionId: "restored-active",+ message: "accepted work",+ agentMessageId: "agentmsg_accepted",+ }),+ ]);+ const promptIndex = mockState.requestPayloads.findIndex((request) => request.type === "prompt");+ const subsequentNextTurnIndex = mockState.requestPayloads.findIndex(+ (request) =>+ request.type === "restore_next_turn" &&+ request.messages?.some((message) => message.content === "subsequent turn context") === true,+ );+ expect(promptIndex).toBeGreaterThanOrEqual(0);+ expect(subsequentNextTurnIndex).toBeGreaterThan(promptIndex);+ } finally {+ errorSpy.mockRestore();+ logSpy.mockRestore();+ }+ });++ it("continues restoring later sessions when one session restore throws", async () => {+ const failedSessionFile = join(projectDir, "failed.jsonl");+ const restoredSessionFile = join(projectDir, "restored.jsonl");+ mockState.createThrowSessionPaths = [failedSessionFile];+ mockState.prepareManifest = {+ createdAt: "2026-07-07T00:00:00.000Z",+ sessions: [+ {+ activeSessionId: "failed-active",+ sessionId: "failed-session",+ sessionFile: failedSessionFile,+ cwd: projectDir,+ config: { cwd: projectDir, agentDir },+ queue: { steering: [], followUp: [], nextTurn: [] },+ shouldResume: true,+ wasStreaming: true,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: false,+ },+ {+ activeSessionId: "restored-active",+ sessionId: "restored-session",+ sessionFile: restoredSessionFile,+ cwd: projectDir,+ config: { cwd: projectDir, agentDir },+ queue: { steering: [], followUp: [], nextTurn: [] },+ shouldResume: true,+ wasStreaming: true,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: false,+ },+ ],+ };+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});++ try {+ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ expect(+ mockState.requestPayloads+ .filter((request) => request.type === "create")+ .map((request) => request.sessionPath),+ ).toEqual([failedSessionFile, restoredSessionFile]);+ expect(+ mockState.requestPayloads.some(+ (request) => request.type === "prompt" && request.activeSessionId === "restored-active",+ ),+ ).toBe(true);+ } finally {+ errorSpy.mockRestore();+ logSpy.mockRestore();+ }+ });++ it("restores subagent runtime metadata under the recreated parent session", async () => {+ const parentSessionFile = join(projectDir, "parent.jsonl");+ const childSessionFile = join(projectDir, "child.jsonl");+ mockState.createActiveSessionIds = ["new-parent", "new-child"];+ mockState.prepareManifest = {+ createdAt: "2026-07-07T00:00:00.000Z",+ sessions: [+ {+ activeSessionId: "old-parent",+ sessionId: "parent-session",+ sessionFile: parentSessionFile,+ cwd: projectDir,+ config: { cwd: projectDir, agentDir },+ runtimeMetadata: { kind: "top-level", createdAt: 1 },+ queue: { steering: [], followUp: [], nextTurn: [] },+ shouldResume: false,+ wasStreaming: false,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: false,+ },+ {+ activeSessionId: "old-child",+ sessionId: "child-session",+ sessionFile: childSessionFile,+ cwd: projectDir,+ config: { cwd: projectDir, agentDir },+ runtimeMetadata: {+ kind: "subagent",+ createdAt: 2,+ parentActiveSessionId: "old-parent",+ parentSessionId: "parent-session",+ parentSessionFile,+ rlmChildId: "child-1",+ prompt: "child task",+ },+ queue: { steering: [], followUp: [], nextTurn: [] },+ shouldResume: false,+ wasStreaming: false,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: false,+ },+ ],+ };+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});++ try {+ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ const createRequests = mockState.requestPayloads.filter((request) => request.type === "create");+ expect(createRequests).toHaveLength(2);+ expect(createRequests[0]).toMatchObject({+ sessionPath: parentSessionFile,+ runtimeMetadata: { kind: "top-level", createdAt: 1 },+ });+ expect(createRequests[1]).toMatchObject({+ sessionPath: childSessionFile,+ runtimeMetadata: {+ kind: "subagent",+ createdAt: 2,+ parentActiveSessionId: "new-parent",+ parentSessionId: "parent-session",+ parentSessionFile,+ rlmChildId: "child-1",+ prompt: "child task",+ },+ });+ } finally {+ errorSpy.mockRestore();+ logSpy.mockRestore();+ }+ });++ it("preserves queued custom messages when restoring update restart queues", async () => {+ const customMessage: MockCustomMessage = {+ role: "custom",+ customType: "heartbeat_prompt",+ content: "heartbeat body",+ display: true,+ timestamp: Date.now(),+ };+ mockState.prepareManifest = {+ createdAt: "2026-07-07T00:00:00.000Z",+ sessions: [+ {+ activeSessionId: "old-active",+ sessionId: "session-1",+ sessionFile: join(projectDir, "session.jsonl"),+ cwd: projectDir,+ config: { cwd: projectDir, agentDir },+ queue: {+ steering: [],+ followUp: [+ {+ message: "heartbeat body",+ queueKey: "heartbeat:job-1",+ agentMessageId: "agentmsg_followup",+ customMessage,+ },+ ],+ nextTurn: [],+ },+ shouldResume: true,+ wasStreaming: false,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: false,+ },+ ],+ };+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});++ try {+ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ expect(mockState.requestPayloads).toContainEqual(+ expect.objectContaining({+ type: "follow_up",+ activeSessionId: "restored-active",+ message: "heartbeat body",+ queueKey: "heartbeat:job-1",+ agentMessageId: "agentmsg_followup",+ customMessage,+ }),+ );+ } finally {+ errorSpy.mockRestore();+ logSpy.mockRestore();+ }+ });++ it("does not resume queued work when accepted prompt replay fails", async () => {+ mockState.promptFailures = 1;+ mockState.prepareManifest = {+ createdAt: "2026-07-07T00:00:00.000Z",+ sessions: [+ {+ activeSessionId: "old-active",+ sessionId: "session-1",+ sessionFile: join(projectDir, "session.jsonl"),+ cwd: projectDir,+ config: { cwd: projectDir, agentDir },+ queue: {+ steering: [],+ followUp: [{ message: "queued follow-up", agentMessageId: "agentmsg_followup" }],+ nextTurn: [],+ acceptedPrompt: {+ message: "accepted work",+ agentMessageId: "agentmsg_accepted",+ nextTurn: [],+ },+ },+ shouldResume: true,+ wasStreaming: false,+ wasCompacting: false,+ wasBashRunning: false,+ hadRunningRlmChildren: false,+ wasRetrying: false,+ hadAcceptedPromptInFlight: true,+ },+ ],+ };+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});++ try {+ await expect(handlePackageCommand(["update", "--self"])).resolves.toBe(true);++ expect(mockState.requestPayloads.some((request) => request.type === "follow_up")).toBe(true);+ expect(mockState.requestPayloads.some((request) => request.type === "resume_queue")).toBe(false);+ } finally {+ errorSpy.mockRestore();+ logSpy.mockRestore();+ }+ });+});diff --git a/packages/coding-agent/test/startup-notices.test.ts b/packages/coding-agent/test/startup-notices.test.tsindex bcfe0ae1cc..6bf6babac9 100644--- a/packages/coding-agent/test/startup-notices.test.ts+++ b/packages/coding-agent/test/startup-notices.test.ts@@ -17,15 +17,17 @@ describe("startup notice formatters", () => {initTheme("dark");});- test("update notice mentions the version and prime-agent update command", () => {+ test("update notice mentions the version and slash update command", () => {const output = stripAnsi(formatUpdateAvailableNotice("1.2.3"));- expect(output).toBe("Update available: v1.2.3. Run prime-agent update");+ expect(output).toBe("Update available: v1.2.3. Run /update");+ expect(output).not.toContain("prime-agent update");expect(output).not.toContain("pi update");});test("package update notice lists packages and the extensions command", () => {const output = stripAnsi(formatPackageUpdateNotice(["npm:@foo/bar", "npm:@baz/qux"]));- expect(output).toBe("Package updates available: npm:@foo/bar, npm:@baz/qux. Run prime-agent update --extensions");+ expect(output).toBe("Package updates available: npm:@foo/bar, npm:@baz/qux. Run /update --extensions");+ expect(output).not.toContain("prime-agent update");});test("tmux warning notice is prefixed with the warning glyph", () => {diff --git a/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts b/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.tsnew file mode 100644index 0000000000..e8ad07cc94--- /dev/null+++ b/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts@@ -0,0 +1,1121 @@+import { readFileSync, writeFileSync } from "node:fs";+import type { ImageContent, TextContent, UserMessage } from "@earendil-works/pi-ai";+import { fauxAssistantMessage } from "@earendil-works/pi-ai";+import { afterEach, describe, expect, it, vi } from "vitest";+import { getDaemonUpdateRestartManifestPath } from "../../../src/config.js";+import type { AgentSessionRuntime } from "../../../src/core/agent-session-runtime.js";+import type { AgentCronJobStore, AgentCronScheduler } from "../../../src/core/cron-jobs.js";+import type { CustomMessage } from "../../../src/core/messages.js";+import type { BashOperations } from "../../../src/core/tools/bash.js";+import type { ActiveSessionState, DaemonSocketClient } from "../../../src/modes/daemon/active-session-state.js";+import { AgentDaemon } from "../../../src/modes/daemon/daemon-mode.js";+import type { DaemonUpdateRestartManifest } from "../../../src/modes/daemon/daemon-protocol.js";+import { prepareDaemonUpdateRestart } from "../../../src/package-manager-cli.js";+import { createHarness, getUserTexts, type Harness } from "../harness.js";++type AgentDaemonUpdateInternals = {+ sessions: Map<string, ActiveSessionState>;+ cronStore: AgentCronJobStore;+ cronScheduler: AgentCronScheduler;+ prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest>;+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;+};++type QueueInternals = {+ _steeringMessages: Array<{ text: string; agentMessageId?: string; message: UserMessage | CustomMessage }>;+ _followUpMessages: Array<{+ text: string;+ queueKey?: string;+ agentMessageId?: string;+ message: UserMessage | CustomMessage;+ }>;+ _pendingNextTurnMessages: CustomMessage[];+ _acceptedAgentMessagePrompt?: {+ text: string;+ agentMessageId: string;+ message: UserMessage;+ messages: Set<unknown>;+ pendingNextTurnMessages: CustomMessage[];+ deliveredPendingNextTurnMessages: Set<CustomMessage>;+ accepted: Promise<void>;+ resolveAccepted: () => void;+ rejectAccepted: (error: Error) => void;+ turnStarted: boolean;+ cleared: boolean;+ };+};++type AgentInternals = {+ _state: {+ isStreaming: boolean;+ };+};++function createState(+ harness: Harness,+ activeSessionId: string,+ metadata: AgentSessionRuntime["metadata"],+ options: { clientEnv?: Record<string, string>; onDispose?: () => void } = {},+): ActiveSessionState {+ const runtime = {+ session: harness.session,+ metadata,+ runtimeConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ diagnostics: [],+ dispose: async () => {+ options.onDispose?.();+ },+ } as unknown as AgentSessionRuntime;+ return {+ activeSessionId,+ runtime,+ clients: new Set(),+ extensionUiRequests: new Map(),+ lastEventSequence: 0,+ ...(options.clientEnv ? { clientEnv: options.clientEnv } : {}),+ };+}++function hasArchivedState(harness: Harness): boolean {+ return harness.sessionManager+ .getEntries()+ .some((entry) => entry.type === "session_state" && entry.state.status === "archived");+}++async function waitForCondition(predicate: () => boolean): Promise<void> {+ for (let attempt = 0; attempt < 100; attempt++) {+ if (predicate()) {+ return;+ }+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ throw new Error("condition was not met");+}++function createCustomMessage(content: string): CustomMessage {+ return {+ role: "custom",+ customType: "prime-agent.test",+ content,+ display: false,+ timestamp: Date.now(),+ };+}++describe("issue #4257 update restart resume", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("captures a restart manifest and aborts running bash without archiving the session", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.session.recordBashResult("echo before", {+ output: "before",+ exitCode: 0,+ cancelled: false,+ truncated: false,+ });+ const operations: BashOperations = {+ exec: async (_command, _cwd, options) => {+ return await new Promise<{ exitCode: number | null }>((resolve) => {+ options.signal?.addEventListener(+ "abort",+ () => {+ resolve({ exitCode: null });+ },+ { once: true },+ );+ });+ },+ };+ const bashPromise = harness.session.executeBash("sleep", undefined, { operations });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(harness.session.isBashRunning).toBe(true);+ const abortSpy = vi.spyOn(harness.session, "abort");+ const agentAbortSpy = vi.spyOn(harness.session.agent, "abort");++ let disposed = false;+ let abortedBeforeDispose = false;+ const state = createState(+ harness,+ "active-1",+ { kind: "top-level", createdAt: Date.now() },+ {+ onDispose: () => {+ abortedBeforeDispose = agentAbortSpy.mock.calls.length > 0;+ disposed = true;+ },+ },+ );+ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(state.activeSessionId, state);+ const schedulerStopSpy = vi.spyOn(internals.cronScheduler, "stop");+ const now = new Date("2026-01-01T12:00:00.000Z");+ const cron = internals.cronStore.create({+ activeSessionId: state.activeSessionId,+ sessionId: harness.session.sessionId,+ sessionFile: harness.session.sessionFile ?? "",+ cwd: harness.tempDir,+ scheduleText: "in 1h",+ prompt: "check long run",+ now,+ });+ const heartbeat = internals.cronStore.createHeartbeat({+ activeSessionId: state.activeSessionId,+ sessionId: harness.session.sessionId,+ sessionFile: harness.session.sessionFile ?? "",+ cwd: harness.tempDir,+ scheduleText: "every 5m",+ prompt: "keep working",+ now,+ });++ const manifest = await internals.prepareUpdateRestart();+ const bashResult = await bashPromise;++ expect(bashResult.cancelled).toBe(true);+ expect(abortSpy).not.toHaveBeenCalled();+ expect(agentAbortSpy).toHaveBeenCalledOnce();+ expect(abortedBeforeDispose).toBe(true);+ expect(disposed).toBe(true);+ expect(internals.sessions.size).toBe(0);+ expect(schedulerStopSpy).toHaveBeenCalledOnce();+ for (const id of [cron.id, heartbeat.id]) {+ expect(internals.cronStore.list().find((job) => job.id === id)).toMatchObject({ status: "active" });+ }+ expect(manifest.sessions).toHaveLength(1);+ expect(manifest.sessions[0]).toMatchObject({+ activeSessionId: "active-1",+ sessionFile: harness.session.sessionFile,+ shouldResume: true,+ wasBashRunning: true,+ });+ const persistedManifest = JSON.parse(+ readFileSync(getDaemonUpdateRestartManifestPath(harness.tempDir), "utf-8"),+ ) as DaemonUpdateRestartManifest;+ expect(persistedManifest).toEqual(manifest);+ writeFileSync(getDaemonUpdateRestartManifestPath(harness.tempDir), JSON.stringify(manifest));+ await expect(prepareDaemonUpdateRestart(`${harness.tempDir}/missing.sock`, harness.tempDir)).resolves.toEqual(+ manifest,+ );+ expect(hasArchivedState(harness)).toBe(false);+ expect(+ harness.sessionManager+ .getEntries()+ .some((entry) => entry.type === "custom_message" && entry.customType === "prime-agent.update_restart"),+ ).toBe(true);+ abortSpy.mockRestore();+ agentAbortSpy.mockRestore();+ schedulerStopSpy.mockRestore();+ });++ it("keeps active goal abort state until update restart abort settles", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.session.handleGoalHostRequest("goal.create", { objective: "finish the update-safe task" });+ let releaseIdle: (() => void) | undefined;+ const idlePromise = new Promise<void>((resolve) => {+ releaseIdle = resolve;+ });+ const waitForIdleSpy = vi.spyOn(harness.session.agent, "waitForIdle").mockReturnValue(idlePromise);+ const agentAbortSpy = vi.spyOn(harness.session.agent, "abort");+ const internals = harness.session as unknown as { _goalAbortInProgress: boolean };++ harness.session.abortForUpdateRestart();++ expect(agentAbortSpy).toHaveBeenCalledOnce();+ expect(internals._goalAbortInProgress).toBe(true);++ releaseIdle?.();+ await waitForCondition(() => !internals._goalAbortInProgress);++ expect(internals._goalAbortInProgress).toBe(false);+ waitForIdleSpy.mockRestore();+ agentAbortSpy.mockRestore();+ });++ it("rejects new daemon sessions after update restart preparation starts", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const createRuntime = vi.fn(async () => {+ throw new Error("unexpected runtime creation");+ });+ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime,+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );++ await internals.prepareUpdateRestart();+ const writes: string[] = [];+ const client: DaemonSocketClient = {+ id: "client-1",+ socket: {+ destroyed: false,+ write: vi.fn((chunk: string) => {+ writes.push(chunk);+ return true;+ }),+ } as unknown as DaemonSocketClient["socket"],+ attachedActiveSessionIds: new Set(),+ detachInput: vi.fn(),+ supportsExtensionUi: false,+ capabilities: new Set(),+ };++ await internals.handleLine(client, JSON.stringify({ id: "late-create", type: "create" }));++ expect(createRuntime).not.toHaveBeenCalled();+ expect(JSON.parse(writes.join("").trim())).toMatchObject({+ id: "late-create",+ type: "response",+ command: "create",+ success: false,+ });+ });++ it("keeps queued draft sessions and subagents resumable", async () => {+ const parentHarness = await createHarness({ persistSession: true });+ const childHarness = await createHarness({ persistSession: true });+ harnesses.push(parentHarness, childHarness);++ const image: ImageContent = { type: "image", data: "ZmFrZQ==", mimeType: "image/png" };+ const content: (TextContent | ImageContent)[] = [+ { type: "text", text: "queued context" },+ { type: "text", text: "queued work" },+ image,+ ];+ const message: UserMessage = { role: "user", content, timestamp: Date.now() };+ const followUpContent: TextContent[] = [+ { type: "text", text: "follow-up context" },+ { type: "text", text: "heartbeat" },+ ];+ const followUpMessage: UserMessage = {+ role: "user",+ content: followUpContent,+ timestamp: Date.now(),+ };+ const customFollowUp = createCustomMessage("custom heartbeat");+ const queueInternals = parentHarness.session as unknown as QueueInternals;+ queueInternals._steeringMessages = [{ text: "queued work", agentMessageId: "agentmsg_steer", message }];+ queueInternals._followUpMessages = [+ {+ text: "heartbeat",+ queueKey: "heartbeat:job-1",+ agentMessageId: "agentmsg_followup",+ message: followUpMessage,+ },+ {+ text: "custom heartbeat",+ queueKey: "heartbeat:custom",+ agentMessageId: "agentmsg_custom",+ message: customFollowUp,+ },+ ];+ childHarness.session.recordBashResult("echo child", {+ output: "child",+ exitCode: 0,+ cancelled: false,+ truncated: false,+ });++ const daemon = new AgentDaemon(`${parentHarness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: parentHarness.tempDir, agentDir: parentHarness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "parent-active",+ createState(+ parentHarness,+ "parent-active",+ { kind: "top-level", createdAt: Date.now() },+ { clientEnv: { PRIME_SESSION: "pane-1" } },+ ),+ );+ internals.sessions.set(+ "child-active",+ createState(childHarness, "child-active", {+ kind: "subagent",+ parentActiveSessionId: "parent-active",+ parentSessionId: parentHarness.session.sessionId,+ parentSessionFile: parentHarness.session.sessionFile,+ createdAt: Date.now(),+ rlmChildId: "child-1",+ }),+ );++ const manifest = await internals.prepareUpdateRestart();++ expect(internals.sessions.size).toBe(0);+ expect(manifest.sessions).toHaveLength(2);+ expect(manifest.sessions[0]).toMatchObject({+ activeSessionId: "parent-active",+ clientEnv: { PRIME_SESSION: "pane-1" },+ runtimeMetadata: { kind: "top-level" },+ queue: {+ steering: [{ message: "queued work", content, images: [image], agentMessageId: "agentmsg_steer" }],+ followUp: [+ {+ message: "heartbeat",+ content: followUpContent,+ queueKey: "heartbeat:job-1",+ agentMessageId: "agentmsg_followup",+ },+ {+ message: "custom heartbeat",+ queueKey: "heartbeat:custom",+ agentMessageId: "agentmsg_custom",+ customMessage: customFollowUp,+ },+ ],+ },+ shouldResume: true,+ });+ expect(manifest.sessions[1]).toMatchObject({+ activeSessionId: "child-active",+ sessionFile: childHarness.session.sessionFile,+ runtimeMetadata: {+ kind: "subagent",+ parentActiveSessionId: "parent-active",+ parentSessionId: parentHarness.session.sessionId,+ parentSessionFile: parentHarness.session.sessionFile,+ rlmChildId: "child-1",+ },+ queue: { steering: [], followUp: [], nextTurn: [] },+ shouldResume: false,+ });+ expect(hasArchivedState(parentHarness)).toBe(false);+ expect(hasArchivedState(childHarness)).toBe(false);+ });++ it("captures next-turn context and accepted prompts in the restart manifest", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);++ const pendingNextTurn = createCustomMessage("pending next turn");+ const acceptedNextTurn = createCustomMessage("accepted prompt context");+ const deliveredAcceptedNextTurn = createCustomMessage("already delivered context");+ const acceptedContent: TextContent[] = [+ { type: "text", text: "accepted prefix" },+ { type: "text", text: "accepted work" },+ ];+ const acceptedMessage: UserMessage = {+ role: "user",+ content: acceptedContent,+ timestamp: Date.now(),+ };+ const queueInternals = harness.session as unknown as QueueInternals;+ queueInternals._pendingNextTurnMessages = [pendingNextTurn];+ queueInternals._acceptedAgentMessagePrompt = {+ text: "accepted work",+ agentMessageId: "agentmsg_accepted",+ message: acceptedMessage,+ messages: new Set([acceptedNextTurn, deliveredAcceptedNextTurn, acceptedMessage]),+ pendingNextTurnMessages: [acceptedNextTurn, deliveredAcceptedNextTurn],+ deliveredPendingNextTurnMessages: new Set([deliveredAcceptedNextTurn]),+ accepted: Promise.resolve(),+ resolveAccepted: () => undefined,+ rejectAccepted: () => undefined,+ turnStarted: false,+ cleared: false,+ };++ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );++ const manifest = await internals.prepareUpdateRestart();++ expect(manifest.sessions).toHaveLength(1);+ expect(manifest.sessions[0]).toMatchObject({+ activeSessionId: "active-1",+ shouldResume: true,+ hadAcceptedPromptInFlight: true,+ });+ expect(manifest.sessions[0]?.queue.nextTurn).toEqual([pendingNextTurn]);+ expect(manifest.sessions[0]?.queue.acceptedPrompt).toEqual({+ message: "accepted work",+ content: acceptedContent,+ agentMessageId: "agentmsg_accepted",+ nextTurn: [acceptedNextTurn],+ });+ });++ it("materializes queued in-memory drafts before update restart", async () => {+ const harness = await createHarness({ persistSession: false });+ harnesses.push(harness);++ const followUpContent: TextContent[] = [+ { type: "text", text: "queued context" },+ { type: "text", text: "queued follow-up" },+ ];+ const queueInternals = harness.session as unknown as QueueInternals;+ queueInternals._followUpMessages = [+ {+ text: "queued follow-up",+ queueKey: "heartbeat:job-1",+ agentMessageId: "agentmsg_followup",+ message: { role: "user", content: followUpContent, timestamp: Date.now() },+ },+ ];++ const sessionDir = `${harness.tempDir}/sessions`;+ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir, sessionDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );++ const manifest = await internals.prepareUpdateRestart();++ expect(manifest.sessions).toHaveLength(1);+ const session = manifest.sessions[0];+ expect(session?.sessionFile.startsWith(`${sessionDir}/`)).toBe(true);+ expect(harness.session.sessionFile).toBe(session?.sessionFile);+ expect(readFileSync(session?.sessionFile ?? "", "utf8")).toContain('"type":"session"');+ expect(session?.queue.followUp).toEqual([+ {+ message: "queued follow-up",+ content: followUpContent,+ queueKey: "heartbeat:job-1",+ agentMessageId: "agentmsg_followup",+ },+ ]);+ expect(session?.shouldResume).toBe(true);+ });++ it("materializes busy in-memory drafts before update restart", async () => {+ const harness = await createHarness({ persistSession: false });+ harnesses.push(harness);+ (harness.session.agent as unknown as AgentInternals)._state.isStreaming = true;++ const sessionDir = `${harness.tempDir}/sessions`;+ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir, sessionDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );++ const manifest = await internals.prepareUpdateRestart();++ expect(manifest.sessions).toHaveLength(1);+ const session = manifest.sessions[0];+ expect(session?.sessionFile.startsWith(`${sessionDir}/`)).toBe(true);+ expect(harness.session.sessionFile).toBe(session?.sessionFile);+ expect(session).toMatchObject({+ shouldResume: true,+ wasStreaming: true,+ queue: { steering: [], followUp: [], nextTurn: [] },+ });+ });++ it("keeps undelivered accepted-prompt context after the accepted turn starts", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);++ const pendingNextTurn = createCustomMessage("pending next turn");+ const acceptedNextTurn = createCustomMessage("accepted prompt context");+ const deliveredAcceptedNextTurn = createCustomMessage("already delivered context");+ const acceptedMessage: UserMessage = {+ role: "user",+ content: [{ type: "text", text: "accepted work" }],+ timestamp: Date.now(),+ };+ const queueInternals = harness.session as unknown as QueueInternals;+ queueInternals._pendingNextTurnMessages = [pendingNextTurn];+ queueInternals._acceptedAgentMessagePrompt = {+ text: "accepted work",+ agentMessageId: "agentmsg_accepted",+ message: acceptedMessage,+ messages: new Set([acceptedMessage, deliveredAcceptedNextTurn]),+ pendingNextTurnMessages: [acceptedNextTurn, deliveredAcceptedNextTurn],+ deliveredPendingNextTurnMessages: new Set([deliveredAcceptedNextTurn]),+ accepted: Promise.resolve(),+ resolveAccepted: () => undefined,+ rejectAccepted: () => undefined,+ turnStarted: true,+ cleared: false,+ };++ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );++ const manifest = await internals.prepareUpdateRestart();++ expect(manifest.sessions).toHaveLength(1);+ expect(manifest.sessions[0]).toMatchObject({+ activeSessionId: "active-1",+ shouldResume: true,+ hadAcceptedPromptInFlight: true,+ });+ expect(manifest.sessions[0]?.queue.nextTurn).toEqual([pendingNextTurn, acceptedNextTurn]);+ expect(manifest.sessions[0]?.queue.acceptedPrompt).toBeUndefined();+ });++ it("accepts restore_next_turn through daemon command parsing", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);++ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );++ const writes: string[] = [];+ const client: DaemonSocketClient = {+ id: "client-1",+ socket: {+ destroyed: false,+ write: vi.fn((chunk: string) => {+ writes.push(chunk);+ return true;+ }),+ } as unknown as DaemonSocketClient["socket"],+ attachedActiveSessionIds: new Set(["active-1"]),+ detachInput: vi.fn(),+ supportsExtensionUi: false,+ capabilities: new Set(),+ };+ const restoredMessage = createCustomMessage("restored next turn");++ await internals.handleLine(+ client,+ JSON.stringify({+ id: "restore-1",+ type: "restore_next_turn",+ activeSessionId: "active-1",+ messages: [restoredMessage],+ }),+ );++ expect(JSON.parse(writes.join("").trim())).toMatchObject({+ id: "restore-1",+ type: "response",+ command: "restore_next_turn",+ success: true,+ });+ expect(harness.session.getPendingNextTurnMessageSnapshots()).toEqual([restoredMessage]);+ });++ it("accepts restored prompt content through daemon command parsing", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.setResponses([fauxAssistantMessage("accepted restored prompt")]);++ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );++ const promptContent: TextContent[] = [+ { type: "text", text: "accepted prefix" },+ { type: "text", text: "accepted work" },+ ];+ const writes: string[] = [];+ const client: DaemonSocketClient = {+ id: "client-1",+ socket: {+ destroyed: false,+ write: vi.fn((chunk: string) => {+ writes.push(chunk);+ return true;+ }),+ } as unknown as DaemonSocketClient["socket"],+ attachedActiveSessionIds: new Set(["active-1"]),+ detachInput: vi.fn(),+ supportsExtensionUi: false,+ capabilities: new Set(),+ };++ await internals.handleLine(+ client,+ JSON.stringify({+ id: "prompt-1",+ type: "prompt",+ activeSessionId: "active-1",+ message: "accepted work",+ content: promptContent,+ expandPromptTemplates: false,+ agentMessageId: "agentmsg_accepted",+ }),+ );+ await new Promise((resolve) => setTimeout(resolve, 0));+ await harness.session.agent.waitForIdle();++ expect(+ writes+ .join("")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line)),+ ).toEqual([expect.objectContaining({ id: "prompt-1", command: "prompt", success: true })]);+ expect(harness.session.messages.find((message) => message.role === "user")?.content).toEqual(promptContent);+ });++ it("restores agent-message ids and reports deduped follow-ups", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);++ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );++ const queueInternals = harness.session as unknown as QueueInternals;+ const restoredSteerContent: TextContent[] = [+ { type: "text", text: "restored steer context" },+ { type: "text", text: "restored steer" },+ ];+ const restoredFollowUpContent: TextContent[] = [+ { type: "text", text: "restored follow-up context" },+ { type: "text", text: "restored follow-up" },+ ];+ queueInternals._followUpMessages = [+ {+ text: "existing",+ queueKey: "heartbeat:job-1",+ agentMessageId: "agentmsg_existing",+ message: { role: "user", content: [{ type: "text", text: "existing" }], timestamp: Date.now() },+ },+ ];+ const writes: string[] = [];+ const client: DaemonSocketClient = {+ id: "client-1",+ socket: {+ destroyed: false,+ write: vi.fn((chunk: string) => {+ writes.push(chunk);+ return true;+ }),+ } as unknown as DaemonSocketClient["socket"],+ attachedActiveSessionIds: new Set(["active-1"]),+ detachInput: vi.fn(),+ supportsExtensionUi: false,+ capabilities: new Set(),+ };++ await internals.handleLine(+ client,+ JSON.stringify({+ id: "steer-1",+ type: "steer",+ activeSessionId: "active-1",+ message: "restored steer",+ content: restoredSteerContent,+ expandPromptTemplates: false,+ agentMessageId: "agentmsg_restored_steer",+ }),+ );+ await internals.handleLine(+ client,+ JSON.stringify({+ id: "follow-up-1",+ type: "follow_up",+ activeSessionId: "active-1",+ message: "duplicate",+ queueKey: "heartbeat:job-1",+ expandPromptTemplates: false,+ agentMessageId: "agentmsg_duplicate",+ }),+ );+ await internals.handleLine(+ client,+ JSON.stringify({+ id: "follow-up-2",+ type: "follow_up",+ activeSessionId: "active-1",+ message: "restored follow-up",+ content: restoredFollowUpContent,+ queueKey: "heartbeat:job-2",+ expandPromptTemplates: false,+ agentMessageId: "agentmsg_restored_followup",+ }),+ );++ const responses = writes+ .join("")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(responses).toEqual([+ expect.objectContaining({ id: "steer-1", command: "steer", success: true }),+ expect.objectContaining({ id: "follow-up-1", command: "follow_up", success: true, data: { queued: false } }),+ expect.objectContaining({ id: "follow-up-2", command: "follow_up", success: true, data: { queued: true } }),+ ]);+ expect(harness.session.getSteeringQueueSnapshots()).toEqual([+ expect.objectContaining({+ text: "restored steer",+ content: restoredSteerContent,+ agentMessageId: "agentmsg_restored_steer",+ }),+ ]);+ expect(harness.session.getFollowUpQueueSnapshots()).toEqual([+ expect.objectContaining({ text: "existing", agentMessageId: "agentmsg_existing" }),+ expect.objectContaining({+ text: "restored follow-up",+ content: restoredFollowUpContent,+ agentMessageId: "agentmsg_restored_followup",+ }),+ ]);+ });++ it("resumes restored queues without promoting steering messages to prompts", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.setResponses([+ fauxAssistantMessage("seed response"),+ fauxAssistantMessage("handled steer 1"),+ fauxAssistantMessage("handled steer 2"),+ fauxAssistantMessage("handled follow-up"),+ ]);+ await harness.session.prompt("start");++ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );+ const writes: string[] = [];+ const client: DaemonSocketClient = {+ id: "client-1",+ socket: {+ destroyed: false,+ write: vi.fn((chunk: string) => {+ writes.push(chunk);+ return true;+ }),+ } as unknown as DaemonSocketClient["socket"],+ attachedActiveSessionIds: new Set(["active-1"]),+ detachInput: vi.fn(),+ supportsExtensionUi: false,+ capabilities: new Set(),+ };++ await internals.handleLine(+ client,+ JSON.stringify({+ id: "steer-1",+ type: "steer",+ activeSessionId: "active-1",+ message: "restored steer 1",+ expandPromptTemplates: false,+ }),+ );+ await internals.handleLine(+ client,+ JSON.stringify({+ id: "steer-2",+ type: "steer",+ activeSessionId: "active-1",+ message: "restored steer 2",+ expandPromptTemplates: false,+ }),+ );+ await internals.handleLine(+ client,+ JSON.stringify({+ id: "follow-up-1",+ type: "follow_up",+ activeSessionId: "active-1",+ message: "restored follow-up",+ expandPromptTemplates: false,+ }),+ );+ await internals.handleLine(+ client,+ JSON.stringify({+ id: "resume-1",+ type: "resume_queue",+ activeSessionId: "active-1",+ }),+ );++ await new Promise((resolve) => setTimeout(resolve, 0));+ await harness.session.agent.waitForIdle();++ const responses = writes+ .join("")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(responses).toEqual([+ expect.objectContaining({ id: "steer-1", command: "steer", success: true }),+ expect.objectContaining({ id: "steer-2", command: "steer", success: true }),+ expect.objectContaining({ id: "follow-up-1", command: "follow_up", success: true }),+ expect.objectContaining({ id: "resume-1", command: "resume_queue", success: true }),+ ]);+ expect(getUserTexts(harness)).toEqual(["start", "restored steer 1", "restored steer 2", "restored follow-up"]);+ expect(harness.session.getSteeringQueueSnapshots()).toEqual([]);+ expect(harness.session.getFollowUpQueueSnapshots()).toEqual([]);+ });++ it("drains restored queues when a continuation prompt resumes interrupted work", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.setResponses([fauxAssistantMessage("handled continuation"), fauxAssistantMessage("handled follow-up")]);+ harness.session.agent.state.messages.push(createCustomMessage("update interrupted"));++ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );+ const writes: string[] = [];+ const client: DaemonSocketClient = {+ id: "client-1",+ socket: {+ destroyed: false,+ write: vi.fn((chunk: string) => {+ writes.push(chunk);+ return true;+ }),+ } as unknown as DaemonSocketClient["socket"],+ attachedActiveSessionIds: new Set(["active-1"]),+ detachInput: vi.fn(),+ supportsExtensionUi: false,+ capabilities: new Set(),+ };++ await internals.handleLine(+ client,+ JSON.stringify({+ id: "steer-1",+ type: "steer",+ activeSessionId: "active-1",+ message: "restored steer",+ expandPromptTemplates: false,+ }),+ );+ await internals.handleLine(+ client,+ JSON.stringify({+ id: "follow-up-1",+ type: "follow_up",+ activeSessionId: "active-1",+ message: "restored follow-up",+ expandPromptTemplates: false,+ }),+ );+ await internals.handleLine(+ client,+ JSON.stringify({+ id: "prompt-1",+ type: "prompt",+ activeSessionId: "active-1",+ message: "continue interrupted work",+ expandPromptTemplates: false,+ }),+ );++ await new Promise((resolve) => setTimeout(resolve, 0));+ await harness.session.agent.waitForIdle();++ const responses = writes+ .join("")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(responses).toEqual([+ expect.objectContaining({ id: "steer-1", command: "steer", success: true }),+ expect.objectContaining({ id: "follow-up-1", command: "follow_up", success: true }),+ expect.objectContaining({ id: "prompt-1", command: "prompt", success: true }),+ ]);+ expect(getUserTexts(harness)).toEqual(["continue interrupted work", "restored steer", "restored follow-up"]);+ expect(harness.session.getSteeringQueueSnapshots()).toEqual([]);+ expect(harness.session.getFollowUpQueueSnapshots()).toEqual([]);+ });++ it("resumes restored queues after an update marker without prior transcript messages", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.setResponses([fauxAssistantMessage("handled restored follow-up")]);+ harness.session.agent.state.messages.push(createCustomMessage("update interrupted"));++ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );+ const writes: string[] = [];+ const client: DaemonSocketClient = {+ id: "client-1",+ socket: {+ destroyed: false,+ write: vi.fn((chunk: string) => {+ writes.push(chunk);+ return true;+ }),+ } as unknown as DaemonSocketClient["socket"],+ attachedActiveSessionIds: new Set(["active-1"]),+ detachInput: vi.fn(),+ supportsExtensionUi: false,+ capabilities: new Set(),+ };++ await internals.handleLine(+ client,+ JSON.stringify({+ id: "follow-up-1",+ type: "follow_up",+ activeSessionId: "active-1",+ message: "restored follow-up",+ expandPromptTemplates: false,+ }),+ );+ await internals.handleLine(+ client,+ JSON.stringify({+ id: "resume-1",+ type: "resume_queue",+ activeSessionId: "active-1",+ }),+ );++ await new Promise((resolve) => setTimeout(resolve, 0));+ await harness.session.agent.waitForIdle();++ const responses = writes+ .join("")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(responses).toEqual([+ expect.objectContaining({ id: "follow-up-1", command: "follow_up", success: true }),+ expect.objectContaining({ id: "resume-1", command: "resume_queue", success: true }),+ ]);+ expect(getUserTexts(harness)).toEqual(["restored follow-up"]);+ expect(harness.session.getFollowUpQueueSnapshots()).toEqual([]);+ });++ it("reports resume_queue failure when no work can resume", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);++ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {+ defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const internals = daemon as unknown as AgentDaemonUpdateInternals;+ internals.sessions.set(+ "active-1",+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),+ );+ const writes: string[] = [];+ const client: DaemonSocketClient = {+ id: "client-1",+ socket: {+ destroyed: false,+ write: vi.fn((chunk: string) => {+ writes.push(chunk);+ return true;+ }),+ } as unknown as DaemonSocketClient["socket"],+ attachedActiveSessionIds: new Set(["active-1"]),+ detachInput: vi.fn(),+ supportsExtensionUi: false,+ capabilities: new Set(),+ };++ await internals.handleLine(+ client,+ JSON.stringify({+ id: "resume-1",+ type: "resume_queue",+ activeSessionId: "active-1",+ }),+ );+ await Promise.resolve();++ const response = JSON.parse(writes.join("").trim());+ expect(response).toMatchObject({ id: "resume-1", command: "resume_queue", success: false });+ expect(JSON.stringify(response)).toContain("No messages to continue from");+ });+});