Skip to content

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

Rust

refactor(coding-agent): publish session action protocol (#575)

Sebastian Müller941576dbec6d
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index a8b5e4c600..a8025afe9a 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -10,6 +10,7 @@
- Fixed compaction retaining runtime resources after an explicitly deleted subagent had a transient cleanup failure.
- Fixed long-running thinking timers to display hours and days instead of unbounded minutes.
- Fixed overlapping daemon snapshot catch-ups closing healthy workers and preventing new sessions from starting.
+- Changed daemon and RPC session state to report literal queued actions separately from active scheduler work.
## [0.4.0] - 2026-08-01
diff --git a/packages/coding-agent/docs/json.md b/packages/coding-agent/docs/json.md
index a8b22b4754..a119f6d71e 100644
--- a/packages/coding-agent/docs/json.md
+++ b/packages/coding-agent/docs/json.md
@@ -13,14 +13,14 @@ Events are defined in [`AgentSessionEvent`](../src/core/agent-session.ts):
```typescript
type AgentSessionEvent =
| AgentEvent
- | { type: "queue_update"; steering: readonly string[]; followUp: readonly string[] }
+ | { type: "session_action_update"; actions: SessionActionSnapshot }
| { type: "compaction_start"; reason: "manual" | "threshold" | "overflow" }
| { type: "compaction_end"; reason: "manual" | "threshold" | "overflow"; result: CompactionResult | undefined; aborted: boolean; willRetry: boolean; errorMessage?: string }
| { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
| { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string };
```
-`queue_update` emits the full pending steering and follow-up queues whenever they change. `compaction_start` and `compaction_end` cover both manual and automatic compaction.
+`session_action_update` emits literal queued actions separately from active scheduler work whenever either projection changes. `compaction_start` and `compaction_end` cover both manual and automatic compaction.
Base events from [`AgentEvent`](../../agent/src/types.ts):
diff --git a/packages/coding-agent/docs/rpc.md b/packages/coding-agent/docs/rpc.md
index f04bce1330..aab84704d3 100644
--- a/packages/coding-agent/docs/rpc.md
+++ b/packages/coding-agent/docs/rpc.md
@@ -184,7 +184,12 @@ Response:
"sessionName": "my-feature-work",
"autoCompactionEnabled": true,
"messageCount": 5,
- "pendingMessageCount": 0
+ "unfinishedActionCount": 0,
+ "sessionActions": {
+ "queuedCount": 0,
+ "steering": [],
+ "followUps": []
+ }
}
}
```
@@ -795,7 +800,7 @@ Events are streamed to stdout as JSON lines during agent operation. Events do NO
| `tool_execution_start` | Tool begins execution |
| `tool_execution_update` | Tool execution progress (streaming output) |
| `tool_execution_end` | Tool completes |
-| `queue_update` | Pending steering/follow-up queue changed |
+| `session_action_update` | Pending steering/follow-up queue changed |
| `compaction_start` | Compaction begins |
| `compaction_end` | Compaction completes |
| `auto_retry_start` | Auto-retry begins (after transient error) |
@@ -933,15 +938,19 @@ When complete:
Use `toolCallId` to correlate events. The `partialResult` in `tool_execution_update` contains the accumulated output so far (not just the delta), allowing clients to simply replace their display on each update.
-### queue_update
+### session_action_update
-Emitted whenever the pending steering or follow-up queue changes.
+Emitted whenever literal queued actions or the active scheduler action changes.
```json
{
- "type": "queue_update",
- "steering": ["Focus on error handling"],
- "followUp": ["After that, summarize the result"]
+ "type": "session_action_update",
+ "actions": {
+ "queuedCount": 2,
+ "steering": ["Focus on error handling"],
+ "followUps": ["After that, summarize the result"],
+ "active": { "kind": "session_command", "phase": "running", "label": "/compact" }
+ }
}
```
diff --git a/packages/coding-agent/docs/sdk.md b/packages/coding-agent/docs/sdk.md
index 1f02cec9e3..b3c3d3dd8e 100644
--- a/packages/coding-agent/docs/sdk.md
+++ b/packages/coding-agent/docs/sdk.md
@@ -316,8 +316,8 @@ session.subscribe((event) => {
break;
// Session events (queue, compaction, retry)
- case "queue_update":
- console.log(event.steering, event.followUp);
+ case "session_action_update":
+ console.log(event.actions.steering, event.actions.followUps);
break;
case "compaction_start":
case "compaction_end":
diff --git a/packages/coding-agent/examples/sdk/13-session-runtime.ts b/packages/coding-agent/examples/sdk/13-session-runtime.ts
index 52c7f244c8..a49d71ab09 100644
--- a/packages/coding-agent/examples/sdk/13-session-runtime.ts
+++ b/packages/coding-agent/examples/sdk/13-session-runtime.ts
@@ -42,8 +42,8 @@ async function bindSession() {
const session = runtime.session;
await session.bindExtensions({});
unsubscribe = session.subscribe((event) => {
- if (event.type === "queue_update") {
- console.log("Queued:", event.steering.length + event.followUp.length);
+ if (event.type === "session_action_update") {
+ console.log("Queued:", event.actions.steering.length + event.actions.followUps.length);
}
});
return session;
diff --git a/packages/coding-agent/src/cli-main.ts b/packages/coding-agent/src/cli-main.ts
index 34350b70ba..c598dc7b7d 100644
--- a/packages/coding-agent/src/cli-main.ts
+++ b/packages/coding-agent/src/cli-main.ts
@@ -1,14 +1,12 @@
import { enableCompileCache } from "node:module";
-import { maybeStartDaemonEarly, shouldUseLegacyOwnedSessionWorkerFrontend } from "./cli/daemon-launch.js";
+import { maybeStartDaemonEarly } from "./cli/daemon-launch.js";
import {
- classifyOwnedSessionWorkerInvocation,
closeOwnedSessionWorkerOwnerWatch,
installOwnedSessionWorkerOwnerWatch,
isOwnedSessionWorkerProcess,
maybeRunOwnedSessionWorkerFrontend,
} from "./cli/owned-session-worker.js";
import { APP_NAME } from "./config.js";
-import { defaultDaemonSocketPath } from "./modes/daemon/daemon-socket.js";
export async function runCli(): Promise<void> {
try {
@@ -24,12 +22,7 @@ export async function runCli(): Promise<void> {
installOwnedSessionWorkerOwnerWatch();
const args = process.argv.slice(2);
- const ownedWorkerProfile = classifyOwnedSessionWorkerInvocation(args, process.stdin.isTTY);
- const useLegacyOwnedWorker =
- process.env.PRIME_AGENT_INTERNAL_LEGACY_OWNED_WORKER_FRONTEND !== "1" &&
- ownedWorkerProfile !== undefined &&
- (await shouldUseLegacyOwnedSessionWorkerFrontendFromArgs(args));
- const handledByOwnedWorker = await maybeRunOwnedSessionWorkerFrontend(args, useLegacyOwnedWorker);
+ const handledByOwnedWorker = await maybeRunOwnedSessionWorkerFrontend(args);
if (!handledByOwnedWorker) {
if (!isOwnedSessionWorkerProcess()) {
// Boot a cold daemon concurrently with this process's heavy imports.
@@ -51,10 +44,3 @@ export async function runCli(): Promise<void> {
}
}
}
-
-async function shouldUseLegacyOwnedSessionWorkerFrontendFromArgs(args: readonly string[]): Promise<boolean> {
- const socketIndex = args.indexOf("--daemon-socket");
- const socketPath =
- socketIndex !== -1 && args[socketIndex + 1] ? (args[socketIndex + 1] as string) : defaultDaemonSocketPath();
- return shouldUseLegacyOwnedSessionWorkerFrontend(socketPath);
-}
diff --git a/packages/coding-agent/src/cli/daemon-command.ts b/packages/coding-agent/src/cli/daemon-command.ts
index 2fb10d5bd2..0c5085ff60 100644
--- a/packages/coding-agent/src/cli/daemon-command.ts
+++ b/packages/coding-agent/src/cli/daemon-command.ts
@@ -1451,10 +1451,12 @@ class DaemonAttachTerminal {
case "tool_execution_end":
this.writeLine(chalk.dim(`Tool ${event.isError ? "failed" : "finished"}: ${event.toolName}`));
return;
- case "queue_update":
- if (event.steering.length > 0 || event.followUp.length > 0) {
+ case "session_action_update":
+ if (event.actions.queuedCount > 0) {
this.writeLine(
- chalk.dim(`Queued: ${event.steering.length} steering, ${event.followUp.length} follow-up`),
+ chalk.dim(
+ `Queued: ${event.actions.steering.length} steering, ${event.actions.followUps.length} follow-up`,
+ ),
);
}
return;
@@ -1648,11 +1650,17 @@ function isSessionSummary(value: unknown): value is SessionSummary {
typeof candidate.cwd === "string" &&
typeof candidate.lifecycle === "string" &&
typeof candidate.activity === "string" &&
+ typeof candidate.isSessionActive === "boolean" &&
typeof candidate.isStreaming === "boolean" &&
typeof candidate.isCompacting === "boolean" &&
typeof candidate.attachedClients === "number" &&
typeof candidate.messageCount === "number" &&
- typeof candidate.pendingMessageCount === "number"
+ (candidate.unfinishedActionCount === undefined || typeof candidate.unfinishedActionCount === "number") &&
+ typeof candidate.sessionActions === "object" &&
+ candidate.sessionActions !== null &&
+ typeof candidate.sessionActions.queuedCount === "number" &&
+ Array.isArray(candidate.sessionActions.steering) &&
+ Array.isArray(candidate.sessionActions.followUps)
);
}
diff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.ts
index 0083582997..c8c45b56b9 100644
--- a/packages/coding-agent/src/cli/daemon-launch.ts
+++ b/packages/coding-agent/src/cli/daemon-launch.ts
@@ -62,7 +62,7 @@ async function canConnectToDaemon(socketPath: string, timeoutMs: number): Promis
type DaemonVersionProbe =
| { status: "absent" }
| { status: "current"; hello: DaemonHello }
- | { status: "stale"; hello?: DaemonHello; compatible: boolean };
+ | { status: "stale"; hello?: DaemonHello };
/** Connect to a running daemon and check whether it matches this client's protocol and app version. */
export async function probeDaemonVersion(socketPath: string): Promise<DaemonVersionProbe> {
@@ -96,15 +96,11 @@ export async function probeDaemonVersion(socketPath: string): Promise<DaemonVers
if (current) {
return { status: "current", hello };
}
- return {
- status: "stale",
- hello,
- compatible: hello.protocol.version === 3,
- };
+ return { status: "stale", hello };
} catch {
// Connected but no recognizable greeting: assume a stale daemon.
logDaemonLaunch(`running daemon on ${socketPath} sent no recognizable hello; treating as stale`);
- return { status: "stale", compatible: false };
+ return { status: "stale" };
} finally {
client.close();
}
@@ -121,11 +117,7 @@ async function queryActiveDaemonSessions(
client: DaemonClient,
options: { includeClientOwned?: boolean } = {},
): Promise<{ sessions: SessionSummary[]; busyClientOwnedSessionCount: number }> {
- const hello = await client.waitForHello(2000).catch(() => undefined);
- const response =
- hello && hello.protocol.version < DAEMON_PROTOCOL_VERSION
- ? await client.requestLegacy({ type: "list", includeClientOwned: options.includeClientOwned })
- : await client.request({ type: "list", includeClientOwned: options.includeClientOwned });
+ const response = await client.request({ type: "list", includeClientOwned: options.includeClientOwned });
if (!response.success) {
throw new Error(response.error);
}
@@ -249,11 +241,7 @@ export async function shutdownConnectedDaemonAndWait(
let shutdownAccepted = false;
const expectedIdentity = processIdentityFromDaemonHello(hello);
try {
- const request =
- hello && hello.protocol.version < DAEMON_PROTOCOL_VERSION
- ? client.requestLegacy.bind(client)
- : client.request.bind(client);
- const response = await request({ type: "shutdown" }).catch(() => undefined);
+ const response = await client.request({ type: "shutdown" }).catch(() => undefined);
shutdownAccepted = response?.success === true;
} catch {
// A connect failure isn't treated as "gone"; waitForDaemonGone is the source of truth.
@@ -309,20 +297,6 @@ export async function probeRunningDaemonSessions(socketPath: string): Promise<Ru
}
}
-export async function shouldUseLegacyOwnedSessionWorkerFrontend(socketPath: string): Promise<boolean> {
- const version = await probeDaemonVersion(socketPath);
- if (version.status !== "stale") {
- return false;
- }
- const running = await probeRunningDaemonSessions(socketPath);
- return (
- running.reachable &&
- (running.activeSessions === undefined ||
- (running.busyClientOwnedSessionCount ?? 0) > 0 ||
- running.activeSessions.some((summary) => isSessionBusy(summary)))
- );
-}
-
// Idle-but-loaded sessions reload from disk on the fresh daemon, so only a busy
// session blocks replacing a stale daemon.
async function shutdownStaleDaemonIfNotBusy(socketPath: string): Promise<boolean> {
@@ -368,13 +342,7 @@ async function ensureDaemonRunning(socketPath: string, spawnCwd?: string): Promi
}
if (probe.status === "stale") {
const stopped = await shutdownStaleDaemonIfNotBusy(socketPath);
- if (!stopped) {
- if (probe.compatible) {
- logDaemonLaunch(`using compatible legacy daemon on ${socketPath} while busy work completes`);
- return;
- }
- throw new StaleDaemonError(socketPath, probe.hello);
- }
+ if (!stopped) throw new StaleDaemonError(socketPath, probe.hello);
}
const entrypoint = process.argv[1];
diff --git a/packages/coding-agent/src/core/agent-messages.ts b/packages/coding-agent/src/core/agent-messages.ts
index f066e9b742..10de6d8846 100644
--- a/packages/coding-agent/src/core/agent-messages.ts
+++ b/packages/coding-agent/src/core/agent-messages.ts
@@ -31,7 +31,7 @@ export interface AgentSessionMessageSender extends Partial<AgentSessionMessageEn
export interface AgentSessionMessageAgentSummary extends AgentSessionMessageEndpoint {
cwd: string;
isStreaming: boolean;
- pendingMessageCount: number;
+ unfinishedActionCount: number;
parentActiveSessionId?: string;
rlmChildId?: string;
}
@@ -134,12 +134,12 @@ export function assertDirectAgentMessageTarget(target: string): string {
}
export function assertAgentMessageQueueCapacity(
- pendingMessageCount: number,
+ unfinishedActionCount: number,
maxPending = DEFAULT_AGENT_MESSAGE_MAX_PENDING_PER_SESSION,
): void {
- if (pendingMessageCount >= maxPending) {
+ if (unfinishedActionCount >= maxPending) {
throw new Error(
- `Target session has too many pending messages: ${pendingMessageCount} pending, limit is ${maxPending}`,
+ `Target session has too many pending messages: ${unfinishedActionCount} unfinished, limit is ${maxPending}`,
);
}
}
diff --git a/packages/coding-agent/src/core/agent-observe.ts b/packages/coding-agent/src/core/agent-observe.ts
index 4be28b2ad9..a53f2c9b8b 100644
--- a/packages/coding-agent/src/core/agent-observe.ts
+++ b/packages/coding-agent/src/core/agent-observe.ts
@@ -16,7 +16,8 @@ export interface AgentObserveAgentSummary {
isCompacting: boolean;
attachedClients: number;
messageCount: number;
- pendingMessageCount: number;
+ queuedCount: number;
+ isSessionActive: boolean;
parentActiveSessionId?: string;
parentSessionId?: string;
rlmChildId?: string;
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index 7f8a853cb7..410222d021 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -237,10 +237,12 @@ import {
type DeliveryRecord,
type RuntimeActivity,
type SessionAction,
+ type SessionActionSnapshot,
type SessionCommandPayload,
type SessionTurnPayload,
shouldYieldLowerRun,
transitionSessionAction,
+ type WakePolicy,
} from "./session-action-store.js";
import type { BranchSummaryEntry, CompactionEntry, SessionContext, SessionMessageEntry } from "./session-manager.js";
import {
@@ -309,11 +311,7 @@ export type CompactionReason = "manual" | "threshold" | "overflow" | "requested"
export type AgentSessionEvent =
| AgentEvent
| { type: "ipython_sent_agent_message"; toolCallId: string; message: KernelSentAgentMessage }
- | {
- type: "queue_update";
- steering: readonly string[];
- followUp: readonly string[];
- }
+ | { type: "session_action_update"; actions: SessionActionSnapshot }
| { type: "compaction_start"; reason: CompactionReason; customInstructions?: string }
| { type: "session_info_changed"; name: string | undefined }
| { type: "thinking_level_changed"; level: ThinkingLevel }
@@ -582,7 +580,7 @@ interface CommitPreparationSteps<TPrepared, TCommitted> {
type QueuedAgentMessage = UserMessage | CustomMessage;
type SessionInputSchedule = "steer" | "followUp";
-interface TurnExecutionPolicy {
+export interface TurnExecutionPolicy {
preparation: CommitPreparationPolicy;
runBeforeAgentStart: boolean;
nextTurnContextTiming: "preparation" | "commit" | "skip";
@@ -645,7 +643,7 @@ function oncePreflight(
};
}
-export interface QueuedAgentInputSnapshot {
+interface RestoredPromptInput {
text: string;
content?: (TextContent | ImageContent)[];
images?: ImageContent[];
@@ -655,12 +653,50 @@ export interface QueuedAgentInputSnapshot {
prefixMessages?: CustomMessage[];
}
-export interface AcceptedAgentInputSnapshot extends QueuedAgentInputSnapshot {
- nextTurn: CustomMessage[];
+export const SESSION_ACTION_RECOVERY_FORMAT_VERSION = 1;
+
+export interface SessionActionRecoveryRecord {
+ id: string;
+ role: DeliveryRecord["role"];
+ message: QueuedAgentMessage;
+ ownerActionId: string;
}
-interface SessionActionRecoverySnapshot {
- actions: readonly QueuedSessionAction[];
+export type SessionActionRecoveryPayload =
+ | {
+ kind: "turn";
+ text: string;
+ preview?: string;
+ records: SessionActionRecoveryRecord[];
+ images?: ImageContent[];
+ content?: (TextContent | ImageContent)[];
+ customMessage?: CustomMessage;
+ executionPolicy: TurnExecutionPolicy;
+ queueVisible: boolean;
+ acceptedAgentMessage: boolean;
+ acceptedBeforeCompletion: boolean;
+ }
+ | {
+ kind: "session_command";
+ text: string;
+ command: SessionSlashCommand;
+ images?: ImageContent[];
+ };
+
+export interface SessionActionRecoveryAction {
+ id: string;
+ source: InputSource | "internal";
+ delivery: DeliveryPolicy;
+ wake: WakePolicy;
+ payload: SessionActionRecoveryPayload;
+ queueKey?: string;
+ agentMessageId?: string;
+ suppressAutonomousContinuation?: boolean;
+}
+
+export interface SessionActionRecoverySnapshot {
+ formatVersion: typeof SESSION_ACTION_RECOVERY_FORMAT_VERSION;
+ actions: SessionActionRecoveryAction[];
}
function cloneCustomMessage(message: CustomMessage): CustomMessage {
@@ -670,20 +706,12 @@ function cloneCustomMessage(message: CustomMessage): CustomMessage {
};
}
-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 cloneQueuedAgentMessage(message: QueuedAgentMessage): QueuedAgentMessage {
+ if (message.role === "custom") return cloneCustomMessage(message);
+ return {
+ ...message,
+ content: Array.isArray(message.content) ? message.content.map((block) => ({ ...block })) : message.content,
+ };
}
function primaryDeliveryRecord(action: QueuedSessionAction): DeliveryRecord {
@@ -701,33 +729,6 @@ function actionPrefixMessages(action: QueuedSessionAction): CustomMessage[] {
: [];
}
-function createQueuedAgentInputSnapshot(action: QueuedSessionAction): QueuedAgentInputSnapshot {
- const payload = action.payload;
- if (payload.kind === "session_command") {
- return {
- text: payload.text,
- ...(payload.images ? { images: payload.images.map((image) => ({ ...image })) } : {}),
- ...(action.agentMessageId ? { agentMessageId: action.agentMessageId } : {}),
- customMessage: createSessionSlashCommandMessage(payload.command),
- };
- }
- const message = primaryDeliveryRecord(action).message;
- const legacySnapshot = createQueuedAgentInputSnapshotFromUserMessage(payload.text, message);
- const prefixMessages = actionPrefixMessages(action);
- return {
- ...legacySnapshot,
- text: payload.text,
- ...(payload.content ? { content: payload.content.map((block) => ({ ...block })) } : {}),
- ...(payload.images ? { images: payload.images.map((image) => ({ ...image })) } : {}),
- ...(payload.customMessage ? { customMessage: cloneCustomMessage(payload.customMessage) } : {}),
- ...(prefixMessages.length > 0
- ? { prefixMessages: prefixMessages.map((prefix) => cloneCustomMessage(prefix)) }
- : {}),
- ...(action.agentMessageId ? { agentMessageId: action.agentMessageId } : {}),
- ...(action.queueKey ? { queueKey: action.queueKey } : {}),
- };
-}
-
function normalizeMessageContent(content: string | (TextContent | ImageContent)[]): {
text: string;
images?: ImageContent[];
@@ -750,6 +751,15 @@ function queuedAgentMessagePreview(action: QueuedSessionAction): string {
return payload.preview ?? payload.text;
}
+function visibleSessionActionProjection(actions: readonly QueuedSessionAction[]): readonly QueuedSessionAction[] {
+ return actions.filter(
+ (action) =>
+ action.payload.kind === "session_command" ||
+ action.payload.queueVisible ||
+ action.payload.acceptedAgentMessage,
+ );
+}
+
const IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_ENTRY = "ipython_sent_agent_message";
interface PersistedIpythonSentAgentMessage {
@@ -1036,7 +1046,7 @@ export class AgentSession {
// Event subscription state
private _unsubscribeAgent?: () => void;
private _eventListeners: AgentSessionEventListener[] = [];
- private _lastQueueUpdate = { steering: [] as string[], followUp: [] as string[] };
+ private _lastSessionActionSnapshot: SessionActionSnapshot = { queuedCount: 0, steering: [], followUps: [] };
private _agentEventQueue: Promise<void> = Promise.resolve();
/** Session-owned actions. Items are never fed into Agent.steer/followUp. */
@@ -1397,18 +1407,10 @@ export class AgentSession {
}
private _emitQueueUpdate(): void {
- const steering = this.legacyPendingProjection("next_turn_boundary").map(queuedAgentMessagePreview);
- const followUp = this.legacyPendingProjection("when_run_idle").map(queuedAgentMessagePreview);
- if (
- steering.length === this._lastQueueUpdate.steering.length &&
- followUp.length === this._lastQueueUpdate.followUp.length &&
- steering.every((value, index) => value === this._lastQueueUpdate.steering[index]) &&
- followUp.every((value, index) => value === this._lastQueueUpdate.followUp[index])
- ) {
- return;
- }
- this._lastQueueUpdate = { steering, followUp };
- this._emit({ type: "queue_update", steering, followUp });
+ const actions = this.getSessionActionSnapshot();
+ if (JSON.stringify(actions) === JSON.stringify(this._lastSessionActionSnapshot)) return;
+ this._lastSessionActionSnapshot = actions;
+ this._emit({ type: "session_action_update", actions });
}
private _restoreLateIpythonSentAgentMessages(): void {
@@ -1584,7 +1586,12 @@ export class AgentSession {
}
for (const action of actions) {
const ticket = this._actionStore.ticketFor(action);
- if (action.payload.kind === "turn" && (action.payload.acceptedAgentMessage || !action.payload.queueVisible)) {
+ if (
+ action.payload.kind === "turn" &&
+ (action.payload.acceptedAgentMessage ||
+ !action.payload.queueVisible ||
+ previousStates.get(action.id) !== "queued")
+ ) {
ticket.rejectDelivered(error);
} else {
ticket.settleDelivered({ status: "not_applicable" });
@@ -1613,6 +1620,7 @@ export class AgentSession {
this._actionStore.releaseTerminal(action);
}
}
+ if (actions.length > 0) this._notifySessionInputCheckpointChange();
return actions;
}
@@ -2652,7 +2660,7 @@ export class AgentSession {
if (options.messages === undefined) {
this._continueAfterThresholdCompaction = false;
}
- if (!this.agent.hasQueuedMessages() && this.pendingMessageCount === 0) {
+ if (!this.agent.hasQueuedMessages() && this.unfinishedActionCount === 0) {
this._cancelPostCompactionContinue();
}
}
@@ -3039,7 +3047,7 @@ export class AgentSession {
context: GetContinuationMessagesContext,
signal?: AbortSignal,
): Promise<AgentMessage[]> {
- if (this.pendingMessageCount > 0) {
+ if (this.queuedActionCount > 0) {
return [];
}
const arrivalEpoch = this._sessionInputArrivalEpoch;
@@ -3200,6 +3208,7 @@ export class AgentSession {
if (record?.role === "primary" && action.lifecycle.state === "committing") {
transitionSessionAction(action, { state: "running", execution: "agent_turn" });
this._notifySessionInputCheckpointChange();
+ this._emitQueueUpdate();
}
}
}
@@ -3825,6 +3834,7 @@ export class AgentSession {
if (outcome.completion) this._settleAgentMessage(agentMessageId, "completion", completionError);
}
this._cancelSessionActions(() => true, deliveryError);
+ this._notifySessionInputCheckpointChange();
this.agent.clearAllQueues();
this._extensionRunner.invalidate(
"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().",
@@ -4671,6 +4681,75 @@ export class AgentSession {
});
}
+ async restoreSessionActions(snapshot: SessionActionRecoverySnapshot): Promise<number> {
+ if (snapshot.formatVersion !== SESSION_ACTION_RECOVERY_FORMAT_VERSION) {
+ throw new Error(`Unsupported session action recovery format version: ${snapshot.formatVersion}`);
+ }
+ const actionIds = new Set(this._actionStore.ownedActions().map((action) => action.id));
+ const actions = snapshot.actions.map((recovered): QueuedSessionAction => {
+ if (actionIds.has(recovered.id)) throw new Error(`Duplicate session action id: ${recovered.id}`);
+ actionIds.add(recovered.id);
+ if (
+ recovered.payload.kind === "turn" &&
+ recovered.payload.records.some((record) => record.ownerActionId !== recovered.id)
+ ) {
+ throw new Error(`Session action ${recovered.id} has invalid delivery correlation`);
+ }
+ const payload: PreparedTurnPayload | PreparedCommandPayload =
+ recovered.payload.kind === "turn"
+ ? {
+ kind: "turn",
+ text: recovered.payload.text,
+ ...(recovered.payload.preview ? { preview: recovered.payload.preview } : {}),
+ records: recovered.payload.records.map((record) => ({
+ id: record.id,
+ role: record.role,
+ message: cloneQueuedAgentMessage(record.message),
+ started: false,
+ durable: false,
+ ownerActionId: record.ownerActionId,
+ })),
+ ...(recovered.payload.images
+ ? { images: recovered.payload.images.map((image) => ({ ...image })) }
+ : {}),
+ ...(recovered.payload.content
+ ? { content: recovered.payload.content.map((block) => ({ ...block })) }
+ : {}),
+ ...(recovered.payload.customMessage
+ ? { customMessage: cloneCustomMessage(recovered.payload.customMessage) }
+ : {}),
+ executionPolicy: {
+ ...recovered.payload.executionPolicy,
+ preparation: { ...recovered.payload.executionPolicy.preparation },
+ },
+ queueVisible: recovered.payload.queueVisible,
+ acceptedAgentMessage: recovered.payload.acceptedAgentMessage,
+ acceptedBeforeCompletion: recovered.payload.acceptedBeforeCompletion,
+ }
+ : {
+ kind: "session_command",
+ text: recovered.payload.text,
+ command: { ...recovered.payload.command },
+ ...(recovered.payload.images
+ ? { images: recovered.payload.images.map((image) => ({ ...image })) }
+ : {}),
+ };
+ return {
+ id: recovered.id,
+ source: recovered.source,
+ delivery: recovered.delivery,
+ wake: recovered.wake,
+ payload,
+ lifecycle: { state: "queued" },
+ ...(recovered.queueKey ? { queueKey: recovered.queueKey } : {}),
+ ...(recovered.agentMessageId ? { agentMessageId: recovered.agentMessageId } : {}),
+ ...(recovered.suppressAutonomousContinuation ? { suppressAutonomousContinuation: true } : {}),
+ };
+ });
+ for (const action of actions) this._admitSessionInput(action, { restore: true });
+ return actions.length;
+ }
+
private _restoreSessionCommand(
text: string,
customMessage: CustomMessage | undefined,
@@ -4690,10 +4769,7 @@ export class AgentSession {
).accepted;
}
- private _restoreLegacyRecoveryPrompt(
- schedule: SessionInputSchedule,
- snapshot: QueuedAgentInputSnapshot,
- ): Promise<boolean> {
+ private _restorePromptInput(schedule: SessionInputSchedule, snapshot: RestoredPromptInput): Promise<boolean> {
return this._queuePreparedPrompt(schedule, snapshot.text, snapshot.images, {
queueKey: snapshot.queueKey,
agentMessageId: snapshot.agentMessageId,
@@ -4720,7 +4796,7 @@ export class AgentSession {
)
return;
- await this._restoreLegacyRecoveryPrompt("steer", {
+ await this._restorePromptInput("steer", {
text,
images,
queueKey: options.queueKey,
@@ -4751,7 +4827,7 @@ export class AgentSession {
);
if (restoredCommand !== undefined) return restoredCommand;
- return this._restoreLegacyRecoveryPrompt("followUp", {
+ return this._restorePromptInput("followUp", {
text,
images,
queueKey: options.queueKey,
@@ -4962,7 +5038,7 @@ export class AgentSession {
action: QueuedSessionAction,
options: { restore?: boolean; front?: boolean; wake?: boolean; immediatelyEligible?: boolean } = {},
): { accepted: boolean; disposition: "starts_when_admitted" | "queued"; ticket?: ActionTicket } {
- const coalescedOwner = this._coalescedFollowUpOwner(action);
+ const coalescedOwner = options.restore ? undefined : this._coalescedFollowUpOwner(action);
if (coalescedOwner) {
if (action.agentMessageId !== coalescedOwner.agentMessageId) {
this._rejectAgentMessage(
@@ -5704,67 +5780,125 @@ export class AgentSession {
return { steering: removedSteering, followUp: removedFollowUp };
}
- /** Preserves the active-as-pending wire behavior until the PR 4 protocol break. */
- private legacyPendingProjection(delivery: DeliveryPolicy): readonly QueuedSessionAction[] {
- return this._actionStore.unfinishedActions(delivery).filter((action) => {
- if (action.payload.kind === "turn" && !action.payload.queueVisible) return false;
- if (action.lifecycle.state === "queued") return true;
- if (action.payload.kind === "session_command") {
- return action.lifecycle.state === "selected" || action.lifecycle.state === "running";
- }
- return action.lifecycle.state === "selected" || action.lifecycle.state === "preparing";
- });
+ get queuedActionCount(): number {
+ return visibleSessionActionProjection(this._actionStore.queuedActions()).length;
+ }
+
+ get unfinishedActionCount(): number {
+ return this._actionStore.unfinishedActions().length;
}
- get pendingMessageCount(): number {
+ get isSessionActive(): boolean {
return (
- this.legacyPendingProjection("next_turn_boundary").length +
- this.legacyPendingProjection("when_run_idle").length
+ this.isStreaming ||
+ this.isCompacting ||
+ this.isRetrying ||
+ this.isBashRunning ||
+ this._refineInFlight !== undefined ||
+ this._branchSummaryOperation !== undefined ||
+ this.unfinishedActionCount > 0
);
}
+ getSessionActionSnapshot(): SessionActionSnapshot {
+ const steering = visibleSessionActionProjection(this._actionStore.queuedActions("next_turn_boundary")).map(
+ queuedAgentMessagePreview,
+ );
+ const followUps = visibleSessionActionProjection(this._actionStore.queuedActions("when_run_idle")).map(
+ queuedAgentMessagePreview,
+ );
+ const active = visibleSessionActionProjection(this._actionStore.activeActions())[0];
+ const activeState = active?.lifecycle.state;
+ const phase =
+ activeState === "selected"
+ ? "preparing"
+ : activeState === "preparing" || activeState === "committing" || activeState === "running"
+ ? activeState
+ : undefined;
+ return {
+ queuedCount: steering.length + followUps.length,
+ steering,
+ followUps,
+ ...(active && phase
+ ? { active: { kind: active.payload.kind, phase, label: compactRlmText(active.payload.text) } }
+ : {}),
+ };
+ }
+
getSteeringMessages(): readonly string[] {
- return this.legacyPendingProjection("next_turn_boundary").map((action) => action.payload.text);
+ return visibleSessionActionProjection(this._actionStore.queuedActions("next_turn_boundary")).map(
+ (action) => action.payload.text,
+ );
}
getSteeringMessagePreviews(): readonly string[] {
- return this.legacyPendingProjection("next_turn_boundary").map(queuedAgentMessagePreview);
+ return visibleSessionActionProjection(this._actionStore.queuedActions("next_turn_boundary")).map(
+ queuedAgentMessagePreview,
+ );
}
getFollowUpMessages(): readonly string[] {
- return this.legacyPendingProjection("when_run_idle").map((action) => action.payload.text);
+ return visibleSessionActionProjection(this._actionStore.queuedActions("when_run_idle")).map(
+ (action) => action.payload.text,
+ );
}
getFollowUpMessagePreviews(): readonly string[] {
- return this.legacyPendingProjection("when_run_idle").map(queuedAgentMessagePreview);
- }
-
- private _sessionActionRecoverySnapshot(): SessionActionRecoverySnapshot {
- return { actions: this._actionStore.snapshotActions() };
- }
-
- /** Private old-manifest adapter; deleted when PR 4 versions the recovery format. */
- private _legacyRecoverySnapshots(delivery: DeliveryPolicy): readonly QueuedAgentInputSnapshot[] {
- const recovery = new Set(
- this._sessionActionRecoverySnapshot().actions.filter((action) => action.delivery === delivery),
+ return visibleSessionActionProjection(this._actionStore.queuedActions("when_run_idle")).map(
+ queuedAgentMessagePreview,
);
- const legacy = new Set(this.legacyPendingProjection(delivery));
- return this._actionStore
- .unfinishedActions(delivery)
- .filter(
- (action) =>
- (recovery.has(action) || legacy.has(action)) &&
- !(action.payload.kind === "turn" && action.payload.acceptedAgentMessage && !action.payload.queueVisible),
- )
- .map(createQueuedAgentInputSnapshot);
}
- getSteeringQueueSnapshots(): readonly QueuedAgentInputSnapshot[] {
- return this._legacyRecoverySnapshots("next_turn_boundary");
- }
-
- getFollowUpQueueSnapshots(): readonly QueuedAgentInputSnapshot[] {
- return this._legacyRecoverySnapshots("when_run_idle");
+ getSessionActionRecoverySnapshot(): SessionActionRecoverySnapshot {
+ return {
+ formatVersion: SESSION_ACTION_RECOVERY_FORMAT_VERSION,
+ actions: this._actionStore.snapshotActions().map((action) => ({
+ id: action.id,
+ source: action.source,
+ delivery: action.delivery,
+ wake: action.wake,
+ ...(action.queueKey ? { queueKey: action.queueKey } : {}),
+ ...(action.agentMessageId ? { agentMessageId: action.agentMessageId } : {}),
+ ...(action.suppressAutonomousContinuation ? { suppressAutonomousContinuation: true } : {}),
+ payload:
+ action.payload.kind === "turn"
+ ? {
+ kind: "turn",
+ text: action.payload.text,
+ ...(action.payload.preview ? { preview: action.payload.preview } : {}),
+ records: action.payload.records.map((record) => ({
+ id: record.id,
+ role: record.role,
+ message: cloneQueuedAgentMessage(record.message),
+ ownerActionId: record.ownerActionId,
+ })),
+ ...(action.payload.images
+ ? { images: action.payload.images.map((image) => ({ ...image })) }
+ : {}),
+ ...(action.payload.content
+ ? { content: action.payload.content.map((block) => ({ ...block })) }
+ : {}),
+ ...(action.payload.customMessage
+ ? { customMessage: cloneCustomMessage(action.payload.customMessage) }
+ : {}),
+ executionPolicy: {
+ ...action.payload.executionPolicy,
+ preparation: { ...action.payload.executionPolicy.preparation },
+ },
+ queueVisible: action.payload.queueVisible,
+ acceptedAgentMessage: action.payload.acceptedAgentMessage,
+ acceptedBeforeCompletion: action.payload.acceptedBeforeCompletion,
+ }
+ : {
+ kind: "session_command",
+ text: action.payload.text,
+ command: { ...action.payload.command },
+ ...(action.payload.images
+ ? { images: action.payload.images.map((image) => ({ ...image })) }
+ : {}),
+ },
+ })),
+ };
}
private _notifySessionInputCheckpointChange(): void {
@@ -5842,6 +5976,7 @@ export class AgentSession {
released = true;
this._queuedWorkPauses.delete(token);
if (this._queuedWorkPauses.size === 0) this._wakeQueuedWorkAdmissionWaiters();
+ this._notifySessionInputCheckpointChange();
this._scheduleSessionInputPump();
},
};
@@ -5856,7 +5991,7 @@ export class AgentSession {
if (this._disposed || this._disposing) {
throw new Error("Cannot admit a session action because the session is disposing or disposed.");
}
- if (this.pendingMessageCount > 0 && this._sessionInputPumpSuspended) {
+ if (this.unfinishedActionCount > 0 && this._sessionInputPumpSuspended) {
throw new Error("Cannot admit a session action while queued session input is suspended.");
}
}
@@ -5937,8 +6072,9 @@ export class AgentSession {
/** Resume the scheduler after requestAbort/abortForUpdateRestart suspended it; owned pause leases are unaffected. */
resumeQueuedWork(): boolean {
this._sessionInputPumpSuspended = false;
+ this._notifySessionInputCheckpointChange();
this._scheduleSessionInputPump();
- return this.pendingMessageCount > 0;
+ return this._hasSelectableSessionInput();
}
async waitForSessionInputIdle(): Promise<void> {
@@ -5951,6 +6087,13 @@ export class AgentSession {
async waitForIdle(): Promise<void> {
while (true) {
+ if (this._actionStore.queuedActions().length > 0) {
+ if (this._sessionInputPumpSuspended || this._queuedWorkPauses.size > 0) {
+ await new Promise<void>((resolve) => this._sessionInputCheckpointWaiters.add(resolve));
+ continue;
+ }
+ this._scheduleSessionInputPump();
+ }
const pump = this._sessionInputPump;
await pump;
await this.agent.waitForIdle();
@@ -5959,7 +6102,7 @@ export class AgentSession {
!this._sessionInputPumpRequested &&
!this._pumpingSessionInput &&
!this.agent.state.isStreaming &&
- this._actionStore.activeActions().length === 0
+ this.unfinishedActionCount === 0
) {
return;
}
@@ -5990,32 +6133,6 @@ export class AgentSession {
return messages;
}
- getAcceptedPromptSnapshot(): AcceptedAgentInputSnapshot | undefined {
- const action = this._actionStore
- .unfinishedActions()
- .find(
- (candidate) =>
- candidate.payload.kind === "turn" &&
- candidate.payload.acceptedAgentMessage &&
- !candidate.payload.queueVisible &&
- !primaryDeliveryRecord(candidate).started,
- );
- if (!action || action.payload.kind !== "turn") return undefined;
- const nextTurn = action.payload.records
- .filter(
- (record): record is DeliveryRecord & { message: CustomMessage } =>
- (record.role === "next_turn" || record.role === "prefix") &&
- record.message.role === "custom" &&
- !record.durable,
- )
- .map((record) => cloneCustomMessage(record.message));
- return {
- ...createQueuedAgentInputSnapshotFromUserMessage(action.payload.text, primaryDeliveryRecord(action).message),
- agentMessageId: action.agentMessageId,
- nextTurn,
- };
- }
-
restorePendingNextTurnMessages(messages: readonly CustomMessage[]): void {
this._pendingNextTurnMessages.push(...messages.map((message) => cloneCustomMessage(message)));
}
@@ -6602,7 +6719,7 @@ export class AgentSession {
// Queued agent or session-owned inputs resume the loop; defer refine
// behind them instead of interleaving it before their turns.
this._scheduleAutoRefineAfterCompaction(
- hadPostCompactionContinue || this.agent.hasQueuedMessages() || this.pendingMessageCount > 0,
+ hadPostCompactionContinue || this.agent.hasQueuedMessages() || this.unfinishedActionCount > 0,
);
}
}
@@ -6852,19 +6969,14 @@ export class AgentSession {
return;
}
// An empty queue is not idle while the scheduler still owns active work.
- if (
- this.pendingMessageCount > 0 ||
- this._actionStore.activeActions().length > 0 ||
- this._pumpingSessionInput ||
- this._sessionInputPumpRequested
- ) {
+ if (this.unfinishedActionCount > 0 || this._pumpingSessionInput || this._sessionInputPumpRequested) {
this._scheduleSessionInputPump();
await this._sessionInputPump;
if (this._postCompactionContinuationScheduled) {
this._postCompactionContinuationScheduled = false;
const shouldReschedule =
continuationMessages.length === 0
- ? this.pendingMessageCount > 0
+ ? this.unfinishedActionCount > 0
: this._sessionOwnsScheduledContinuations(continuationMessages);
if (shouldReschedule) {
this._schedulePostCompactionContinue();
@@ -7924,7 +8036,7 @@ export class AgentSession {
isIdle: () => !this.isStreaming,
getSignal: () => this.agent.signal,
abort: () => this.abort(),
- hasPendingMessages: () => this.pendingMessageCount > 0,
+ hasPendingMessages: () => this.queuedActionCount > 0,
shutdown: () => {
this._extensionShutdownHandler?.();
},
diff --git a/packages/coding-agent/src/core/cron-jobs.ts b/packages/coding-agent/src/core/cron-jobs.ts
index 783db5dac4..8e8e2254f0 100644
--- a/packages/coding-agent/src/core/cron-jobs.ts
+++ b/packages/coding-agent/src/core/cron-jobs.ts
@@ -87,8 +87,7 @@ export interface HeartbeatCronSessionActivity {
isCompacting?: boolean;
isRetrying?: boolean;
isBashRunning: boolean;
- hasAcceptedPromptInFlight?: boolean;
- pendingMessageCount: number;
+ unfinishedActionCount: number;
}
interface CronJobsFile {
@@ -1358,8 +1357,7 @@ export function shouldDeferHeartbeatCronJob(job: AgentCronJob, activity: Heartbe
activity.isCompacting === true ||
activity.isRetrying === true ||
activity.isBashRunning ||
- activity.hasAcceptedPromptInFlight === true ||
- activity.pendingMessageCount > 0;
+ activity.unfinishedActionCount > 0;
if (busyBesidesStreaming) {
return true;
}
diff --git a/packages/coding-agent/src/core/messages.ts b/packages/coding-agent/src/core/messages.ts
index 991d5a5122..0a4535e73d 100644
--- a/packages/coding-agent/src/core/messages.ts
+++ b/packages/coding-agent/src/core/messages.ts
@@ -286,7 +286,7 @@ function hasValidCustomMessageEnvelope(message: Record<string, unknown>, customT
);
}
-function isSessionSlashCommand(value: unknown): value is SessionSlashCommand {
+export function isSessionSlashCommand(value: unknown): value is SessionSlashCommand {
if (
!isRecord(value) ||
!isSessionSlashCommandName(value.name) ||
diff --git a/packages/coding-agent/src/core/session-action-store.ts b/packages/coding-agent/src/core/session-action-store.ts
index 4cd44344e9..db969f4134 100644
--- a/packages/coding-agent/src/core/session-action-store.ts
+++ b/packages/coding-agent/src/core/session-action-store.ts
@@ -7,6 +7,17 @@ import type { SessionSlashCommand } from "./slash-commands.js";
export type DeliveryPolicy = "next_turn_boundary" | "when_run_idle";
export type WakePolicy = "immediate" | "on_lower_boundary" | "external_resume";
+export interface SessionActionSnapshot {
+ queuedCount: number;
+ steering: readonly string[];
+ followUps: readonly string[];
+ active?: {
+ kind: "turn" | "session_command";
+ phase: "preparing" | "committing" | "running";
+ label?: string;
+ };
+}
+
export interface DeliveryRecord {
id: string;
role: "primary" | "prefix" | "next_turn";
diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts
index 7a25e8e862..093da58deb 100644
--- a/packages/coding-agent/src/index.ts
+++ b/packages/coding-agent/src/index.ts
@@ -179,6 +179,7 @@ export {
type RlmSubagentRuntime,
type SubagentRuntimeHost,
} from "./core/sdk.js";
+export type { SessionActionSnapshot } from "./core/session-action-store.js";
export { SessionImportFileNotFoundError } from "./core/session-import-errors.js";
export {
type BranchSummaryEntry,
diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
index 46ffc1d5bb..8b566b1726 100644
--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts
@@ -600,7 +600,7 @@ export class InProcessAgentConnection implements AgentConnection {
await session.bindExtensions({
uiContext: this.headlessExtensionOptions?.uiContext,
commandContextActions: {
- waitForIdle: () => session.agent.waitForIdle(),
+ waitForIdle: () => session.waitForIdle(),
newSession: (options) => this.runtimeHost.newSession(options),
fork: async (entryId, options) => {
const result = await this.runtimeHost.fork(entryId, options);
diff --git a/packages/coding-agent/src/modes/agent-connection/snapshot.ts b/packages/coding-agent/src/modes/agent-connection/snapshot.ts
index 9f54b77a62..2c397645e0 100644
--- a/packages/coding-agent/src/modes/agent-connection/snapshot.ts
+++ b/packages/coding-agent/src/modes/agent-connection/snapshot.ts
@@ -45,7 +45,7 @@ export function createAgentConnectionState(
leafId: sessionManager.getLeafId(),
autoCompactionEnabled: session.autoCompactionEnabled,
messageCount: session.messages.length,
- pendingMessageCount: session.pendingMessageCount,
+ sessionActions: session.getSessionActionSnapshot(),
compactionCount: sessionManager.getEntries().filter((entry) => entry.type === "compaction").length,
goal: session.goalState,
scopedModels: session.scopedModels.map((scoped) => ({
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index cf885c21b7..118e04a94b 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -21,6 +21,7 @@ import type { InputSource } from "../../core/extensions/types.js";
import type { GoalState } from "../../core/goals.js";
import type { KernelSentAgentMessage } from "../../core/kernel/index.js";
import type { RefinementResult } from "../../core/refinement/index.js";
+import type { SessionActionSnapshot } from "../../core/session-action-store.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
import type { SessionStats } from "../../core/session-stats.js";
@@ -335,7 +336,7 @@ export interface AgentConnectionState {
leafId: string | null;
autoCompactionEnabled: boolean;
messageCount: number;
- pendingMessageCount: number;
+ sessionActions: SessionActionSnapshot;
compactionCount: number;
goal: GoalState;
heartbeat?: AgentCronJob | null;
@@ -561,11 +562,7 @@ export interface AgentConnectionRlmChildAgentSnapshot {
export type AgentConnectionSessionEvent =
| AgentEvent
| { type: "ipython_sent_agent_message"; toolCallId: string; message: KernelSentAgentMessage }
- | {
- type: "queue_update";
- steering: readonly string[];
- followUp: readonly string[];
- }
+ | { type: "session_action_update"; actions: SessionActionSnapshot }
| {
type: "compaction_start";
reason: "manual" | "threshold" | "overflow" | "requested";
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
index bd99ba3e14..319bf1b9ee 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
@@ -58,14 +58,7 @@ export function classifyAgentsViewSession(summary: SessionSummary): AgentsViewSe
}
function isAgentsViewSessionBusy(summary: SessionSummary): boolean {
- return (
- summary.isStreaming ||
- summary.isCompacting ||
- summary.isBashRunning === true ||
- summary.isRunningTools === true ||
- summary.hasRunningRlmChildren === true ||
- summary.pendingMessageCount > 0
- );
+ return summary.isSessionActive || summary.hasRunningRlmChildren === true;
}
export function classifyUnifiedSession(record: Pick<UnifiedSessionRecord, "daemon" | "heartbeat">): AgentsViewSection {
@@ -223,6 +216,7 @@ export function summaryForUnifiedRecord(record: UnifiedSessionRecord): SessionSu
id: saved.id,
lifecycle: "archived",
activity: "idle",
+ isSessionActive: false,
sessionId: saved.id,
sessionFile: canonicalSessionPath(saved.path),
sessionName: saved.name,
@@ -231,7 +225,7 @@ export function summaryForUnifiedRecord(record: UnifiedSessionRecord): SessionSu
isCompacting: false,
attachedClients: 0,
messageCount: saved.messageCount,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
created: saved.created.toISOString(),
modified: saved.modified.toISOString(),
firstMessage: saved.firstMessage,
@@ -753,8 +747,11 @@ function getSessionStatusLabel(summary: SessionSummary, hasActiveHeartbeat = sum
if (summary.hasRunningRlmChildren === true) {
return "subagents running";
}
- if (summary.pendingMessageCount > 0) {
- return `${summary.pendingMessageCount} queued`;
+ if (summary.sessionActions.active) {
+ return summary.sessionActions.active.label ?? summary.sessionActions.active.kind.replace("_", " ");
+ }
+ if (summary.sessionActions.queuedCount > 0) {
+ return `${summary.sessionActions.queuedCount} queued`;
}
if (summary.lifecycle === "archived") {
return "archived";
diff --git a/packages/coding-agent/src/modes/daemon/daemon-extension-binding.ts b/packages/coding-agent/src/modes/daemon/daemon-extension-binding.ts
index 3c40d7fe59..cecd046186 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-extension-binding.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-extension-binding.ts
@@ -98,7 +98,7 @@ export async function bindActiveSessionState(
function createCommandContextActions(state: ActiveSessionState): ExtensionCommandContextActions {
return {
- waitForIdle: () => state.runtime.session.agent.waitForIdle(),
+ waitForIdle: () => state.runtime.session.waitForIdle(),
newSession: async (options) => state.runtime.newSession(options),
fork: async (entryId, options) => {
const result = await state.runtime.fork(entryId, options);
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index e76e012f75..80d1aadfd9 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -133,6 +133,7 @@ import {
DAEMON_SCHEMA_ID,
DAEMON_SCHEMA_REVISION,
DAEMON_SUPPORTED_CLIENT_CAPABILITIES,
+ DAEMON_UPDATE_RESTART_FORMAT_VERSION,
type DaemonAttachResult,
type DaemonClientCapability,
type DaemonClosingReason,
@@ -221,6 +222,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"steer",
"follow_up",
"restore_next_turn",
+ "restore_actions",
"append_custom_message",
"resume_queue",
"send_message",
@@ -321,7 +323,7 @@ const RECOVERY_CHECKPOINT_EVENTS: ReadonlySet<string> = new Set([
"auto_retry_end",
"bash_start",
"bash_end",
- "queue_update",
+ "session_action_update",
"rlm_child_update",
]);
@@ -1291,8 +1293,7 @@ export class AgentDaemon {
session.isCompacting ||
session.isRetrying ||
session.isBashRunning ||
- session.hasAcceptedPromptInFlight ||
- session.pendingMessageCount > 0;
+ session.unfinishedActionCount > 0;
if (!isHeartbeatCronJob(runnableJob) && shouldQueueCronPrompt) {
if (!this.isCronJobRunnableForState(runnableJob, state, requirePersistedJob)) {
return "skipped";
@@ -2342,11 +2343,7 @@ export class AgentDaemon {
: "model"
: session.isCompacting
? "compacting"
- : session.isRetrying ||
- session.isBashRunning ||
- session.hasAcceptedPromptInFlight ||
- session.pendingMessageCount > 0 ||
- session.hasRunningRlmChildren()
+ : session.isSessionActive || session.hasRunningRlmChildren()
? "busy"
: state.clients.size > 0
? "user"
@@ -2363,7 +2360,8 @@ export class AgentDaemon {
isCompacting: summary.isCompacting,
attachedClients: summary.attachedClients,
messageCount: summary.messageCount,
- pendingMessageCount: summary.pendingMessageCount,
+ queuedCount: summary.sessionActions.queuedCount,
+ isSessionActive: summary.isSessionActive,
...(summary.parentActiveSessionId ? { parentActiveSessionId: summary.parentActiveSessionId } : {}),
...(summary.parentSessionId ? { parentSessionId: summary.parentSessionId } : {}),
...(summary.rlmChildId ? { rlmChildId: summary.rlmChildId } : {}),
@@ -3236,6 +3234,13 @@ export class AgentDaemon {
return success(command.id, "restore_next_turn");
}
+ case "restore_actions": {
+ const state = this.getSessionState(command.activeSessionId);
+ const restored = await state.runtime.session.restoreSessionActions(command.snapshot);
+ if (restored > 0) this.recordWorkerRecoveryState(state, "actions_restored", true);
+ return success(command.id, "restore_actions", { restored });
+ }
+
case "append_custom_message": {
const state = this.getSessionState(command.activeSessionId);
await state.runtime.session.sendCustomMessage(command.message);
@@ -4148,8 +4153,7 @@ export class AgentDaemon {
...this.createAgentSessionMessageEndpoint(state),
cwd: state.runtime.cwd,
isStreaming: state.runtime.session.isStreaming,
- pendingMessageCount:
- state.runtime.session.pendingMessageCount + (state.runtime.session.hasAcceptedPromptInFlight ? 1 : 0),
+ unfinishedActionCount: state.runtime.session.unfinishedActionCount,
...(metadata.parentActiveSessionId ? { parentActiveSessionId: metadata.parentActiveSessionId } : {}),
...(metadata.rlmChildId ? { rlmChildId: metadata.rlmChildId } : {}),
};
@@ -4220,9 +4224,7 @@ export class AgentDaemon {
const activeSessionId = targetState.activeSessionId;
const reserved = this.agentMessagePendingReservations.get(activeSessionId) ?? 0;
assertAgentMessageQueueCapacity(
- targetState.runtime.session.pendingMessageCount +
- (targetState.runtime.session.hasAcceptedPromptInFlight ? 1 : 0) +
- reserved,
+ targetState.runtime.session.unfinishedActionCount + reserved,
DEFAULT_AGENT_MESSAGE_MAX_PENDING_PER_SESSION,
);
this.agentMessagePendingReservations.set(activeSessionId, reserved + 1);
@@ -4396,7 +4398,7 @@ export class AgentDaemon {
const reserved = this.agentMessagePendingReservations.get(targetState.activeSessionId) ?? 0;
const otherReservations = Math.max(0, reserved - 1);
assertAgentMessageQueueCapacity(
- session.pendingMessageCount + (session.hasAcceptedPromptInFlight ? 1 : 0) + otherReservations,
+ session.unfinishedActionCount + otherReservations,
DEFAULT_AGENT_MESSAGE_MAX_PENDING_PER_SESSION,
);
const shouldQueue =
@@ -4406,8 +4408,7 @@ export class AgentDaemon {
session.isCompacting ||
session.isRetrying ||
session.isBashRunning ||
- session.hasAcceptedPromptInFlight ||
- session.pendingMessageCount > 0;
+ session.unfinishedActionCount > 0;
const streamingBehavior =
resolveAgentSessionMessageStreamingBehavior(shouldQueue, payload.deliveryMode) ??
(payload.deliveryMode === "follow_up" ? "followUp" : "steer");
@@ -4419,7 +4420,7 @@ export class AgentDaemon {
if (!didQueue) {
throw new Error("Agent message was not queued");
}
- // The queued message now counts in pendingMessageCount.
+ // The queued message now counts in unfinishedActionCount.
releaseReservation();
// Do not await delivery: a queued message delivers only when the target's
// turn progresses, and the sender is blocked inside its own turn — awaiting
@@ -4507,47 +4508,10 @@ export class AgentDaemon {
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.queueKey ? { queueKey: message.queueKey } : {}),
- ...(message.agentMessageId ? { agentMessageId: message.agentMessageId } : {}),
- ...(message.customMessage ? { customMessage: message.customMessage } : {}),
- ...(message.prefixMessages ? { prefixMessages: message.prefixMessages } : {}),
- })),
- 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 } : {}),
- ...(message.prefixMessages ? { prefixMessages: message.prefixMessages } : {}),
- })),
+ actions: session.getSessionActionRecoverySnapshot(),
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 } : {}),
- ...(acceptedPrompt.customMessage ? { customMessage: acceptedPrompt.customMessage } : {}),
- agentMessageId: acceptedPrompt.agentMessageId,
- nextTurn: acceptedPrompt.nextTurn,
- },
- }
- : {}),
- };
- const hasQueuedMessages =
- restartQueue.steering.length > 0 ||
- restartQueue.followUp.length > 0 ||
- restartQueue.nextTurn.length > 0 ||
- restartQueue.acceptedPrompt !== undefined;
+ const hasQueuedMessages = queue.actions.actions.length > 0 || queue.nextTurn.length > 0;
const wasStreaming = session.isStreaming;
const wasCompacting = session.isCompacting;
const wasBashRunning = session.isBashRunning;
@@ -4561,9 +4525,7 @@ export class AgentDaemon {
hadRunningRlmChildren ||
wasRetrying ||
hadAcceptedPromptInFlight ||
- restartQueue.steering.length > 0 ||
- restartQueue.followUp.length > 0 ||
- restartQueue.acceptedPrompt !== undefined;
+ queue.actions.actions.length > 0;
const sessionFile =
session.sessionFile ??
(hasQueuedMessages || shouldResume
@@ -4585,7 +4547,7 @@ export class AgentDaemon {
},
runtimeMetadata: state.runtime.metadata,
...(state.clientEnv ? { clientEnv: { ...state.clientEnv } } : {}),
- queue: restartQueue,
+ queue,
shouldResume,
wasStreaming,
wasCompacting,
@@ -4721,6 +4683,7 @@ export class AgentDaemon {
)
.map((state) => state.activeSessionId);
return {
+ formatVersion: DAEMON_UPDATE_RESTART_FORMAT_VERSION,
createdAt: new Date().toISOString(),
sessions: restartSessions,
...(discardedActiveSessionIds.length > 0 ? { discardedActiveSessionIds } : {}),
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 304a1f29f2..a22e6643d5 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -5,6 +5,7 @@ import type {
AgentSessionMessageReceipt,
AgentSessionMessageSafetyStatus,
} from "../../core/agent-messages.js";
+import type { SessionActionRecoverySnapshot } from "../../core/agent-session.js";
import type { AgentSessionRuntimeConfig } from "../../core/agent-session-config.js";
import type { AgentSessionRuntimeMetadata } from "../../core/agent-session-runtime.js";
import type { AgentAutonomousStatus } from "../../core/autonomous.js";
@@ -48,12 +49,11 @@ import type { SessionSummary } from "./daemon-session-list.js";
*/
export const DAEMON_PROTOCOL_NAME = "prime-agent.daemon";
-export const DAEMON_PROTOCOL_VERSION = 6;
-export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 2;
-// Revision 6 combines prompt-admission cancellation with side-question transcripts and transient bash.
-// Revision 7 makes get_session_tree return flatNodes instead of a recursively nested tree.
-export const DAEMON_SCHEMA_REVISION = 7;
-export const DAEMON_SCHEMA_ID = "protocol-6-schema-7-48a562b9bffe";
+export const DAEMON_PROTOCOL_VERSION = 7;
+export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;
+// Revision 8 publishes literal session-action queues and activity separately.
+export const DAEMON_SCHEMA_REVISION = 8;
+export const DAEMON_SCHEMA_ID = "protocol-7-schema-8-b56e29842cfa";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -290,25 +290,11 @@ export interface DaemonAttachResult {
};
}
-export interface DaemonUpdateRestartQueuedMessage {
- message: string;
- content?: (TextContent | ImageContent)[];
- images?: ImageContent[];
- queueKey?: string;
- agentMessageId?: string;
- customMessage?: CustomMessage;
- prefixMessages?: CustomMessage[];
-}
-
-export interface DaemonUpdateRestartAcceptedPrompt extends DaemonUpdateRestartQueuedMessage {
- nextTurn: CustomMessage[];
-}
+export const DAEMON_UPDATE_RESTART_FORMAT_VERSION = 1;
export interface DaemonUpdateRestartQueue {
- steering: DaemonUpdateRestartQueuedMessage[];
- followUp: DaemonUpdateRestartQueuedMessage[];
+ actions: SessionActionRecoverySnapshot;
nextTurn: CustomMessage[];
- acceptedPrompt?: DaemonUpdateRestartAcceptedPrompt;
}
export interface DaemonUpdateRestartSession {
@@ -330,6 +316,7 @@ export interface DaemonUpdateRestartSession {
}
export interface DaemonUpdateRestartManifest {
+ formatVersion: typeof DAEMON_UPDATE_RESTART_FORMAT_VERSION;
createdAt: string;
sessions: DaemonUpdateRestartSession[];
discardedActiveSessionIds?: string[];
@@ -455,6 +442,7 @@ export type DaemonCommand =
prefixMessages?: CustomMessage[];
}
| { id?: string; type: "restore_next_turn"; activeSessionId: string; messages: CustomMessage[] }
+ | { id?: string; type: "restore_actions"; activeSessionId: string; snapshot: SessionActionRecoverySnapshot }
| {
id?: string;
type: "append_custom_message";
@@ -611,22 +599,22 @@ export interface DaemonCommandCompatibility {
capability?: DaemonServerCapability;
}
-const LEGACY_DAEMON_COMMAND = { minProtocol: 1 } as const;
-const CURRENT_DAEMON_COMMAND = { minProtocol: 4 } as const;
+const LEGACY_DAEMON_COMMAND = { minProtocol: 7 } as const;
+const CURRENT_DAEMON_COMMAND = { minProtocol: 7 } as const;
const SESSION_INPUT_ADMISSION_COMMAND = {
- minProtocol: 4,
+ minProtocol: 7,
capability: "session_input_admission",
} as const;
const PROMPT_ADMISSION_CANCELLATION_COMMAND = {
- minProtocol: 5,
- minSchemaRevision: 6,
+ minProtocol: 7,
+ minSchemaRevision: 8,
capability: "prompt_admission_cancellation",
} as const;
const CLIENT_OWNED_DAEMON_COMMAND = {
- minProtocol: 4,
+ minProtocol: 7,
capability: "client_owned_sessions",
} as const;
-const FLAT_SESSION_TREE_COMMAND = { minProtocol: 6 } as const;
+const FLAT_SESSION_TREE_COMMAND = { minProtocol: 7 } as const;
export const DAEMON_COMMAND_COMPATIBILITY = {
ack_result: LEGACY_DAEMON_COMMAND,
@@ -646,6 +634,7 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
steer: SESSION_INPUT_ADMISSION_COMMAND,
follow_up: SESSION_INPUT_ADMISSION_COMMAND,
restore_next_turn: LEGACY_DAEMON_COMMAND,
+ restore_actions: LEGACY_DAEMON_COMMAND,
append_custom_message: LEGACY_DAEMON_COMMAND,
resume_queue: SESSION_INPUT_ADMISSION_COMMAND,
send_message: LEGACY_DAEMON_COMMAND,
@@ -669,14 +658,14 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
get_context_tree: LEGACY_DAEMON_COMMAND,
get_commands: LEGACY_DAEMON_COMMAND,
get_resource_snapshot: LEGACY_DAEMON_COMMAND,
- get_model_catalog: { minProtocol: 4, capability: "model_catalog" },
+ get_model_catalog: { minProtocol: 7, capability: "model_catalog" },
get_available_models: LEGACY_DAEMON_COMMAND,
get_queue: LEGACY_DAEMON_COMMAND,
clear_queue: LEGACY_DAEMON_COMMAND,
abort_and_clear_queue: LEGACY_DAEMON_COMMAND,
cron_list: LEGACY_DAEMON_COMMAND,
- heartbeats_list: { minProtocol: 3, capability: "heartbeat_catalog" },
- heartbeat_manage: { minProtocol: 3, capability: "heartbeat_management" },
+ heartbeats_list: { minProtocol: 7, capability: "heartbeat_catalog" },
+ heartbeat_manage: { minProtocol: 7, capability: "heartbeat_management" },
cron_add: LEGACY_DAEMON_COMMAND,
cron_cancel: LEGACY_DAEMON_COMMAND,
heartbeat_get: LEGACY_DAEMON_COMMAND,
@@ -919,7 +908,7 @@ export const DAEMON_OUTBOUND_COMPATIBILITY = {
session_list_item: LEGACY_DAEMON_COMMAND,
daemon_hello: LEGACY_DAEMON_COMMAND,
daemon_closing: LEGACY_DAEMON_COMMAND,
- heartbeats_changed: { minProtocol: 3, capability: "heartbeat_catalog" },
+ heartbeats_changed: { minProtocol: 7, capability: "heartbeat_catalog" },
session_event: LEGACY_DAEMON_COMMAND,
side_question_event: LEGACY_DAEMON_COMMAND,
session_status: LEGACY_DAEMON_COMMAND,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
index 2dfe6de0e5..7e6a5397ac 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -6,6 +6,7 @@ import { compactRlmText, rlmChildLabel } from "../../core/agent-session.js";
import type { AgentSessionRuntimeMetadata } from "../../core/agent-session-runtime.js";
import type { AgentSessionRuntimeDiagnostic } from "../../core/agent-session-services.js";
import { type AgentCronJob, isHeartbeatCronJob } from "../../core/cron-jobs.js";
+import type { SessionActionSnapshot } from "../../core/session-action-store.js";
import type { AgentTaskState, SessionInfo } from "../../core/session-manager.js";
import type { AgentConnectionRlmChildAgentSnapshot } from "../agent-connection/types.js";
import type { ActiveSessionState } from "./active-session-state.js";
@@ -28,6 +29,7 @@ export interface SessionSummary {
id: string;
lifecycle: SessionLifecycle;
activity: SessionActivity;
+ isSessionActive: boolean;
hasActiveHeartbeat?: boolean;
runtimeKind?: "top-level" | "subagent";
activeSessionId?: string;
@@ -45,7 +47,8 @@ export interface SessionSummary {
isRunningTools?: boolean;
attachedClients: number;
messageCount: number;
- pendingMessageCount: number;
+ unfinishedActionCount?: number;
+ sessionActions: SessionActionSnapshot;
streamingMessage?: AgentMessage;
created?: string;
modified?: string;
@@ -88,13 +91,7 @@ export function resolveAttachModelFallbackMessage(
}
export function isSessionSummaryBusy(summary: SessionSummary): boolean {
- return (
- summary.isStreaming ||
- summary.isCompacting ||
- summary.isBashRunning === true ||
- summary.hasRunningRlmChildren === true ||
- summary.pendingMessageCount > 0
- );
+ return summary.isSessionActive || summary.hasRunningRlmChildren === true;
}
export function buildSessionList(
@@ -145,17 +142,12 @@ export function buildSessionList(
return entries;
}
-function effectivePendingMessageCount(session: ActiveSessionState["runtime"]["session"]): number {
- return session.pendingMessageCount + (session.hasAcceptedPromptInFlight ? 1 : 0);
-}
-
export function summaryForActiveSession(
activeSession: ActiveSessionState,
savedSession?: SessionInfo,
hasActiveHeartbeat = false,
): SessionSummary {
const session = activeSession.runtime.session;
- const pendingMessageCount = effectivePendingMessageCount(session);
const metadata = activeSession.runtime.metadata ?? { kind: "top-level" as const };
let modified = savedSession?.modified.toISOString();
if (!modified && session.sessionFile) {
@@ -170,6 +162,7 @@ export function summaryForActiveSession(
id: activeSession.activeSessionId,
lifecycle: activeLifecycleForSession(activeSession),
activity: activeActivityForSession(activeSession),
+ isSessionActive: session.isSessionActive,
hasActiveHeartbeat: hasActiveHeartbeat || undefined,
runtimeKind: metadata.kind,
activeSessionId: activeSession.activeSessionId,
@@ -186,7 +179,8 @@ export function summaryForActiveSession(
isRunningTools: session.isStreaming && session.state.pendingToolCalls.size > 0,
attachedClients: activeSession.clients.size,
messageCount: session.messages.length,
- pendingMessageCount,
+ unfinishedActionCount: session.unfinishedActionCount,
+ sessionActions: session.getSessionActionSnapshot(),
streamingMessage: session.state.streamingMessage,
created: savedSession?.created.toISOString() ?? session.sessionManager.getHeader?.()?.timestamp,
modified,
@@ -227,6 +221,7 @@ export function summaryForInactiveSession(session: SessionInfo): SessionSummary
id: session.id,
lifecycle: inactiveLifecycleForSession(session),
activity: "idle",
+ isSessionActive: false,
sessionId: session.id,
sessionFile: session.path,
sessionName: session.name,
@@ -235,7 +230,8 @@ export function summaryForInactiveSession(session: SessionInfo): SessionSummary
isCompacting: false,
attachedClients: 0,
messageCount: session.messageCount,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
created: session.created.toISOString(),
modified: session.modified.toISOString(),
firstMessage: session.firstMessage,
@@ -314,7 +310,7 @@ function rlmChildSnapshotForActiveSession(
const runStatus = metadata.rlmChildId
? parent?.runtime.session.getRlmChildRunStatus(metadata.rlmChildId)
: undefined;
- const status = runStatus ?? (session.isStreaming || effectivePendingMessageCount(session) > 0 ? "running" : "done");
+ const status = runStatus ?? (session.isSessionActive ? "running" : "done");
return {
id: metadata.rlmChildId ?? activeSession.activeSessionId,
parentId: parentNodeId,
@@ -368,13 +364,7 @@ function readMessageText(content: unknown): string {
export function isActiveSessionBusy(activeSession: ActiveSessionState): boolean {
const session = activeSession.runtime.session;
// Background subagents keep the parent "working" even after its own turn ends.
- return (
- session.isStreaming ||
- session.isCompacting ||
- session.isBashRunning ||
- effectivePendingMessageCount(session) > 0 ||
- session.hasRunningRlmChildren()
- );
+ return session.isSessionActive || session.hasRunningRlmChildren();
}
export function activeActivityForSession(activeSession: ActiveSessionState): SessionActivity {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-summarizer.ts b/packages/coding-agent/src/modes/daemon/daemon-session-summarizer.ts
index 0cbdf11e22..1af8a1cbd6 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-summarizer.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-summarizer.ts
@@ -199,7 +199,7 @@ export function agentStatusChanged(previous: AgentStatus | undefined, next: Agen
function isSessionWorking(state: ActiveSessionState): boolean {
const session = state.runtime.session;
- return session.isStreaming || session.isCompacting || session.pendingMessageCount > 0;
+ return session.isSessionActive;
}
/**
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index a27d859fe9..9b43aac5e8 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -43,11 +43,13 @@ import {
collectDaemonClientEnv,
createDaemonEventMeta,
DAEMON_COMMAND_COMPATIBILITY,
+ DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION,
DAEMON_DEFAULT_CLIENT_CAPABILITIES,
DAEMON_DEFAULT_SERVER_CAPABILITIES,
DAEMON_PROTOCOL_INFO,
DAEMON_SCHEMA_ID,
DAEMON_SCHEMA_REVISION,
+ DAEMON_UPDATE_RESTART_FORMAT_VERSION,
type DaemonAttachResult,
type DaemonClientCapability,
type DaemonClosingReason,
@@ -136,6 +138,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"steer",
"follow_up",
"restore_next_turn",
+ "restore_actions",
"append_custom_message",
"resume_queue",
"send_message",
@@ -1023,7 +1026,10 @@ export class DaemonSupervisor {
} {
const parsed = JSON.parse(line) as unknown;
const envelope = isDaemonCommandEnvelope(parsed) ? parsed : undefined;
- const command = (envelope ? { ...envelope.command, id: envelope.id } : parsed) as DaemonCommand;
+ if (!envelope) {
+ throw new Error(`Daemon commands require protocol ${DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION} or newer`);
+ }
+ const command = { ...envelope.command, id: envelope.id } as DaemonCommand;
let admission: SupervisorPromptAdmission | undefined;
if ((command.type === "prompt" || command.type === "prompt_and_wait") && command.admissionId !== undefined) {
if (typeof command.activeSessionId !== "string" || typeof command.admissionId !== "string") {
@@ -1047,8 +1053,8 @@ export class DaemonSupervisor {
}
return {
command,
- envelopeClientId: envelope ? (envelope.clientId ?? client.id) : undefined,
- protocolVersion: envelope?.protocol.version ?? 1,
+ envelopeClientId: envelope.clientId ?? client.id,
+ protocolVersion: envelope.protocol.version,
admission,
};
}
@@ -2685,7 +2691,11 @@ export class DaemonSupervisor {
runtimeKind: summary.runtimeKind ?? "top-level",
cwd: summary.cwd,
isStreaming: summary.isStreaming,
- pendingMessageCount: summary.pendingMessageCount,
+ unfinishedActionCount:
+ summary.unfinishedActionCount ??
+ (summary.sessionActions.active
+ ? 1 + summary.sessionActions.queuedCount
+ : summary.sessionActions.queuedCount),
...(summary.parentActiveSessionId ? { parentActiveSessionId: summary.parentActiveSessionId } : {}),
...(summary.rlmChildId ? { rlmChildId: summary.rlmChildId } : {}),
};
@@ -3888,6 +3898,9 @@ export class DaemonSupervisor {
throw new Error(`Worker ${worker.descriptor.workerId} disconnected during update preparation`);
}
const manifest = response.data as DaemonUpdateRestartManifest;
+ if (manifest.formatVersion !== DAEMON_UPDATE_RESTART_FORMAT_VERSION) {
+ throw new Error(`Worker returned unsupported update manifest version ${manifest.formatVersion}`);
+ }
if (
!manifest.sessions.some(
(session) => session.activeSessionId === worker.descriptor.rootActiveSessionId,
@@ -3934,7 +3947,8 @@ export class DaemonSupervisor {
result.status === "fulfilled" ? [result.value.manifest] : [],
);
const discardedActiveSessionIds = responses.flatMap((manifest) => manifest.discardedActiveSessionIds ?? []);
- const manifest = {
+ const manifest: DaemonUpdateRestartManifest = {
+ formatVersion: DAEMON_UPDATE_RESTART_FORMAT_VERSION,
createdAt: new Date().toISOString(),
sessions: responses.flatMap((manifest) => manifest.sessions),
...(discardedActiveSessionIds.length > 0 ? { discardedActiveSessionIds } : {}),
@@ -3989,6 +4003,9 @@ export class DaemonSupervisor {
}
private validateAndPersistUpdateManifest(manifest: DaemonUpdateRestartManifest): void {
+ if (manifest.formatVersion !== DAEMON_UPDATE_RESTART_FORMAT_VERSION) {
+ throw new Error(`Unsupported update manifest version ${manifest.formatVersion}`);
+ }
const activeSessionIds = new Set<string>();
const sessionFiles = new Set<string>();
for (const discardedActiveSessionId of manifest.discardedActiveSessionIds ?? []) {
diff --git a/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts b/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts
index bc4dcb15e7..f61aa4ec03 100644
--- a/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts
+++ b/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts
@@ -8,13 +8,10 @@ export async function listDaemonHeartbeats(
activeSessionId?: string,
): Promise<AgentConnectionHeartbeat[]> {
if (!client.hello) await client.waitForHello();
- const hasCapability = client.supportsServerCapability("heartbeat_catalog");
- if (!hasCapability && client.hello?.protocol.version !== 3) {
- return [];
- }
+ if (!client.supportsServerCapability("heartbeat_catalog")) return [];
try {
const command = { type: "heartbeats_list", ...(activeSessionId ? { activeSessionId } : {}) } as const;
- const response = hasCapability ? await client.request(command) : await client.requestLegacy(command);
+ const response = await client.request(command);
if (!response.success) {
throw deserializeDaemonError(response);
}
diff --git a/packages/coding-agent/src/modes/headless-completion.ts b/packages/coding-agent/src/modes/headless-completion.ts
index f082a45d58..b3d51d03f5 100644
--- a/packages/coding-agent/src/modes/headless-completion.ts
+++ b/packages/coding-agent/src/modes/headless-completion.ts
@@ -75,7 +75,7 @@ export async function waitForHeadlessCompletion(session: AgentSession): Promise<
let lastPromptedProgressKey: string | undefined;
let repeatedProgressPrompts = 0;
while (true) {
- await session.agent.waitForIdle();
+ await session.waitForIdle();
const status = session.getAutonomousStatus();
if (!shouldContinueAutonomousGates(status) || !status.lastGateFailure) {
return status;
@@ -102,7 +102,7 @@ export async function waitForHeadlessCompletion(session: AgentSession): Promise<
suppressAutonomousContinuation: true,
},
);
- await session.agent.waitForIdle();
+ await session.waitForIdle();
await session.refreshAutonomousGates();
const { primary } = selectHeadlessTerminalResult(session.state.messages);
if (primary?.role === "assistant") {
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 4772c9c799..1cd07b516e 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -2681,10 +2681,8 @@ export class InteractiveMode {
case "agent_end":
this.patchConnectionState({ isStreaming: false, activeToolNames: [] });
break;
- case "queue_update":
- this.patchConnectionState({
- pendingMessageCount: event.steering.length + event.followUp.length,
- });
+ case "session_action_update":
+ this.patchConnectionState({ sessionActions: event.actions });
break;
case "compaction_start":
this.patchConnectionState({ isCompacting: true });
@@ -2765,6 +2763,7 @@ export class InteractiveMode {
this.isAgentCompacting() ||
this.isBashRunning() ||
this.getRetryAttempt() > 0 ||
+ this.connectionState?.sessionActions.active !== undefined ||
this.traceUploadAllAbortController !== undefined ||
this.sideQuestionEvent?.status === "running"
);
@@ -2774,8 +2773,8 @@ export class InteractiveMode {
return this.connectionState?.retryAttempt ?? 0;
}
- private getPendingMessageCount(): number {
- return this.connectionState?.pendingMessageCount ?? 0;
+ private getQueuedActionCount(): number {
+ return this.connectionState?.sessionActions.queuedCount ?? 0;
}
private getGoalState(): GoalState {
@@ -3104,7 +3103,7 @@ export class InteractiveMode {
isIdle: () => !this.isAgentStreaming(),
signal: localSessionHost.getAbortSignal(),
abort: () => this.agentConnection.abort(),
- hasPendingMessages: () => this.getPendingMessageCount() > 0,
+ hasPendingMessages: () => this.getQueuedActionCount() > 0,
shutdown: () => {
this.shutdownRequested = true;
},
@@ -5362,10 +5361,10 @@ export class InteractiveMode {
this.ui.requestRender();
break;
- case "queue_update":
+ case "session_action_update":
this.connectionQueue = {
- steering: [...event.steering],
- followUp: [...event.followUp],
+ steering: [...event.actions.steering],
+ followUp: [...event.actions.followUps],
};
this.updatePendingMessagesDisplay();
this.ui.requestRender();
diff --git a/packages/coding-agent/src/modes/rpc/rpc-mode.ts b/packages/coding-agent/src/modes/rpc/rpc-mode.ts
index 637f72948f..5abcb782e6 100644
--- a/packages/coding-agent/src/modes/rpc/rpc-mode.ts
+++ b/packages/coding-agent/src/modes/rpc/rpc-mode.ts
@@ -256,7 +256,7 @@ async function runRpcModeWithConnectionInternal(
sessionName: state.sessionName,
autoCompactionEnabled: state.autoCompactionEnabled,
messageCount: state.messageCount,
- pendingMessageCount: state.pendingMessageCount,
+ sessionActions: state.sessionActions,
goal: state.goal,
};
return success(id, command.type, rpcState);
diff --git a/packages/coding-agent/src/modes/rpc/rpc-types.ts b/packages/coding-agent/src/modes/rpc/rpc-types.ts
index c1ebe26608..f86de0f9af 100644
--- a/packages/coding-agent/src/modes/rpc/rpc-types.ts
+++ b/packages/coding-agent/src/modes/rpc/rpc-types.ts
@@ -22,6 +22,7 @@ import type {
} from "../../core/cron-jobs.js";
import type { GoalState } from "../../core/goals.js";
import type { RefinementResult } from "../../core/refinement/index.js";
+import type { SessionActionSnapshot } from "../../core/session-action-store.js";
import type { SessionStats } from "../../core/session-stats.js";
import type { AgentConnectionHeartbeat, AgentConnectionSourceInfo } from "../agent-connection/types.js";
@@ -151,7 +152,7 @@ export interface RpcSessionState {
sessionName?: string;
autoCompactionEnabled: boolean;
messageCount: number;
- pendingMessageCount: number;
+ sessionActions: SessionActionSnapshot;
goal: GoalState;
}
diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.ts
index d991734bb8..f0f7cd51ef 100644
--- a/packages/coding-agent/src/package-manager-cli.ts
+++ b/packages/coding-agent/src/package-manager-cli.ts
@@ -1,3 +1,4 @@
+import type { ImageContent, TextContent, UserMessage } from "@earendil-works/pi-ai";
import chalk from "chalk";
import { spawn } from "child_process";
import { readFileSync, rmSync, statSync } from "fs";
@@ -41,21 +42,18 @@ import {
type SelfUpdateCommand,
VERSION,
} from "./config.js";
-import { parseAgentSessionMessagePromptId } from "./core/agent-messages.js";
+import type { SessionActionRecoverySnapshot } from "./core/agent-session.js";
+import { SESSION_ACTION_RECOVERY_FORMAT_VERSION } from "./core/agent-session.js";
import type { AgentSessionRuntimeMetadata } from "./core/agent-session-runtime.js";
-import {
- type CustomMessage,
- isSessionSlashCommandMessage,
- SESSION_SLASH_COMMAND_CUSTOM_TYPE,
-} from "./core/messages.js";
+import { type CustomMessage, isSessionSlashCommand } from "./core/messages.js";
import { DefaultPackageManager } from "./core/package-manager.js";
import { SettingsManager } from "./core/settings-manager.js";
import { DaemonClient, type DaemonHello } from "./modes/daemon/daemon-client.js";
import {
DAEMON_PROTOCOL_VERSION,
DAEMON_SCHEMA_ID,
+ DAEMON_UPDATE_RESTART_FORMAT_VERSION,
type DaemonUpdateRestartManifest,
- type DaemonUpdateRestartQueuedMessage,
type DaemonUpdateRestartSession,
isUnknownDaemonCommandError,
} from "./modes/daemon/daemon-protocol.js";
@@ -516,6 +514,10 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+function isStringEnum(value: unknown, allowed: readonly string[]): boolean {
+ return typeof value === "string" && allowed.includes(value);
+}
+
function readString(value: unknown, fieldName: string): string {
if (typeof value !== "string") {
throw new Error(`Daemon update restart response is missing ${fieldName}`);
@@ -557,36 +559,16 @@ function readOptionalStringRecord(value: unknown, fieldName: string): Record<str
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] {
+function isMessageContentBlock(value: unknown): value is TextContent | ImageContent {
return (
- isRecord(value) && value.type === "image" && typeof value.data === "string" && typeof value.mimeType === "string"
+ isRecord(value) &&
+ ((value.type === "text" && typeof value.text === "string") ||
+ (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 isImageContent(value: unknown): value is ImageContent {
+ return isMessageContentBlock(value) && value.type === "image";
}
function isCustomMessage(value: unknown): value is CustomMessage {
@@ -595,85 +577,100 @@ function isCustomMessage(value: unknown): value is CustomMessage {
value.role === "custom" &&
typeof value.customType === "string" &&
(typeof value.content === "string" ||
- (Array.isArray(value.content) && value.content.every(isCustomMessageContentBlock))) &&
+ (Array.isArray(value.content) && value.content.every(isMessageContentBlock))) &&
typeof value.display === "boolean" &&
typeof value.timestamp === "number"
);
}
+function isUserMessage(value: unknown): value is UserMessage {
+ return (
+ isRecord(value) &&
+ value.role === "user" &&
+ (typeof value.content === "string" ||
+ (Array.isArray(value.content) && value.content.every(isMessageContentBlock))) &&
+ typeof value.timestamp === "number"
+ );
+}
+
+function isQueuedAgentMessage(value: unknown): value is UserMessage | CustomMessage {
+ return isUserMessage(value) || isCustomMessage(value);
+}
+
function readCustomMessages(value: unknown, fieldName: string): CustomMessage[] {
- if (value === undefined) {
- return [];
- }
+ 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 prefixMessages = readCustomMessages(value.prefixMessages, "queue.prefixMessages");
- const customMessage =
- value.customMessage === undefined
- ? undefined
- : isCustomMessage(value.customMessage)
- ? value.customMessage
- : undefined;
+function isSessionActionRecoveryAction(value: unknown): value is SessionActionRecoverySnapshot["actions"][number] {
if (
- value.customMessage !== undefined &&
- (!customMessage ||
- (customMessage.customType === SESSION_SLASH_COMMAND_CUSTOM_TYPE &&
- (!isSessionSlashCommandMessage(customMessage) || message !== customMessage.details.command.text)))
+ !isRecord(value) ||
+ typeof value.id !== "string" ||
+ typeof value.source !== "string" ||
+ (value.delivery !== "next_turn_boundary" && value.delivery !== "when_run_idle") ||
+ (value.wake !== "immediate" && value.wake !== "on_lower_boundary" && value.wake !== "external_resume") ||
+ !isRecord(value.payload) ||
+ typeof value.payload.text !== "string" ||
+ (value.payload.images !== undefined &&
+ (!Array.isArray(value.payload.images) || !value.payload.images.every(isImageContent)))
) {
- throw new Error("Daemon update restart response contains an invalid custom queued message");
+ return false;
}
- const restoredAgentMessageId = readOptionalString(value.agentMessageId, "queue.agentMessageId");
- if (restoredAgentMessageId === "") throw new Error("queue.agentMessageId must not be empty");
- const agentMessageId = restoredAgentMessageId ?? parseAgentSessionMessagePromptId(message);
- return {
- message,
- ...(content ? { content } : {}),
- ...(images ? { images } : {}),
- ...(queueKey ? { queueKey } : {}),
- ...(agentMessageId ? { agentMessageId } : {}),
- ...(customMessage ? { customMessage } : {}),
- ...(prefixMessages.length > 0 ? { prefixMessages } : {}),
- };
+ if (value.payload.kind === "session_command") return isSessionSlashCommand(value.payload.command);
+ return (
+ value.payload.kind === "turn" &&
+ Array.isArray(value.payload.records) &&
+ value.payload.records.filter((record) => isRecord(record) && record.role === "primary").length === 1 &&
+ value.payload.records.every(
+ (record) =>
+ isRecord(record) &&
+ typeof record.id === "string" &&
+ (record.role === "primary" || record.role === "prefix" || record.role === "next_turn") &&
+ record.ownerActionId === value.id &&
+ isQueuedAgentMessage(record.message),
+ ) &&
+ (value.payload.content === undefined ||
+ (Array.isArray(value.payload.content) && value.payload.content.every(isMessageContentBlock))) &&
+ (value.payload.customMessage === undefined || isCustomMessage(value.payload.customMessage)) &&
+ isRecord(value.payload.executionPolicy) &&
+ isRecord(value.payload.executionPolicy.preparation) &&
+ isStringEnum(value.payload.executionPolicy.preparation.initialRefineBarrier, ["always", "ifInFlight", "skip"]) &&
+ typeof value.payload.executionPolicy.preparation.flushPendingBashBeforeValidation === "boolean" &&
+ typeof value.payload.executionPolicy.preparation.validateModelAndAuth === "boolean" &&
+ typeof value.payload.executionPolicy.preparation.awaitPendingModelSelection === "boolean" &&
+ isStringEnum(value.payload.executionPolicy.preparation.preTurnCompaction, [
+ "beforeModelSelection",
+ "afterModelSelection",
+ "skip",
+ ]) &&
+ isStringEnum(value.payload.executionPolicy.preparation.finalRefineBarrier, ["always", "ifInFlight", "skip"]) &&
+ typeof value.payload.executionPolicy.runBeforeAgentStart === "boolean" &&
+ isStringEnum(value.payload.executionPolicy.nextTurnContextTiming, ["preparation", "commit", "skip"]) &&
+ typeof value.payload.executionPolicy.preserveEmptyExtensionPrompt === "boolean" &&
+ typeof value.payload.executionPolicy.completionIncludesRetryChain === "boolean" &&
+ typeof value.payload.queueVisible === "boolean" &&
+ typeof value.payload.acceptedAgentMessage === "boolean" &&
+ typeof value.payload.acceptedBeforeCompletion === "boolean"
+ );
}
-function parseDaemonUpdateRestartAcceptedPrompt(
- value: unknown,
-): NonNullable<DaemonUpdateRestartSession["queue"]["acceptedPrompt"]> {
- if (!isRecord(value)) {
- throw new Error("Daemon update restart response contains an invalid accepted prompt");
+function parseSessionActionRecoverySnapshot(value: unknown): SessionActionRecoverySnapshot {
+ if (!isRecord(value)) throw new Error("Daemon update restart response contains invalid session actions");
+ if (value.formatVersion !== SESSION_ACTION_RECOVERY_FORMAT_VERSION) {
+ throw new Error(`Unsupported session action recovery format version: ${String(value.formatVersion)}`);
+ }
+ if (!Array.isArray(value.actions) || !value.actions.every(isSessionActionRecoveryAction)) {
+ throw new Error("Daemon update restart response is missing session actions");
}
return {
- ...parseDaemonUpdateRestartQueuedMessage(value),
- nextTurn: readCustomMessages(value.nextTurn, "queue.acceptedPrompt.nextTurn"),
+ formatVersion: SESSION_ACTION_RECOVERY_FORMAT_VERSION,
+ actions: value.actions,
};
}
-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;
@@ -710,10 +707,6 @@ function parseDaemonUpdateRestartRuntimeMetadata(value: unknown): AgentSessionRu
};
}
-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");
@@ -737,12 +730,8 @@ function parseDaemonUpdateRestartSession(value: unknown): DaemonUpdateRestartSes
...(runtimeMetadata ? { runtimeMetadata } : {}),
...(clientEnv ? { clientEnv } : {}),
queue: {
- steering: readQueuedMessages(queue.steering, "queue.steering"),
- followUp: readQueuedMessages(queue.followUp, "queue.followUp"),
+ actions: parseSessionActionRecoverySnapshot(queue.actions),
nextTurn: readCustomMessages(queue.nextTurn, "queue.nextTurn"),
- ...(queue.acceptedPrompt !== undefined
- ? { acceptedPrompt: readOptionalAcceptedPrompt(queue.acceptedPrompt) }
- : {}),
},
shouldResume: readBoolean(value.shouldResume, "shouldResume"),
wasStreaming: readBoolean(value.wasStreaming, "wasStreaming"),
@@ -758,11 +747,15 @@ function parseDaemonUpdateRestartManifest(value: unknown): DaemonUpdateRestartMa
if (!isRecord(value)) {
throw new Error("Daemon update restart response is invalid");
}
+ if (value.formatVersion !== DAEMON_UPDATE_RESTART_FORMAT_VERSION) {
+ throw new Error(`Unsupported daemon update restart format version: ${String(value.formatVersion)}`);
+ }
const sessions = value.sessions;
if (!Array.isArray(sessions)) {
throw new Error("Daemon update restart response is missing sessions");
}
return {
+ formatVersion: DAEMON_UPDATE_RESTART_FORMAT_VERSION,
createdAt: readString(value.createdAt, "createdAt"),
sessions: sessions.map(parseDaemonUpdateRestartSession),
};
@@ -812,6 +805,7 @@ function tryReadPreparedDaemonUpdateRestartManifest(
try {
return readPreparedDaemonUpdateRestartManifest(socketPath, agentDir);
} catch {
+ clearPreparedDaemonUpdateRestartManifest(socketPath, agentDir);
return undefined;
}
}
@@ -874,11 +868,8 @@ async function prepareConnectedDaemonUpdateRestart(
if (hasFixedDaemonSupervisorOwnerIdentity(hello)) {
fixedOwnerIdentity = hello;
}
- const useLegacyProtocol = hello !== undefined && hello.protocol.version < DAEMON_PROTOCOL_VERSION;
if (pendingManifest && pendingManifest.sessions.length > 0) {
- const listResponse = useLegacyProtocol
- ? await client.requestLegacy({ type: "list" }, 30000)
- : await client.request({ type: "list" }, 30000);
+ const listResponse = await client.request({ type: "list" }, 30000);
if (listResponse.success && !responseHasActiveDaemonSessions(listResponse.data)) {
await persistPreparedRestartFence();
return pendingManifest;
@@ -886,9 +877,7 @@ async function prepareConnectedDaemonUpdateRestart(
}
clearPreparedDaemonUpdateRestartManifest(socketPath, agentDir);
startedAt = Date.now();
- const response = useLegacyProtocol
- ? await client.requestLegacy({ type: "prepare_update_restart" }, 120000)
- : await client.request({ type: "prepare_update_restart" }, 120000);
+ const response = await client.request({ type: "prepare_update_restart" }, 120000);
if (!response.success) {
throw new Error(response.error);
}
@@ -1043,11 +1032,9 @@ async function restoreDaemonUpdateRestartSession(
);
}
}
- const acceptedPrompt = session.queue.acceptedPrompt;
- if (!session.shouldResume) {
- await restoreNextTurnMessages(client, activeSessionId, session.sessionFile, session.queue.nextTurn);
- return { restored: true, resumed: false };
- }
+ await restoreNextTurnMessages(client, activeSessionId, session.sessionFile, session.queue.nextTurn);
+ if (!session.shouldResume) return { restored: true, resumed: false };
+
const needsContinuationPrompt =
session.wasStreaming ||
session.wasCompacting ||
@@ -1055,87 +1042,28 @@ async function restoreDaemonUpdateRestartSession(
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) {
+ if (session.queue.actions.actions.length > 0) {
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,
- prefixMessages: queued.prefixMessages,
- },
+ { type: "restore_actions", activeSessionId, snapshot: session.queue.actions },
30000,
);
if (response.success) {
restoredQueuedWork = true;
} else {
console.error(
- chalk.yellow(
- `Warning: could not restore queued steering message for ${session.sessionFile}: ${response.error}`,
- ),
+ chalk.yellow(`Warning: could not restore queued actions 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,
- prefixMessages: queued.prefixMessages,
- },
- 30000,
+ const restoredAcceptedTurn =
+ restoredQueuedWork &&
+ session.queue.actions.actions.some(
+ (action) =>
+ action.payload.kind === "turn" && !action.payload.queueVisible && action.payload.acceptedBeforeCompletion,
);
- 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,
- customMessage: acceptedPrompt.customMessage,
- },
- 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) {
+ if (needsContinuationPrompt && !restoredAcceptedTurn) {
const promptResponse = await client.request(
{
type: "prompt",
@@ -1151,7 +1079,7 @@ async function restoreDaemonUpdateRestartSession(
resumedSession = true;
}
}
- if (!resumedSession && restoredQueuedWork && !acceptedPrompt) {
+ if (!resumedSession && restoredQueuedWork) {
const response = await client.request({ type: "resume_queue", activeSessionId }, 30000);
if (response.success) {
resumedSession = true;
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index 9a7d81f130..0d8bf77ccc 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -586,7 +586,7 @@ function createConnectionState(activeSessionId: string, sessionId: string): Agen
leafId: `${sessionId}-leaf`,
autoCompactionEnabled: true,
messageCount: 1,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
compactionCount: 0,
goal: {
active: false,
@@ -627,13 +627,14 @@ function createAttachResult(
activeSessionId,
lifecycle: "live" as const,
activity: "idle" as const,
+ isSessionActive: state.isStreaming,
sessionId: state.sessionId,
cwd: "/tmp/project",
isStreaming: state.isStreaming,
isCompacting: false,
attachedClients: 1,
messageCount: messages.length,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
...(options.streamingMessage ? { streamingMessage: options.streamingMessage } : {}),
};
// Slim shape: the daemon omits top-level state/messages for clients with the
@@ -689,9 +690,8 @@ function emitSequencedQueueUpdate(client: FakeDaemonClient, activeSessionId: str
type: "session_event",
activeSessionId,
event: {
- type: "queue_update",
- steering: [],
- followUp: [],
+ type: "session_action_update",
+ actions: { queuedCount: 0, steering: [], followUps: [] },
},
meta: {
id: `${activeSessionId}:${sequence}`,
@@ -965,7 +965,7 @@ describe("DaemonAgentConnection", () => {
expect(fakeClient.requests).toEqual([]);
});
- it("uses heartbeat commands supported by a retained protocol-3 daemon", async () => {
+ it("does not query the heartbeat catalog on a retained protocol-3 daemon", async () => {
const fakeClient = new FakeDaemonClient();
fakeClient.hello = {
type: "daemon_hello",
@@ -981,7 +981,7 @@ describe("DaemonAgentConnection", () => {
await expect(connection.manageHeartbeat("active-original", "job-1", "pause")).resolves.toMatchObject({
id: "job-1",
});
- expect(fakeClient.requests.map((request) => request.type)).toEqual(["heartbeats_list", "heartbeat_manage"]);
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["heartbeat_manage"]);
});
it("degrades heartbeat commands missing from an older protocol-3 daemon", async () => {
@@ -999,7 +999,7 @@ describe("DaemonAgentConnection", () => {
await expect(connection.manageHeartbeat("active-original", "job-1", "pause")).rejects.toThrow(
"Heartbeat management requires a newer Prime Agent daemon.",
);
- expect(fakeClient.requests.map((request) => request.type)).toEqual(["heartbeats_list", "heartbeat_manage"]);
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["heartbeat_manage"]);
});
it("reattaches an open window to its restored session after an update restart", async () => {
@@ -1735,7 +1735,7 @@ describe("DaemonAgentConnection", () => {
emitSequencedQueueUpdate(fakeClient, "active-2", 13);
await vi.waitFor(() => expect(siblingEvents).toHaveLength(1));
- expect(siblingEvents[0]).toMatchObject({ type: "session_event", event: { type: "queue_update" } });
+ expect(siblingEvents[0]).toMatchObject({ type: "session_event", event: { type: "session_action_update" } });
expect(fakeClient.closeCount).toBe(0);
await failed.dispose();
await sibling.dispose();
@@ -1959,7 +1959,7 @@ describe("DaemonAgentConnection", () => {
]);
emitSequencedQueueUpdate(fakeClient, "active-2", 13);
await vi.waitFor(() => expect(siblingEvents).toHaveLength(1));
- expect(siblingEvents[0]).toMatchObject({ type: "session_event", event: { type: "queue_update" } });
+ expect(siblingEvents[0]).toMatchObject({ type: "session_event", event: { type: "session_action_update" } });
expect(fakeClient.closeCount).toBe(0);
expect((connection as unknown as { snapshotAssemblies: Map<string, unknown> }).snapshotAssemblies.size).toBe(
0,
@@ -2396,9 +2396,8 @@ describe("DaemonAgentConnection", () => {
type: "session_event",
activeSessionId: "active-1",
event: {
- type: "queue_update",
- steering: [],
- followUp: [],
+ type: "session_action_update",
+ actions: { queuedCount: 0, steering: [], followUps: [] },
},
meta: {
id: "active-1:13",
@@ -2429,9 +2428,8 @@ describe("DaemonAgentConnection", () => {
type: "session_event",
activeSessionId: "active-1",
event: {
- type: "queue_update",
- steering: [],
- followUp: [],
+ type: "session_action_update",
+ actions: { queuedCount: 0, steering: [], followUps: [] },
},
meta: {
id: "active-1:13",
@@ -2499,9 +2497,8 @@ describe("DaemonAgentConnection", () => {
type: "session_event",
activeSessionId: "active-1",
event: {
- type: "queue_update",
- steering: ["interrupt"],
- followUp: ["later"],
+ type: "session_action_update",
+ actions: { queuedCount: 2, steering: ["interrupt"], followUps: ["later"] },
},
meta: {
id: "active-1:14",
@@ -2515,9 +2512,8 @@ describe("DaemonAgentConnection", () => {
type: "session_event",
activeSessionId: "other",
event: {
- type: "queue_update",
- steering: ["ignored"],
- followUp: [],
+ type: "session_action_update",
+ actions: { queuedCount: 1, steering: ["ignored"], followUps: [] },
},
});
@@ -2525,9 +2521,8 @@ describe("DaemonAgentConnection", () => {
{
type: "session_event",
event: {
- type: "queue_update",
- steering: ["interrupt"],
- followUp: ["later"],
+ type: "session_action_update",
+ actions: { queuedCount: 2, steering: ["interrupt"], followUps: ["later"] },
},
},
]);
@@ -2563,8 +2558,8 @@ describe("DaemonAgentConnection", () => {
const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
const steeringUpdates: Array<readonly string[]> = [];
connection.subscribe((event) => {
- if (event.type === "session_event" && event.event.type === "queue_update") {
- steeringUpdates.push(event.event.steering);
+ if (event.type === "session_event" && event.event.type === "session_action_update") {
+ steeringUpdates.push(event.event.actions.steering);
}
});
await connection.attach();
@@ -2572,7 +2567,7 @@ describe("DaemonAgentConnection", () => {
fakeClient.emitMessage({
type: "session_event",
activeSessionId: "active-1",
- event: { type: "queue_update", steering: [steering], followUp: [] },
+ event: { type: "session_action_update", actions: { queuedCount: 1, steering: [steering], followUps: [] } },
meta: {
id: `${generation}:${sequence}`,
protocol: DAEMON_PROTOCOL_INFO,
diff --git a/packages/coding-agent/test/agent-connection-in-process.test.ts b/packages/coding-agent/test/agent-connection-in-process.test.ts
index 0a4c08061b..be9054a098 100644
--- a/packages/coding-agent/test/agent-connection-in-process.test.ts
+++ b/packages/coding-agent/test/agent-connection-in-process.test.ts
@@ -99,7 +99,7 @@ function createFakeSession(id: string, messages: AgentMessage[]): FakeSessionCon
sessionName: `${id} name`,
autoCompactionEnabled: true,
messages,
- pendingMessageCount: 0,
+ getSessionActionSnapshot: () => ({ queuedCount: 0, steering: [], followUps: [] }),
goalState: emptyGoalState(),
modelRegistry: {
refreshModelCatalog: async () => ({ models: model ? [model] : [], configuredProviders: ["openai"] }),
@@ -321,13 +321,19 @@ describe("InProcessAgentConnection", () => {
]);
events.length = 0;
- oldSession.emit({ type: "queue_update", steering: ["old"], followUp: [] });
- newSession.emit({ type: "queue_update", steering: ["new"], followUp: ["later"] });
+ oldSession.emit({ type: "session_action_update", actions: { queuedCount: 1, steering: ["old"], followUps: [] } });
+ newSession.emit({
+ type: "session_action_update",
+ actions: { queuedCount: 2, steering: ["new"], followUps: ["later"] },
+ });
expect(events).toEqual([
{
type: "session_event",
- event: { type: "queue_update", steering: ["new"], followUp: ["later"] },
+ event: {
+ type: "session_action_update",
+ actions: { queuedCount: 2, steering: ["new"], followUps: ["later"] },
+ },
},
]);
diff --git a/packages/coding-agent/test/agent-session-concurrent.test.ts b/packages/coding-agent/test/agent-session-concurrent.test.ts
index 34eafd087e..c26fb84eab 100644
--- a/packages/coding-agent/test/agent-session-concurrent.test.ts
+++ b/packages/coding-agent/test/agent-session-concurrent.test.ts
@@ -158,7 +158,7 @@ describe("AgentSession concurrent prompt guard", () => {
// steer should work while streaming
expect(() => session.steer("Steering message")).not.toThrow();
- expect(session.pendingMessageCount).toBe(1);
+ expect(session.queuedActionCount).toBe(1);
// Cleanup
await session.abort();
@@ -174,7 +174,7 @@ describe("AgentSession concurrent prompt guard", () => {
// followUp should work while streaming
expect(() => session.followUp("Follow-up message")).not.toThrow();
- expect(session.pendingMessageCount).toBe(1);
+ expect(session.queuedActionCount).toBe(1);
// Cleanup
await session.abort();
@@ -259,8 +259,8 @@ describe("AgentSession concurrent prompt guard", () => {
resourceLoader: createTestResourceLoader({ extensionsResult }),
});
session.subscribe((event) => {
- if (event.type === "queue_update") {
- queueEvents.push({ steering: event.steering, followUp: event.followUp });
+ if (event.type === "session_action_update") {
+ queueEvents.push({ steering: event.actions.steering, followUp: event.actions.followUps });
}
});
@@ -280,7 +280,7 @@ describe("AgentSession concurrent prompt guard", () => {
pi!.sendUserMessage("Steer from extension", { deliverAs: "steer" });
await new Promise((resolve) => setTimeout(resolve, 25));
- expect(session.pendingMessageCount).toBe(1);
+ expect(session.queuedActionCount).toBe(1);
expect(session.getSteeringMessages()).toContain("Steer from extension");
expect(lastInputSource).toBe("extension");
expect(queueEvents.some((event) => event.steering.includes("Steer from extension"))).toBe(true);
@@ -290,12 +290,12 @@ describe("AgentSession concurrent prompt guard", () => {
expect(sawSteeringMessage).toBe(false);
expect(session.getSteeringMessages()).toContain("Steer from extension");
- expect(session.pendingMessageCount).toBe(1);
+ expect(session.queuedActionCount).toBe(1);
await session.prompt("After abort");
expect(sawSteeringMessage).toBe(true);
- expect(session.pendingMessageCount).toBe(0);
+ expect(session.queuedActionCount).toBe(0);
});
it("delivers accepted agent messages without extension input interception", async () => {
diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.ts
index bc3da17c57..d6c70d0465 100644
--- a/packages/coding-agent/test/agent-session-recursion.test.ts
+++ b/packages/coding-agent/test/agent-session-recursion.test.ts
@@ -482,7 +482,7 @@ describe("AgentSession rlm recursion", () => {
runtimeKind: "subagent",
cwd: tempDir,
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
parentActiveSessionId: "other-parent",
rlmChildId: daemonChildId,
},
@@ -492,7 +492,7 @@ describe("AgentSession rlm recursion", () => {
runtimeKind: "subagent",
cwd: tempDir,
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
parentActiveSessionId: "parent-active",
rlmChildId: daemonChildId,
},
diff --git a/packages/coding-agent/test/agent-session-services.test.ts b/packages/coding-agent/test/agent-session-services.test.ts
index 8a292bb987..3b0f486db7 100644
--- a/packages/coding-agent/test/agent-session-services.test.ts
+++ b/packages/coding-agent/test/agent-session-services.test.ts
@@ -81,7 +81,7 @@ describe("createAgentSessionFromServices", () => {
runtimeKind: "top-level",
cwd: tempDir,
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
},
],
}),
@@ -173,7 +173,8 @@ describe("createAgentSessionFromServices", () => {
isCompacting: false,
attachedClients: 1,
messageCount: 0,
- pendingMessageCount: 0,
+ queuedCount: 0,
+ isSessionActive: false,
},
agents: [],
}),
diff --git a/packages/coding-agent/test/agents-view-inactive-reply.test.ts b/packages/coding-agent/test/agents-view-inactive-reply.test.ts
index ae3556f256..e1733c40e0 100644
--- a/packages/coding-agent/test/agents-view-inactive-reply.test.ts
+++ b/packages/coding-agent/test/agents-view-inactive-reply.test.ts
@@ -21,8 +21,9 @@ function summary(overrides: Partial<SessionSummary>): SessionSummary {
isCompacting: false,
attachedClients: 0,
messageCount: 3,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
...overrides,
+ isSessionActive: overrides.isSessionActive ?? false,
};
}
diff --git a/packages/coding-agent/test/agents-view-missing-cwd.test.ts b/packages/coding-agent/test/agents-view-missing-cwd.test.ts
index c122551ca7..8d7894ddd8 100644
--- a/packages/coding-agent/test/agents-view-missing-cwd.test.ts
+++ b/packages/coding-agent/test/agents-view-missing-cwd.test.ts
@@ -48,6 +48,7 @@ describe("agents view open with a missing session cwd", () => {
id: session.getSessionId(),
lifecycle: "live",
activity: "idle",
+ isSessionActive: false,
sessionId: session.getSessionId(),
sessionFile,
cwd: worktree,
@@ -55,7 +56,7 @@ describe("agents view open with a missing session cwd", () => {
isCompacting: false,
attachedClients: 0,
messageCount: 2,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
};
const { overrideCwd, notice } = resolveAgentsViewOpenCwd(summary, launchCwd);
expect(overrideCwd).toBe(launchCwd);
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 73f26d21e7..74ad3c9be7 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -56,7 +56,11 @@ function heartbeat(id: string, nextRunAt?: string, activeSessionId = "child") {
describe("agents view state", () => {
test("classifies active daemon sessions into coarse fleet sections", () => {
expect(classifyAgentsViewSession(makeSummary({ isStreaming: true, activity: "working" }))).toBe("running");
- expect(classifyAgentsViewSession(makeSummary({ pendingMessageCount: 1, activity: "working" }))).toBe("running");
+ expect(
+ classifyAgentsViewSession(
+ makeSummary({ sessionActions: { queuedCount: 1, steering: [], followUps: [] }, activity: "working" }),
+ ),
+ ).toBe("running");
expect(classifyAgentsViewSession(makeSummary({ activity: "working" }))).toBe("running");
expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 2 }))).toBe("idle");
expect(classifyAgentsViewSession(makeSummary({ activity: "idle", messageCount: 0 }))).toBe("idle");
@@ -304,6 +308,7 @@ describe("agents view state", () => {
runtimeKind: "subagent",
parentActiveSessionId: "parent-active",
activity: "idle",
+ isSessionActive: true,
isRunningTools: true,
}),
makeSummary({
@@ -1135,13 +1140,14 @@ function makeSummary(overrides: Partial<SessionSummary>): SessionSummary {
activeSessionId: "active-1",
lifecycle: "live",
activity: "idle",
+ isSessionActive: false,
sessionId: "session-1",
cwd: "/tmp/project",
isStreaming: false,
isCompacting: false,
attachedClients: 0,
messageCount: 1,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
...overrides,
};
}
diff --git a/packages/coding-agent/test/cron-jobs.test.ts b/packages/coding-agent/test/cron-jobs.test.ts
index c7ea1e7220..0229a37d03 100644
--- a/packages/coding-agent/test/cron-jobs.test.ts
+++ b/packages/coding-agent/test/cron-jobs.test.ts
@@ -1352,21 +1352,21 @@ describe("shouldDeferHeartbeatCronJob", () => {
shouldDeferHeartbeatCronJob(job, {
isStreaming: true,
isBashRunning: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
}),
).toBe(true);
expect(
shouldDeferHeartbeatCronJob(job, {
isStreaming: false,
isBashRunning: true,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
}),
).toBe(true);
expect(
shouldDeferHeartbeatCronJob(job, {
isStreaming: false,
isBashRunning: false,
- pendingMessageCount: 1,
+ unfinishedActionCount: 1,
}),
).toBe(true);
}
@@ -1383,7 +1383,7 @@ describe("shouldDeferHeartbeatCronJob", () => {
shouldDeferHeartbeatCronJob(job, {
isStreaming: true,
isBashRunning: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
}),
).toBe(false);
}
@@ -1398,21 +1398,21 @@ describe("shouldDeferHeartbeatCronJob", () => {
isStreaming: true,
isCompacting: true,
isBashRunning: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
}),
).toBe(true);
expect(
shouldDeferHeartbeatCronJob(job, {
isStreaming: false,
isBashRunning: true,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
}),
).toBe(true);
expect(
shouldDeferHeartbeatCronJob(job, {
isStreaming: false,
isBashRunning: false,
- pendingMessageCount: 1,
+ unfinishedActionCount: 1,
}),
).toBe(true);
expect(
@@ -1420,15 +1420,14 @@ describe("shouldDeferHeartbeatCronJob", () => {
isStreaming: false,
isRetrying: true,
isBashRunning: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
}),
).toBe(true);
expect(
shouldDeferHeartbeatCronJob(job, {
isStreaming: false,
isBashRunning: false,
- hasAcceptedPromptInFlight: true,
- pendingMessageCount: 0,
+ unfinishedActionCount: 1,
}),
).toBe(true);
});
@@ -1437,7 +1436,7 @@ describe("shouldDeferHeartbeatCronJob", () => {
expect(
shouldDeferHeartbeatCronJob(
{ ...baseJob, source: "heartbeat" },
- { isStreaming: false, isBashRunning: false, pendingMessageCount: 0 },
+ { isStreaming: false, isBashRunning: false, unfinishedActionCount: 0 },
),
).toBe(false);
});
@@ -1446,7 +1445,7 @@ describe("shouldDeferHeartbeatCronJob", () => {
expect(
shouldDeferHeartbeatCronJob(
{ ...baseJob, source: "cron" },
- { isStreaming: true, isBashRunning: true, pendingMessageCount: 2 },
+ { isStreaming: true, isBashRunning: true, unfinishedActionCount: 2 },
),
).toBe(false);
});
diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.ts
index f7d6cc8c1e..d43f3c39bd 100644
--- a/packages/coding-agent/test/daemon-client.test.ts
+++ b/packages/coding-agent/test/daemon-client.test.ts
@@ -215,16 +215,16 @@ describe("DaemonClient", () => {
client.close();
});
- it("rejects flat session-tree requests to an old daemon", async () => {
+ it("rejects an old daemon before requesting session state", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
const connect = client.connect();
const socket = netMock.sockets[0]!;
socket.emit("connect");
await connect;
- emitHello(socket, 5);
+ emitHello(socket, DAEMON_PROTOCOL_VERSION - 1);
- await expect(client.request({ type: "get_session_tree", activeSessionId: "active-1" })).rejects.toThrow(
- "does not support get_session_tree",
+ await expect(client.request({ type: "get_state", activeSessionId: "active-1" })).rejects.toThrow(
+ "does not support get_state",
);
expect(socket.writes).toEqual([]);
client.close();
@@ -403,40 +403,20 @@ describe("DaemonClient", () => {
client.close();
});
- it("uses legacy framing automatically after a v1 daemon hello", async () => {
+ it("keeps durable command envelopes on the session-action protocol", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
const connect = client.connect();
const socket = netMock.sockets[0]!;
socket.emit("connect");
await connect;
- emitHello(socket, 1);
-
- const response = client.request({ type: "create" });
- const command = JSON.parse(socket.writes[0]!.trim()) as { id: string; type: string };
- expect(command.type).toBe("create");
- expect(command).not.toHaveProperty("protocol");
- socket.emit(
- "data",
- `${JSON.stringify({ id: command.id, type: "response", command: command.type, success: true })}\n`,
- );
- await expect(response).resolves.toMatchObject({ success: true });
- client.close();
- });
-
- it("keeps durable command envelopes when connected to a v2 daemon", async () => {
- const client = new DaemonClient("/tmp/prime-agent.sock");
- const connect = client.connect();
- const socket = netMock.sockets[0]!;
- socket.emit("connect");
- await connect;
- emitHello(socket, 2);
+ emitHello(socket, DAEMON_PROTOCOL_VERSION);
const response = client.request({ type: "create" });
const request = JSON.parse(socket.writes[0]!.trim()) as {
id: string;
protocol: { version: number };
};
- expect(request.protocol.version).toBe(2);
+ expect(request.protocol.version).toBe(DAEMON_PROTOCOL_VERSION);
socket.emit(
"data",
@@ -449,7 +429,7 @@ describe("DaemonClient", () => {
command: { type: string; commandId: string };
};
expect(acknowledgement).toMatchObject({
- protocol: { version: 2 },
+ protocol: { version: DAEMON_PROTOCOL_VERSION },
command: { type: "ack_result", commandId: request.id },
});
client.close();
diff --git a/packages/coding-agent/test/daemon-command.test.ts b/packages/coding-agent/test/daemon-command.test.ts
index 71777eda3f..9769f30163 100644
--- a/packages/coding-agent/test/daemon-command.test.ts
+++ b/packages/coding-agent/test/daemon-command.test.ts
@@ -570,11 +570,12 @@ function makeSessionSummary(activeSessionId: string, sessionId: string, sessionN
cwd: "/tmp/project",
lifecycle: "ready",
activity: "idle",
+ isSessionActive: false,
isStreaming: false,
isCompacting: false,
attachedClients: 0,
messageCount: 0,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
};
}
diff --git a/packages/coding-agent/test/daemon-launch.test.ts b/packages/coding-agent/test/daemon-launch.test.ts
index 7572499d90..634864a4e0 100644
--- a/packages/coding-agent/test/daemon-launch.test.ts
+++ b/packages/coding-agent/test/daemon-launch.test.ts
@@ -9,7 +9,6 @@ import {
probeDaemonVersion,
probeRunningDaemonSessions,
shouldStartDaemonEarly,
- shouldUseLegacyOwnedSessionWorkerFrontend,
shutdownDaemonAndWait,
} from "../src/cli/daemon-launch.js";
import { VERSION } from "../src/config.js";
@@ -47,9 +46,9 @@ async function startFakeDaemon(options: FakeDaemonOptions = {}): Promise<FakeDae
send(socket, {
type: "daemon_hello",
socketPath,
- protocol: { name: "prime-agent-daemon", version: options.protocolVersion ?? 1 },
+ protocol: { name: "prime-agent.daemon", version: options.protocolVersion ?? DAEMON_PROTOCOL_VERSION },
appVersion: options.appVersion,
- schemaId: options.schemaId,
+ schemaId: options.schemaId ?? DAEMON_SCHEMA_ID,
clientId: "fake-client",
serverCapabilities: options.serverCapabilities ?? [],
});
@@ -75,7 +74,7 @@ async function startFakeDaemon(options: FakeDaemonOptions = {}): Promise<FakeDae
send(socket, {
type: "response",
command: "list",
- id: command.id,
+ id: wire.id,
...(options.failList
? { success: false, error: "list failed" }
: {
@@ -90,7 +89,7 @@ async function startFakeDaemon(options: FakeDaemonOptions = {}): Promise<FakeDae
if (options.respondToShutdown === false) {
continue;
}
- send(socket, { type: "response", command: "shutdown", id: command.id, success: true });
+ send(socket, { type: "response", command: "shutdown", id: wire.id, success: true });
server.close();
socket.end();
}
@@ -119,15 +118,21 @@ async function startCrashingDaemon(): Promise<FakeDaemon> {
const socketPath = process.argv[1];
const send = (socket, message) => socket.write(JSON.stringify(message) + "\\n");
const server = createServer((socket) => {
- send(socket, { type: "daemon_hello", socketPath, protocol: { name: "prime-agent-daemon", version: 1 } });
+ send(socket, {
+ type: "daemon_hello",
+ socketPath,
+ protocol: { name: "prime-agent.daemon", version: ${DAEMON_PROTOCOL_VERSION} },
+ schemaId: ${JSON.stringify(DAEMON_SCHEMA_ID)},
+ });
let buffer = "";
socket.on("data", (chunk) => {
buffer += chunk.toString();
const newline = buffer.indexOf("\\n");
if (newline === -1) return;
- const command = JSON.parse(buffer.slice(0, newline));
+ const wire = JSON.parse(buffer.slice(0, newline));
+ const command = wire.command ?? wire;
if (command.type !== "shutdown") return;
- send(socket, { type: "response", command: "shutdown", id: command.id, success: true });
+ send(socket, { type: "response", command: "shutdown", id: wire.id ?? command.id, success: true });
socket.end(() => process.kill(process.pid, "SIGKILL"));
});
});
@@ -223,7 +228,7 @@ describe("ensureInteractiveDaemonRunning", () => {
await Promise.all(cleanups.splice(0).map((fn) => fn()));
});
- it("keeps a compatible protocol-3 daemon serving busy work instead of bricking startup", async () => {
+ it("rejects a busy pre-session-action daemon before attach", async () => {
const commands: string[] = [];
const daemon = await startFakeDaemon({
protocolVersion: 3,
@@ -233,8 +238,8 @@ describe("ensureInteractiveDaemonRunning", () => {
});
cleanups.push(daemon.close);
- await expect(ensureInteractiveDaemonRunning(daemon.socketPath)).resolves.toBeUndefined();
- expect(commands).toContain("list");
+ await expect(ensureInteractiveDaemonRunning(daemon.socketPath)).rejects.toThrow("incompatible");
+ expect(commands).not.toContain("list");
expect(commands).not.toContain("shutdown");
});
@@ -249,23 +254,11 @@ describe("ensureInteractiveDaemonRunning", () => {
});
cleanups.push(daemon.close);
- await expect(shouldUseLegacyOwnedSessionWorkerFrontend(daemon.socketPath)).resolves.toBe(true);
await expect(ensureInteractiveDaemonRunning(daemon.socketPath)).rejects.toThrow("stale");
expect(commands).toContain("list");
expect(commands).not.toContain("shutdown");
});
- it("routes owned clients through the legacy frontend while a compatible legacy daemon is busy", async () => {
- const daemon = await startFakeDaemon({
- protocolVersion: 3,
- appVersion: VERSION,
- sessions: [{ id: "active-1", activeSessionId: "active-1", isStreaming: true }],
- });
- cleanups.push(daemon.close);
-
- await expect(shouldUseLegacyOwnedSessionWorkerFrontend(daemon.socketPath)).resolves.toBe(true);
- });
-
it("does not treat a live daemon as absent when cold startup delays the first connection", async () => {
const daemon = await startFakeDaemon({
protocolVersion: DAEMON_PROTOCOL_VERSION,
diff --git a/packages/coding-agent/test/daemon-list-format.test.ts b/packages/coding-agent/test/daemon-list-format.test.ts
index 66d5c58d43..98fa7d6a76 100644
--- a/packages/coding-agent/test/daemon-list-format.test.ts
+++ b/packages/coding-agent/test/daemon-list-format.test.ts
@@ -66,6 +66,7 @@ function makeSummary(options: {
id: options.id,
lifecycle: options.lifecycle,
activity: options.activity,
+ isSessionActive: options.activity === "working",
sessionId: options.id,
sessionName: options.name,
cwd: "/tmp/project",
@@ -74,7 +75,7 @@ function makeSummary(options: {
isCompacting: false,
attachedClients: options.clients ?? 0,
messageCount: 2,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
modified: "2026-05-29T10:00:00.000Z",
};
}
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index 91d6003cf6..78b50cd6b0 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -115,7 +115,7 @@ describe("daemon mode helpers", () => {
sessionId: string;
sessionName: string;
isStreaming: boolean;
- pendingMessageCount: number;
+ unfinishedActionCount: number;
acceptAgentMessagePrompt: ReturnType<typeof vi.fn>;
};
};
@@ -136,7 +136,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
acceptAgentMessagePrompt,
},
} as never;
@@ -192,7 +192,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-parent",
sessionName: "Parent",
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
},
} as never;
const defaultSubagentName = createDefaultRlmSubagentSessionName("retained worker", "child-1");
@@ -202,7 +202,7 @@ describe("daemon mode helpers", () => {
sessionId: string;
sessionName: string;
isStreaming: boolean;
- pendingMessageCount: number;
+ unfinishedActionCount: number;
acceptAgentMessagePrompt: ReturnType<typeof vi.fn>;
};
};
@@ -224,7 +224,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-child",
sessionName: defaultSubagentName,
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
acceptAgentMessagePrompt,
},
} as never;
@@ -386,7 +386,7 @@ describe("daemon mode helpers", () => {
isRetrying: false,
isBashRunning: false,
hasAcceptedPromptInFlight: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
promptHeartbeat,
model: { provider: "current-provider", id: "current-model" },
});
@@ -510,7 +510,7 @@ describe("daemon mode helpers", () => {
isRetrying: false,
isBashRunning: false,
hasAcceptedPromptInFlight: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
promptHeartbeat,
});
if (options.sessionOptions?.rlmSessionDir === childSessionDir) {
@@ -748,7 +748,7 @@ describe("daemon mode helpers", () => {
sessionName: sessionId,
prompt: sessionPrompt,
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
},
} as unknown as ActiveSessionState["runtime"];
}
@@ -863,7 +863,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-source",
sessionName: "Source",
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
},
} as never;
const remoteSelector = "remote is closing";
@@ -897,7 +897,7 @@ describe("daemon mode helpers", () => {
runtimeKind: "top-level",
cwd: "/tmp/remote",
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
});
internals.sendRemoteAgentSessionMessage = sendRemoteAgentSessionMessage;
@@ -936,7 +936,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-source",
sessionName: "Source",
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
},
} as never;
const sendRemoteAgentSessionMessage = vi.fn();
@@ -986,7 +986,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
acceptAgentMessagePrompt,
},
} as never;
@@ -1058,7 +1058,7 @@ describe("daemon mode helpers", () => {
sessionId: `session-${targetState.activeSessionId}`,
sessionName: targetState.activeSessionId,
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
prompt: vi.fn(async () => {}),
followUp: vi.fn(async () => true),
clearQueue: vi.fn(() => ({ cleared: 0 })),
@@ -1143,7 +1143,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 2,
+ unfinishedActionCount: 2,
clearQueuedUserMessagesMatching,
clearQueue,
},
@@ -1189,7 +1189,7 @@ describe("daemon mode helpers", () => {
sessionId: `session-${state.activeSessionId}`,
sessionName: state.activeSessionId,
isStreaming: false,
- pendingMessageCount: 1,
+ unfinishedActionCount: 1,
clearQueuedUserMessagesMatching,
},
} as never;
@@ -1241,7 +1241,7 @@ describe("daemon mode helpers", () => {
sessionId: `session-${state.activeSessionId}`,
sessionName: state.activeSessionId,
isStreaming: false,
- pendingMessageCount: 1,
+ unfinishedActionCount: 1,
clearQueuedUserMessagesMatching,
},
} as never;
@@ -1286,7 +1286,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt: vi.fn(async () => {
throw new Error("missing model");
}),
@@ -1351,7 +1351,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: true,
- pendingMessageCount: 19,
+ unfinishedActionCount: 19,
clearQueue: vi.fn(() => ({ cleared: 0 })),
clearQueuedUserMessagesMatching: vi.fn(() => ({ steering: [], followUp: [] })),
queueAgentMessagePrompt,
@@ -1420,7 +1420,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: true,
- get pendingMessageCount() {
+ get unfinishedActionCount() {
return pending;
},
queueAgentMessagePrompt,
@@ -1494,7 +1494,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: true,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
queueAgentMessagePrompt,
waitForAgentMessagePromptDelivery,
},
@@ -1542,7 +1542,7 @@ describe("daemon mode helpers", () => {
sessionId: `session-${name}`,
sessionName: name,
isStreaming: true,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
queueAgentMessagePrompt: vi.fn(async () => true),
// Neither turn ends while both sessions block inside their own send.
waitForAgentMessagePromptDelivery: vi.fn(() => new Promise<void>(() => {})),
@@ -1604,7 +1604,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 19,
+ unfinishedActionCount: 20,
hasAcceptedPromptInFlight: true,
acceptAgentMessagePrompt,
queueAgentMessagePrompt: vi.fn(async () => true),
@@ -1648,17 +1648,19 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 2,
+ unfinishedActionCount: 3,
hasAcceptedPromptInFlight: true,
},
} as never;
const internals = daemon as unknown as {
sessions: Map<string, ActiveSessionState>;
- createAgentMessageListResult(current: ActiveSessionState): { agents: Array<{ pendingMessageCount: number }> };
+ createAgentMessageListResult(current: ActiveSessionState): {
+ agents: Array<{ unfinishedActionCount: number }>;
+ };
};
internals.sessions.set(targetState.activeSessionId, targetState);
- expect(internals.createAgentMessageListResult(targetState).agents[0]?.pendingMessageCount).toBe(3);
+ expect(internals.createAgentMessageListResult(targetState).agents[0]?.unfinishedActionCount).toBe(3);
});
it("reports non-streaming busy sessions as active in agent-observe summaries", () => {
@@ -1686,7 +1688,9 @@ describe("daemon mode helpers", () => {
isBashRunning: false,
isRetrying: false,
hasAcceptedPromptInFlight: false,
- pendingMessageCount: 1,
+ unfinishedActionCount: 1,
+ isSessionActive: true,
+ getSessionActionSnapshot: () => ({ queuedCount: 1, steering: [], followUps: [] }),
messages: [],
state: { pendingToolCalls: new Set(), streamingMessage: undefined },
hasRunningRlmChildren: () => false,
@@ -1700,8 +1704,9 @@ describe("daemon mode helpers", () => {
expect(internals.createAgentObserveListResult(targetState).current.status).toBe("busy");
- (targetState.runtime.session as { isCompacting: boolean; pendingMessageCount: number }).isCompacting = true;
- (targetState.runtime.session as { isCompacting: boolean; pendingMessageCount: number }).pendingMessageCount = 0;
+ (targetState.runtime.session as { isCompacting: boolean; unfinishedActionCount: number }).isCompacting = true;
+ (targetState.runtime.session as { isCompacting: boolean; unfinishedActionCount: number }).unfinishedActionCount =
+ 0;
expect(internals.createAgentObserveListResult(targetState).current.status).toBe("compacting");
});
@@ -1734,7 +1739,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt,
followUp,
},
@@ -1803,7 +1808,7 @@ describe("daemon mode helpers", () => {
sessionName: "Target",
isStreaming: false,
isRetrying: true,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt,
followUp,
queueAgentMessagePrompt,
@@ -1859,7 +1864,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 1,
+ unfinishedActionCount: 1,
prompt,
followUp,
queueAgentMessagePrompt,
@@ -1915,7 +1920,7 @@ describe("daemon mode helpers", () => {
sessionName: "Target",
isStreaming: false,
isCompacting: true,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt,
queueAgentMessagePrompt,
},
@@ -1969,7 +1974,7 @@ describe("daemon mode helpers", () => {
sessionName: "Target",
isStreaming: false,
isBashRunning: true,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
acceptAgentMessagePrompt,
queueAgentMessagePrompt,
},
@@ -2028,7 +2033,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: true,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
queueAgentMessagePrompt,
waitForAgentMessagePromptDelivery,
},
@@ -2088,7 +2093,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt,
followUp,
queueAgentMessagePrompt,
@@ -2156,7 +2161,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: true,
- pendingMessageCount: 1,
+ unfinishedActionCount: 1,
queueAgentMessagePrompt,
},
} as never;
@@ -2209,7 +2214,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
acceptAgentMessagePrompt,
},
} as never;
@@ -2260,7 +2265,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt,
acceptAgentMessagePrompt,
queueAgentMessagePrompt,
@@ -2329,7 +2334,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt,
acceptAgentMessagePrompt,
},
@@ -2401,7 +2406,7 @@ describe("daemon mode helpers", () => {
sessionName: "Target",
isStreaming: false,
isBashRunning: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt,
promptUntilAccepted,
acceptAgentMessagePrompt,
@@ -2463,7 +2468,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt,
acceptAgentMessagePrompt,
queueAgentMessagePrompt,
@@ -2543,7 +2548,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
acceptAgentMessagePrompt,
followUp,
},
@@ -2574,7 +2579,7 @@ describe("daemon mode helpers", () => {
});
await Promise.resolve();
await Promise.resolve();
- (targetState.runtime.session as { pendingMessageCount: number }).pendingMessageCount = 20;
+ (targetState.runtime.session as { unfinishedActionCount: number }).unfinishedActionCount = 20;
resolveFirstPrompt();
await expect(first).resolves.toMatchObject({ message: "first" });
@@ -2597,7 +2602,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt: vi.fn(async () => {}),
},
} as never;
@@ -2652,7 +2657,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
acceptAgentMessagePrompt,
clearQueuedUserMessagesMatching,
},
@@ -2713,7 +2718,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
acceptAgentMessagePrompt,
clearQueuedUserMessagesMatching,
},
@@ -2773,7 +2778,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
acceptAgentMessagePrompt,
clearQueuedUserMessagesMatching,
},
@@ -2838,7 +2843,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-target",
sessionName: "Target",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
messages: [],
acceptAgentMessagePrompt,
clearQueuedUserMessagesMatching,
@@ -2902,7 +2907,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-self",
sessionName: "Self",
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
prompt: vi.fn(async () => {}),
},
} as never;
@@ -4016,7 +4021,7 @@ describe("daemon mode helpers", () => {
sessionId: "session-grandchild",
sessionName: "Grandchild",
isStreaming: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
},
} as never;
internals.sessions.set(grandchildState.activeSessionId, grandchildState);
@@ -4170,7 +4175,12 @@ describe("daemon mode helpers", () => {
fromState.runtime = {
...fromState.runtime,
cwd: tempDir,
- session: { sessionId: "session-source", sessionName: "Source", isStreaming: false, pendingMessageCount: 0 },
+ session: {
+ sessionId: "session-source",
+ sessionName: "Source",
+ isStreaming: false,
+ unfinishedActionCount: 0,
+ },
} as never;
internals.sessions.set(fromState.activeSessionId, fromState);
@@ -4610,7 +4620,7 @@ describe("daemon mode helpers", () => {
},
{
name: "does not enqueue another heartbeat when one is already pending",
- activity: { isStreaming: true, pendingMessageCount: 1 },
+ activity: { isStreaming: true, unfinishedActionCount: 1 },
jobs: [{ id: "heartbeat-1", source: "heartbeat" }],
acceptingAgentMessage: false,
assertQueuedHeartbeatUntouched: true,
@@ -4624,7 +4634,7 @@ describe("daemon mode helpers", () => {
},
{
name: "defers heartbeat cron jobs while an accepted agent message prompt is in flight",
- activity: { hasAcceptedPromptInFlight: true },
+ activity: { unfinishedActionCount: 1 },
jobs: [{ id: "heartbeat-1", source: "heartbeat" }],
acceptingAgentMessage: false,
assertQueuedHeartbeatUntouched: false,
@@ -4654,12 +4664,12 @@ describe("daemon mode helpers", () => {
},
{
name: "queues generic cron jobs behind accepted agent message prompts",
- activity: { hasAcceptedPromptInFlight: true },
+ activity: { unfinishedActionCount: 1 },
acceptingAgentMessage: false,
},
{
name: "queues generic cron jobs behind pending messages",
- activity: { pendingMessageCount: 1 },
+ activity: { unfinishedActionCount: 1 },
acceptingAgentMessage: false,
},
] as const)("$name", async ({ activity, acceptingAgentMessage }) => {
@@ -4732,7 +4742,7 @@ describe("daemon mode helpers", () => {
const sessionState = {
isStreaming: false,
isBashRunning: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
};
const prompt = vi.fn(async (_message: string, options?: { preflightResult?: (didSucceed: boolean) => void }) => {
sessionState.isStreaming = true;
@@ -5793,8 +5803,7 @@ type CronAdmissionActivity = Partial<{
isCompacting: boolean;
isRetrying: boolean;
isBashRunning: boolean;
- hasAcceptedPromptInFlight: boolean;
- pendingMessageCount: number;
+ unfinishedActionCount: number;
}>;
function makeCronAdmissionFixture(
@@ -5832,8 +5841,7 @@ function makeCronAdmissionFixture(
isCompacting: false,
isRetrying: false,
isBashRunning: false,
- hasAcceptedPromptInFlight: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
...activity,
prompt,
promptHeartbeat,
diff --git a/packages/coding-agent/test/daemon-multiclient-bench.ts b/packages/coding-agent/test/daemon-multiclient-bench.ts
index 03526faeeb..998e4b48c1 100644
--- a/packages/coding-agent/test/daemon-multiclient-bench.ts
+++ b/packages/coding-agent/test/daemon-multiclient-bench.ts
@@ -285,7 +285,7 @@ function createAttachResponseForMessages(
isCompacting: false,
attachedClients: clientIndex + 1,
messageCount: messages.length,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
};
const state = {
activeSessionId,
@@ -301,7 +301,7 @@ function createAttachResponseForMessages(
leafId: "leaf-benchmark",
autoCompactionEnabled: true,
messageCount: messages.length,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
compactionCount: 0,
scopedModels: [],
activeToolNames: ["read", "bash", "edit"],
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index 677f667f20..979c7fa5c3 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -36,22 +36,22 @@ describe("daemon protocol helpers", () => {
});
it("requires compatibility metadata for the heartbeat protocol surface", () => {
- expect(DAEMON_PROTOCOL_VERSION).toBe(6);
+ expect(DAEMON_PROTOCOL_VERSION).toBe(7);
expect(DAEMON_SCHEMA_ID).toContain(`protocol-${DAEMON_PROTOCOL_VERSION}`);
expect(DAEMON_COMMAND_COMPATIBILITY.heartbeats_list).toEqual({
- minProtocol: 3,
+ minProtocol: 7,
capability: "heartbeat_catalog",
});
expect(DAEMON_COMMAND_COMPATIBILITY.heartbeat_manage).toEqual({
- minProtocol: 3,
+ minProtocol: 7,
capability: "heartbeat_management",
});
expect(DAEMON_COMMAND_COMPATIBILITY.complete_owned_session).toEqual({
- minProtocol: 4,
+ minProtocol: 7,
capability: "client_owned_sessions",
});
expect(DAEMON_OUTBOUND_COMPATIBILITY.heartbeats_changed).toEqual({
- minProtocol: 3,
+ minProtocol: 7,
capability: "heartbeat_catalog",
});
expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toEqual(
@@ -61,7 +61,7 @@ describe("daemon protocol helpers", () => {
it("capability-gates the optional model catalog surface", () => {
expect(DAEMON_COMMAND_COMPATIBILITY.get_model_catalog).toEqual({
- minProtocol: 4,
+ minProtocol: 7,
capability: "model_catalog",
});
expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("model_catalog");
@@ -69,8 +69,8 @@ describe("daemon protocol helpers", () => {
it("version- and capability-gates prompt admission cancellation", () => {
expect(DAEMON_COMMAND_COMPATIBILITY.cancel_prompt_admission).toEqual({
- minProtocol: 5,
- minSchemaRevision: 6,
+ minProtocol: 7,
+ minSchemaRevision: 8,
capability: "prompt_admission_cancellation",
});
expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("prompt_admission_cancellation");
@@ -85,7 +85,7 @@ describe("daemon protocol helpers", () => {
// Refine events remain on the original session-event channel across later schema revisions.
expect(DAEMON_SCHEMA_REVISION).toBeGreaterThanOrEqual(6);
- expect(DAEMON_OUTBOUND_COMPATIBILITY.session_event).toEqual({ minProtocol: 1 });
+ expect(DAEMON_OUTBOUND_COMPATIBILITY.session_event).toEqual({ minProtocol: 7 });
expect(event).toMatchObject({ event: { type: "refine_failed", error: "disk full" } });
});
@@ -112,9 +112,9 @@ describe("daemon protocol helpers", () => {
event: { type: "bash_end", exitCode: 0, cancelled: false, truncated: false },
};
- expect(DAEMON_COMMAND_COMPATIBILITY.start_side_question).toEqual({ minProtocol: 1 });
- expect(DAEMON_COMMAND_COMPATIBILITY.execute_bash).toEqual({ minProtocol: 1 });
- expect(DAEMON_OUTBOUND_COMPATIBILITY.session_event).toEqual({ minProtocol: 1 });
+ expect(DAEMON_COMMAND_COMPATIBILITY.start_side_question).toEqual({ minProtocol: 7 });
+ expect(DAEMON_COMMAND_COMPATIBILITY.execute_bash).toEqual({ minProtocol: 7 });
+ expect(DAEMON_OUTBOUND_COMPATIBILITY.session_event).toEqual({ minProtocol: 7 });
expect(oldClientSideQuestion).not.toHaveProperty("previousTurns");
expect(oldClientBash).not.toHaveProperty("transient");
expect(oldClientBash).not.toHaveProperty("runId");
@@ -158,11 +158,11 @@ describe("daemon protocol helpers", () => {
expect(eventMeta.cursor).toEqual({ generation: "active-1", sequence: 3 });
});
- it("accepts command envelopes from the compatible v2 protocol", () => {
+ it("rejects command envelopes from pre-session-action protocols", () => {
const command = { id: "cmd-1", type: "attach", activeSessionId: "active-1" } as const;
- expect(isDaemonCommandEnvelope(createDaemonCommandEnvelope(command, "cmd-1", "client-1", 2))).toBe(true);
- expect(isDaemonCommandEnvelope(createDaemonCommandEnvelope(command, "cmd-1", "client-1", 1))).toBe(false);
+ expect(isDaemonCommandEnvelope(createDaemonCommandEnvelope(command, "cmd-1", "client-1", 7))).toBe(true);
+ expect(isDaemonCommandEnvelope(createDaemonCommandEnvelope(command, "cmd-1", "client-1", 6))).toBe(false);
});
it("keeps attachment routing out of the durable mutation journal", () => {
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index 83fc4a144e..f3cd64d5af 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -111,7 +111,7 @@ describe("buildSessionList", () => {
});
});
- it("counts accepted in-flight agent prompts as pending work", () => {
+ it("reports accepted in-flight prompts as active with no queued work", () => {
const oneMessage = [{ role: "user", content: "hi" }] as unknown as AgentMessage[];
const summary = summaryForActiveSession(
makeState({
@@ -122,10 +122,23 @@ describe("buildSessionList", () => {
}),
);
- expect(summary.pendingMessageCount).toBe(1);
+ expect(summary.sessionActions).toMatchObject({ queuedCount: 0, active: { kind: "turn", phase: "running" } });
expect(summary.activity).toBe("working");
});
+ it("reports the exact unfinished action count independently of the visible action snapshot", () => {
+ const summary = summaryForActiveSession(
+ makeState({
+ activeSessionId: "batched",
+ unfinishedActionCount: 3,
+ hasAcceptedPromptInFlight: true,
+ }),
+ );
+
+ expect(summary.sessionActions).toMatchObject({ queuedCount: 0, active: { kind: "turn" } });
+ expect(summary.unfinishedActionCount).toBe(3);
+ });
+
it("marks a finished subagent idle instead of holding it at working", () => {
const oneMessage = [{ role: "user", content: "hi" }] as unknown as AgentMessage[];
const entries = buildSessionList(
@@ -515,8 +528,9 @@ describe("resolveAttachModelFallbackMessage", () => {
isCompacting: false,
attachedClients: 0,
messageCount: 0,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
...overrides,
+ isSessionActive: overrides.isSessionActive ?? false,
};
}
@@ -551,6 +565,7 @@ interface StateOptions {
childRunStatuses?: Record<string, "queued" | "running" | "done" | "error" | "cancelled">;
hasRunningRlmChildren?: boolean;
hasAcceptedPromptInFlight?: boolean;
+ unfinishedActionCount?: number;
contextTokens?: number;
streamingMessage?: AgentMessage;
metadata?: {
@@ -598,9 +613,18 @@ function makeState(options: StateOptions): ActiveSessionState {
getRlmChildRunStatus: (childId: string) => options.childRunStatuses?.[childId],
hasRunningRlmChildren: () => options.hasRunningRlmChildren ?? false,
hasAcceptedPromptInFlight: options.hasAcceptedPromptInFlight ?? false,
+ unfinishedActionCount: options.unfinishedActionCount ?? (options.hasAcceptedPromptInFlight ? 1 : 0),
+ isSessionActive: options.isStreaming === true || options.hasAcceptedPromptInFlight === true,
getCurrentRecap: () => undefined,
_contextTokensForCurrentMessages: () => options.contextTokens,
- pendingMessageCount: 0,
+ getSessionActionSnapshot: () => ({
+ queuedCount: 0,
+ steering: [],
+ followUps: [],
+ ...(options.hasAcceptedPromptInFlight
+ ? { active: { kind: "turn" as const, phase: "running" as const } }
+ : {}),
+ }),
state: {
streamingMessage: options.streamingMessage,
pendingToolCalls: new Set(options.pendingToolCalls ?? []),
diff --git a/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts b/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts
index 441df8920e..e7f7ae0442 100644
--- a/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts
+++ b/packages/coding-agent/test/daemon-session-summarizer-lifecycle.test.ts
@@ -18,7 +18,8 @@ function makeState(
session: {
isStreaming: opts.working ?? false,
isCompacting: false,
- pendingMessageCount: 0,
+ isSessionActive: opts.working ?? false,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
messages: Array.from({ length: opts.messages ?? 2 }, () => ({ role: "user", content: "hi" })),
state: { streamingMessage: undefined },
modelRegistry: {},
diff --git a/packages/coding-agent/test/daemon-stop-confirm.test.ts b/packages/coding-agent/test/daemon-stop-confirm.test.ts
index 1ad47c7a41..b671185bd7 100644
--- a/packages/coding-agent/test/daemon-stop-confirm.test.ts
+++ b/packages/coding-agent/test/daemon-stop-confirm.test.ts
@@ -18,7 +18,7 @@ function session(overrides: Partial<SessionSummary>): SessionSummary {
return {
isStreaming: false,
isCompacting: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
...overrides,
} as unknown as SessionSummary;
}
@@ -55,14 +55,25 @@ describe("confirmDaemonSessionLoss", () => {
setTTY(true);
const probe: RunningDaemonProbe = {
reachable: true,
- activeSessions: [session({ isStreaming: false }), session({ pendingMessageCount: 0 })],
+ activeSessions: [
+ session({ isStreaming: false }),
+ session({ sessionActions: { queuedCount: 0, steering: [], followUps: [] } }),
+ ],
};
expect(await confirmDaemonSessionLoss(probe, { force: false, copy: COPY })).toBe(true);
});
it("aborts without prompting when not at a TTY and a session is busy", async () => {
setTTY(false);
- const probe: RunningDaemonProbe = { reachable: true, activeSessions: [session({ pendingMessageCount: 2 })] };
+ const probe: RunningDaemonProbe = {
+ reachable: true,
+ activeSessions: [
+ session({
+ isSessionActive: true,
+ sessionActions: { queuedCount: 2, steering: [], followUps: [] },
+ }),
+ ],
+ };
expect(await confirmDaemonSessionLoss(probe, { force: false, copy: COPY })).toBe(false);
expect(console.error).toHaveBeenCalledWith(expect.stringContaining("hint"));
expect(console.error).toHaveBeenCalledWith(expect.stringContaining("busy:1"));
@@ -89,10 +100,10 @@ describe("confirmDaemonSessionLoss", () => {
it("treats compacting and pending-message sessions as busy", async () => {
setTTY(false);
for (const overrides of [
- { isCompacting: true },
- { pendingMessageCount: 1 },
- { isStreaming: true },
- { isBashRunning: true },
+ { isSessionActive: true, isCompacting: true },
+ { isSessionActive: true, sessionActions: { queuedCount: 1, steering: [], followUps: [] } },
+ { isSessionActive: true, isStreaming: true },
+ { isSessionActive: true, isBashRunning: true },
{ hasRunningRlmChildren: true },
]) {
vi.mocked(console.error).mockClear();
diff --git a/packages/coding-agent/test/daemon-supervisor-admission.test.ts b/packages/coding-agent/test/daemon-supervisor-admission.test.ts
index fd711c5a3e..770910275b 100644
--- a/packages/coding-agent/test/daemon-supervisor-admission.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-admission.test.ts
@@ -34,6 +34,10 @@ function client(id: string): DaemonSocketClient {
return { id, attachedActiveSessionIds: new Set(), capabilities: new Set() } as DaemonSocketClient;
}
+function commandLine(command: DaemonCommand & { id: string }, clientId?: string): string {
+ return JSON.stringify(createDaemonCommandEnvelope(command, command.id, clientId));
+}
+
function admissionFor(supervisor: SupervisorHarness, owner: DaemonSocketClient): AdmissionRecord | undefined {
return [...(supervisor.promptAdmissions.get(owner)?.values() ?? [])][0];
}
@@ -107,7 +111,7 @@ describe("daemon supervisor prompt admission ownership", () => {
message: "hello",
} satisfies DaemonCommand;
- const pendingPrompt = supervisor.handleLine(owner, JSON.stringify(prompt));
+ const pendingPrompt = supervisor.handleLine(owner, commandLine(prompt));
const admission = admissionFor(supervisor, owner);
expect(admission).toMatchObject({
client: owner,
@@ -139,10 +143,10 @@ describe("daemon supervisor prompt admission ownership", () => {
message: "hello",
} satisfies DaemonCommand;
- await supervisor.handleLine(owner, JSON.stringify(prompt));
+ await supervisor.handleLine(owner, commandLine(prompt));
expect(supervisor.promptAdmissions.size).toBe(0);
- await supervisor.handleLine(owner, JSON.stringify({ ...prompt, id: "prompt-2" }));
+ await supervisor.handleLine(owner, commandLine({ ...prompt, id: "prompt-2" }));
expect(supervisor.promptAdmissions.size).toBe(0);
});
@@ -161,7 +165,7 @@ describe("daemon supervisor prompt admission ownership", () => {
await supervisor.handleLine(
owner,
- JSON.stringify({
+ commandLine({
id: "cancel-1",
type: "cancel_prompt_admission",
activeSessionId: "session-1",
@@ -220,7 +224,7 @@ describe("daemon supervisor prompt admission ownership", () => {
const owner = client("connection-owner");
const pendingPrompt = supervisor.handleLine(
owner,
- JSON.stringify({
+ commandLine({
id: "prompt-1",
type: "prompt",
activeSessionId: "session-1",
@@ -230,7 +234,7 @@ describe("daemon supervisor prompt admission ownership", () => {
);
const pendingCancel = supervisor.handleLine(
owner,
- JSON.stringify({
+ commandLine({
id: "cancel-1",
type: "cancel_prompt_admission",
activeSessionId: "session-1",
@@ -251,7 +255,7 @@ describe("daemon supervisor prompt admission ownership", () => {
const workerPrompt = deferred<DaemonResponse>();
const worker = { descriptor: { lifecycle: "ready", rootActiveSessionId: "worker-session" } };
const supervisor = createHarness({
- assertCurrent: () => (++ownershipChecks === 1 ? Promise.resolve() : cancelOwnership.promise),
+ assertCurrent: () => (++ownershipChecks === 2 ? cancelOwnership.promise : Promise.resolve()),
findWorker: vi.fn(async () => ({
worker,
summary: { id: "worker-session", activeSessionId: "worker-session" },
@@ -261,7 +265,7 @@ describe("daemon supervisor prompt admission ownership", () => {
const owner = client("connection-owner");
const pendingPrompt = supervisor.handleLine(
owner,
- JSON.stringify({
+ commandLine({
id: "prompt-1",
type: "prompt",
activeSessionId: "session-1",
@@ -272,7 +276,7 @@ describe("daemon supervisor prompt admission ownership", () => {
await waitFor(() => admissionFor(supervisor, owner)?.worker !== undefined);
const pendingCancel = supervisor.handleLine(
owner,
- JSON.stringify({
+ commandLine({
id: "cancel-1",
type: "cancel_prompt_admission",
activeSessionId: "session-1",
@@ -309,7 +313,7 @@ describe("daemon supervisor prompt admission ownership", () => {
const owner = client("connection-owner");
void supervisor.handleLine(
owner,
- JSON.stringify({
+ commandLine({
id: "prompt-1",
type: "prompt",
activeSessionId: "session-1",
@@ -325,7 +329,7 @@ describe("daemon supervisor prompt admission ownership", () => {
await supervisor.handleLine(
owner,
- JSON.stringify({
+ commandLine({
id: "cancel-1",
type: "cancel_prompt_admission",
activeSessionId: "session-1",
@@ -378,8 +382,8 @@ describe("daemon supervisor prompt admission ownership", () => {
message: id,
}) as const satisfies DaemonCommand;
- const pendingA = supervisor.handleLine(ownerA, JSON.stringify(makePrompt("prompt-a")));
- const pendingB = supervisor.handleLine(ownerB, JSON.stringify(makePrompt("prompt-b")));
+ const pendingA = supervisor.handleLine(ownerA, commandLine(makePrompt("prompt-a")));
+ const pendingB = supervisor.handleLine(ownerB, commandLine(makePrompt("prompt-b")));
await waitFor(() => promptResponses.size === 2);
const admissionA = admissionFor(supervisor, ownerA)!;
const admissionB = admissionFor(supervisor, ownerB)!;
@@ -406,7 +410,7 @@ describe("daemon supervisor prompt admission ownership", () => {
expect(admissionFor(supervisor, ownerA)).toBe(admissionA);
expect(admissionFor(supervisor, ownerB)).toBe(admissionB);
- const pendingCancelA = supervisor.handleLine(ownerA, JSON.stringify({ ...spoofedCancel, id: "cancel-a" }));
+ const pendingCancelA = supervisor.handleLine(ownerA, commandLine({ ...spoofedCancel, id: "cancel-a" }));
await waitFor(() => cancelResponses.has(admissionA.workerAdmissionId));
expect(cancelResponses.has(admissionB.workerAdmissionId)).toBe(false);
expect(admissionFor(supervisor, ownerA)).toBe(admissionA);
@@ -481,7 +485,7 @@ describe("daemon supervisor prompt admission ownership", () => {
const owner = [...supervisor.clients][0]!;
const pendingPrompt = supervisor.handleLine(
owner,
- JSON.stringify({
+ commandLine({
id: "prompt-1",
type: "prompt",
activeSessionId: "public-session",
@@ -549,7 +553,7 @@ describe("daemon supervisor prompt admission ownership", () => {
const owner = [...supervisor.clients][0]!;
const pendingPrompt = supervisor.handleLine(
owner,
- JSON.stringify({
+ commandLine({
id: "prompt-1",
type: "prompt",
activeSessionId: "public-session",
diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
index 088fe32717..c05afc018b 100644
--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
@@ -11,7 +11,12 @@ import { CommandRecoveryJournal } from "../src/modes/daemon/command-recovery-jou
import { DaemonCatalogClient } from "../src/modes/daemon/daemon-catalog-process.js";
import { DaemonClient } from "../src/modes/daemon/daemon-client.js";
import { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";
-import { createDaemonCommandEnvelope, type DaemonAttachResult, success } from "../src/modes/daemon/daemon-protocol.js";
+import {
+ createDaemonCommandEnvelope,
+ DAEMON_UPDATE_RESTART_FORMAT_VERSION,
+ type DaemonAttachResult,
+ success,
+} from "../src/modes/daemon/daemon-protocol.js";
import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";
import {
@@ -1521,13 +1526,14 @@ describe("daemon worker supervisor monitoring", () => {
activeSessionId,
lifecycle: "live",
activity: "working",
+ isSessionActive: true,
sessionId: "session-1",
cwd: "/tmp/project",
isStreaming: true,
isCompacting: false,
attachedClients: 0,
messageCount: 1,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
streamingMessage,
};
const result = {
@@ -1658,13 +1664,14 @@ describe("daemon worker supervisor monitoring", () => {
activeSessionId,
lifecycle: "live",
activity: "idle",
+ isSessionActive: false,
sessionId: "session-failed-attach",
cwd: "/tmp/project",
isStreaming: false,
isCompacting: false,
attachedClients: 0,
messageCount: 0,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
} satisfies SessionSummary;
const worker = {
descriptor: { workerId: "worker-1", lifecycle: "ready", pid: 1234 },
@@ -1770,7 +1777,11 @@ describe("daemon worker supervisor monitoring", () => {
});
it.each([
{ name: "malformed data", data: undefined, error: /invalid update manifest/ },
- { name: "missing root disposition", data: { createdAt: "now", sessions: [] }, error: /root disposition/ },
+ {
+ name: "missing root disposition",
+ data: { formatVersion: DAEMON_UPDATE_RESTART_FORMAT_VERSION, createdAt: "now", sessions: [] },
+ error: /root disposition/,
+ },
])("cancels a prepare acknowledgement with $name", async ({ data, error }) => {
const client = {
requestWorker: vi.fn(async ({ type }: { type: string }) =>
@@ -1793,7 +1804,15 @@ describe("daemon worker supervisor monitoring", () => {
const client = {
requestWorker: vi.fn(async ({ type }: { type: string }) =>
type === "worker_prepare_update"
- ? { success: true, data: { createdAt: "now", sessions: [], discardedActiveSessionIds: ["root"] } }
+ ? {
+ success: true,
+ data: {
+ formatVersion: DAEMON_UPDATE_RESTART_FORMAT_VERSION,
+ createdAt: "now",
+ sessions: [],
+ discardedActiveSessionIds: ["root"],
+ },
+ }
: { success: true },
),
};
@@ -1914,7 +1933,11 @@ describe("daemon worker supervisor monitoring", () => {
firstDrain.resolve();
});
mutationDrain.begin(); // The prepare command itself remains in flight at the supervisor boundary.
- const prepareFenced = vi.fn(async () => ({ createdAt: "now", sessions: [] }));
+ const prepareFenced = vi.fn(async () => ({
+ formatVersion: DAEMON_UPDATE_RESTART_FORMAT_VERSION,
+ createdAt: "now",
+ sessions: [],
+ }));
const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
mutationDrain,
workers: new Map(),
diff --git a/packages/coding-agent/test/daemon-supervisor-side-question.test.ts b/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
index fc717d66bc..9b2529f0d3 100644
--- a/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
@@ -1,5 +1,10 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { createConnection, type Socket } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import type { DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
+import { DaemonCatalogClient } from "../src/modes/daemon/daemon-catalog-process.js";
import {
createDaemonCommandEnvelope,
DAEMON_COMMAND_COMPATIBILITY,
@@ -31,6 +36,12 @@ describe("daemon supervisor side-question routing", () => {
clients: new Set(),
protocolClientIds: new WeakMap(),
mutationDrain: new MutationDrainLatch(),
+ commandJournal: {
+ lookup: vi.fn(() => undefined),
+ begin: vi.fn(() => ({ status: "new" })),
+ recordResult: vi.fn(),
+ },
+ cancelOwnedWorkerCleanup: vi.fn(),
handleCommand,
write,
log: vi.fn(),
@@ -53,7 +64,10 @@ describe("daemon supervisor side-question routing", () => {
] satisfies DaemonCommand[];
for (const command of commands) {
- await supervisor.handleLine(client, JSON.stringify(command));
+ await supervisor.handleLine(
+ client,
+ JSON.stringify(createDaemonCommandEnvelope(command, command.id!, client.id)),
+ );
}
expect(handleCommand.mock.calls.map((call) => call[1])).toEqual(commands);
@@ -62,7 +76,7 @@ describe("daemon supervisor side-question routing", () => {
expect.objectContaining({ command: "abort_side_question", success: true }),
]);
});
- it("rejects flat session-tree requests from an old client", async () => {
+ it("rejects an old client before forwarding a state request", async () => {
const handleCommand = vi.fn();
const write = vi.fn();
const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
@@ -72,22 +86,27 @@ describe("daemon supervisor side-question routing", () => {
clients: new Set(),
protocolClientIds: new WeakMap(),
mutationDrain: new MutationDrainLatch(),
+ commandJournal: {
+ lookup: vi.fn(() => undefined),
+ begin: vi.fn(() => ({ status: "new" })),
+ recordResult: vi.fn(),
+ },
cancelOwnedWorkerCleanup: vi.fn(),
handleCommand,
write,
log: vi.fn(),
}) as SupervisorHarness;
const client = { id: "old-client" } as DaemonSocketClient;
- const command = { type: "get_session_tree", activeSessionId: "active-1" } as const;
+ const command = { type: "get_state", activeSessionId: "active-1" } as const;
await supervisor.handleLine(
client,
JSON.stringify(
createDaemonCommandEnvelope(
command,
- "tree-1",
+ "state-1",
undefined,
- DAEMON_COMMAND_COMPATIBILITY.get_session_tree.minProtocol - 1,
+ DAEMON_COMMAND_COMPATIBILITY.get_state.minProtocol - 1,
),
),
);
@@ -96,11 +115,68 @@ describe("daemon supervisor side-question routing", () => {
expect(write).toHaveBeenCalledWith(
client,
expect.objectContaining({
- id: "tree-1",
- command: "get_session_tree",
+ command: "parse",
success: false,
- error: expect.stringContaining("requires client protocol 6"),
+ error: expect.stringContaining("require protocol 7"),
}),
);
});
+
+ it("rejects a protocol-6 client through the supervisor socket before state exchange", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-supervisor-old-client-"));
+ const socketPath = join(root, "supervisor.sock");
+ const supervisor = new DaemonSupervisor(socketPath, {
+ defaultSessionConfig: { cwd: root, agentDir: root },
+ descriptorDir: join(root, "workers"),
+ });
+ const catalogStart = vi.spyOn(DaemonCatalogClient.prototype, "start").mockResolvedValue();
+ let socket: Socket | undefined;
+ try {
+ await supervisor.start();
+ const connectedSocket = createConnection(socketPath);
+ socket = connectedSocket;
+ await new Promise<void>((resolve, reject) => {
+ connectedSocket.once("connect", resolve);
+ connectedSocket.once("error", reject);
+ });
+ const messages = new Promise<Array<Record<string, unknown>>>((resolve, reject) => {
+ const received: Array<Record<string, unknown>> = [];
+ let buffer = "";
+ const timer = setTimeout(() => reject(new Error("Timed out waiting for protocol rejection")), 2000);
+ connectedSocket.on("data", (chunk) => {
+ buffer += chunk.toString();
+ let newline = buffer.indexOf("\n");
+ while (newline >= 0) {
+ const line = buffer.slice(0, newline);
+ buffer = buffer.slice(newline + 1);
+ newline = buffer.indexOf("\n");
+ if (!line) continue;
+ const message = JSON.parse(line) as Record<string, unknown>;
+ received.push(message);
+ if (message.type === "response") {
+ clearTimeout(timer);
+ resolve(received);
+ }
+ }
+ });
+ });
+ const command = { type: "get_state", activeSessionId: "active-1" } as const;
+ connectedSocket.write(`${JSON.stringify(createDaemonCommandEnvelope(command, "state-1", "old-client", 6))}\n`);
+
+ await expect(messages).resolves.toEqual([
+ expect.objectContaining({ type: "daemon_hello" }),
+ expect.objectContaining({
+ type: "response",
+ command: "parse",
+ success: false,
+ error: expect.stringContaining("require protocol 7"),
+ }),
+ ]);
+ } finally {
+ socket?.destroy();
+ await Reflect.apply(Reflect.get(supervisor, "cleanupSupervisorResources"), supervisor, []);
+ catalogStart.mockRestore();
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
});
diff --git a/packages/coding-agent/test/heartbeat-catalog.test.ts b/packages/coding-agent/test/heartbeat-catalog.test.ts
index 8c4e4caab8..1d812100a6 100644
--- a/packages/coding-agent/test/heartbeat-catalog.test.ts
+++ b/packages/coding-agent/test/heartbeat-catalog.test.ts
@@ -33,7 +33,6 @@ describe("daemon heartbeat catalog", () => {
success: true,
data: { heartbeats: [heartbeat] },
})),
- requestLegacy: vi.fn(),
} as unknown as DaemonClient;
await expect(listDaemonHeartbeats(client)).resolves.toEqual([heartbeat]);
diff --git a/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts b/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
index 982ce6bb4e..35d21ccafe 100644
--- a/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
+++ b/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
@@ -24,6 +24,7 @@ type FakeInteractiveMode = {
isCompacting: boolean;
isBashRunning: boolean;
retryAttempt: number;
+ sessionActions: { queuedCount: number; steering: readonly string[]; followUps: readonly string[] };
};
connectionQueue: { steering: string[]; followUp: string[] };
agentConnection: {
@@ -93,6 +94,7 @@ function createInteractiveFake(options: {
isCompacting: options.compacting ?? false,
isBashRunning: options.bashRunning ?? false,
retryAttempt: options.retryAttempt ?? 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
},
connectionQueue: { steering: [], followUp: [] },
agentConnection: {
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index e758e9c0b9..1a0500844a 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -111,7 +111,7 @@ function createConnectionState(overrides: Partial<AgentConnectionState> = {}): A
leafId: null,
autoCompactionEnabled: true,
messageCount: 0,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
compactionCount: 0,
goal: emptyGoalState(),
scopedModels: [],
@@ -2894,7 +2894,8 @@ function createFakeConnectionSession(commandName: string): AgentSessionRuntime["
followUpMode: "all",
sessionId: commandName,
autoCompactionEnabled: true,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
+ getSessionActionSnapshot: () => ({ queuedCount: 0, steering: [], followUps: [] }),
goalState: emptyGoalState(),
scopedModels: [],
subscribe: () => () => {},
diff --git a/packages/coding-agent/test/kernel-agent-message-skill.test.ts b/packages/coding-agent/test/kernel-agent-message-skill.test.ts
index ec9bd1ebe1..7b9ba11d5c 100644
--- a/packages/coding-agent/test/kernel-agent-message-skill.test.ts
+++ b/packages/coding-agent/test/kernel-agent-message-skill.test.ts
@@ -55,7 +55,7 @@ describe("agent-message skill over the kernel host bridge", () => {
sessionId: "session-alpha",
cwd: tempDir,
isStreaming: false,
- pendingMessageCount: 0,
+ unfinishedActionCount: 0,
},
{
activeSessionId: "beta",
@@ -63,7 +63,7 @@ describe("agent-message skill over the kernel host bridge", () => {
sessionName: "Beta",
cwd: tempDir,
isStreaming: true,
- pendingMessageCount: 1,
+ unfinishedActionCount: 1,
},
],
};
diff --git a/packages/coding-agent/test/main-interactive-routing.test.ts b/packages/coding-agent/test/main-interactive-routing.test.ts
index dc3b7b97de..fe00b2aa35 100644
--- a/packages/coding-agent/test/main-interactive-routing.test.ts
+++ b/packages/coding-agent/test/main-interactive-routing.test.ts
@@ -250,13 +250,14 @@ describe("daemon-backed interactive session manager routing", () => {
activeSessionId: "active-1",
lifecycle: "draft",
activity: "idle",
+ isSessionActive: false,
sessionId: "session-1",
cwd: "/tmp/project",
isStreaming: false,
isCompacting: false,
attachedClients: 0,
messageCount: 0,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
}),
}),
).resolves.toMatchObject({ activeSessionId: "active-1" });
@@ -472,7 +473,8 @@ function makeSessionSummary(overrides: Partial<SessionSummary>): SessionSummary
isCompacting: false,
attachedClients: 0,
messageCount: 0,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
...overrides,
+ isSessionActive: overrides.isSessionActive ?? false,
};
}
diff --git a/packages/coding-agent/test/package-self-update-daemon.test.ts b/packages/coding-agent/test/package-self-update-daemon.test.ts
index bb80e373b8..af8ebf000d 100644
--- a/packages/coding-agent/test/package-self-update-daemon.test.ts
+++ b/packages/coding-agent/test/package-self-update-daemon.test.ts
@@ -34,7 +34,7 @@ interface MockSessionSummary {
isCompacting: boolean;
isBashRunning?: boolean;
hasRunningRlmChildren?: boolean;
- pendingMessageCount: number;
+ sessionActions: { queuedCount: number; steering: string[]; followUps: string[] };
}
type MockRunningDaemonProbe = { reachable: false } | { reachable: true; activeSessions?: MockSessionSummary[] };
@@ -48,13 +48,15 @@ interface MockCustomMessage {
details?: unknown;
}
-interface MockQueuedMessage {
- message: string;
- content?: Array<{ type: "text"; text: string }>;
- agentMessageId?: string;
+interface MockRecoveryAction {
+ id: string;
+ source: "internal";
+ delivery: "next_turn_boundary" | "when_run_idle";
+ wake: "immediate" | "on_lower_boundary" | "external_resume";
queueKey?: string;
- customMessage?: MockCustomMessage;
- prefixMessages?: MockCustomMessage[];
+ snapshot?: unknown;
+ agentMessageId?: string;
+ payload: { kind: "turn" | "session_command"; text: string; [key: string]: unknown };
}
interface MockUpdateRestartSession {
@@ -65,10 +67,8 @@ interface MockUpdateRestartSession {
config: Record<string, unknown>;
runtimeMetadata?: AgentSessionRuntimeMetadata;
queue: {
- steering: MockQueuedMessage[];
- followUp: MockQueuedMessage[];
+ actions: { formatVersion: 1; actions: MockRecoveryAction[] };
nextTurn: MockCustomMessage[];
- acceptedPrompt?: MockQueuedMessage & { nextTurn: MockCustomMessage[] };
};
shouldResume: boolean;
wasStreaming: boolean;
@@ -80,10 +80,28 @@ interface MockUpdateRestartSession {
}
interface MockUpdateRestartManifest {
+ formatVersion: 1;
createdAt: string;
sessions: MockUpdateRestartSession[];
}
+function createMockTurnExecutionPolicy(): Record<string, unknown> {
+ return {
+ preparation: {
+ initialRefineBarrier: "skip",
+ flushPendingBashBeforeValidation: false,
+ validateModelAndAuth: true,
+ awaitPendingModelSelection: true,
+ preTurnCompaction: "beforeModelSelection",
+ finalRefineBarrier: "always",
+ },
+ runBeforeAgentStart: true,
+ nextTurnContextTiming: "commit",
+ preserveEmptyExtensionPrompt: true,
+ completionIncludesRetryChain: true,
+ };
+}
+
interface MockDaemonRequest {
type: string;
activeSessionId?: string;
@@ -94,6 +112,7 @@ interface MockDaemonRequest {
content?: unknown;
messages?: MockCustomMessage[];
queueKey?: string;
+ snapshot?: unknown;
sessionPath?: string;
runtimeMetadata?: AgentSessionRuntimeMetadata;
}
@@ -121,7 +140,11 @@ const mockState = vi.hoisted(() => ({
listResponse: undefined as MockDaemonResponse | undefined,
noticeError: undefined as string | undefined,
prepareError: undefined as string | undefined,
- prepareManifest: { createdAt: "2026-07-07T00:00:00.000Z", sessions: [] } as MockUpdateRestartManifest,
+ prepareManifest: {
+ formatVersion: 1,
+ createdAt: "2026-07-07T00:00:00.000Z",
+ sessions: [],
+ } as MockUpdateRestartManifest,
preparedManifestPath: "",
prepareResponse: undefined as MockDaemonResponse | undefined,
promptFailures: 0,
@@ -131,6 +154,7 @@ const mockState = vi.hoisted(() => ({
disconnectAfterPersistRequestTypes: [] as string[],
requestPayloads: [] as MockDaemonRequest[],
helloWaitFailures: 0,
+ restoreActionFailures: 0,
restoreNextTurnFailures: 0,
socketPath: "",
successorProcessStartId: "replacement-start" as string | undefined,
@@ -235,7 +259,7 @@ vi.mock("../src/cli/daemon-launch.js", () => ({
summary.isCompacting ||
summary.isBashRunning === true ||
summary.hasRunningRlmChildren === true ||
- summary.pendingMessageCount > 0,
+ summary.sessionActions.queuedCount > 0,
probeRunningDaemonSessions: vi.fn(async (socketPath: string) => {
mockState.calls.push("probe-daemon");
mockState.probeSocketPaths.push(socketPath);
@@ -307,10 +331,6 @@ vi.mock("../src/modes/daemon/daemon-client.js", () => ({
return hello;
}
- async requestLegacy(request: MockDaemonRequest): Promise<MockDaemonResponse> {
- return this.request(request);
- }
-
async request(request: MockDaemonRequest): Promise<MockDaemonResponse> {
this.observedHello ??= mockState.hello;
mockState.calls.push(`daemon-request:${request.type}`);
@@ -349,6 +369,10 @@ vi.mock("../src/modes/daemon/daemon-client.js", () => ({
const activeSessionId = mockState.createActiveSessionIds.shift() ?? "restored-active";
return { success: true, data: { id: activeSessionId, activeSessionId } };
}
+ if (request.type === "restore_actions" && mockState.restoreActionFailures > 0) {
+ mockState.restoreActionFailures--;
+ return { success: false, error: "restore failed" };
+ }
if (request.type === "restore_next_turn" && mockState.restoreNextTurnFailures > 0) {
mockState.restoreNextTurnFailures--;
return { success: false, error: "restore failed" };
@@ -389,6 +413,60 @@ describe("self-update daemon restart", () => {
});
}
+ function createAcceptedRecoveryManifest(nextTurn: MockCustomMessage[] = []): MockUpdateRestartManifest {
+ return {
+ formatVersion: 1,
+ 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: {
+ actions: {
+ formatVersion: 1,
+ actions: [
+ {
+ id: "accepted-action",
+ source: "internal",
+ delivery: "when_run_idle",
+ wake: "external_resume",
+ agentMessageId: "agentmsg_accepted",
+ payload: {
+ kind: "turn",
+ text: "accepted work",
+ records: [
+ {
+ id: "accepted-action-primary",
+ role: "primary",
+ message: { role: "user", content: "accepted work", timestamp: 1 },
+ ownerActionId: "accepted-action",
+ },
+ ],
+ executionPolicy: createMockTurnExecutionPolicy(),
+ queueVisible: false,
+ acceptedAgentMessage: false,
+ acceptedBeforeCompletion: true,
+ },
+ },
+ ],
+ },
+ nextTurn,
+ },
+ shouldResume: true,
+ wasStreaming: false,
+ wasCompacting: false,
+ wasBashRunning: false,
+ hadRunningRlmChildren: false,
+ wasRetrying: false,
+ hadAcceptedPromptInFlight: true,
+ },
+ ],
+ };
+ }
+
beforeEach(() => {
tempDir = join(tmpdir(), `pi-self-update-daemon-${Date.now()}-${Math.random().toString(36).slice(2)}`);
agentDir = join(tempDir, "agent");
@@ -411,7 +489,7 @@ describe("self-update daemon restart", () => {
mockState.daemonProbeAfterShutdown = undefined;
mockState.disconnectAfterPersistRequestTypes = [];
mockState.disconnectRequestTypes = [];
- mockState.prepareManifest = { createdAt: "2026-07-07T00:00:00.000Z", sessions: [] };
+ mockState.prepareManifest = { formatVersion: 1, createdAt: "2026-07-07T00:00:00.000Z", sessions: [] };
mockState.preparedManifestPath = getDaemonUpdateRestartManifestPath(mockState.socketPath, agentDir);
mockState.prepareResponse = undefined;
mockState.helloWaitFailures = 0;
@@ -419,6 +497,7 @@ describe("self-update daemon restart", () => {
mockState.probeSocketPaths = [];
mockState.requestThrowTypes = [];
mockState.requestPayloads = [];
+ mockState.restoreActionFailures = 0;
mockState.restoreNextTurnFailures = 0;
mockState.spawnExitCodes = [];
mockState.shutdownResult = true;
@@ -474,6 +553,18 @@ describe("self-update daemon restart", () => {
);
});
+ it.each([
+ ["unreadable", "{"],
+ ["unknown-format", JSON.stringify({ formatVersion: 0, createdAt: "stale", sessions: [] })],
+ ])("ignores a %s pending restart manifest when probing", async (_name, contents) => {
+ writeFileSync(mockState.preparedManifestPath, contents);
+
+ await expect(prepareDaemonUpdateRestart(mockState.socketPath, agentDir)).resolves.toEqual(
+ mockState.prepareManifest,
+ );
+ expect(mockState.calls).toContain("daemon-request:prepare_update_restart");
+ });
+
it("uses the interactive no-change sentinel only when self-update is unchanged", async () => {
process.env[SELF_UPDATE_INTERACTIVE_CHILD_ENV] = "1";
vi.stubGlobal(
@@ -497,7 +588,7 @@ describe("self-update daemon restart", () => {
activeSessionId: "busy",
isStreaming: true,
isCompacting: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
},
],
};
@@ -671,6 +762,7 @@ describe("self-update daemon restart", () => {
it("clears the prepared manifest after fallback restoration when shutdown fails", async () => {
mockState.shutdownResult = false;
mockState.prepareManifest = {
+ formatVersion: 1,
createdAt: "2026-07-07T00:00:00.000Z",
sessions: [
{
@@ -679,7 +771,7 @@ describe("self-update daemon restart", () => {
sessionFile: join(tempDir, "session.jsonl"),
cwd: tempDir,
config: {},
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, nextTurn: [] },
shouldResume: false,
wasStreaming: false,
wasCompacting: false,
@@ -704,6 +796,7 @@ describe("self-update daemon restart", () => {
mockState.shutdownResult = false;
mockState.daemonProbeAfterShutdown = { reachable: false };
mockState.prepareManifest = {
+ formatVersion: 1,
createdAt: "2026-07-07T00:00:00.000Z",
sessions: [
{
@@ -712,7 +805,7 @@ describe("self-update daemon restart", () => {
sessionFile: join(tempDir, "session.jsonl"),
cwd: tempDir,
config: {},
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, nextTurn: [] },
shouldResume: false,
wasStreaming: false,
wasCompacting: false,
@@ -737,6 +830,7 @@ describe("self-update daemon restart", () => {
it("continues queued-work restoration when the update notice request rejects", async () => {
mockState.noticeError = "socket closed";
mockState.prepareManifest = {
+ formatVersion: 1,
createdAt: "2026-07-07T00:00:00.000Z",
sessions: [
{
@@ -746,8 +840,7 @@ describe("self-update daemon restart", () => {
cwd: tempDir,
config: {},
queue: {
- steering: [],
- followUp: [],
+ actions: { formatVersion: 1, actions: [] },
nextTurn: [
{
role: "custom",
@@ -783,20 +876,6 @@ describe("self-update daemon restart", () => {
}
});
- it("restarts an idle legacy daemon without a restorable manifest", async () => {
- mockState.hello = { protocol: { version: 1 } };
- mockState.prepareError = "Unknown daemon command: prepare_update_restart";
-
- await performUpdateAndRunCoordinator();
-
- expect(mockState.lastCoordinatorStatus).toMatchObject({
- phase: "complete",
- counts: { total: 0, restored: 0, resumed: 0, failed: 0 },
- });
- expect(mockState.calls).toContain("shutdown-daemon");
- expect(mockState.calls).toContain("ensure-daemon");
- });
-
it("restarts the daemon only after the package update succeeds", async () => {
useFixedOwnerHello();
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
@@ -837,7 +916,10 @@ describe("self-update daemon restart", () => {
for (const prepareResponse of [
{ success: false, error: "prepare failed" } as const,
- { success: true, data: { createdAt: "2026-07-07T00:00:00.000Z", sessions: "invalid" } } as const,
+ {
+ success: true,
+ data: { formatVersion: 1, createdAt: "2026-07-07T00:00:00.000Z", sessions: "invalid" },
+ } as const,
]) {
mockState.calls = [];
mockState.prepareResponse = prepareResponse;
@@ -867,6 +949,7 @@ describe("self-update daemon restart", () => {
mockState.preparedManifestPath = legacyManifestPath;
mockState.disconnectAfterPersistRequestTypes = ["prepare_update_restart"];
mockState.prepareManifest = {
+ formatVersion: 1,
createdAt: "2026-07-07T00:00:00.000Z",
sessions: [
{
@@ -875,7 +958,7 @@ describe("self-update daemon restart", () => {
sessionFile: join(tempDir, "session.jsonl"),
cwd: tempDir,
config: { apiKey: "legacy-secret" },
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, nextTurn: [] },
shouldResume: false,
wasStreaming: false,
wasCompacting: false,
@@ -901,6 +984,7 @@ describe("self-update daemon restart", () => {
it("fences a pending prepared restart only after verifying the live daemon is empty", async () => {
useFixedOwnerHello();
const pendingManifest: MockUpdateRestartManifest = {
+ formatVersion: 1,
createdAt: "2026-07-07T00:00:00.000Z",
sessions: [
{
@@ -909,7 +993,7 @@ describe("self-update daemon restart", () => {
sessionFile: join(projectDir, "pending.jsonl"),
cwd: projectDir,
config: { cwd: projectDir, agentDir },
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, nextTurn: [] },
shouldResume: false,
wasStreaming: false,
wasCompacting: false,
@@ -948,7 +1032,7 @@ describe("self-update daemon restart", () => {
id: "live-active",
isStreaming: false,
isCompacting: false,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
},
],
},
@@ -981,80 +1065,33 @@ describe("self-update daemon restart", () => {
});
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,
- },
- ],
- };
+ mockState.restoreActionFailures = 1;
+ mockState.prepareManifest = createAcceptedRecoveryManifest();
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
try {
await expect(performUpdateAndRunCoordinator("old-active")).resolves.toBeUndefined();
- const promptRequests = mockState.requestPayloads.filter((request) => request.type === "prompt");
- expect(promptRequests).toEqual([
- expect.objectContaining({
- activeSessionId: "restored-active",
- message: "accepted work",
- agentMessageId: "agentmsg_accepted",
- }),
- ]);
- const noticeIndex = mockState.requestPayloads.findIndex(
- (request) => request.type === "append_custom_message" && request.activeSessionId === "restored-active",
- );
- const promptIndex = mockState.requestPayloads.findIndex((request) => request.type === "prompt");
- expect(noticeIndex).toBeGreaterThanOrEqual(0);
- expect(promptIndex).toBeGreaterThan(noticeIndex);
- 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);
+ expect(mockState.requestPayloads.some((request) => request.type === "restore_actions")).toBe(true);
+ expect(mockState.requestPayloads.some((request) => request.type === "prompt")).toBe(true);
+ } finally {
+ errorSpy.mockRestore();
+ logSpy.mockRestore();
+ }
+ });
+
+ it("does not replay a continuation after restoring an accepted turn", async () => {
+ mockState.prepareManifest = createAcceptedRecoveryManifest();
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+
+ try {
+ await expect(performUpdateAndRunCoordinator("old-active")).resolves.toBeUndefined();
+
+ expect(mockState.requestPayloads.filter((request) => request.type === "restore_actions")).toHaveLength(1);
+ expect(mockState.requestPayloads.some((request) => request.type === "prompt")).toBe(false);
+ expect(mockState.requestPayloads.filter((request) => request.type === "resume_queue")).toHaveLength(1);
} finally {
errorSpy.mockRestore();
logSpy.mockRestore();
@@ -1066,6 +1103,7 @@ describe("self-update daemon restart", () => {
const restoredSessionFile = join(projectDir, "restored.jsonl");
mockState.createThrowSessionPaths = [failedSessionFile];
mockState.prepareManifest = {
+ formatVersion: 1,
createdAt: "2026-07-07T00:00:00.000Z",
sessions: [
{
@@ -1074,7 +1112,7 @@ describe("self-update daemon restart", () => {
sessionFile: failedSessionFile,
cwd: projectDir,
config: { cwd: projectDir, agentDir },
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, nextTurn: [] },
shouldResume: true,
wasStreaming: true,
wasCompacting: false,
@@ -1089,7 +1127,7 @@ describe("self-update daemon restart", () => {
sessionFile: restoredSessionFile,
cwd: projectDir,
config: { cwd: projectDir, agentDir },
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, nextTurn: [] },
shouldResume: true,
wasStreaming: true,
wasCompacting: false,
@@ -1136,6 +1174,7 @@ describe("self-update daemon restart", () => {
const childSessionFile = join(projectDir, "child.jsonl");
mockState.createActiveSessionIds = ["new-parent", "new-child"];
mockState.prepareManifest = {
+ formatVersion: 1,
createdAt: "2026-07-07T00:00:00.000Z",
sessions: [
{
@@ -1145,7 +1184,7 @@ describe("self-update daemon restart", () => {
cwd: projectDir,
config: { cwd: projectDir, agentDir },
runtimeMetadata: { kind: "top-level", createdAt: 1 },
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, nextTurn: [] },
shouldResume: false,
wasStreaming: false,
wasCompacting: false,
@@ -1169,7 +1208,7 @@ describe("self-update daemon restart", () => {
rlmChildId: "child-1",
prompt: "child task",
},
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, nextTurn: [] },
shouldResume: false,
wasStreaming: false,
wasCompacting: false,
@@ -1210,7 +1249,61 @@ describe("self-update daemon restart", () => {
}
});
- it("preserves queued custom messages and prefixes when restoring update restart queues", async () => {
+ it("rejects malformed recovery actions while parsing the manifest", async () => {
+ const manifest = createAcceptedRecoveryManifest();
+ const session = manifest.sessions[0]!;
+ const action = session.queue.actions.actions[0]!;
+ const incompleteExecutionPolicy = createMockTurnExecutionPolicy();
+ delete incompleteExecutionPolicy.nextTurnContextTiming;
+ const cases: { name: string; action: MockRecoveryAction }[] = [
+ {
+ name: "turn without primary record",
+ action: { ...action, payload: { ...action.payload, records: [] } },
+ },
+ {
+ name: "non-array images",
+ action: { ...action, payload: { ...action.payload, images: {} } },
+ },
+ {
+ name: "turn execution policy missing next-turn context timing",
+ action: {
+ ...action,
+ payload: { ...action.payload, executionPolicy: incompleteExecutionPolicy },
+ },
+ },
+ {
+ name: "unknown session command",
+ action: {
+ ...action,
+ payload: {
+ kind: "session_command",
+ text: "/bogus",
+ command: { name: "bogus", args: "", text: "/bogus" },
+ },
+ },
+ },
+ ];
+
+ for (const testCase of cases) {
+ mockState.prepareResponse = {
+ success: true,
+ data: {
+ ...manifest,
+ sessions: [
+ {
+ ...session,
+ queue: { ...session.queue, actions: { formatVersion: 1, actions: [testCase.action] } },
+ },
+ ],
+ },
+ };
+ await expect(prepareDaemonUpdateRestart(mockState.socketPath, agentDir), testCase.name).rejects.toThrow(
+ "Daemon update restart response is missing session actions",
+ );
+ }
+ });
+
+ it("preserves complete queued actions and rejects unknown recovery formats", async () => {
const customMessage: MockCustomMessage = {
role: "custom",
customType: "heartbeat_prompt",
@@ -1218,24 +1311,33 @@ describe("self-update daemon restart", () => {
display: true,
timestamp: Date.now(),
};
- const commandMessage: MockCustomMessage = {
- role: "custom",
- customType: "session_slash_command",
- content: "/autonomous on",
- display: true,
- timestamp: Date.now(),
- details: {
- command: { name: "autonomous", args: "on", text: "/autonomous on" },
+ const recoveredAction: MockRecoveryAction = {
+ id: "action-1",
+ source: "internal",
+ delivery: "when_run_idle",
+ wake: "external_resume",
+ queueKey: "heartbeat:job-1",
+ agentMessageId: "agentmsg_followup",
+ payload: {
+ kind: "turn",
+ text: "heartbeat body",
+ customMessage,
+ records: [
+ {
+ id: "action-1-primary",
+ role: "primary",
+ message: customMessage,
+ ownerActionId: "action-1",
+ },
+ ],
+ executionPolicy: createMockTurnExecutionPolicy(),
+ queueVisible: true,
+ acceptedAgentMessage: false,
+ acceptedBeforeCompletion: false,
},
};
- const prefixMessage: MockCustomMessage = {
- role: "custom",
- customType: "ipython_state_restored",
- content: "restore context",
- display: true,
- timestamp: Date.now(),
- };
mockState.prepareManifest = {
+ formatVersion: 1,
createdAt: "2026-07-07T00:00:00.000Z",
sessions: [
{
@@ -1244,24 +1346,7 @@ describe("self-update daemon restart", () => {
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,
- prefixMessages: [prefixMessage],
- },
- {
- message: "/autonomous on",
- agentMessageId: "agentmsg_command",
- customMessage: commandMessage,
- },
- ],
- nextTurn: [],
- },
+ queue: { actions: { formatVersion: 1, actions: [recoveredAction] }, nextTurn: [] },
shouldResume: true,
wasStreaming: false,
wasCompacting: false,
@@ -1277,42 +1362,17 @@ describe("self-update daemon restart", () => {
try {
await expect(performUpdateAndRunCoordinator()).resolves.toBeUndefined();
-
- expect(mockState.requestPayloads).toContainEqual(
- expect.objectContaining({
- type: "follow_up",
- activeSessionId: "restored-active",
- message: "heartbeat body",
- queueKey: "heartbeat:job-1",
- agentMessageId: "agentmsg_followup",
- customMessage,
- prefixMessages: [prefixMessage],
- }),
- );
- expect(mockState.requestPayloads).toContainEqual(
- expect.objectContaining({
- type: "follow_up",
- activeSessionId: "restored-active",
- message: "/autonomous on",
- agentMessageId: "agentmsg_command",
- customMessage: commandMessage,
- }),
- );
+ expect(mockState.requestPayloads).toContainEqual({
+ type: "restore_actions",
+ activeSessionId: "restored-active",
+ snapshot: { formatVersion: 1, actions: [recoveredAction] },
+ });
mockState.prepareResponse = {
success: true,
- data: {
- ...mockState.prepareManifest,
- sessions: mockState.prepareManifest.sessions.map((session) => ({
- ...session,
- queue: {
- ...session.queue,
- followUp: [{ message: "/autonomous off", customMessage: commandMessage }],
- },
- })),
- },
+ data: { ...mockState.prepareManifest, formatVersion: 2 },
};
await expect(prepareDaemonUpdateRestart(mockState.socketPath, agentDir)).rejects.toThrow(
- "invalid custom queued message",
+ "Unsupported daemon update restart format version: 2",
);
} finally {
errorSpy.mockRestore();
@@ -1320,9 +1380,33 @@ describe("self-update daemon restart", () => {
}
});
- it("does not resume queued work when accepted prompt replay fails", async () => {
+ it("resumes restored queued work when continuation replay fails", async () => {
mockState.promptFailures = 1;
+ const recoveredAction: MockRecoveryAction = {
+ id: "action-queued",
+ source: "internal",
+ delivery: "when_run_idle",
+ wake: "external_resume",
+ agentMessageId: "agentmsg_followup",
+ payload: {
+ kind: "turn",
+ text: "queued follow-up",
+ records: [
+ {
+ id: "action-queued-primary",
+ role: "primary",
+ message: { role: "user", content: "queued follow-up", timestamp: 1 },
+ ownerActionId: "action-queued",
+ },
+ ],
+ executionPolicy: createMockTurnExecutionPolicy(),
+ queueVisible: true,
+ acceptedAgentMessage: false,
+ acceptedBeforeCompletion: false,
+ },
+ };
mockState.prepareManifest = {
+ formatVersion: 1,
createdAt: "2026-07-07T00:00:00.000Z",
sessions: [
{
@@ -1331,16 +1415,7 @@ describe("self-update daemon restart", () => {
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: [],
- },
- },
+ queue: { actions: { formatVersion: 1, actions: [recoveredAction] }, nextTurn: [] },
shouldResume: true,
wasStreaming: false,
wasCompacting: false,
@@ -1356,9 +1431,8 @@ describe("self-update daemon restart", () => {
try {
await expect(performUpdateAndRunCoordinator()).resolves.toBeUndefined();
-
- expect(mockState.requestPayloads.some((request) => request.type === "follow_up")).toBe(true);
- expect(mockState.requestPayloads.some((request) => request.type === "resume_queue")).toBe(false);
+ expect(mockState.requestPayloads.some((request) => request.type === "restore_actions")).toBe(true);
+ expect(mockState.requestPayloads.some((request) => request.type === "resume_queue")).toBe(true);
} finally {
errorSpy.mockRestore();
logSpy.mockRestore();
diff --git a/packages/coding-agent/test/print-mode.test.ts b/packages/coding-agent/test/print-mode.test.ts
index 4ef87094d0..1c64bb1438 100644
--- a/packages/coding-agent/test/print-mode.test.ts
+++ b/packages/coding-agent/test/print-mode.test.ts
@@ -27,6 +27,7 @@ type FakeExtensionRunner = {
type FakeSession = {
sessionManager: { getHeader: () => object | undefined };
agent: { waitForIdle: ReturnType<typeof vi.fn<() => Promise<void>>> };
+ waitForIdle: ReturnType<typeof vi.fn<() => Promise<void>>>;
state: { messages: AgentMessage[] };
messages: AgentMessage[];
extensionRunner: FakeExtensionRunner;
@@ -96,6 +97,7 @@ function createRuntimeHost(
const session: FakeSession = {
sessionManager: { getHeader: () => undefined },
agent: { waitForIdle: vi.fn(async () => {}) },
+ waitForIdle: vi.fn(async () => {}),
state,
messages: state.messages,
extensionRunner,
@@ -505,7 +507,7 @@ describe("runPrintMode", () => {
() => statuses[Math.min(statusIndex++, statuses.length - 1)] as AgentAutonomousStatus,
);
let waitCount = 0;
- session.agent.waitForIdle.mockImplementation(async () => {
+ session.waitForIdle.mockImplementation(async () => {
waitCount++;
if (waitCount === 2) {
session.state.messages = [createAssistantMessage({ text: "queued retry completed" })];
@@ -520,7 +522,7 @@ describe("runPrintMode", () => {
expect(exitCode).toBe(0);
expect(session.prompt).toHaveBeenCalledTimes(1);
expect(session.recordHostAutonomousContinuation).toHaveBeenCalledTimes(1);
- expect(session.agent.waitForIdle).toHaveBeenCalledTimes(3);
+ expect(session.waitForIdle).toHaveBeenCalledTimes(3);
expect(errorSpy).not.toHaveBeenCalledWith("provider down");
});
@@ -694,7 +696,7 @@ describe("runPrintMode", () => {
});
expect(exitCode).toBe(0);
- expect(session.agent.waitForIdle).toHaveBeenCalledBefore(session.prompt);
+ expect(session.waitForIdle).toHaveBeenCalledBefore(session.prompt);
expect(session.prompt).toHaveBeenCalledTimes(2);
expect(session.prompt.mock.calls[0][0]).toContain("Autonomous quality gate failed (attempt 1/3)");
expect(session.prompt.mock.calls[0][0]).toContain("0/9");
@@ -801,7 +803,7 @@ describe("runPrintMode", () => {
});
expect(exitCode).toBe(1);
- expect(session.agent.waitForIdle).toHaveBeenCalledTimes(7);
+ expect(session.waitForIdle).toHaveBeenCalledTimes(7);
expect(session.prompt).toHaveBeenCalledTimes(3);
expect(session.recordHostAutonomousContinuation).toHaveBeenCalledTimes(3);
expect(session.prompt.mock.calls[1][0]).toContain("workspace unchanged");
diff --git a/packages/coding-agent/test/suite/agent-session-action-contracts.test.ts b/packages/coding-agent/test/suite/agent-session-action-contracts.test.ts
index f9faf7e8a9..bfdbcb810a 100644
--- a/packages/coding-agent/test/suite/agent-session-action-contracts.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-action-contracts.test.ts
@@ -49,7 +49,7 @@ describe("AgentSession action contracts", () => {
await harness.session.prompt("handled", { streamingBehavior: "followUp" });
expect(harness.session.getFollowUpMessages()).toEqual(["transformed:queued"]);
- expect(harness.session.pendingMessageCount).toBe(1);
+ expect(harness.session.queuedActionCount).toBe(1);
withStreaming(harness, false);
expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: ["transformed:queued"] });
});
@@ -65,7 +65,7 @@ describe("AgentSession action contracts", () => {
);
expect(harness.session.messages).toEqual([]);
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
expect(harness.getPendingResponseCount()).toBe(1);
await harness.session.prompt("consume context");
diff --git a/packages/coding-agent/test/suite/agent-session-autonomous.test.ts b/packages/coding-agent/test/suite/agent-session-autonomous.test.ts
index 303b50eec1..100fa982d7 100644
--- a/packages/coding-agent/test/suite/agent-session-autonomous.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-autonomous.test.ts
@@ -327,7 +327,7 @@ describe("AgentSession autonomous mode", () => {
});
sessionInternals._compactionAbortController = undefined;
expect(harness.session.resumeQueuedWork()).toBe(true);
- await vi.waitFor(() => expect(harness.session.pendingMessageCount).toBe(0));
+ await vi.waitFor(() => expect(harness.session.queuedActionCount).toBe(0));
await harness.session.waitForSessionInputIdle();
expect(getAssistantTexts(harness)).toEqual(["Still failing."]);
diff --git a/packages/coding-agent/test/suite/agent-session-bash-persistence.test.ts b/packages/coding-agent/test/suite/agent-session-bash-persistence.test.ts
index 5df6b6cf64..ef14362de3 100644
--- a/packages/coding-agent/test/suite/agent-session-bash-persistence.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-bash-persistence.test.ts
@@ -368,16 +368,16 @@ describe("AgentSession bash and persistence characterization", () => {
await bashStartedPromise;
expect(harness.session.isBashRunning).toBe(true);
await harness.session.queueAgentMessagePrompt(agentPrompt, "followUp");
- expect(harness.session.pendingMessageCount).toBe(1);
+ expect(harness.session.queuedActionCount).toBe(1);
releaseBash?.();
await bashRun;
- for (let i = 0; i < 10 && harness.session.pendingMessageCount > 0; i++) {
+ for (let i = 0; i < 10 && harness.session.queuedActionCount > 0; i++) {
await Promise.resolve();
}
await delivery;
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
});
it("drains steering before follow-up prompts after user bash finishes", async () => {
@@ -427,7 +427,7 @@ describe("AgentSession bash and persistence characterization", () => {
expect(userTexts.findIndex((text) => text.includes("steer after bash"))).toBeLessThan(
userTexts.findIndex((text) => text.includes("follow-up after bash")),
);
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
});
it("flushes pending bash output before draining queued prompts", async () => {
diff --git a/packages/coding-agent/test/suite/agent-session-compaction.test.ts b/packages/coding-agent/test/suite/agent-session-compaction.test.ts
index aabbc62f5e..dc7e86590c 100644
--- a/packages/coding-agent/test/suite/agent-session-compaction.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-compaction.test.ts
@@ -184,10 +184,21 @@ describe("AgentSession compaction characterization", () => {
});
});
- it("emits compaction lifecycle events when /compact was queued behind a running turn", async () => {
+ it("renders an executing /compact as activity instead of queued work", async () => {
+ let releaseCompaction: () => void = () => {};
+ const compactionGate = new Promise<void>((resolve) => {
+ releaseCompaction = resolve;
+ });
const harness = await createHarness({
settings: { compaction: { keepRecentTokens: 1 } },
persistSession: true,
+ extensionFactories: [
+ (pi) => {
+ pi.on("session_before_compact", async () => {
+ await compactionGate;
+ });
+ },
+ ],
});
harnesses.push(harness);
let releaseTurn: () => void = () => {};
@@ -206,6 +217,16 @@ describe("AgentSession compaction characterization", () => {
// Queue the command while the turn streams, then let the turn finish.
const queued = harness.session.prompt("/compact", { streamingBehavior: "steer" });
releaseTurn();
+ await vi.waitFor(() =>
+ expect(harness.session.getSessionActionSnapshot()).toMatchObject({
+ queuedCount: 0,
+ steering: [],
+ followUps: [],
+ active: { kind: "session_command", phase: "running", label: "/compact" },
+ }),
+ );
+ expect(harness.session.isSessionActive).toBe(true);
+ releaseCompaction();
await Promise.all([running, queued]);
const order = harness.events.map((event) => event.type);
@@ -280,7 +301,7 @@ describe("AgentSession compaction characterization", () => {
// Hold the input in the session-owned follow-up queue across compaction.
const pause = harness.session.acquireQueuedWorkPause();
await harness.session.followUp("queued across compaction", undefined, { resumeIfIdle: true });
- expect(harness.session.pendingMessageCount).toBe(1);
+ expect(harness.session.queuedActionCount).toBe(1);
await harness.session.compact();
@@ -963,6 +984,7 @@ describe("AgentSession compaction characterization", () => {
expect(harness.session.getFollowUpMessages()).toHaveLength(1);
await harness.session.prompt("/autonomous off");
+ await harness.session.waitForIdle();
expect(harness.session.getAutonomousStatus().enabled).toBe(false);
expect(harness.session.getFollowUpMessages()).toEqual([]);
diff --git a/packages/coding-agent/test/suite/agent-session-observe.test.ts b/packages/coding-agent/test/suite/agent-session-observe.test.ts
index cfec58f113..a41767f1c5 100644
--- a/packages/coding-agent/test/suite/agent-session-observe.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-observe.test.ts
@@ -15,7 +15,8 @@ function createController(): AgentObserveController {
isCompacting: false,
attachedClients: 0,
messageCount: 1,
- pendingMessageCount: 0,
+ queuedCount: 0,
+ isSessionActive: false,
},
agents: [],
})),
@@ -30,7 +31,8 @@ function createController(): AgentObserveController {
isCompacting: false,
attachedClients: 1,
messageCount: 3,
- pendingMessageCount: 0,
+ queuedCount: 0,
+ isSessionActive: false,
},
})),
recentMessages: vi.fn((input) => ({
@@ -44,7 +46,8 @@ function createController(): AgentObserveController {
isCompacting: false,
attachedClients: 1,
messageCount: 3,
- pendingMessageCount: 0,
+ queuedCount: 0,
+ isSessionActive: false,
},
messages: [{ index: 2, role: "assistant", text: "working", truncated: false }],
limit: input.limit ?? 8,
diff --git a/packages/coding-agent/test/suite/agent-session-prompt.test.ts b/packages/coding-agent/test/suite/agent-session-prompt.test.ts
index 9d18f96771..bbb26ef6b4 100644
--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts
@@ -143,10 +143,10 @@ describe("AgentSession prompt characterization", () => {
expect(harness.session.messages.map((message) => message.role)).toEqual(["user", "assistant"]);
expect(getMessageText(harness.session.messages[0]!)).toBe("hi");
expect(harness.getPendingResponseCount()).toBe(0);
- expect(harness.eventsOfType("queue_update")).toEqual([]);
+ expect(harness.eventsOfType("session_action_update")).toEqual([]);
});
- it("admits concurrent idle prompts in FIFO order without exposing queue rows", async () => {
+ it("admits concurrent idle prompts in FIFO order with only the waiting action queued", async () => {
const harness = await createHarness();
harnesses.push(harness);
const firstResponse = createDeferred();
@@ -172,7 +172,7 @@ describe("AgentSession prompt characterization", () => {
await new Promise<void>((resolve) => setImmediate(resolve));
expect(secondSettled).toBe(false);
expect(harness.session.getFollowUpMessages()).toEqual([]);
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
firstResponse.resolve();
await vi.waitFor(() => expect(getUserTexts(harness)).toEqual(["first", "second"]));
@@ -443,7 +443,7 @@ describe("AgentSession prompt characterization", () => {
signal: controller.signal,
}),
).rejects.toThrow("Prompt admission was cancelled.");
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
releaseToolExecution();
await promptPromise;
@@ -978,7 +978,7 @@ stale post-hook extension instructions`,
await harness.session.prompt("normal prompt");
expect(queuedTurnSawSeparateNextTurnContext).toBe(true);
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
});
it("queues accepted agent messages if the session becomes busy before handoff", async () => {
@@ -1178,7 +1178,7 @@ stale post-hook extension instructions`,
).toEqual(["newer prompt", "newer response"]),
);
expect(harness.session.agent.state.errorMessage).toBeUndefined();
- expect(harness.session.getAcceptedPromptSnapshot()).toBeUndefined();
+ expect(harness.session.unfinishedActionCount).toBe(0);
expect(harness.session.hasAcceptedPromptInFlight).toBe(false);
});
@@ -1730,6 +1730,33 @@ stale post-hook extension instructions`,
expect(getUserTexts(harness)).toEqual(["next prompt"]);
});
+ it("rejects an invisible prompt cancelled after a handoff rollback", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const dispatchReached = createDeferred<void>();
+ const rejectDispatch = createDeferred<void>();
+ vi.spyOn(harness.session.agent, "prompt").mockImplementationOnce(async () => {
+ dispatchReached.resolve();
+ await rejectDispatch.promise;
+ throw new Error("handoff interrupted");
+ });
+ const prompt = harness.session.promptUntilAccepted("rolled back prompt");
+ const outcome = prompt.then(
+ () => ({ error: undefined }),
+ (error: unknown) => ({ error }),
+ );
+ await dispatchReached.promise;
+
+ harness.session.requestAbort();
+ rejectDispatch.resolve();
+ await harness.session.waitForSessionInputIdle();
+ expect(harness.session.getSessionActionRecoverySnapshot().actions).toHaveLength(1);
+ harness.session.requestAbort();
+
+ expect((await outcome).error).toEqual(expect.objectContaining({ message: "Prompt aborted before delivery." }));
+ await harness.session.waitForSessionInputIdle();
+ });
+
it("aborts while a queued prompt is still preparing without consuming its snapshot", async () => {
const preparationReached = createDeferred();
const preparationGate = createDeferred();
diff --git a/packages/coding-agent/test/suite/agent-session-queue.test.ts b/packages/coding-agent/test/suite/agent-session-queue.test.ts
index 9520f71457..9272463472 100644
--- a/packages/coding-agent/test/suite/agent-session-queue.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-queue.test.ts
@@ -1321,8 +1321,8 @@ describe("AgentSession queue characterization", () => {
pause.release();
await hook.reached;
- // The pump owns the prompt during preparation, but it stays visible as pending.
- expect(harness.session.getSteeringMessages()).toEqual(["active steering"]);
+ // The pump owns the prompt during preparation, so it is active rather than queued.
+ expect(harness.session.getSteeringMessages()).toEqual([]);
expect(internals._steeringStopPending).toBe(true);
expect(harness.session.clearQueue()).toEqual({ steering: ["active steering"], followUp: [] });
expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: [] });
@@ -1334,15 +1334,15 @@ describe("AgentSession queue characterization", () => {
expect(getUserTexts(harness)).toEqual([]);
});
- it("keeps owned inputs visible in counts, previews, and queue updates until delivery", async () => {
+ it("removes preparing inputs from literal queue projections", async () => {
const hook = gatedHook({ prompt: "owned prompt" });
const harness = await createHarness({ extensionFactories: [hook.factory] });
harnesses.push(harness);
harness.setResponses([fauxAssistantMessage("delivered")]);
const queueUpdates: { steering: readonly string[]; followUp: readonly string[] }[] = [];
harness.session.subscribe((event) => {
- if (event.type === "queue_update") {
- queueUpdates.push({ steering: [...event.steering], followUp: [...event.followUp] });
+ if (event.type === "session_action_update") {
+ queueUpdates.push({ steering: [...event.actions.steering], followUp: [...event.actions.followUps] });
}
});
const pause = harness.session.acquireQueuedWorkPause();
@@ -1350,20 +1350,97 @@ describe("AgentSession queue characterization", () => {
pause.release();
await hook.reached;
- // The pump moved the prompt into _activeSessionInput (preparing); it must
- // still count as pending and appear in previews and snapshots.
- expect(harness.session.pendingMessageCount).toBe(1);
- expect(harness.session.getFollowUpMessagePreviews()).toEqual(["owned prompt"]);
- expect(harness.session.getFollowUpQueueSnapshots().map((snapshot) => snapshot.text)).toEqual(["owned prompt"]);
- expect(queueUpdates.at(-1)).toEqual({ steering: [], followUp: ["owned prompt"] });
+ expect(harness.session.queuedActionCount).toBe(0);
+ expect(harness.session.getFollowUpMessagePreviews()).toEqual([]);
+ expect(harness.session.getSessionActionRecoverySnapshot().actions).toEqual([]);
+ expect(queueUpdates.at(-1)).toEqual({ steering: [], followUp: [] });
hook.release();
await harness.session.waitForIdle();
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
expect(queueUpdates.at(-1)).toEqual({ steering: [], followUp: [] });
expect(getUserTexts(harness)).toEqual(["owned prompt"]);
});
+ it("hides queued trigger-turn actions from user-visible queue projections", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const internals = harness.session as unknown as { _scheduleSessionInputPump(): void };
+ const schedule = vi.spyOn(internals, "_scheduleSessionInputPump").mockImplementation(() => {});
+ await harness.session.followUp("visible queued prompt");
+ const hidden = harness.session.sendCustomMessage(
+ { customType: "hidden-trigger", content: "hidden queued prompt", display: false },
+ { triggerTurn: true },
+ );
+ const hiddenRejection = expect(hidden).rejects.toThrow("Prompt aborted before delivery.");
+
+ await vi.waitFor(() => expect(harness.session.getSessionActionRecoverySnapshot().actions).toHaveLength(2));
+ expect(harness.session.getFollowUpMessages()).toEqual(["visible queued prompt"]);
+ expect(harness.session.getFollowUpMessagePreviews()).toEqual(["visible queued prompt"]);
+ expect(harness.session.getSessionActionSnapshot()).toMatchObject({
+ queuedCount: 1,
+ steering: [],
+ followUps: ["visible queued prompt"],
+ });
+ expect(harness.session.queuedActionCount).toBe(1);
+ expect(harness.session.getSessionActionRecoverySnapshot().actions.map((action) => action.payload.text)).toEqual([
+ "visible queued prompt",
+ "hidden queued prompt",
+ ]);
+
+ harness.session.requestAbort();
+ expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: ["visible queued prompt"] });
+ schedule.mockRestore();
+ await hiddenRejection;
+ });
+
+ it("emits the running phase when a queued turn starts", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("done")]);
+ const phases: string[] = [];
+ harness.session.subscribe((event) => {
+ if (event.type === "session_action_update" && event.actions.active) {
+ phases.push(event.actions.active.phase);
+ }
+ });
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.followUp("phase probe", undefined, { resumeIfIdle: true });
+
+ pause.release();
+ await harness.session.waitForIdle();
+
+ expect(phases).toContain("running");
+ });
+
+ it("reports selected work when resuming after an abort", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const command = parseSessionSlashCommand("/autonomous status");
+ expect(command).toBeDefined();
+ const selected = createDeferred<void>();
+ const releaseSelection = createDeferred<void>();
+ const internals = harness.session as unknown as {
+ _executeSelectedSessionCommand(action: unknown, epoch?: number): Promise<void>;
+ };
+ internals._executeSelectedSessionCommand = async () => {
+ selected.resolve();
+ await releaseSelection.promise;
+ };
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.restoreFollowUpMessage(command!.text, undefined, {
+ customMessage: createSessionSlashCommandMessage(command!),
+ });
+
+ pause.release();
+ await selected.promise;
+ harness.session.requestAbort();
+ expect(harness.session.resumeQueuedWork()).toBe(true);
+ expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: [command!.text] });
+ releaseSelection.resolve();
+ await harness.session.waitForSessionInputIdle();
+ });
+
it("stops counting cleared preparing inputs as pending", async () => {
const hook = gatedHook({ prompt: "cleared prompt" });
const harness = await createHarness({ extensionFactories: [hook.factory] });
@@ -1373,10 +1450,10 @@ describe("AgentSession queue characterization", () => {
await harness.session.followUp("cleared prompt", undefined, { resumeIfIdle: true });
pause.release();
await hook.reached;
- expect(harness.session.pendingMessageCount).toBe(1);
+ expect(harness.session.queuedActionCount).toBe(0);
expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: ["cleared prompt"] });
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
expect(harness.session.getFollowUpMessagePreviews()).toEqual([]);
hook.release();
@@ -1618,7 +1695,7 @@ describe("AgentSession queue characterization", () => {
const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_queue_update_clear");
let cleared = false;
const unsubscribe = harness.session.subscribe((event) => {
- if (event.type === "queue_update" && !cleared) {
+ if (event.type === "session_action_update" && !cleared) {
cleared = true;
harness.session.clearQueue();
}
@@ -1756,12 +1833,12 @@ describe("AgentSession queue characterization", () => {
await firstProviderStarted.promise;
await new Promise<void>((resolve) => setImmediate(resolve));
- expect(harness.session.pendingMessageCount).toBe(1);
+ expect(harness.session.queuedActionCount).toBe(1);
expect(harness.session.getFollowUpMessages()).toEqual([prompt]);
firstResponse.resolve();
await harness.session.waitForIdle();
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
expect(harness.session.messages.filter((item) => item === message)).toHaveLength(2);
expect(getAssistantTexts(harness)).toEqual(["first done", "second done"]);
});
@@ -2114,8 +2191,7 @@ describe("AgentSession queue characterization", () => {
} else {
withStreaming(harness, false);
await prepared.promise;
- // Owned by the pump during preparation, still reported as pending.
- expect(harness.session.getFollowUpMessages()).toEqual(["accepted"]);
+ expect(harness.session.getFollowUpMessages()).toEqual([]);
}
await expect(
harness.session.restoreFollowUpMessage("duplicate", undefined, { queueKey: "same", agentMessageId: id }),
@@ -2257,6 +2333,100 @@ describe("AgentSession queue characterization", () => {
expect(harness.sessionManager.getLeafId()).not.toBe(secondId);
});
+ it("waitForIdle yields to timers while queued work is paused", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("done")]);
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.followUp("paused follow-up", undefined, { resumeIfIdle: true });
+ const originalWaitForIdle = harness.session.agent.waitForIdle.bind(harness.session.agent);
+ let waitCalls = 0;
+ vi.spyOn(harness.session.agent, "waitForIdle").mockImplementation(async () => {
+ if (++waitCalls > 100) throw new Error("waitForIdle spun without yielding");
+ await originalWaitForIdle();
+ });
+ const waiting = harness.session.waitForIdle().then(
+ () => ({ ok: true as const }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+
+ try {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ expect(waitCalls).toBeLessThan(100);
+ expect(harness.session.getFollowUpMessages()).toEqual(["paused follow-up"]);
+ } finally {
+ pause.release();
+ }
+ expect(await waiting).toEqual({ ok: true });
+ expect(getUserTexts(harness)).toEqual(["paused follow-up"]);
+ });
+
+ it("waitForIdle yields to timers while queued work is suspended after abort", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("done")]);
+ await harness.session.followUp("queued across abort");
+ harness.session.requestAbort();
+ expect(harness.session.getFollowUpMessages()).toEqual(["queued across abort"]);
+ const originalWaitForIdle = harness.session.agent.waitForIdle.bind(harness.session.agent);
+ let waitCalls = 0;
+ vi.spyOn(harness.session.agent, "waitForIdle").mockImplementation(async () => {
+ if (++waitCalls > 100) throw new Error("waitForIdle spun without yielding");
+ await originalWaitForIdle();
+ });
+ const waiting = harness.session.waitForIdle().then(
+ () => ({ ok: true as const }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+
+ try {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ expect(waitCalls).toBeLessThan(100);
+ } finally {
+ harness.session.resumeQueuedWork();
+ }
+ expect(await waiting).toEqual({ ok: true });
+ expect(getUserTexts(harness)).toEqual(["queued across abort"]);
+ });
+
+ it("waitForIdle resolves when the queue is cleared while the pump is suspended", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ await harness.session.followUp("cleared while suspended");
+ harness.session.requestAbort();
+ expect(harness.session.getFollowUpMessages()).toEqual(["cleared while suspended"]);
+ const waiting = harness.session.waitForIdle().then(
+ () => ({ ok: true as const }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ const cleared = harness.session.clearQueue();
+ expect(cleared.followUp).toEqual(["cleared while suspended"]);
+ const outcome = await Promise.race([
+ waiting,
+ new Promise<{ ok: false; error: Error }>((resolve) =>
+ setTimeout(() => resolve({ ok: false, error: new Error("waitForIdle hung after clearQueue") }), 500),
+ ),
+ ]);
+ expect(outcome).toEqual({ ok: true });
+ });
+
+ it("does not report a visible accepted prompt as accepted in flight", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ withStreaming(harness, true);
+
+ await harness.session.promptUntilAccepted("visible queued prompt", {
+ streamingBehavior: "followUp",
+ queueIfBusy: true,
+ });
+
+ expect(harness.session.getFollowUpMessages()).toEqual(["visible queued prompt"]);
+ expect(harness.session.hasAcceptedPromptInFlight).toBe(false);
+ harness.session.clearQueue();
+ withStreaming(harness, false);
+ });
+
it("waitForIdle observes a run that starts at its final idle boundary", async () => {
const responseGate = createDeferred();
const waitForResponseStart = createDeferred();
@@ -2354,7 +2524,7 @@ describe("AgentSession scheduler scenarios", () => {
if (event.type === "message_start" && event.message.role === "user") {
countsAtUserMessageStart.push({
text: getMessageText(event.message),
- pending: harness.session.pendingMessageCount,
+ pending: harness.session.queuedActionCount,
});
}
});
@@ -2421,7 +2591,7 @@ describe("AgentSession scheduler scenarios", () => {
// Phase 2: queued work stays in session queues, not Agent queues.
expect(harness.session.agent.hasQueuedMessages()).toBe(false);
- const pendingAfterQueueing = harness.session.pendingMessageCount;
+ const pendingAfterQueueing = harness.session.queuedActionCount;
expect(pendingAfterQueueing).toBeGreaterThan(0);
expect(harness.session.getFollowUpMessages()).toContain("f1");
expect(harness.session.getFollowUpMessages()).toContain("f2");
@@ -2461,7 +2631,7 @@ describe("AgentSession scheduler scenarios", () => {
expect(rows).toContain("custom:queue-test-follow-up");
// Phase 5: every queued input left the pending count before its message_start.
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
const queuedStarts = countsAtUserMessageStart.filter((entry) => entry.text !== "start");
expect(queuedStarts.length).toBeGreaterThan(0);
for (const entry of queuedStarts) {
@@ -2569,7 +2739,7 @@ describe("AgentSession scheduler scenarios", () => {
expect(continuationSawRemoved).toBe(false);
expect(getUserTexts(harness)).toEqual(["start", "keep me", spoofedPlain]);
expect(getAssistantTexts(harness)).toEqual(["", "continued clean", "keep me done", "spoof done"]);
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
});
it("S3: pause-lease preparation journey with anchor re-preparation and direct handoff", async () => {
@@ -2688,10 +2858,15 @@ describe("AgentSession scheduler scenarios", () => {
await harness.session.waitForSessionInputIdle();
expect(providerCalls).toBe(0);
expect(harness.session.getFollowUpMessages()).toEqual(["queued for restart", "/goal inspect image", agentPrompt]);
- expect(harness.session.getFollowUpQueueSnapshots()).toEqual([
- expect.objectContaining({ text: "queued for restart" }),
- expect.objectContaining({ text: "/goal inspect image", images: [image] }),
- expect.objectContaining({ text: agentPrompt, agentMessageId: "agentmsg_abort" }),
+ expect(harness.session.getSessionActionRecoverySnapshot().actions).toEqual([
+ expect.objectContaining({ payload: expect.objectContaining({ text: "queued for restart" }) }),
+ expect.objectContaining({
+ payload: expect.objectContaining({ text: "/goal inspect image", images: [image] }),
+ }),
+ expect.objectContaining({
+ agentMessageId: "agentmsg_abort",
+ payload: expect.objectContaining({ text: agentPrompt }),
+ }),
]);
expect(deliverySettled).toBe(false);
@@ -2752,7 +2927,7 @@ describe("AgentSession scheduler scenarios", () => {
await expect(delivery).resolves.toBeUndefined();
expect(getUserTexts(harness)).toContain("queued for restart");
expect(getUserTexts(harness)).toContain(agentPrompt);
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
});
it("S5: settles queued command delivery before gated completion and rejects completion on failure", async () => {
diff --git a/packages/coding-agent/test/suite/agent-session-retry-events.test.ts b/packages/coding-agent/test/suite/agent-session-retry-events.test.ts
index 7ee3dd8adb..6e08632645 100644
--- a/packages/coding-agent/test/suite/agent-session-retry-events.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-retry-events.test.ts
@@ -171,7 +171,7 @@ describe("AgentSession retry and event characterization", () => {
await expect(
harness.session.prompt("second", { queueIfBusy: true, streamingBehavior: "followUp" }),
).resolves.toBeUndefined();
- expect(harness.session.pendingMessageCount).toBe(1);
+ expect(harness.session.queuedActionCount).toBe(1);
});
it("does not retry when retry is disabled", async () => {
diff --git a/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts b/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts
index 77f5057465..f3409fb696 100644
--- a/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts
@@ -2375,7 +2375,7 @@ describe("P0 concurrency regressions", () => {
// Queue a follow-up via the public API (no resumeIfIdle flag).
// This populates both the session and Agent queues.
await harness.session.queueAgentMessagePrompt("queued follow-up", "followUp");
- expect(harness.session.pendingMessageCount).toBe(1);
+ expect(harness.session.queuedActionCount).toBe(1);
vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "plan", proposal: { edits: [] } });
vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());
@@ -2384,7 +2384,7 @@ describe("P0 concurrency regressions", () => {
// The forced resume should consume the follow-up and run the provider.
await vi.waitFor(() => {
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.queuedActionCount).toBe(0);
expect(harness.getPendingResponseCount()).toBe(0);
});
});
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.ts
index b770909774..436bcece7e 100644
--- 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.ts
@@ -1,8 +1,9 @@
import { readFileSync, writeFileSync } from "node:fs";
-import type { ImageContent, TextContent, UserMessage } from "@earendil-works/pi-ai";
+import type { ImageContent, TextContent } 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 { SessionActionRecoverySnapshot } from "../../../src/core/agent-session.js";
import type { AgentSessionRuntime } from "../../../src/core/agent-session-runtime.js";
import type { AgentCronJob, AgentCronJobStore, AgentCronScheduler } from "../../../src/core/cron-jobs.js";
import { type CustomMessage, createSessionSlashCommandMessage } from "../../../src/core/messages.js";
@@ -52,26 +53,6 @@ type AgentDaemonUpdateInternals = {
commitPreparedUpdateRestart(transactionId: symbol): Promise<DaemonUpdateRestartManifest>;
};
-type QueueInternals = {
- _compactionAbortController?: AbortController;
- _actionStore: {
- ownedActions(): Array<{
- agentMessageId?: string;
- lifecycle: { state: string; execution?: "agent_turn" | "session_command" };
- payload: {
- kind: string;
- queueVisible: boolean;
- records: Array<{
- role: "primary" | "prefix" | "next_turn";
- message: UserMessage | CustomMessage;
- started: boolean;
- durable: boolean;
- }>;
- };
- }>;
- };
-};
-
function createState(
harness: Harness,
activeSessionId: string,
@@ -257,17 +238,17 @@ describe("issue #4257 update restart resume", () => {
expect(manifest.sessions).toHaveLength(1);
expect(manifest.sessions[0]).toMatchObject({
- queue: { steering: [], nextTurn: [] },
+ queue: { nextTurn: [], actions: { formatVersion: 1 } },
shouldResume: true,
wasStreaming: false,
wasRetrying: false,
hadAcceptedPromptInFlight: false,
});
- expect(manifest.sessions[0]?.queue.followUp).toEqual([
- {
- message: "paused restart input",
- content: [{ type: "text", text: "paused restart input" }],
- },
+ expect(manifest.sessions[0]?.queue.actions.actions).toEqual([
+ expect.objectContaining({
+ delivery: "when_run_idle",
+ payload: expect.objectContaining({ kind: "turn", text: "paused restart input" }),
+ }),
]);
expect(
harness.sessionManager
@@ -346,6 +327,7 @@ describe("issue #4257 update restart resume", () => {
});
Reflect.set(internals, "mutationDrain", mutationDrain);
const checkpoint = vi.spyOn(internals, "prepareUpdateRestartCheckpoint").mockResolvedValue({
+ formatVersion: 1,
createdAt: "now",
sessions: [],
});
@@ -705,7 +687,7 @@ describe("issue #4257 update restart resume", () => {
idleGate.resolve();
await expect(checkpoint).resolves.toBeUndefined();
- expect(harness.session.getFollowUpQueueSnapshots().map((snapshot) => snapshot.text)).toEqual([
+ expect(harness.session.getSessionActionRecoverySnapshot().actions.map((action) => action.payload.text)).toEqual([
"paused before selection",
]);
pause.release();
@@ -815,42 +797,45 @@ describe("issue #4257 update restart resume", () => {
activeSessionId: "parent-active",
clientEnv: { PRIME_SESSION: "pane-1" },
runtimeMetadata: { kind: "top-level" },
- queue: {
- steering: [
- {
- message: "queued work",
- content,
- images: [image],
- prefixMessages: [queuedContext],
- queueKey: "heartbeat:steer",
- agentMessageId: "agentmsg_steer",
- },
- ],
- followUp: [
- {
- message: "heartbeat",
- content: followUpContent,
- prefixMessages: [followUpContext],
- queueKey: "heartbeat:job-1",
- agentMessageId: "agentmsg_followup",
- },
- {
- message: "custom heartbeat",
- queueKey: "heartbeat:custom",
- agentMessageId: "agentmsg_custom",
- customMessage: customFollowUp,
- },
- {
- message: "/autonomous on",
- customMessage: expect.objectContaining({
- customType: "session_slash_command",
- details: { command },
- }),
- },
- ],
- },
+ queue: { actions: { formatVersion: 1 }, nextTurn: [] },
shouldResume: true,
});
+ const recoveredActions = manifest.sessions[0]?.queue.actions.actions ?? [];
+ expect(recoveredActions.map((action) => action.payload.text)).toEqual([
+ "queued work",
+ "heartbeat",
+ "custom heartbeat",
+ "/autonomous on",
+ ]);
+ expect(recoveredActions).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ delivery: "next_turn_boundary",
+ wake: "on_lower_boundary",
+ queueKey: "heartbeat:steer",
+ agentMessageId: "agentmsg_steer",
+ payload: expect.objectContaining({ kind: "turn", text: "queued work", content, images: [image] }),
+ }),
+ expect.objectContaining({
+ delivery: "when_run_idle",
+ queueKey: "heartbeat:job-1",
+ agentMessageId: "agentmsg_followup",
+ payload: expect.objectContaining({ kind: "turn", text: "heartbeat", content: followUpContent }),
+ }),
+ expect.objectContaining({
+ queueKey: "heartbeat:custom",
+ agentMessageId: "agentmsg_custom",
+ payload: expect.objectContaining({
+ kind: "turn",
+ text: "custom heartbeat",
+ customMessage: customFollowUp,
+ }),
+ }),
+ expect.objectContaining({
+ payload: expect.objectContaining({ kind: "session_command", text: "/autonomous on", command }),
+ }),
+ ]),
+ );
expect(manifest.sessions[1]).toMatchObject({
activeSessionId: "child-active",
sessionFile: childHarness.session.sessionFile,
@@ -861,39 +846,26 @@ describe("issue #4257 update restart resume", () => {
parentSessionFile: parentHarness.session.sessionFile,
rlmChildId: "child-1",
},
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, 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 () => {
+ it("captures next-turn context and full queued actions 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 acceptedContent: TextContent[] = [
- { type: "text", text: "accepted prefix" },
- { type: "text", text: "accepted work" },
- ];
- const queueInternals = harness.session as unknown as QueueInternals;
- harness.session.restorePendingNextTurnMessages([acceptedNextTurn]);
- queueInternals._compactionAbortController = new AbortController();
- await harness.session.acceptAgentMessagePrompt("accepted work", {
- content: acceptedContent,
- agentMessageId: "agentmsg_accepted",
- expandPromptTemplates: false,
- queueIfBusy: true,
- streamingBehavior: "followUp",
+ const queuedContext = createCustomMessage("queued prompt context");
+ const content: TextContent[] = [{ type: "text", text: "queued work" }];
+ await harness.session.restoreFollowUpMessage("queued work", undefined, {
+ content,
+ agentMessageId: "agentmsg_queued",
+ queueKey: "recovery-key",
+ prefixMessages: [queuedContext],
});
- queueInternals._compactionAbortController = undefined;
- const acceptedAction = queueInternals._actionStore
- .ownedActions()
- .find((action) => action.agentMessageId === "agentmsg_accepted");
- if (!acceptedAction) throw new Error("Accepted action was not admitted");
- acceptedAction.payload.queueVisible = false;
harness.session.restorePendingNextTurnMessages([pendingNextTurn]);
const internals = createDaemonInternals(harness);
@@ -904,18 +876,24 @@ describe("issue #4257 update restart resume", () => {
const manifest = await internals.prepareUpdateRestart();
- expect(manifest.sessions).toHaveLength(1);
- expect(manifest.sessions[0]).toMatchObject({
- activeSessionId: "active-1",
- shouldResume: true,
- hadAcceptedPromptInFlight: true,
- });
+ expect(manifest.formatVersion).toBe(1);
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],
+ const recovered = manifest.sessions[0]?.queue.actions.actions[0];
+ expect(recovered).toMatchObject({
+ id: expect.any(String),
+ delivery: "when_run_idle",
+ wake: "external_resume",
+ queueKey: "recovery-key",
+ agentMessageId: "agentmsg_queued",
+ payload: {
+ kind: "turn",
+ text: "queued work",
+ content,
+ records: expect.arrayContaining([
+ expect.objectContaining({ role: "prefix", message: queuedContext, ownerActionId: recovered?.id }),
+ expect.objectContaining({ role: "primary", ownerActionId: recovered?.id }),
+ ]),
+ },
});
});
@@ -947,13 +925,12 @@ describe("issue #4257 update restart resume", () => {
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,
+ expect(session?.queue.actions.actions).toEqual([
+ expect.objectContaining({
queueKey: "heartbeat:job-1",
agentMessageId: "agentmsg_followup",
- },
+ payload: expect.objectContaining({ kind: "turn", text: "queued follow-up", content: followUpContent }),
+ }),
]);
expect(session?.shouldResume).toBe(true);
});
@@ -979,61 +956,43 @@ describe("issue #4257 update restart resume", () => {
expect(session).toMatchObject({
shouldResume: true,
wasStreaming: true,
- queue: { steering: [], followUp: [], nextTurn: [] },
+ queue: { actions: { formatVersion: 1, actions: [] }, 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 queueInternals = harness.session as unknown as QueueInternals;
- harness.session.restorePendingNextTurnMessages([acceptedNextTurn, deliveredAcceptedNextTurn]);
- queueInternals._compactionAbortController = new AbortController();
- await harness.session.acceptAgentMessagePrompt("accepted work", {
- agentMessageId: "agentmsg_accepted",
- expandPromptTemplates: false,
- queueIfBusy: true,
- streamingBehavior: "followUp",
- });
- queueInternals._compactionAbortController = undefined;
- const acceptedAction = queueInternals._actionStore
- .ownedActions()
- .find((action) => action.agentMessageId === "agentmsg_accepted");
- expect(acceptedAction?.payload.kind).toBe("turn");
- const primary = acceptedAction?.payload.records.find((record) => record.role === "primary");
- if (!acceptedAction || !primary) throw new Error("Accepted action was not admitted");
- primary.started = true;
- primary.durable = true;
- const deliveredContext = acceptedAction.payload.records.find(
- (record) => record.message.role === "custom" && record.message.content === "already delivered context",
- );
- if (!deliveredContext) throw new Error("Accepted context was not attached");
- deliveredContext.started = true;
- deliveredContext.durable = true;
- acceptedAction.payload.queueVisible = false;
- acceptedAction.lifecycle = { state: "running", execution: "agent_turn" };
- harness.session.restorePendingNextTurnMessages([pendingNextTurn]);
-
- const internals = createDaemonInternals(harness);
- internals.sessions.set(
- "active-1",
- createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
- );
-
- const manifest = await internals.prepareUpdateRestart();
+ it("restores queued actions through the public recovery API with stable ids and FIFO", async () => {
+ const source = await createHarness({ persistSession: true });
+ const target = await createHarness({ persistSession: true });
+ harnesses.push(source, target);
+ await source.session.restoreSteeringMessage("steering one");
+ await source.session.restoreSteeringMessage("steering two");
+ await source.session.restoreFollowUpMessage("follow-up one", undefined, { queueKey: "job-1" });
+
+ const snapshot = source.session.getSessionActionRecoverySnapshot();
+ await target.session.restoreSessionActions(snapshot);
+
+ expect(target.session.getSessionActionRecoverySnapshot()).toEqual(snapshot);
+ expect(target.session.getSteeringMessages()).toEqual(["steering one", "steering two"]);
+ expect(target.session.getFollowUpMessages()).toEqual(["follow-up one"]);
+ await expect(
+ target.session.restoreSessionActions({
+ formatVersion: 2,
+ actions: [],
+ } as unknown as SessionActionRecoverySnapshot),
+ ).rejects.toThrow("Unsupported session action recovery format version: 2");
+ });
- 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("rejects duplicate recovered action ids without partial admission", async () => {
+ const source = await createHarness({ persistSession: true });
+ const target = await createHarness({ persistSession: true });
+ harnesses.push(source, target);
+ await source.session.restoreFollowUpMessage("follow-up");
+ const action = source.session.getSessionActionRecoverySnapshot().actions[0]!;
+
+ await expect(
+ target.session.restoreSessionActions({ formatVersion: 1, actions: [action, action] }),
+ ).rejects.toThrow(`Duplicate session action id: ${action.id}`);
+ expect(target.session.getSessionActionRecoverySnapshot().actions).toEqual([]);
});
it("accepts restore_next_turn through daemon command parsing", async () => {
@@ -1188,21 +1147,22 @@ describe("issue #4257 update restart resume", () => {
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([
+ const recovery = harness.session.getSessionActionRecoverySnapshot().actions;
+ expect(recovery.filter((action) => action.delivery === "next_turn_boundary")).toEqual([
expect.objectContaining({
- text: "restored steer",
- content: restoredSteerContent,
- prefixMessages: [restoredPrefix],
queueKey: "heartbeat:steer",
agentMessageId: "agentmsg_restored_steer",
+ payload: expect.objectContaining({ kind: "turn", text: "restored steer", content: restoredSteerContent }),
}),
]);
- expect(harness.session.getFollowUpQueueSnapshots()).toEqual([
- expect.objectContaining({ text: "existing", agentMessageId: "agentmsg_existing" }),
+ expect(recovery.filter((action) => action.delivery === "when_run_idle")).toEqual([
+ expect.objectContaining({
+ agentMessageId: "agentmsg_existing",
+ payload: expect.objectContaining({ text: "existing" }),
+ }),
expect.objectContaining({
- text: "restored follow-up",
- content: restoredFollowUpContent,
agentMessageId: "agentmsg_restored_followup",
+ payload: expect.objectContaining({ text: "restored follow-up", content: restoredFollowUpContent }),
}),
]);
});
@@ -1280,8 +1240,7 @@ describe("issue #4257 update restart resume", () => {
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([]);
+ expect(harness.session.getSessionActionRecoverySnapshot().actions).toEqual([]);
});
it("drains restored queues when a continuation prompt resumes interrupted work", async () => {
@@ -1345,8 +1304,7 @@ describe("issue #4257 update restart resume", () => {
expect.objectContaining({ id: "prompt-1", command: "prompt", success: true }),
]);
expect(getUserTexts(harness)).toEqual(["restored steer", "restored follow-up", "continue interrupted work"]);
- expect(harness.session.getSteeringQueueSnapshots()).toEqual([]);
- expect(harness.session.getFollowUpQueueSnapshots()).toEqual([]);
+ expect(harness.session.getSessionActionRecoverySnapshot().actions).toEqual([]);
});
it("resumes restored queues after an update marker without prior transcript messages", async () => {
@@ -1395,7 +1353,7 @@ describe("issue #4257 update restart resume", () => {
expect.objectContaining({ id: "resume-1", command: "resume_queue", success: true }),
]);
expect(getUserTexts(harness)).toEqual(["restored follow-up"]);
- expect(harness.session.getFollowUpQueueSnapshots()).toEqual([]);
+ expect(harness.session.getSessionActionRecoverySnapshot().actions).toEqual([]);
});
it("adopts attach env after a fenced update preparation rolls back", async () => {
diff --git a/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts b/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts
index 95d4ee9af9..b4fe6b75c1 100644
--- a/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts
@@ -212,8 +212,8 @@ describe("ENG-4482 heartbeat injected prompt UI", () => {
let queuedPendingContextText = "";
const queueEvents: Array<{ steering: readonly string[]; followUp: readonly string[] }> = [];
harness.session.subscribe((event) => {
- if (event.type === "queue_update") {
- queueEvents.push({ steering: event.steering, followUp: event.followUp });
+ if (event.type === "session_action_update") {
+ queueEvents.push({ steering: event.actions.steering, followUp: event.actions.followUps });
}
});
harness.setResponses([
diff --git a/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts b/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts
index af90265b0c..2336b2eb9f 100644
--- a/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts
@@ -86,10 +86,16 @@ describe("ENG-4530 IPython state restore message", () => {
});
await harness.session.prompt("stop the heartbeat", { streamingBehavior: "followUp" });
- const [queued] = harness.session.getFollowUpQueueSnapshots();
- expect(queued?.content).toEqual([{ type: "text", text: "stop the heartbeat" }]);
- expect(queued?.prefixMessages).toHaveLength(1);
- expect(queued?.prefixMessages?.[0]).toMatchObject({
+ const [queued] = harness.session.getSessionActionRecoverySnapshot().actions;
+ expect(queued?.payload.kind === "turn" ? queued.payload.content : undefined).toEqual([
+ { type: "text", text: "stop the heartbeat" },
+ ]);
+ const prefixMessages =
+ queued?.payload.kind === "turn"
+ ? queued.payload.records.filter((record) => record.role === "prefix").map((record) => record.message)
+ : [];
+ expect(prefixMessages).toHaveLength(1);
+ expect(prefixMessages[0]).toMatchObject({
role: "custom",
customType: IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
display: true,
@@ -143,9 +149,11 @@ describe("ENG-4530 IPython state restore message", () => {
harness.session.resumeQueuedWork();
await harness.session.waitForSessionInputIdle();
- const [queued] = harness.session.getFollowUpQueueSnapshots();
- expect(queued).toMatchObject({ text: "queued prompt" });
- expect(queued?.prefixMessages).toBeUndefined();
+ const [queued] = harness.session.getSessionActionRecoverySnapshot().actions;
+ expect(queued?.payload).toMatchObject({ text: "queued prompt" });
+ expect(
+ queued?.payload.kind === "turn" ? queued.payload.records.filter((record) => record.role === "prefix") : [],
+ ).toEqual([]);
expect(harness.session.messages).toEqual([
expect.objectContaining({ customType: IPYTHON_STATE_RESTORED_CUSTOM_TYPE }),
]);
diff --git a/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts b/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts
index 47368d56e5..8e1a816420 100644
--- a/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts
@@ -139,7 +139,8 @@ describe("ENG-4531 agent message UI", () => {
await harness.session.queueAgentMessagePrompt(prompt, "followUp", message);
expect(harness.session.getFollowUpMessagePreviews()).toEqual(["Agent message received: Use shard seven."]);
- expect(harness.session.getFollowUpQueueSnapshots()[0]?.customMessage).toMatchObject({
+ const queued = harness.session.getSessionActionRecoverySnapshot().actions[0];
+ expect(queued?.payload.kind === "turn" ? queued.payload.customMessage : undefined).toMatchObject({
customType: "agent_message",
details: { id: "agentmsg_4531", message: "Use shard seven." },
});
@@ -271,7 +272,8 @@ describe("ENG-4531 agent message UI", () => {
queueIfBusy: true,
});
- expect(harness.session.getFollowUpQueueSnapshots()[0]?.customMessage).toMatchObject({
+ const queued = harness.session.getSessionActionRecoverySnapshot().actions[0];
+ expect(queued?.payload.kind === "turn" ? queued.payload.customMessage : undefined).toMatchObject({
customType: "agent_message",
details: { message: "Queue behind the active turn." },
});
diff --git a/packages/coding-agent/test/suite/regressions/4601-worker-snapshot-cache.test.ts b/packages/coding-agent/test/suite/regressions/4601-worker-snapshot-cache.test.ts
index 038bce7142..38423943a7 100644
--- a/packages/coding-agent/test/suite/regressions/4601-worker-snapshot-cache.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4601-worker-snapshot-cache.test.ts
@@ -57,13 +57,14 @@ function streamedResult(
activeSessionId: resultActiveSessionId,
lifecycle: "live",
activity: "idle",
+ isSessionActive: false,
sessionId: `session-${resultActiveSessionId}`,
cwd: "/tmp",
isStreaming: false,
isCompacting: false,
attachedClients: 0,
messageCount,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
},
state: {
activeSessionId: resultActiveSessionId,
diff --git a/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts b/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts
index 9f30c2caed..195274e758 100644
--- a/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts
@@ -52,13 +52,14 @@ function summary(): SessionSummary {
activeSessionId,
lifecycle: "live",
activity: "idle",
+ isSessionActive: false,
sessionId: "session-4602",
cwd: "/tmp",
isStreaming: false,
isCompacting: false,
attachedClients: 0,
messageCount: 1,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
};
}
@@ -382,6 +383,7 @@ describe("ENG-4602 snapshot transfer containment", () => {
summary: {
...frames.begin.snapshot.summary,
activity: "working" as const,
+ isSessionActive: true,
attachedClients: 2,
},
},
@@ -392,6 +394,7 @@ describe("ENG-4602 snapshot transfer containment", () => {
await new Promise<void>((resolve) => setImmediate(resolve));
expect(worker.snapshotCache.get(activeSessionId)?.snapshot.summary).toMatchObject({
activity: "working",
+ isSessionActive: true,
});
expect(streamSnapshot).toHaveBeenCalledOnce();
expect(close).not.toHaveBeenCalled();
diff --git a/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.ts b/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.ts
index 12b0987706..26ce76e1b5 100644
--- a/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4606-update-restart-coordinator.test.ts
@@ -113,6 +113,15 @@ async function waitForExit(child: ChildProcess, timeoutMs = 60_000): Promise<voi
});
}
+async function waitForProcessExit(pid: number, timeoutMs = 30_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (!isProcessAlive(pid)) return;
+ await delay(25);
+ }
+ throw new Error(`Timed out waiting for process ${pid} to exit`);
+}
+
async function waitForFile(path: string, timeoutMs = 30_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
@@ -431,5 +440,11 @@ describe("ENG-4606 update restart coordinator", () => {
const owners = listSupervisorOwnerRecords(paths.registryDir);
expect(owners).toHaveLength(1);
expect(owners[0]).toMatchObject({ pid: status.successor?.pid, socketPath: resolve(paths.socketPath) });
+ await stopDaemon(paths.socketPath);
+ sockets.delete(paths.socketPath);
+ if (replacementHello.supervisorPid === undefined) {
+ throw new Error("Replacement daemon did not report its supervisor PID");
+ }
+ await waitForProcessExit(replacementHello.supervisorPid);
}, 180_000);
});
diff --git a/packages/coding-agent/test/suite/regressions/4620-fast-mode-child-agents.test.ts b/packages/coding-agent/test/suite/regressions/4620-fast-mode-child-agents.test.ts
index 3ed0e9b9b4..9d26e8b1e2 100644
--- a/packages/coding-agent/test/suite/regressions/4620-fast-mode-child-agents.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4620-fast-mode-child-agents.test.ts
@@ -3,7 +3,11 @@ import { describe, expect, it, vi } from "vitest";
import { SessionManager } from "../../../src/core/session-manager.js";
import { startSideQuestion } from "../../../src/core/side-question.js";
import type { DaemonSocketClient } from "../../../src/modes/daemon/active-session-state.js";
-import type { DaemonCommand, DaemonResponse } from "../../../src/modes/daemon/daemon-protocol.js";
+import {
+ createDaemonCommandEnvelope,
+ type DaemonCommand,
+ type DaemonResponse,
+} from "../../../src/modes/daemon/daemon-protocol.js";
import { DaemonSupervisor } from "../../../src/modes/daemon/daemon-supervisor.js";
import { MutationDrainLatch } from "../../../src/modes/daemon/mutation-drain-latch.js";
import { createHarness } from "../harness.js";
@@ -36,6 +40,12 @@ describe("ENG-4620 fast mode child agents", () => {
clients: new Set(),
protocolClientIds: new WeakMap(),
mutationDrain: new MutationDrainLatch(),
+ commandJournal: {
+ lookup: vi.fn(() => undefined),
+ begin: vi.fn(() => ({ status: "new" })),
+ recordResult: vi.fn(),
+ acknowledge: vi.fn(),
+ },
handleCommand,
write,
log: vi.fn(),
@@ -48,7 +58,7 @@ describe("ENG-4620 fast mode child agents", () => {
serviceTier: "priority",
} satisfies DaemonCommand;
- await supervisor.handleLine(client, JSON.stringify(command));
+ await supervisor.handleLine(client, JSON.stringify(createDaemonCommandEnvelope(command, command.id)));
expect(handleCommand.mock.calls[0]?.slice(0, 2)).toEqual([client, command]);
expect(write).toHaveBeenCalledWith(
diff --git a/packages/coding-agent/test/suite/regressions/4653-queued-steer-after-agent-end.test.ts b/packages/coding-agent/test/suite/regressions/4653-queued-steer-after-agent-end.test.ts
index 47d4d6c656..faeda8ae78 100644
--- a/packages/coding-agent/test/suite/regressions/4653-queued-steer-after-agent-end.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4653-queued-steer-after-agent-end.test.ts
@@ -14,7 +14,7 @@ describe("ENG-4653 queued messages after agent end", () => {
async function waitForDelivery(harness: Harness, expectedCalls: number): Promise<void> {
await vi.waitFor(() => expect(harness.faux.state.callCount).toBe(expectedCalls));
await harness.session.agent.waitForIdle();
- await vi.waitFor(() => expect(harness.session.pendingMessageCount).toBe(0));
+ await vi.waitFor(() => expect(harness.session.queuedActionCount).toBe(0));
}
it("starts a new turn for steering queued from agent_end", async () => {
diff --git a/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts b/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts
index c0c0167900..0903122698 100644
--- a/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts
@@ -141,7 +141,7 @@ function createConnectionState(activeSessionId: string): AgentConnectionState {
leafId: `${activeSessionId}-leaf`,
autoCompactionEnabled: true,
messageCount: 1,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
compactionCount: 0,
goal: { active: false, status: "idle", tokensUsed: 0, timeUsedSeconds: 0, continuationsUsed: 0 },
scopedModels: [],
@@ -158,6 +158,7 @@ function createAttachResult(activeSessionId: string, messages: AgentMessage[] =
activeSessionId,
lifecycle: "live",
activity: "idle",
+ isSessionActive: false,
sessionId: state.sessionId,
sessionFile: state.sessionFile,
cwd: state.cwd,
@@ -165,7 +166,7 @@ function createAttachResult(activeSessionId: string, messages: AgentMessage[] =
isCompacting: false,
attachedClients: 1,
messageCount: messages.length,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
};
return {
protocol: DAEMON_PROTOCOL_INFO,
diff --git a/packages/coding-agent/test/suite/regressions/4677-snapshot-catchup-replacement.test.ts b/packages/coding-agent/test/suite/regressions/4677-snapshot-catchup-replacement.test.ts
index 695a211694..a988a6d741 100644
--- a/packages/coding-agent/test/suite/regressions/4677-snapshot-catchup-replacement.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4677-snapshot-catchup-replacement.test.ts
@@ -63,13 +63,14 @@ function summary(messageCount: number): SessionSummary {
activeSessionId,
lifecycle: "live",
activity: "idle",
+ isSessionActive: false,
sessionId: "session-4677",
cwd: "/tmp",
isStreaming: false,
isCompacting: false,
attachedClients: 0,
messageCount,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
};
}
diff --git a/packages/coding-agent/test/suite/regressions/502-unified-session-view.test.ts b/packages/coding-agent/test/suite/regressions/502-unified-session-view.test.ts
index efff0658ef..2e83c4ad0b 100644
--- a/packages/coding-agent/test/suite/regressions/502-unified-session-view.test.ts
+++ b/packages/coding-agent/test/suite/regressions/502-unified-session-view.test.ts
@@ -11,12 +11,13 @@ function summary(id: string): SessionSummary {
sessionId: `session-${id}`,
lifecycle: "live",
activity: "idle",
+ isSessionActive: false,
cwd: "/tmp/project",
isStreaming: false,
isCompacting: false,
attachedClients: 0,
messageCount: 1,
- pendingMessageCount: 0,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
};
}