Skip to content

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

Rust

feat: canonical session-input scheduling with durable, queueable commands (#540)

Sebastian Müller3fc0ac54fad7
diff --git a/packages/agent/src/agent-loop.ts b/packages/agent/src/agent-loop.ts
index c9d3ea70a0..aadffc8d7e 100644
--- a/packages/agent/src/agent-loop.ts
+++ b/packages/agent/src/agent-loop.ts
@@ -317,6 +317,8 @@ async function runLoop(
// Check for steering messages at start (user may have typed while waiting)
let pendingMessages: AgentMessage[] = await pollMessagesUnlessAborted(config.getSteeringMessages, signal);
+ const shouldStopBeforeTurn = (): boolean => !firstTurn && (config.shouldStopBeforeTurn?.() ?? false);
+
// Outer loop: continues when queued follow-up messages arrive after agent would stop
while (true) {
throwIfAborted(signal);
@@ -396,7 +398,7 @@ async function runLoop(
await emit({ type: "agent_end", messages: newMessages });
return;
}
- if (shouldStopResult.value) {
+ if (shouldStopResult.value || shouldStopBeforeTurn()) {
await emit({ type: "agent_end", messages: newMessages });
return;
}
@@ -410,9 +412,15 @@ async function runLoop(
return;
}
pendingMessages = steeringMessagesResult.value;
+ // Steering drained by this poll owns the turn boundary; stop only when it was empty.
+ if (pendingMessages.length === 0 && shouldStopBeforeTurn()) {
+ await emit({ type: "agent_end", messages: newMessages });
+ return;
+ }
}
// Agent would stop here. Check for follow-up messages.
+ if (shouldStopBeforeTurn()) break;
const followUpMessagesResult = await settlePostTurn(
pollMessagesUnlessAborted(config.getFollowUpMessages, signal),
signal,
@@ -428,6 +436,7 @@ async function runLoop(
continue;
}
+ if (shouldStopBeforeTurn()) break;
const continuationMessagesResult = lastTurn
? await settlePostTurn(
maybePromiseWithAbort(config.getContinuationMessages?.(lastTurn, signal) ?? [], signal),
diff --git a/packages/agent/src/agent.ts b/packages/agent/src/agent.ts
index 55f28e678d..56609d38ac 100644
--- a/packages/agent/src/agent.ts
+++ b/packages/agent/src/agent.ts
@@ -106,6 +106,7 @@ export interface AgentOptions {
beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
+ shouldStopBeforeTurn?: () => boolean;
getContinuationMessages?: (context: GetContinuationMessagesContext, signal?: AbortSignal) => Promise<AgentMessage[]>;
steeringMode?: QueueMode;
followUpMode?: QueueMode;
@@ -199,6 +200,7 @@ export class Agent {
signal?: AbortSignal,
) => Promise<AfterToolCallResult | undefined>;
public shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
+ public shouldStopBeforeTurn?: () => boolean;
public getContinuationMessages?: (
context: GetContinuationMessagesContext,
signal?: AbortSignal,
@@ -226,6 +228,7 @@ export class Agent {
this.beforeToolCall = options.beforeToolCall;
this.afterToolCall = options.afterToolCall;
this.shouldStopAfterTurn = options.shouldStopAfterTurn;
+ this.shouldStopBeforeTurn = options.shouldStopBeforeTurn;
this.getContinuationMessages = options.getContinuationMessages;
this.steeringQueue = new PendingMessageQueue(options.steeringMode ?? "one-at-a-time");
this.followUpQueue = new PendingMessageQueue(options.followUpMode ?? "one-at-a-time");
@@ -481,6 +484,7 @@ export class Agent {
beforeToolCall: this.beforeToolCall,
afterToolCall: this.afterToolCall,
shouldStopAfterTurn: async (context) => this.shouldStopAfterTurn?.(context) ?? false,
+ shouldStopBeforeTurn: () => this.shouldStopBeforeTurn?.() ?? false,
convertToLlm: this.convertToLlm,
transformContext: this.transformContext,
getApiKey: this.getApiKey,
diff --git a/packages/agent/src/types.ts b/packages/agent/src/types.ts
index 51ada71f42..a6788e6574 100644
--- a/packages/agent/src/types.ts
+++ b/packages/agent/src/types.ts
@@ -191,6 +191,15 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
*/
shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
+ /**
+ * Called synchronously after a completed turn and before polling work for another turn.
+ * Return true to emit `agent_end` without starting another provider call. Work returned by
+ * an asynchronous poll owns that boundary; queue owners must suppress stale continuation
+ * results if their higher-level stop condition changes while generating them.
+ * The hook is never checked before the initial assistant turn.
+ */
+ shouldStopBeforeTurn?: () => boolean;
+
/**
* Returns steering messages to inject into the conversation mid-run.
*
diff --git a/packages/agent/test/agent-loop.test.ts b/packages/agent/test/agent-loop.test.ts
index 2410a7770b..1b3ca26377 100644
--- a/packages/agent/test/agent-loop.test.ts
+++ b/packages/agent/test/agent-loop.test.ts
@@ -1336,6 +1336,241 @@ describe("agentLoop with AgentMessage", () => {
expect(parallelObserved).toBe(true);
});
+ const naturalCompletionCases: Array<{
+ name: string;
+ stopBefore: "always" | "afterTurn" | "never";
+ steerOnce?: boolean;
+ naturalWork?: boolean;
+ expected: { llmCalls: number; stopChecks?: number; steeringPolls?: number; naturalPolls?: number };
+ }> = [
+ {
+ name: "stops only after completing the initial turn",
+ stopBefore: "always",
+ expected: { llmCalls: 1, stopChecks: 1 },
+ },
+ {
+ name: "observes a stop requested after the turn before polling steering",
+ stopBefore: "afterTurn",
+ expected: { llmCalls: 1, steeringPolls: 1 },
+ },
+ {
+ name: "stops before polling natural-completion work",
+ stopBefore: "always",
+ naturalWork: true,
+ expected: { llmCalls: 1, naturalPolls: 0 },
+ },
+ {
+ name: "continues with steering when no stop is requested",
+ stopBefore: "never",
+ steerOnce: true,
+ expected: { llmCalls: 2 },
+ },
+ ];
+
+ it.each(naturalCompletionCases)("$name", async ({ stopBefore, steerOnce, naturalWork, expected }) => {
+ let llmCalls = 0;
+ let stopRequested = false;
+ let steeringDelivered = false;
+ const shouldStopBeforeTurn = vi.fn(() => stopBefore === "always" || stopRequested);
+ const getSteeringMessages = vi.fn(async () => {
+ if (steerOnce && llmCalls === 1 && !steeringDelivered) {
+ steeringDelivered = true;
+ return [createUserMessage("steer")];
+ }
+ return [];
+ });
+ const getFollowUpMessages = vi.fn(async () => (naturalWork ? [createUserMessage("follow up")] : []));
+ const getContinuationMessages = vi.fn(async () => (naturalWork ? [createUserMessage("continue")] : []));
+ const stream = agentLoop(
+ [createUserMessage("start")],
+ { systemPrompt: "", messages: [], tools: [] },
+ {
+ model: createModel(),
+ convertToLlm: identityConverter,
+ shouldStopBeforeTurn,
+ getSteeringMessages,
+ getFollowUpMessages,
+ getContinuationMessages,
+ ...(stopBefore === "afterTurn" && {
+ shouldStopAfterTurn: async () => {
+ await Promise.resolve();
+ stopRequested = true;
+ return false;
+ },
+ }),
+ },
+ undefined,
+ () => {
+ llmCalls++;
+ const mockStream = new MockAssistantStream();
+ queueMicrotask(() =>
+ mockStream.push({
+ type: "done",
+ reason: "stop",
+ message: createAssistantMessage([{ type: "text", text: "done" }]),
+ }),
+ );
+ return mockStream;
+ },
+ );
+ for await (const _event of stream) {
+ // Drain the stream.
+ }
+
+ expect(llmCalls).toBe(expected.llmCalls);
+ if (expected.stopChecks !== undefined) expect(shouldStopBeforeTurn).toHaveBeenCalledTimes(expected.stopChecks);
+ if (expected.steeringPolls !== undefined)
+ expect(getSteeringMessages).toHaveBeenCalledTimes(expected.steeringPolls);
+ if (expected.naturalPolls !== undefined) {
+ expect(getFollowUpMessages).toHaveBeenCalledTimes(expected.naturalPolls);
+ expect(getContinuationMessages).toHaveBeenCalledTimes(expected.naturalPolls);
+ }
+ });
+
+ it("rechecks a tool-cycle stop after polling steering", async () => {
+ const execute = vi.fn(async () => ({ content: [{ type: "text" as const, text: "done" }], details: {} }));
+ let stopRequested = false;
+ let llmCalls = 0;
+ const stream = agentLoop(
+ [createUserMessage("start")],
+ {
+ systemPrompt: "",
+ messages: [],
+ tools: [{ name: "work", label: "Work", description: "Work", parameters: Type.Object({}), execute }],
+ },
+ {
+ model: createModel(),
+ convertToLlm: identityConverter,
+ shouldStopBeforeTurn: () => stopRequested,
+ getSteeringMessages: async () => {
+ // Flip only on the post-tool-batch poll; the pre-loop poll would stop before the recheck runs.
+ if (llmCalls > 0) stopRequested = true;
+ return [];
+ },
+ },
+ undefined,
+ () => {
+ llmCalls++;
+ const mockStream = new MockAssistantStream();
+ queueMicrotask(() =>
+ mockStream.push({
+ type: "done",
+ reason: "toolUse",
+ message: createAssistantMessage(
+ [{ type: "toolCall", id: "tool-1", name: "work", arguments: {} }],
+ "toolUse",
+ ),
+ }),
+ );
+ return mockStream;
+ },
+ );
+ for await (const _event of stream) {
+ // Drain the stream.
+ }
+ expect(llmCalls).toBe(1);
+ });
+
+ it("injects steering drained by the poll even when a stop flips during it", async () => {
+ const execute = vi.fn(async () => ({ content: [{ type: "text" as const, text: "done" }], details: {} }));
+ let stopRequested = false;
+ const injected: string[] = [];
+ let llmCalls = 0;
+ const stream = agentLoop(
+ [createUserMessage("start")],
+ {
+ systemPrompt: "",
+ messages: [],
+ tools: [{ name: "work", label: "Work", description: "Work", parameters: Type.Object({}), execute }],
+ },
+ {
+ model: createModel(),
+ convertToLlm: identityConverter,
+ shouldStopBeforeTurn: () => stopRequested,
+ getSteeringMessages: async () => {
+ // Only the post-tool-batch poll returns steering; the stop flips during it.
+ if (llmCalls !== 1 || stopRequested) return [];
+ stopRequested = true;
+ return [createUserMessage("late steer")];
+ },
+ },
+ undefined,
+ () => {
+ llmCalls++;
+ const mockStream = new MockAssistantStream();
+ const calls = llmCalls;
+ queueMicrotask(() =>
+ mockStream.push({
+ type: "done",
+ reason: calls === 1 ? "toolUse" : "stop",
+ message:
+ calls === 1
+ ? createAssistantMessage(
+ [{ type: "toolCall", id: "tool-1", name: "work", arguments: {} }],
+ "toolUse",
+ )
+ : createAssistantMessage([{ type: "text", text: "steered reply" }], "stop"),
+ }),
+ );
+ return mockStream;
+ },
+ );
+ for await (const event of stream) {
+ if (event.type === "message_end" && event.message.role === "user") {
+ const text = event.message.content;
+ if (typeof text !== "string") continue;
+ injected.push(text);
+ }
+ }
+ expect(injected).toContain("late steer");
+ expect(llmCalls).toBe(2);
+ });
+
+ it("checks shouldStopBeforeTurn after a tool batch and before another model call", async () => {
+ const execute = vi.fn(async () => ({ content: [{ type: "text" as const, text: "done" }], details: {} }));
+ const context: AgentContext = {
+ systemPrompt: "",
+ messages: [],
+ tools: [
+ {
+ name: "work",
+ label: "Work",
+ description: "Work",
+ parameters: Type.Object({}),
+ execute,
+ },
+ ],
+ };
+ let llmCalls = 0;
+ const stream = agentLoop(
+ [createUserMessage("start")],
+ context,
+ { model: createModel(), convertToLlm: identityConverter, shouldStopBeforeTurn: () => true },
+ undefined,
+ () => {
+ llmCalls++;
+ const mockStream = new MockAssistantStream();
+ queueMicrotask(() =>
+ mockStream.push({
+ type: "done",
+ reason: "toolUse",
+ message: createAssistantMessage(
+ [{ type: "toolCall", id: "tool-1", name: "work", arguments: {} }],
+ "toolUse",
+ ),
+ }),
+ );
+ return mockStream;
+ },
+ );
+ for await (const _event of stream) {
+ // Drain the stream.
+ }
+
+ expect(execute).toHaveBeenCalledOnce();
+ expect(llmCalls).toBe(1);
+ });
+
it("should stop after the current turn when shouldStopAfterTurn returns true", async () => {
const toolSchema = Type.Object({ value: Type.String() });
const executed: string[] = [];
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index d7a5a59a86..63e92d3677 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -15,6 +15,7 @@
- Removed the bundled orchestration heartbeat skill from the model system prompt.
- Fixed feature hints crowding queued messages and side questions by placing them below the recap and hiding them while messages are queued ([ENG-4741](https://linear.app/primeintellect/issue/ENG-4741/recap-queuefollow-upmessage-hint-looks-cluttered)).
- Fixed `/btw` truncating long answers by rendering side questions in the scrollable transcript.
+- Unified prompt, steering, follow-up, and session-command scheduling under session-owned admission with durable queue state and coordinated update/restart checkpoints.
- Changed selection cursors from `→` to `›` across model selectors, scoped-models, and the theme default for consistency with tree and user-message selectors.
- Changed the queued follow-up hint connector from `↳` to `╰─` to match the tool-execution continuation connector.
- Changed `/context` tree connectors from `├ `/`└ ` to `├─ `/`└─ ` to match the tree selector and session picker.
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index b7e35abb31..0da3e2f11a 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -170,11 +170,17 @@ import { type RestoreResult, snapshotPathIn } from "./kernel/state-snapshot.js";
import type { McpManager } from "./mcp/mcp-manager.js";
import {
type BashExecutionMessage,
+ type CompactionOutcome,
+ type CompactionOutcomeReason,
type CustomMessage,
+ createCompactionOutcomeMessage,
createHeartbeatPromptMessage,
+ createSessionSlashCommandMessage,
+ createSessionSlashCommandResultMessage,
HEARTBEAT_PROMPT_CUSTOM_TYPE,
HEARTBEAT_PROMPT_PREVIEW_LABEL,
IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
+ isSessionSlashCommandMessage,
} from "./messages.js";
import type { ModelRegistry } from "./model-registry.js";
import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.js";
@@ -232,7 +238,12 @@ import {
import type { SessionStats } from "./session-stats.js";
import type { SettingsManager } from "./settings-manager.js";
import { getPythonSkillRuntimeInfo, type Skill } from "./skills.js";
-import type { SlashCommandInfo } from "./slash-commands.js";
+import {
+ parseRefineCommandOptions,
+ parseSessionSlashCommand,
+ type SessionSlashCommand,
+ type SlashCommandInfo,
+} from "./slash-commands.js";
import { createSyntheticSourceInfo, type SourceInfo } from "./source-info.js";
import { type BuildSystemPromptOptions, buildSystemPrompt } from "./system-prompt.js";
import { type BashOperations, createLocalBashOperations } from "./tools/bash.js";
@@ -494,12 +505,18 @@ export interface PromptOptions {
preflightResult?: (success: boolean, queued?: boolean) => void;
/** Queue instead of starting immediately when the session is idle but already has queued work. */
queueIfBusy?: boolean;
+ /** Start queued work when no agent turn is currently running. */
+ resumeIfIdle?: boolean;
/** Host-generated prompt that must bypass extension/slash/template input interception. */
internalPrompt?: boolean;
/** Prevent host-driven prompts from causing autonomous continuation injection. */
suppressAutonomousContinuation?: boolean;
/** Skip extension input handlers for replaying already-accepted input. */
skipInputHandlers?: boolean;
+ /** Cancel this prompt while it is waiting for direct-turn admission. */
+ signal?: AbortSignal;
+ /** Internal host hook fired at the direct-turn ownership commit point. */
+ admissionCommitted?: () => void;
agentMessageId?: string;
content?: (TextContent | ImageContent)[];
customMessage?: CustomMessage;
@@ -509,29 +526,92 @@ interface InternalPromptOptions extends PromptOptions {
skipPrePromptWork?: boolean;
returnAfterAccepted?: boolean;
agentMessageId?: string;
- resumeIfIdle?: boolean;
}
type QueuedAgentMessage = UserMessage | CustomMessage;
+type SessionInputSchedule = "steer" | "followUp";
-interface QueuedSteeringMessage {
+interface PreparedPromptInput {
+ kind: "prompt";
text: string;
+ images?: ImageContent[];
+ content?: (TextContent | ImageContent)[];
+ customMessage?: CustomMessage;
previewLabel?: string;
queueKey?: string;
agentMessageId?: string;
prefixMessages: CustomMessage[];
+ suppressAutonomousContinuation?: boolean;
+ autoPump: boolean;
+ preparation?: PreparedPromptPreparation;
message: QueuedAgentMessage;
}
-interface QueuedFollowUpMessage {
+interface PreparedPromptPreparation {
+ result: Awaited<ReturnType<ExtensionRunner["emitBeforeAgentStart"]>>;
+ /** Base system prompt captured at emitBeforeAgentStart, for stale-base refresh at handoff. */
+ basePromptSnapshot: string;
+}
+
+class DeferredSessionInputError extends Error {}
+
+/** Wrap a preflight callback so only the first report wins. */
+function oncePreflight(
+ preflightResult: ((success: boolean, queued?: boolean) => void) | undefined,
+): (success: boolean, queued?: boolean) => void {
+ let settled = false;
+ return (success, queued = false) => {
+ if (!settled) {
+ settled = true;
+ preflightResult?.(success, queued);
+ }
+ };
+}
+
+function throwIfPromptAdmissionCancelled(signal: AbortSignal | undefined): void {
+ if (signal?.aborted) throw new Error("Prompt admission was cancelled.");
+}
+
+export function waitForPromptAdmission<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
+ if (!signal) return promise;
+ if (signal.aborted) {
+ void promise.catch(() => {});
+ throwIfPromptAdmissionCancelled(signal);
+ }
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => {
+ cleanup();
+ reject(new Error("Prompt admission was cancelled."));
+ };
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
+ signal.addEventListener("abort", onAbort, { once: true });
+ // Close the listener-registration race before observing the awaited work.
+ if (signal.aborted) return onAbort();
+ promise.then(
+ (value) => {
+ cleanup();
+ resolve(value);
+ },
+ (error: unknown) => {
+ cleanup();
+ reject(error);
+ },
+ );
+ });
+}
+
+interface PreparedCommandInput {
+ kind: "command";
text: string;
- previewLabel?: string;
- queueKey?: string;
+ command: SessionSlashCommand;
+ images?: ImageContent[];
+ queueKey?: undefined;
agentMessageId?: string;
- prefixMessages: CustomMessage[];
- message: QueuedAgentMessage;
+ message?: undefined;
}
+type QueuedSessionInput = PreparedPromptInput | PreparedCommandInput;
+
export interface QueuedAgentInputSnapshot {
text: string;
content?: (TextContent | ImageContent)[];
@@ -569,17 +649,27 @@ function createQueuedAgentInputSnapshotFromUserMessage(
return { text, content, ...(images.length > 0 ? { images } : {}) };
}
-function createQueuedAgentInputSnapshot(
- message: QueuedSteeringMessage | QueuedFollowUpMessage,
-): QueuedAgentInputSnapshot {
- const snapshot = createQueuedAgentInputSnapshotFromUserMessage(message.text, message.message);
+function createQueuedAgentInputSnapshot(message: QueuedSessionInput): QueuedAgentInputSnapshot {
+ if (message.kind === "command") {
+ return {
+ text: message.text,
+ ...(message.images ? { images: message.images.map((image) => ({ ...image })) } : {}),
+ ...(message.agentMessageId ? { agentMessageId: message.agentMessageId } : {}),
+ customMessage: createSessionSlashCommandMessage(message.command),
+ };
+ }
+ const legacySnapshot = createQueuedAgentInputSnapshotFromUserMessage(message.text, message.message);
return {
- ...snapshot,
+ ...legacySnapshot,
+ text: message.text,
+ ...(message.content ? { content: message.content.map((block) => ({ ...block })) } : {}),
+ ...(message.images ? { images: message.images.map((image) => ({ ...image })) } : {}),
+ ...(message.customMessage ? { customMessage: cloneCustomMessage(message.customMessage) } : {}),
...(message.prefixMessages.length > 0
? { prefixMessages: message.prefixMessages.map((prefix) => cloneCustomMessage(prefix)) }
: {}),
...(message.agentMessageId ? { agentMessageId: message.agentMessageId } : {}),
- ...("queueKey" in message && message.queueKey ? { queueKey: message.queueKey } : {}),
+ ...(message.queueKey ? { queueKey: message.queueKey } : {}),
};
}
@@ -587,9 +677,25 @@ function queuedMessagePreview(message: { text: string; previewLabel?: string }):
return message.previewLabel ? `${message.previewLabel}: ${message.text}` : message.text;
}
-function queuedAgentMessagePreview(message: QueuedSteeringMessage | QueuedFollowUpMessage): string {
- if (isAgentSessionMessage(message.message)) {
- return `${AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL}: ${message.message.details.message}`;
+function normalizeMessageContent(content: string | (TextContent | ImageContent)[]): {
+ text: string;
+ images?: ImageContent[];
+} {
+ if (typeof content === "string") return { text: content };
+ const text = content
+ .filter((part): part is TextContent => part.type === "text")
+ .map((part) => part.text)
+ .join("\n");
+ const images = content.filter((part): part is ImageContent => part.type === "image");
+ return { text, ...(images.length > 0 ? { images } : {}) };
+}
+
+function queuedAgentMessagePreview(message: QueuedSessionInput): string {
+ if (message.kind === "command") {
+ return message.text;
+ }
+ if (message.customMessage && isAgentSessionMessage(message.customMessage)) {
+ return `${AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL}: ${message.customMessage.details.message}`;
}
return queuedMessagePreview(message);
}
@@ -682,12 +788,31 @@ function undeliveredPendingNextTurnMessages(accepted: AcceptedAgentMessagePrompt
return accepted.pendingNextTurnMessages.filter((message) => !accepted.deliveredPendingNextTurnMessages.has(message));
}
-interface AgentMessageDeliveryWaiter {
+interface AgentMessageDeferred {
promise: Promise<void>;
resolve: () => void;
reject: (error: Error) => void;
}
+/**
+ * Per-agent-message settlement record: `delivery` settles when the prompt reaches agent state,
+ * `completion` when its turn (or command) finishes. Settled deferreds are removed immediately.
+ */
+interface AgentMessageOutcome {
+ delivery?: AgentMessageDeferred;
+ completion?: AgentMessageDeferred;
+}
+
+function createAgentMessageDeferred(): AgentMessageDeferred {
+ const deferred = {} as AgentMessageDeferred;
+ deferred.promise = new Promise<void>((resolve, reject) => {
+ deferred.resolve = resolve;
+ deferred.reject = reject;
+ });
+ deferred.promise.catch(() => undefined);
+ return deferred;
+}
+
/** Result from cycleModel() */
export interface ModelCycleResult {
model: Model<any>;
@@ -825,6 +950,35 @@ function readAssistantText(message: AssistantMessage): string {
.join("");
}
+function waitForPromiseOrAbort<T>(
+ promise: Promise<T>,
+ signal: AbortSignal | undefined,
+ abortMessage: string,
+): Promise<T> {
+ if (!signal) return promise;
+ if (signal.aborted) return Promise.reject(new Error(abortMessage));
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => {
+ cleanup();
+ reject(new Error(abortMessage));
+ };
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
+ signal.addEventListener("abort", onAbort, { once: true });
+ // Close the listener-registration race before observing the awaited work.
+ if (signal.aborted) return onAbort();
+ promise.then(
+ (value) => {
+ cleanup();
+ resolve(value);
+ },
+ (error: unknown) => {
+ cleanup();
+ reject(error);
+ },
+ );
+ });
+}
+
function attributeChildUsage(parentUsage: Usage, childUsage: Usage): void {
const parentContextTokens =
parentUsage.totalTokens ||
@@ -852,14 +1006,38 @@ export class AgentSession {
private _unsubscribeAgent?: () => void;
private _eventListeners: AgentSessionEventListener[] = [];
private _agentEventQueue: Promise<void> = Promise.resolve();
- private _pendingMessageResumeQueue: Promise<void> = Promise.resolve();
- private _pendingMessageResumeEpoch = 0;
- private _pendingMessageResumeRequested = false;
-
- /** Tracks pending steering messages for UI display. Removed when delivered. */
- private _steeringMessages: QueuedSteeringMessage[] = [];
- /** Tracks pending follow-up messages for UI display. Removed when delivered. */
- private _followUpMessages: QueuedFollowUpMessage[] = [];
+
+ /** Session-owned typed queues. Items are never fed into Agent.steer/followUp. */
+ private _steeringMessages: QueuedSessionInput[] = [];
+ private _followUpMessages: QueuedSessionInput[] = [];
+ private _sessionInputPump: Promise<void> = Promise.resolve();
+ private _sessionInputPumpRequested = false;
+ private _sessionInputPumpEpoch = 0;
+ private _sessionInputArrivalEpoch = 0;
+ private _sessionInputPumpSuspended = false;
+ private readonly _queuedWorkPauses = new Set<symbol>();
+ private readonly _queuedWorkAdmissionWaiters = new Set<() => void>();
+ private _turnAdmissionTail: Promise<void> = Promise.resolve();
+ private _turnAdmissionOwner: symbol | undefined;
+ private readonly _turnAdmissionContext = new AsyncLocalStorage<symbol>();
+ private _legacyQueuedWorkPause: { release(): void } | undefined;
+ private _pumpingSessionInput = false;
+ private _activeSessionInput:
+ | {
+ kind: "prompt";
+ lane: SessionInputSchedule;
+ items: PreparedPromptInput[];
+ phase: "preparing" | "handedOff";
+ cancelled?: boolean;
+ }
+ | { kind: "command"; lane: SessionInputSchedule; item: PreparedCommandInput; phase: "executing" }
+ | undefined;
+ private readonly _sessionInputCheckpointWaiters = new Set<() => void>();
+ /** Direct prompts between admission and agent handoff; restart checkpoints wait for zero. */
+ private _directPromptSectionCount = 0;
+ /** One-shot waiters resolved when a dispatched message reaches message_start. */
+ private _directDispatchObservers = new Set<{ message: AgentMessage; resolve: () => void }>();
+ private _steeringStopPending = false;
/** Messages queued to be included with the next user prompt as context ("asides"). */
private _pendingNextTurnMessages: CustomMessage[] = [];
@@ -875,7 +1053,8 @@ export class AgentSession {
private _compactionAbortController: AbortController | undefined = undefined;
private _autoCompactionAbortController: AbortController | undefined = undefined;
private _compactionOperation: Promise<void> | undefined = undefined;
- private _overflowRecoveryAttempted = false;
+ /** One recovery attempt per overflow; "reported" dedups the failure notice. */
+ private _overflowRecovery: "idle" | "attempted" | "reported" = "idle";
private _continueAfterThresholdCompaction = false;
private _pendingRequestedCompaction: { customInstructions?: string } | undefined;
private _pendingRequestedRefine: { instructions?: string; global?: boolean } | undefined;
@@ -892,10 +1071,10 @@ export class AgentSession {
private _retryAuthFailureSources: AuthSourceToken[] = [];
private _acceptedPromptCompletions = new Set<Promise<void>>();
private _acceptedAgentMessagePrompt: AcceptedAgentMessagePrompt | undefined = undefined;
- private _agentMessageDeliveryWaiters = new Map<string, AgentMessageDeliveryWaiter>();
- private _deliveredAgentMessageIds = new Set<string>();
- private _failedAgentMessageDeliveries = new Map<string, Error>();
+ private _agentMessageOutcomes = new Map<string, AgentMessageOutcome>();
private _lateIpythonSentAgentMessages = new Map<string, KernelSentAgentMessage[]>();
+ /** Outcome disclosures whose session-file append failed; retained for context rebuilds. */
+ private readonly _unpersistedCompactionOutcomes: CustomMessage[] = [];
// Bash execution state
private _bashAbortController: AbortController | undefined = undefined;
@@ -988,6 +1167,7 @@ export class AgentSession {
private _postCompactionContinuationScheduled = false;
private _postCompactionContinuationTimer: ReturnType<typeof setTimeout> | undefined;
private _postCompactionContinuationMessages: AgentMessage[] = [];
+ private _scheduledPostCompactionContinuationMessages: AgentMessage[] = [];
private _queuedAutonomousThresholdContinuations = new WeakMap<AssistantMessage, AgentMessage>();
private _queuedAutonomousContinuationSnapshots = new WeakMap<AgentMessage, AutonomousRuntimeSnapshot>();
private _pendingThresholdCompactionAutonomousMessages: AgentMessage[] = [];
@@ -1183,6 +1363,7 @@ export class AgentSession {
}
private _installAgentTurnHook(): void {
+ this.agent.shouldStopBeforeTurn = () => this._shouldStopBeforeTurn();
this.agent.shouldStopAfterTurn = (context) => this._shouldStopAfterTurn(context);
}
@@ -1203,13 +1384,10 @@ export class AgentSession {
}
private _emitQueueUpdate(): void {
- if (this.pendingMessageCount === 0) {
- this._pendingMessageResumeRequested = false;
- }
this._emit({
type: "queue_update",
- steering: this._steeringMessages.map(queuedAgentMessagePreview),
- followUp: this._followUpMessages.map(queuedAgentMessagePreview),
+ steering: this._pendingSessionInputs("steer").map(queuedAgentMessagePreview),
+ followUp: this._pendingSessionInputs("followUp").map(queuedAgentMessagePreview),
});
}
@@ -1367,6 +1545,13 @@ export class AgentSession {
this.agent.removeQueuedMessages(
(message) => message.role === "custom" && message.customType === GOAL_CONTEXT_CUSTOM_TYPE,
);
+ const isGoalContext = (input: QueuedSessionInput) =>
+ input.kind === "prompt" && input.customMessage?.customType === GOAL_CONTEXT_CUSTOM_TYPE;
+ this._removeActivePreparingPrompts(isGoalContext);
+ this._steeringMessages = this._steeringMessages.filter((input) => !isGoalContext(input));
+ this._followUpMessages = this._followUpMessages.filter((input) => !isGoalContext(input));
+ this._syncSteeringStopPending();
+ this._emitQueueUpdate();
}
private _startGoal(objectiveText: string, tokenBudget: number | undefined): GoalState {
@@ -1481,11 +1666,10 @@ export class AgentSession {
}
private _parseGoalSlashCommand(text: string): GoalSlashCommand | undefined {
- if (text !== "/goal" && !text.startsWith("/goal ")) {
- return undefined;
- }
+ const command = parseSessionSlashCommand(text);
+ if (command?.name !== "goal") return undefined;
- const rest = text.slice("/goal".length).trim();
+ const rest = command.args;
const normalized = rest.toLowerCase();
if (!rest || normalized === "status") {
return { kind: "status" };
@@ -1530,10 +1714,9 @@ export class AgentSession {
}
private _parseAutonomousSlashCommand(text: string): AutonomousSlashCommand | undefined {
- if (text !== "/autonomous" && !text.startsWith("/autonomous ")) {
- return undefined;
- }
- const rest = text.slice("/autonomous".length).trim().toLowerCase();
+ const command = parseSessionSlashCommand(text);
+ if (command?.name !== "autonomous") return undefined;
+ const rest = command.args.toLowerCase();
if (!rest || rest === "status") {
return { kind: "status" };
}
@@ -1587,6 +1770,24 @@ export class AgentSession {
return true;
}
+ /** Append custom messages returned by before_agent_start extension handlers. */
+ private _appendBeforeAgentStartMessages(
+ messages: AgentMessage[],
+ result: Awaited<ReturnType<ExtensionRunner["emitBeforeAgentStart"]>>,
+ ): void {
+ if (!result?.messages) return;
+ for (const message of result.messages) {
+ messages.push({
+ role: "custom",
+ customType: message.customType,
+ content: message.content,
+ display: message.display,
+ details: message.details,
+ timestamp: Date.now(),
+ });
+ }
+ }
+
private async _validateCanStartAgentRun(): Promise<void> {
if (!this.model) {
throw new Error(formatNoModelSelectedMessage());
@@ -1636,14 +1837,29 @@ export class AgentSession {
}
this._ensureGoalRuntimeActive();
const message = createGoalContextMessage(this._goalState, kind, images);
- if (this.isStreaming) {
+ if (this._pumpingSessionInput) {
+ const normalized = normalizeMessageContent(message.content);
if (kind === "budget_limit") {
- this.agent.steer(message);
+ await this._queuePreparedPrompt("steer", normalized.text, normalized.images, {
+ message,
+ resumeIfIdle: true,
+ });
} else {
- this.agent.followUp(message);
+ const input = this._createPreparedPromptInput(normalized.text, normalized.images, {
+ message,
+ resumeIfIdle: true,
+ });
+ this._followUpMessages.unshift(input);
+ this._sessionInputArrivalEpoch++;
+ this._emitQueueUpdate();
}
return;
}
+ if (this.isStreaming) {
+ if (kind === "budget_limit") this.agent.steer(message);
+ else this.agent.followUp(message);
+ return;
+ }
await this._validateCanStartAgentRun();
// Wait immediately before the handoff so a refine starting during the
@@ -1730,13 +1946,32 @@ export class AgentSession {
return true;
}
+ private _syncSteeringStopPending(): void {
+ const activeSteeringHandoff =
+ this._activeSessionInput?.kind === "prompt" &&
+ this._activeSessionInput.lane === "steer" &&
+ this._activeSessionInput.phase === "preparing" &&
+ !this._activeSessionInput.cancelled &&
+ this._activeSessionInput.items.length > 0;
+ this._steeringStopPending = this._steeringMessages.length > 0 || activeSteeringHandoff;
+ }
+
+ private _shouldStopBeforeTurn(): boolean {
+ return this._steeringStopPending;
+ }
+
private async _shouldStopAfterTurn(context: ShouldStopAfterTurnContext): Promise<boolean> {
if (this._stopGoalContinuationForTerminalMessage(context.message)) {
return true;
}
try {
if (this._accountGoalUsageForAssistantMessage(context.message)) {
- this.agent.steer(createGoalContextMessage(this._goalState, "budget_limit"));
+ const message = createGoalContextMessage(this._goalState, "budget_limit");
+ const normalized = normalizeMessageContent(message.content);
+ await this._queuePreparedPrompt("steer", normalized.text, normalized.images, {
+ message,
+ resumeIfIdle: true,
+ });
}
} catch {
// Goal accounting must not interrupt the core agent loop.
@@ -1756,7 +1991,9 @@ export class AgentSession {
if (await this._shouldStopForThresholdCompaction(context)) {
return true;
}
- return false;
+ // Steering stops continuation only after mandatory serialized checkpoints.
+ // Returning true here still prevents the agent loop from starting another turn.
+ return this._steeringStopPending;
}
private async _shouldStopForThresholdCompaction(context: ShouldStopAfterTurnContext): Promise<boolean> {
@@ -2030,7 +2267,7 @@ export class AgentSession {
if (this._refineInFlight === applySettled) {
this._refineInFlight = undefined;
}
- this._schedulePendingMessageResume();
+ this._scheduleSessionInputPump();
}
}
@@ -2191,7 +2428,7 @@ export class AgentSession {
if (this._refineAbortController === refineAbort) {
this._refineAbortController = undefined;
}
- this._schedulePendingMessageResume();
+ this._scheduleSessionInputPump();
throw error;
} finally {
if (this._refinePlanInFlight === planSettled) {
@@ -2203,7 +2440,7 @@ export class AgentSession {
if (this._refineAbortController === refineAbort) {
this._refineAbortController = undefined;
}
- this._schedulePendingMessageResume();
+ this._scheduleSessionInputPump();
return;
}
@@ -2221,7 +2458,7 @@ export class AgentSession {
if (this._refineInFlight === applySettled) {
this._refineInFlight = undefined;
}
- this._schedulePendingMessageResume();
+ this._scheduleSessionInputPump();
}
}
@@ -2277,6 +2514,7 @@ export class AgentSession {
return queuedMessage;
}
const snapshot = this._snapshotAutonomousRuntimeState();
+ const arrivalEpoch = this._sessionInputArrivalEpoch;
const autonomousMessage = await nextAutonomousContinuation(this._autonomousState, message, {
cwd: this._cwd,
signal: this.agent.signal,
@@ -2284,11 +2522,22 @@ export class AgentSession {
if (!autonomousMessage) {
return undefined;
}
+ if (this._sessionInputArrivalEpoch !== arrivalEpoch) {
+ this._restoreAutonomousRuntimeSnapshot(snapshot);
+ return undefined;
+ }
this._queuedAutonomousThresholdContinuations.set(message, autonomousMessage);
this._queuedAutonomousContinuationSnapshots.set(autonomousMessage, snapshot);
this._postCompactionContinuationMessages.push(autonomousMessage);
this._pendingThresholdCompactionAutonomousMessages.push(autonomousMessage);
- this.agent.followUp(autonomousMessage);
+ const text =
+ typeof autonomousMessage.content === "string"
+ ? autonomousMessage.content
+ : autonomousMessage.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
+ this._enqueueSessionInput(
+ this._createPreparedPromptInput(text, undefined, { message: autonomousMessage }),
+ "followUp",
+ );
return autonomousMessage;
}
@@ -2308,6 +2557,12 @@ export class AgentSession {
(message) => !queuedMessageSet.has(message),
);
this.agent.removeQueuedMessages((message) => queuedMessageSet.has(message));
+ const isQueuedContinuation = (input: QueuedSessionInput) =>
+ input.kind === "prompt" && queuedMessageSet.has(input.message);
+ this._steeringMessages = this._steeringMessages.filter((input) => !isQueuedContinuation(input));
+ this._followUpMessages = this._followUpMessages.filter((input) => !isQueuedContinuation(input));
+ this._syncSteeringStopPending();
+ this._emitQueueUpdate();
if (options.restoreAutonomousState) {
for (const queuedMessage of queuedMessages) {
const snapshot = this._queuedAutonomousContinuationSnapshots.get(queuedMessage);
@@ -2326,7 +2581,7 @@ export class AgentSession {
if (options.messages === undefined) {
this._continueAfterThresholdCompaction = false;
}
- if (!this.agent.hasQueuedMessages()) {
+ if (!this.agent.hasQueuedMessages() && this.pendingMessageCount === 0) {
this._cancelPostCompactionContinue();
}
}
@@ -2713,8 +2968,19 @@ export class AgentSession {
context: GetContinuationMessagesContext,
signal?: AbortSignal,
): Promise<AgentMessage[]> {
+ if (this.pendingMessageCount > 0) {
+ return [];
+ }
+ const arrivalEpoch = this._sessionInputArrivalEpoch;
+ const goalSnapshot = this._goalState;
+ const goalAccountingStartedAt = this._goalAccountingStartedAt;
const goalMessages = await this._getGoalContinuationMessages(context, signal);
if (goalMessages.length > 0 || signal?.aborted) {
+ if (goalMessages.length > 0 && this._sessionInputArrivalEpoch !== arrivalEpoch) {
+ this._setGoalState(goalSnapshot);
+ this._goalAccountingStartedAt = goalAccountingStartedAt;
+ return [];
+ }
return goalMessages;
}
if (
@@ -2723,69 +2989,70 @@ export class AgentSession {
) {
return [];
}
+ const autonomousSnapshot = this._snapshotAutonomousRuntimeState();
const autonomousMessage = await nextAutonomousContinuation(this._autonomousState, context.message, {
cwd: this._cwd,
signal,
});
+ if (autonomousMessage && this._sessionInputArrivalEpoch !== arrivalEpoch) {
+ this._restoreAutonomousRuntimeSnapshot(autonomousSnapshot);
+ return [];
+ }
return autonomousMessage ? [autonomousMessage] : [];
}
// Track last assistant message for auto-compaction check
private _lastAssistantMessage: AssistantMessage | undefined = undefined;
+ private _agentMessageOutcome(agentMessageId: string): AgentMessageOutcome {
+ let outcome = this._agentMessageOutcomes.get(agentMessageId);
+ if (!outcome) {
+ outcome = {};
+ this._agentMessageOutcomes.set(agentMessageId, outcome);
+ }
+ return outcome;
+ }
+
+ /**
+ * Register a delivery waiter before submitting the prompt. Delivery outcomes are not retained
+ * for late lookup, so callers that register after admission may wait for a future use of the id.
+ */
waitForAgentMessagePromptDelivery(agentMessageId: string): Promise<void> {
- if (this._deliveredAgentMessageIds.has(agentMessageId)) {
- return Promise.resolve();
- }
- const failedDelivery = this._failedAgentMessageDeliveries.get(agentMessageId);
- if (failedDelivery) {
- return Promise.reject(failedDelivery);
- }
- let waiter = this._agentMessageDeliveryWaiters.get(agentMessageId);
- if (waiter) {
- return waiter.promise;
- }
- let resolveDelivery = () => {};
- let rejectDelivery = (_error: Error) => {};
- const promise = new Promise<void>((resolve, reject) => {
- resolveDelivery = resolve;
- rejectDelivery = reject;
- });
- waiter = { promise, resolve: resolveDelivery, reject: rejectDelivery };
- this._agentMessageDeliveryWaiters.set(agentMessageId, waiter);
- void promise
- .finally(() => {
- if (this._agentMessageDeliveryWaiters.get(agentMessageId) === waiter) {
- this._agentMessageDeliveryWaiters.delete(agentMessageId);
- }
- })
- .catch(() => undefined);
- return promise;
+ const outcome = this._agentMessageOutcome(agentMessageId);
+ outcome.delivery ??= createAgentMessageDeferred();
+ return outcome.delivery.promise;
}
- private _resolveAgentMessageDelivery(agentMessageId: string | undefined): void {
- if (agentMessageId === undefined) {
- return;
+ /** Resolve (no error) or reject an existing leg of an agent message outcome. */
+ private _settleAgentMessage(
+ agentMessageId: string | undefined,
+ leg: "delivery" | "completion",
+ error?: Error,
+ ): void {
+ if (agentMessageId === undefined) return;
+ const outcome = this._agentMessageOutcomes.get(agentMessageId);
+ if (!outcome) return;
+ const deferred = outcome[leg];
+ if (!deferred) return;
+ outcome[leg] = undefined;
+ if (!outcome.delivery && !outcome.completion) {
+ this._agentMessageOutcomes.delete(agentMessageId);
}
- this._failedAgentMessageDeliveries.delete(agentMessageId);
- this._deliveredAgentMessageIds.add(agentMessageId);
- this._agentMessageDeliveryWaiters.get(agentMessageId)?.resolve();
+ if (error) deferred.reject(error);
+ else deferred.resolve();
}
- private _rejectAgentMessageDelivery(agentMessageId: string | undefined, error: Error): void {
- if (agentMessageId === undefined || this._deliveredAgentMessageIds.has(agentMessageId)) {
- return;
- }
- this._failedAgentMessageDeliveries.set(agentMessageId, error);
- this._agentMessageDeliveryWaiters.get(agentMessageId)?.reject(error);
+ /** Reject both currently registered legs of an agent message outcome. */
+ private _rejectAgentMessage(agentMessageId: string | undefined, error: Error): void {
+ if (agentMessageId === undefined) return;
+ this._settleAgentMessage(agentMessageId, "delivery", error);
+ this._settleAgentMessage(agentMessageId, "completion", error);
}
- private _rejectQueuedAgentMessageDeliveries(error: Error): void {
- for (const message of this._steeringMessages) {
- this._rejectAgentMessageDelivery(message.agentMessageId, error);
- }
- for (const message of this._followUpMessages) {
- this._rejectAgentMessageDelivery(message.agentMessageId, error);
+ private _rejectQueuedAgentMessageDeliveries(deliveryError: Error, completionError = deliveryError): void {
+ for (const message of [...this._steeringMessages, ...this._followUpMessages]) {
+ this._settleAgentMessage(message.agentMessageId, "delivery", deliveryError);
+ this._settleAgentMessage(message.agentMessageId, "completion", completionError);
}
}
@@ -2798,10 +3065,23 @@ export class AgentSession {
// and waitForRetry() can miss the in-flight retry.
this._createRetryPromiseForAgentEnd(event);
const acceptedPrompt = this._acceptedAgentMessagePrompt;
- if (event.type === "message_start" && acceptedPrompt?.message === event.message && !acceptedPrompt.cleared) {
- acceptedPrompt.turnStarted = true;
- this._resolveAgentMessageDelivery(acceptedPrompt.agentMessageId);
- acceptedPrompt.resolveAccepted();
+ if (event.type === "message_start") {
+ if (acceptedPrompt?.message === event.message && !acceptedPrompt.cleared) {
+ acceptedPrompt.turnStarted = true;
+ this._settleAgentMessage(acceptedPrompt.agentMessageId, "delivery");
+ acceptedPrompt.resolveAccepted();
+ }
+ const activeInput =
+ this._activeSessionInput?.kind === "prompt"
+ ? this._activeSessionInput.items.find((input) => input.message === event.message)
+ : undefined;
+ this._settleAgentMessage(activeInput?.agentMessageId, "delivery");
+ for (const observer of this._directDispatchObservers) {
+ if (observer.message === event.message) {
+ this._directDispatchObservers.delete(observer);
+ observer.resolve();
+ }
+ }
}
this._agentEventQueue = this._agentEventQueue.then(
() => this._processAgentEvent(event),
@@ -2909,24 +3189,8 @@ export class AgentSession {
this._resolveRetry();
}
- // Remove queued messages before emitting so the UI sees the updated queue.
- if (event.type === "message_start") {
- if (this._isPromptTurnStartMessage(event.message)) {
- this._overflowRecoveryAttempted = false;
- }
- const steeringIndex = this._steeringMessages.findIndex((message) => message.message === event.message);
- if (steeringIndex !== -1) {
- const [removed] = this._steeringMessages.splice(steeringIndex, 1);
- this._resolveAgentMessageDelivery(removed?.agentMessageId);
- this._emitQueueUpdate();
- } else {
- const followUpIndex = this._followUpMessages.findIndex((message) => message.message === event.message);
- if (followUpIndex !== -1) {
- const [removed] = this._followUpMessages.splice(followUpIndex, 1);
- this._resolveAgentMessageDelivery(removed?.agentMessageId);
- this._emitQueueUpdate();
- }
- }
+ if (event.type === "message_start" && this._isPromptTurnStartMessage(event.message)) {
+ this._overflowRecovery = "idle";
}
// Emit to extensions first
@@ -2986,7 +3250,7 @@ export class AgentSession {
this._maybeStartSerializedBackgroundPlan();
}
if (assistantMsg.stopReason !== "error") {
- this._overflowRecoveryAttempted = false;
+ this._overflowRecovery = "idle";
}
if (this._isConcreteProviderAuthFailure(assistantMsg)) {
this._captureRetryAuthFailureSource(assistantMsg);
@@ -3004,7 +3268,12 @@ export class AgentSession {
this._retryAuthFailureSources = [];
}
if (this._accountGoalUsageForAssistantMessage(assistantMsg)) {
- this.agent.steer(createGoalContextMessage(this._goalState, "budget_limit"));
+ const message = createGoalContextMessage(this._goalState, "budget_limit");
+ const normalized = normalizeMessageContent(message.content);
+ await this._queuePreparedPrompt("steer", normalized.text, normalized.images, {
+ message,
+ resumeIfIdle: true,
+ });
}
}
}
@@ -3073,7 +3342,7 @@ export class AgentSession {
this._retryResolve();
this._retryResolve = undefined;
this._retryPromise = undefined;
- this._schedulePendingMessageResume();
+ this._scheduleSessionInputPump();
}
}
@@ -3246,6 +3515,7 @@ export class AgentSession {
return;
}
this._disposing = true;
+ this._wakeQueuedWorkAdmissionWaiters();
await this._disposeAsyncOnce();
})();
return this._disposeAsyncPromise;
@@ -3413,6 +3683,7 @@ export class AgentSession {
return;
}
this._disposed = true;
+ this._wakeQueuedWorkAdmissionWaiters();
try {
// Invalidate scheduled timers and abort any in-flight review so a late
// resolution cannot write harness state or re-subscribe handlers.
@@ -3439,9 +3710,16 @@ export class AgentSession {
this._deletedRlmChildIds.clear();
this._retryableRlmSubagentDeletions.clear();
this._pendingNextTurnMessages = [];
- this._rejectQueuedAgentMessageDeliveries(new Error("Queued agent message was cleared before delivery."));
+ const deliveryError = new Error("Session disposed before prompt delivery.");
+ const completionError = new Error("Session disposed before prompt completion.");
+ this._rejectQueuedAgentMessageDeliveries(deliveryError, completionError);
+ for (const [agentMessageId, outcome] of this._agentMessageOutcomes) {
+ if (outcome.delivery) this._settleAgentMessage(agentMessageId, "delivery", deliveryError);
+ if (outcome.completion) this._settleAgentMessage(agentMessageId, "completion", completionError);
+ }
this._steeringMessages = [];
this._followUpMessages = [];
+ this._syncSteeringStopPending();
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().",
@@ -3578,9 +3856,24 @@ export class AgentSession {
for (const message of context.messages) {
this._applyLateIpythonSentAgentMessages(message);
}
+ this._mergeUnpersistedCompactionOutcomes(context.messages);
return context;
}
+ /**
+ * Merge disclosures whose session-file append failed into a rebuilt message
+ * list at their timestamp position, where they appeared live.
+ */
+ private _mergeUnpersistedCompactionOutcomes(messages: AgentMessage[]): void {
+ for (const outcome of this._unpersistedCompactionOutcomes) {
+ let insertAt = messages.length;
+ while (insertAt > 0 && messages[insertAt - 1]!.timestamp > outcome.timestamp) {
+ insertAt -= 1;
+ }
+ messages.splice(insertAt, 0, outcome);
+ }
+ }
+
/** Current steering mode */
get steeringMode(): "all" | "one-at-a-time" {
return this.agent.steeringMode;
@@ -3740,6 +4033,28 @@ export class AgentSession {
return this._prompt(text, options);
}
+ /** Resolve once the session has accepted ownership, before queued or active execution completes. */
+ async promptUntilAccepted(text: string, options?: PromptOptions): Promise<void> {
+ return this._prompt(text, { ...options, returnAfterAccepted: true });
+ }
+
+ async promptAndWait(text: string, options?: PromptOptions): Promise<void> {
+ const agentMessageId = options?.agentMessageId ?? `prompt-wait:${randomUUID()}`;
+ if (this._agentMessageOutcomes.get(agentMessageId)?.completion) {
+ throw new Error(`Prompt completion id is already in use: ${agentMessageId}`);
+ }
+ const outcome = this._agentMessageOutcome(agentMessageId);
+ outcome.completion = createAgentMessageDeferred();
+ const completion = outcome.completion.promise;
+ try {
+ await this.promptUntilAccepted(text, { ...options, agentMessageId });
+ await completion;
+ } catch (error) {
+ this._settleAgentMessage(agentMessageId, "completion", this._asError(error));
+ throw error;
+ }
+ }
+
async acceptAgentMessagePrompt(text: string, options?: PromptOptions): Promise<void> {
const customMessage =
options?.customMessage && isAgentSessionMessage(options.customMessage) ? options.customMessage : undefined;
@@ -3761,10 +4076,10 @@ export class AgentSession {
): Promise<boolean> {
const agentMessageId = customMessage?.details.id ?? parseAgentSessionMessagePromptId(text);
if (streamingBehavior === "steer") {
- await this._queueSteer(text, undefined, { agentMessageId, message: customMessage });
+ await this._queuePreparedPrompt("steer", text, undefined, { agentMessageId, message: customMessage });
return true;
}
- return this._queueFollowUp(text, undefined, { agentMessageId, message: customMessage });
+ return this._queuePreparedPrompt("followUp", text, undefined, { agentMessageId, message: customMessage });
}
async promptHeartbeat(job: AgentCronJob, options?: PromptOptions): Promise<void> {
@@ -3776,18 +4091,66 @@ export class AgentSession {
});
}
+ private _observeDirectDispatch(message: AgentMessage): {
+ observed: Promise<true>;
+ wasObserved(): boolean;
+ stop(): void;
+ } {
+ let fired = false;
+ let observer!: { message: AgentMessage; resolve: () => void };
+ const observed = new Promise<true>((resolve) => {
+ observer = {
+ message,
+ resolve: () => {
+ fired = true;
+ resolve(true);
+ },
+ };
+ });
+ this._directDispatchObservers.add(observer);
+ return {
+ observed,
+ wasObserved: () => fired,
+ stop: () => this._directDispatchObservers.delete(observer),
+ };
+ }
+
private async _promptInjectedMessage(
text: string,
message: CustomMessage,
options?: InternalPromptOptions,
): Promise<void> {
- const preflightResult = options?.preflightResult;
- let preflightSettled = false;
- const reportPreflight = (success: boolean, queued = false) => {
- if (!preflightSettled) {
- preflightSettled = true;
- preflightResult?.(success, queued);
- }
+ if (!this.isStreaming && options?.resumeIfIdle) this._sessionInputPumpSuspended = false;
+ const admission = await this._acquireDirectTurnAdmission({
+ allowStreaming: true,
+ allowPendingQueue: options?.queueIfBusy === true,
+ signal: options?.signal,
+ });
+ try {
+ // Ownership commits before destructive preflight, but cancellation and the
+ // commit callback are covered by release if either throws.
+ throwIfPromptAdmissionCancelled(options?.signal);
+ options?.admissionCommitted?.();
+ await this._turnAdmissionContext.run(admission.owner, () =>
+ this._promptInjectedMessageUnserialized(text, message, options, admission.release),
+ );
+ } finally {
+ admission.release();
+ this._scheduleSessionInputPump();
+ }
+ }
+
+ private async _promptInjectedMessageUnserialized(
+ text: string,
+ message: CustomMessage,
+ options: InternalPromptOptions | undefined,
+ releaseAdmission: () => void,
+ ): Promise<void> {
+ const endDirectPromptSection = this._enterDirectPromptSection();
+ const reportInput = oncePreflight(options?.preflightResult);
+ const reportPreflight: typeof reportInput = (success, queued) => {
+ endDirectPromptSection();
+ reportInput(success, queued);
};
let messages: AgentMessage[] | undefined;
@@ -3797,13 +4160,7 @@ export class AgentSession {
let basePromptSnapshot: string | undefined;
try {
const shouldQueueForStreaming = this.isStreaming;
- const shouldQueueForPendingWork =
- options?.queueIfBusy === true &&
- (this.pendingMessageCount > 0 ||
- this.isCompacting ||
- this.isRetrying ||
- this.isBashRunning ||
- this.hasAcceptedPromptInFlight);
+ const shouldQueueForPendingWork = options?.queueIfBusy === true && this._isBusyForSessionInput("preflight");
if (shouldQueueForStreaming || shouldQueueForPendingWork) {
if (!options?.streamingBehavior) {
const stateDescription = shouldQueueForStreaming
@@ -3813,37 +4170,20 @@ export class AgentSession {
`${stateDescription}. Specify streamingBehavior ('steer' or 'followUp') to queue the message.`,
);
}
- const queued = await this._queueInjectedMessageWithPendingNextTurnMessages(
- text,
+ await this._queueWithPendingNextTurnMessages(text, options.streamingBehavior, reportPreflight, {
message,
- options.streamingBehavior,
- {
- queueKey: options.followUpQueueKey,
- previewLabel,
- suppressAutonomousContinuation: options.suppressAutonomousContinuation,
- resumeIfIdle: options.resumeIfIdle,
- },
- );
- if (!queued) {
- reportPreflight(false);
- return;
- }
- reportPreflight(true, true);
+ queueKey: options.followUpQueueKey,
+ previewLabel,
+ suppressAutonomousContinuation: options.suppressAutonomousContinuation,
+ resumeIfIdle: options.resumeIfIdle,
+ });
+
return;
}
await this._waitForRefineIdle();
this._flushPendingBashMessages();
- if (!this.model) {
- throw new Error(formatNoModelSelectedMessage());
- }
- if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
- const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
- if (isOAuth) {
- throw new Error(formatAuthenticationFailedMessage(this.model.provider));
- }
- throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
- }
+ await this._validateCanStartAgentRun();
const lastAssistant = this._findLastAssistantMessage();
if (lastAssistant) {
@@ -3866,18 +4206,7 @@ export class AgentSession {
basePromptSnapshot,
this._baseSystemPromptOptions,
);
- if (extensionResult?.messages) {
- for (const msg of extensionResult.messages) {
- messages.push({
- role: "custom",
- customType: msg.customType,
- content: msg.content,
- display: msg.display,
- details: msg.details,
- timestamp: Date.now(),
- });
- }
- }
+ this._appendBeforeAgentStartMessages(messages, extensionResult);
this.agent.state.systemPrompt =
extensionResult?.systemPrompt !== undefined
? this._refreshExtensionSystemPrompt(extensionResult.systemPrompt, basePromptSnapshot)
@@ -3888,6 +4217,7 @@ export class AgentSession {
}
if (!messages) {
+ endDirectPromptSection();
return;
}
@@ -3902,70 +4232,114 @@ export class AgentSession {
this.agent.state.systemPrompt = this._baseSystemPrompt;
}
}
- const shouldQueueAtHandoff =
- options?.queueIfBusy === true &&
- (this.isStreaming ||
- this.pendingMessageCount > 0 ||
- this.isCompacting ||
- this.isRetrying ||
- this.isBashRunning ||
- this._acceptedPromptCompletions.size > 0 ||
- this._acceptedAgentMessagePrompt !== undefined);
+ const shouldQueueAtHandoff = options?.queueIfBusy === true && this._isBusyForSessionInput("handoff");
if (shouldQueueAtHandoff) {
+ this._pendingNextTurnMessages.unshift(...drainedNextTurnMessages.map((pending) => ({ ...pending })));
if (!options?.streamingBehavior) {
- this._pendingNextTurnMessages.unshift(...drainedNextTurnMessages.map((pending) => ({ ...pending })));
reportPreflight(false);
throw new Error(
"Agent became busy before prompt delivery. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
);
}
- this._pendingNextTurnMessages.unshift(...drainedNextTurnMessages.map((pending) => ({ ...pending })));
- const queued = await this._queueInjectedMessageWithPendingNextTurnMessages(
- text,
- message,
- options.streamingBehavior,
- {
+ try {
+ await this._queueWithPendingNextTurnMessages(text, options.streamingBehavior, reportPreflight, {
+ message,
queueKey: options.followUpQueueKey,
previewLabel,
suppressAutonomousContinuation: options.suppressAutonomousContinuation,
resumeIfIdle: options.resumeIfIdle,
- },
- );
- if (!queued) {
+ });
+ } catch (error) {
+ // A failed enqueue must still settle the preflight outcome, or the
+ // direct-prompt section would fence checkpoints forever.
reportPreflight(false);
- return;
+ throw error;
}
- reportPreflight(true, true);
+
return;
}
+ if (options?.suppressAutonomousContinuation) this._markAutonomousContinuationSuppressed(message);
+ // Register the observer before dispatch so a synchronously-emitted
+ // message_start cannot be missed.
+ const dispatchObserver = this._observeDirectDispatch(message);
+ const promptPromise = options?.suppressAutonomousContinuation
+ ? this._runWithAutonomousContinuationSuppressed(() => this.agent.prompt(messages))
+ : this.agent.prompt(messages);
+ releaseAdmission();
+ // Settle the preflight outcome at the handoff, not after the whole turn: the
+ // direct-prompt section must keep fencing update-restart checkpoints until
+ // message_start proves the input reached the run's event stream, and a
+ // rejected dispatch must still release the section. A resolved prompt alone
+ // is not proof: Agent.prompt() converts lifecycle failures into a synthetic
+ // error turn without the message ever reaching agent state.
+ const dispatched = await Promise.race([
+ promptPromise.then(
+ () => dispatchObserver.wasObserved() || this.agent.state.messages.includes(message),
+ () => false,
+ ),
+ dispatchObserver.observed,
+ ]);
+ dispatchObserver.stop();
+ reportPreflight(dispatched);
try {
- if (options?.suppressAutonomousContinuation) {
- this._markAutonomousContinuationSuppressed(message);
- await this._runWithAutonomousContinuationSuppressed(() => this.agent.prompt(messages));
- } else {
- await this.agent.prompt(messages);
- }
+ await promptPromise;
} catch (error) {
this._pendingNextTurnMessages.unshift(...drainedNextTurnMessages.map((pending) => ({ ...pending })));
throw error;
}
- reportPreflight(true);
await this.waitForRetry();
}
private async _prompt(text: string, options?: InternalPromptOptions): Promise<void> {
+ if (!this.isStreaming) this._sessionInputPumpSuspended = false;
+ const admission = !this.isStreaming
+ ? await this._acquireDirectTurnAdmission({
+ allowPendingQueue: options?.queueIfBusy === true,
+ signal: options?.signal,
+ })
+ : undefined;
+ // The streaming path skips admission, so this is its cancellation commit point.
+ if (!admission) throwIfPromptAdmissionCancelled(options?.signal);
+ const releaseAdmission = admission?.release ?? (() => {});
+ try {
+ // Streaming prompts skip direct-turn admission but still transfer ownership
+ // before any queue/interception work begins. Keep this before destructive
+ // preflight while ensuring a directly acquired admission is always released.
+ throwIfPromptAdmissionCancelled(options?.signal);
+ options?.admissionCommitted?.();
+ if (admission) {
+ await this._turnAdmissionContext.run(admission.owner, () =>
+ this._promptUnserialized(text, options, releaseAdmission),
+ );
+ } else {
+ await this._promptUnserialized(text, options, releaseAdmission);
+ }
+ } finally {
+ releaseAdmission();
+ }
+ if (admission) {
+ this._scheduleSessionInputPump();
+ // promptUntilAccepted resolves at ownership commit, before queued work runs.
+ if (!options?.returnAfterAccepted) await this._sessionInputPump;
+ }
+ }
+
+ private async _promptUnserialized(
+ text: string,
+ options: InternalPromptOptions | undefined,
+ releaseAdmission: () => void,
+ ): Promise<void> {
const isInternalPrompt = options?.internalPrompt === true;
const expandPromptTemplates = isInternalPrompt ? false : (options?.expandPromptTemplates ?? true);
- const preflightResult = options?.preflightResult;
- let preflightSettled = false;
- const reportPreflight = (success: boolean, queued = false) => {
- if (!preflightSettled) {
- preflightSettled = true;
- preflightResult?.(success, queued);
- }
+ const endDirectPromptSection = this._enterDirectPromptSection();
+ const reportInput = oncePreflight(options?.preflightResult);
+ const reportPreflight: typeof reportInput = (success, queued) => {
+ endDirectPromptSection();
+ reportInput(success, queued);
};
let messages: AgentMessage[] | undefined;
+ let primaryPromptMessage: QueuedAgentMessage | undefined;
let acceptedAgentMessagePrompt: AcceptedAgentMessagePrompt | undefined;
let drainedNextTurnMessages: CustomMessage[] = [];
let expandedText = text;
@@ -3975,50 +4349,48 @@ export class AgentSession {
try {
let currentText = text;
- const hasQueueIfBusyBackpressure = () =>
- options?.queueIfBusy === true &&
- (this.pendingMessageCount > 0 ||
+ const shouldHandleBuiltInSlashCommands = !isInternalPrompt && !options?.skipPrePromptWork;
+ const sessionCommand = shouldHandleBuiltInSlashCommands ? parseSessionSlashCommand(currentText) : undefined;
+ if (sessionCommand) {
+ const wasBusy =
+ this.isStreaming ||
this.isCompacting ||
this.isRetrying ||
this.isBashRunning ||
- this.hasAcceptedPromptInFlight);
-
- const shouldHandleBuiltInSlashCommands = !isInternalPrompt && !options?.skipPrePromptWork;
- const isBuiltInSlashCommand =
- shouldHandleBuiltInSlashCommands &&
- (currentText === "/autonomous" ||
- currentText.startsWith("/autonomous ") ||
- currentText === "/goal" ||
- currentText.startsWith("/goal "));
- if (!this.isStreaming && isBuiltInSlashCommand && hasQueueIfBusyBackpressure()) {
- reportPreflight(false);
- throw new Error("Agent has queued work. Retry the slash command after pending work finishes.");
- }
- if (
- shouldHandleBuiltInSlashCommands &&
- (currentText === "/autonomous" || currentText.startsWith("/autonomous "))
- ) {
- const handledAutonomousCommand = await this._handleAutonomousSlashCommand(currentText);
- if (handledAutonomousCommand) {
- reportPreflight(true);
- return;
- }
- }
- if (shouldHandleBuiltInSlashCommands && (currentText === "/goal" || currentText.startsWith("/goal "))) {
- const handledGoalCommand = await this._handleGoalSlashCommand(currentText, currentImages);
- if (handledGoalCommand) {
- reportPreflight(true);
- return;
- }
+ this.hasAcceptedPromptInFlight ||
+ this._sessionInputPumpSuspended ||
+ this._queuedWorkPauses.size > 0 ||
+ this._activeSessionInput !== undefined ||
+ this.pendingMessageCount > 0;
+ const schedule = options?.streamingBehavior ?? (this.isStreaming ? "steer" : "followUp");
+ const queued = this._enqueueSessionInput(
+ {
+ kind: "command",
+ text: currentText,
+ command: sessionCommand,
+ images: currentImages,
+ agentMessageId: options?.agentMessageId,
+ },
+ schedule,
+ );
+ reportPreflight(queued, queued);
+ releaseAdmission();
+ if (!wasBusy && !options?.returnAfterAccepted) await this._sessionInputPump;
+ return;
}
// Handle extension commands first (execute immediately, even during streaming)
// Extension commands manage their own LLM interaction via pi.sendMessage()
if (expandPromptTemplates && currentText.startsWith("/")) {
- const handled = await this._tryExecuteExtensionCommand(currentText);
- if (handled) {
- // Extension command executed, no prompt to send
+ const commandCompletion = this._executeExtensionCommand(currentText);
+ if (commandCompletion) {
reportPreflight(true);
+ void commandCompletion.then(
+ () => this._settleAgentMessage(options?.agentMessageId, "completion"),
+ (error) => this._settleAgentMessage(options?.agentMessageId, "completion", error),
+ );
+ void commandCompletion.catch(() => undefined);
+ if (!options?.returnAfterAccepted) await commandCompletion.catch(() => undefined);
return;
}
}
@@ -4034,6 +4406,7 @@ export class AgentSession {
);
if (inputResult.action === "handled") {
reportPreflight(true);
+ this._settleAgentMessage(options?.agentMessageId, "completion");
return;
}
if (inputResult.action === "transform") {
@@ -4052,7 +4425,7 @@ export class AgentSession {
// If streaming, or a caller explicitly asked to respect existing queued work,
// enqueue according to the requested behavior.
const shouldQueueForStreaming = this.isStreaming;
- const shouldQueueForPendingWork = hasQueueIfBusyBackpressure();
+ const shouldQueueForPendingWork = options?.queueIfBusy === true && this._isBusyForSessionInput("preflight");
if (shouldQueueForStreaming || shouldQueueForPendingWork) {
if (!options?.streamingBehavior) {
const stateDescription = shouldQueueForStreaming
@@ -4062,23 +4435,15 @@ export class AgentSession {
`${stateDescription}. Specify streamingBehavior ('steer' or 'followUp') to queue the message.`,
);
}
- const queued = await this._queuePromptWithPendingNextTurnMessages(
- expandedText,
- currentImages,
- options.streamingBehavior,
- {
- queueKey: options.followUpQueueKey,
- agentMessageId: options.agentMessageId,
- suppressAutonomousContinuation: options.suppressAutonomousContinuation,
- customMessage: options.customMessage,
- resumeIfIdle: options.resumeIfIdle,
- },
- );
- if (!queued) {
- reportPreflight(false);
- return;
- }
- reportPreflight(true, true);
+ await this._queueWithPendingNextTurnMessages(expandedText, options.streamingBehavior, reportPreflight, {
+ images: currentImages,
+ queueKey: options.followUpQueueKey,
+ agentMessageId: options.agentMessageId,
+ suppressAutonomousContinuation: options.suppressAutonomousContinuation,
+ message: options.customMessage,
+ resumeIfIdle: options.resumeIfIdle,
+ });
+
return;
}
@@ -4088,24 +4453,21 @@ export class AgentSession {
// Flush any pending bash messages before the new prompt, including accepted agent messages.
this._flushPendingBashMessages();
-
- // Validate model
- if (!this.model) {
- throw new Error(formatNoModelSelectedMessage());
- }
-
- if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
- const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
- if (isOAuth) {
- throw new Error(formatAuthenticationFailedMessage(this.model.provider));
- }
- throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
- }
+ await this._validateCanStartAgentRun();
const pendingModelSelectEmit = this._pendingModelSelectEmit();
if (pendingModelSelectEmit) {
await pendingModelSelectEmit;
}
+ const buildUserContent = (): (TextContent | ImageContent)[] => {
+ const userContent: (TextContent | ImageContent)[] = options?.content
+ ? options.content.map((block) => ({ ...block }))
+ : [{ type: "text", text: expandedText }];
+ if (!options?.content && currentImages) {
+ userContent.push(...currentImages);
+ }
+ return userContent;
+ };
if (options?.skipPrePromptWork) {
this.agent.state.systemPrompt = this._baseSystemPrompt;
messages = [];
@@ -4114,20 +4476,14 @@ export class AgentSession {
messages.push(msg);
}
this._pendingNextTurnMessages = [];
- const userContent: (TextContent | ImageContent)[] = options?.content
- ? options.content.map((block) => ({ ...block }))
- : [{ type: "text", text: expandedText }];
- if (!options?.content && currentImages) {
- userContent.push(...currentImages);
- }
- const promptMessage: QueuedAgentMessage = options.customMessage
+ primaryPromptMessage = options.customMessage
? cloneCustomMessage(options.customMessage)
: {
role: "user",
- content: userContent,
+ content: buildUserContent(),
timestamp: Date.now(),
};
- messages.push(promptMessage);
+ messages.push(primaryPromptMessage);
if (options.agentMessageId !== undefined && options.returnAfterAccepted) {
let resolveAccepted = () => {};
let rejectAccepted = (_error: Error) => {};
@@ -4138,8 +4494,8 @@ export class AgentSession {
acceptedAgentMessagePrompt = {
text: expandedText,
agentMessageId: options.agentMessageId,
- message: promptMessage,
- messages: new Set<AgentMessage>([...drainedNextTurnMessages, promptMessage]),
+ message: primaryPromptMessage,
+ messages: new Set<AgentMessage>([...drainedNextTurnMessages, primaryPromptMessage]),
pendingNextTurnMessages: drainedNextTurnMessages,
deliveredPendingNextTurnMessages: new Set(),
accepted,
@@ -4166,21 +4522,14 @@ export class AgentSession {
}
this._pendingNextTurnMessages = [];
- if (options?.customMessage) {
- messages.push(cloneCustomMessage(options.customMessage));
- } else {
- const userContent: (TextContent | ImageContent)[] = options?.content
- ? options.content.map((block) => ({ ...block }))
- : [{ type: "text", text: expandedText }];
- if (!options?.content && currentImages) {
- userContent.push(...currentImages);
- }
- messages.push({
- role: "user",
- content: userContent,
- timestamp: Date.now(),
- });
- }
+ primaryPromptMessage = options?.customMessage
+ ? cloneCustomMessage(options.customMessage)
+ : {
+ role: "user",
+ content: buildUserContent(),
+ timestamp: Date.now(),
+ };
+ messages.push(primaryPromptMessage);
// Emit before_agent_start extension event
basePromptSnapshot = this._baseSystemPrompt;
@@ -4191,18 +4540,8 @@ export class AgentSession {
this._baseSystemPromptOptions,
);
// Add all custom messages from extensions
- if (extensionResult?.messages) {
- for (const msg of extensionResult.messages) {
- messages.push({
- role: "custom",
- customType: msg.customType,
- content: msg.content,
- display: msg.display,
- details: msg.details,
- timestamp: Date.now(),
- });
- }
- }
+ this._appendBeforeAgentStartMessages(messages, extensionResult);
+ // Apply extension-modified system prompt, or reset to base
this.agent.state.systemPrompt = extensionResult?.systemPrompt
? this._refreshExtensionSystemPrompt(extensionResult.systemPrompt, basePromptSnapshot)
: this._baseSystemPrompt;
@@ -4213,6 +4552,7 @@ export class AgentSession {
}
if (!messages) {
+ endDirectPromptSection();
return;
}
@@ -4237,47 +4577,34 @@ export class AgentSession {
throw new Error("Accepted agent message was cleared before delivery.");
}
const shouldQueueAtHandoff =
- options?.queueIfBusy === true &&
- (this.isStreaming ||
- this.pendingMessageCount > 0 ||
- this.isCompacting ||
- this.isRetrying ||
- this.isBashRunning ||
- this._acceptedPromptCompletions.size > 0 ||
- (this._acceptedAgentMessagePrompt !== undefined &&
- this._acceptedAgentMessagePrompt !== acceptedAgentMessagePrompt));
+ options?.queueIfBusy === true && this._isBusyForSessionInput("handoff", acceptedAgentMessagePrompt);
if (shouldQueueAtHandoff) {
+ if (acceptedAgentMessagePrompt && this._acceptedAgentMessagePrompt === acceptedAgentMessagePrompt) {
+ this._acceptedAgentMessagePrompt = undefined;
+ }
+ this._pendingNextTurnMessages.unshift(...drainedNextTurnMessages.map((message) => ({ ...message })));
if (!options?.streamingBehavior) {
- if (acceptedAgentMessagePrompt && this._acceptedAgentMessagePrompt === acceptedAgentMessagePrompt) {
- this._acceptedAgentMessagePrompt = undefined;
- }
- this._pendingNextTurnMessages.unshift(...drainedNextTurnMessages.map((message) => ({ ...message })));
reportPreflight(false);
throw new Error(
"Agent became busy before prompt delivery. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
);
}
- if (acceptedAgentMessagePrompt && this._acceptedAgentMessagePrompt === acceptedAgentMessagePrompt) {
- this._acceptedAgentMessagePrompt = undefined;
- }
- this._pendingNextTurnMessages.unshift(...drainedNextTurnMessages.map((message) => ({ ...message })));
- const queued = await this._queuePromptWithPendingNextTurnMessages(
- expandedText,
- currentImages,
- options.streamingBehavior,
- {
+ try {
+ await this._queueWithPendingNextTurnMessages(expandedText, options.streamingBehavior, reportPreflight, {
+ images: currentImages,
queueKey: options.followUpQueueKey,
agentMessageId: options.agentMessageId,
suppressAutonomousContinuation: options.suppressAutonomousContinuation,
- customMessage: options.customMessage,
+ message: options.customMessage,
resumeIfIdle: options.resumeIfIdle,
- },
- );
- if (!queued) {
+ });
+ } catch (error) {
+ // A failed enqueue must still settle the preflight outcome, or the
+ // direct-prompt section would fence checkpoints forever.
reportPreflight(false);
- return;
+ throw error;
}
- reportPreflight(true, true);
+
return;
}
if (options?.suppressAutonomousContinuation) {
@@ -4285,18 +4612,24 @@ export class AgentSession {
this._markAutonomousContinuationSuppressed(message);
}
}
+ if (!primaryPromptMessage) {
+ reportPreflight(false);
+ throw new Error("Direct prompt is missing its primary message");
+ }
+ const dispatchObserver = acceptedAgentMessagePrompt
+ ? undefined
+ : this._observeDirectDispatch(primaryPromptMessage);
const promptPromise = options?.suppressAutonomousContinuation
? this._runWithAutonomousContinuationSuppressed(() => this.agent.prompt(messages))
: this.agent.prompt(messages);
+ releaseAdmission();
const promptAccepted = Symbol("promptAccepted");
const acceptance = acceptedAgentMessagePrompt
? acceptedAgentMessagePrompt.accepted.then(
() => promptAccepted,
(error: unknown) => error,
)
- : new Promise<typeof promptAccepted>((resolve) => {
- setTimeout(() => resolve(promptAccepted), 0);
- });
+ : dispatchObserver!.observed.then(() => promptAccepted);
const firstOutcome = await Promise.race([
promptPromise.then(
() => undefined,
@@ -4304,6 +4637,7 @@ export class AgentSession {
),
acceptance,
]);
+ dispatchObserver?.stop();
if (firstOutcome !== undefined && firstOutcome !== promptAccepted) {
// A cleared prompt stays set until the aborted run's agent_end cleanup nulls it;
// nulling here would let the run's late events re-persist cleared messages.
@@ -4329,6 +4663,12 @@ export class AgentSession {
const promptCompletion = promptPromise.then(async () => {
await this.waitForRetry();
});
+ if (options?.agentMessageId) {
+ void promptCompletion.then(
+ () => this._settleAgentMessage(options.agentMessageId, "completion"),
+ (error) => this._settleAgentMessage(options.agentMessageId, "completion", this._asError(error)),
+ );
+ }
void promptCompletion
.finally(() => {
if (
@@ -4337,52 +4677,38 @@ export class AgentSession {
) {
this._acceptedAgentMessagePrompt = undefined;
}
- this._schedulePendingMessageResume();
+ this._scheduleSessionInputPump();
})
.catch(() => undefined);
if (options?.returnAfterAccepted) {
this._acceptedPromptCompletions.add(promptCompletion);
- void promptCompletion.then(
- () => {
- this._acceptedPromptCompletions.delete(promptCompletion);
- },
- () => {
- this._acceptedPromptCompletions.delete(promptCompletion);
- },
- );
- void promptCompletion.catch(() => undefined);
+ void promptCompletion
+ .finally(() => this._acceptedPromptCompletions.delete(promptCompletion))
+ .catch(() => undefined);
return;
}
await promptCompletion;
}
- /**
- * Try to execute an extension command. Returns true if command was found and executed.
- */
- private async _tryExecuteExtensionCommand(text: string): Promise<boolean> {
- // Parse command name and args
+ private _executeExtensionCommand(text: string): Promise<void> | undefined {
const spaceIndex = text.indexOf(" ");
const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
- const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
-
const command = this._extensionRunner.getCommand(commandName);
- if (!command) return false;
-
- // Get command context from extension runner (includes session control methods)
- const ctx = this._extensionRunner.createCommandContext();
-
- try {
- await command.handler(args, ctx);
- return true;
- } catch (err) {
- // Emit error via extension runner
- this._extensionRunner.emitError({
- extensionPath: `command:${commandName}`,
- event: "command",
- error: err instanceof Error ? err.message : String(err),
+ if (!command) return undefined;
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
+ const context = this._extensionRunner.createCommandContext();
+ return Promise.resolve()
+ .then(() => command.handler(args, context))
+
+ .catch((error: unknown) => {
+ const commandError = error instanceof Error ? error : new Error(String(error));
+ this._extensionRunner.emitError({
+ extensionPath: `command:${commandName}`,
+ event: "command",
+ error: commandError.message,
+ });
+ throw commandError;
});
- return true;
- }
}
/**
@@ -4438,7 +4764,7 @@ export class AgentSession {
let expandedText = this._expandSkillCommand(text);
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
- await this._queueSteer(expandedText, images, {
+ await this._queuePreparedPrompt("steer", expandedText, images, {
queueKey: options.queueKey,
agentMessageId: options.agentMessageId,
resumeIfIdle: options.resumeIfIdle,
@@ -4466,13 +4792,36 @@ export class AgentSession {
let expandedText = this._expandSkillCommand(text);
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
- return this._queueFollowUp(expandedText, images, {
+ return this._queuePreparedPrompt("followUp", expandedText, images, {
queueKey: options.queueKey,
agentMessageId: options.agentMessageId,
resumeIfIdle: options.resumeIfIdle,
});
}
+ private _restoreSessionCommand(
+ text: string,
+ customMessage: CustomMessage | undefined,
+ images: ImageContent[] | undefined,
+ schedule: SessionInputSchedule,
+ agentMessageId: string | undefined,
+ ): boolean | undefined {
+ if (!isSessionSlashCommandMessage(customMessage) || text !== customMessage.details.command.text) {
+ return undefined;
+ }
+ return this._enqueueSessionInput(
+ {
+ kind: "command",
+ text,
+ command: customMessage.details.command,
+ images,
+ agentMessageId,
+ },
+ schedule,
+ { restore: true },
+ );
+ }
+
async restoreSteeringMessage(
text: string,
images?: ImageContent[],
@@ -4484,7 +4833,12 @@ export class AgentSession {
prefixMessages?: CustomMessage[];
} = {},
): Promise<void> {
- await this._queueSteer(text, images, {
+ if (
+ this._restoreSessionCommand(text, options.customMessage, images, "steer", options.agentMessageId) !== undefined
+ )
+ return;
+
+ await this._queuePreparedPrompt("steer", text, images, {
queueKey: options.queueKey,
agentMessageId: options.agentMessageId,
content: options.content,
@@ -4504,7 +4858,16 @@ export class AgentSession {
prefixMessages?: CustomMessage[];
} = {},
): Promise<boolean> {
- return this._queueFollowUp(text, images, {
+ const restoredCommand = this._restoreSessionCommand(
+ text,
+ options.customMessage,
+ images,
+ "followUp",
+ options.agentMessageId,
+ );
+ if (restoredCommand !== undefined) return restoredCommand;
+
+ return this._queuePreparedPrompt("followUp", text, images, {
queueKey: options.queueKey,
agentMessageId: options.agentMessageId,
content: options.content,
@@ -4522,98 +4885,53 @@ export class AgentSession {
return content;
}
- private async _queuePromptWithPendingNextTurnMessages(
+ /** Queue via the requested lane, restoring drained next-turn context on failure, and report preflight. */
+ private async _queueWithPendingNextTurnMessages(
text: string,
- images: ImageContent[] | undefined,
streamingBehavior: "steer" | "followUp",
+ reportPreflight: (success: boolean, queued?: boolean) => void,
options: {
+ images?: ImageContent[];
queueKey?: string;
agentMessageId?: string;
- customMessage?: CustomMessage;
- suppressAutonomousContinuation?: boolean;
- resumeIfIdle?: boolean;
- } = {},
- ): Promise<boolean> {
- const pendingNextTurnMessages = this._pendingNextTurnMessages;
- this._pendingNextTurnMessages = [];
- try {
- if (streamingBehavior === "followUp") {
- const queued = await this._queueFollowUp(text, images, {
- queueKey: options.queueKey,
- agentMessageId: options.agentMessageId,
- message: options.customMessage,
- prefixMessages: pendingNextTurnMessages,
- resumeIfIdle: options.resumeIfIdle,
- });
- if (!queued) {
- this._pendingNextTurnMessages.unshift(...pendingNextTurnMessages);
- }
- return queued;
- }
- await this._queueSteer(text, images, {
- agentMessageId: options.agentMessageId,
- queueKey: options.queueKey,
- message: options.customMessage,
- prefixMessages: pendingNextTurnMessages,
- suppressAutonomousContinuation: options.suppressAutonomousContinuation,
- resumeIfIdle: options.resumeIfIdle,
- });
- return true;
- } catch (error) {
- this._pendingNextTurnMessages.unshift(...pendingNextTurnMessages);
- throw error;
- }
- }
-
- private async _queueInjectedMessageWithPendingNextTurnMessages(
- text: string,
- message: CustomMessage,
- streamingBehavior: "steer" | "followUp",
- options: {
- queueKey?: string;
+ message?: QueuedAgentMessage;
previewLabel?: string;
suppressAutonomousContinuation?: boolean;
resumeIfIdle?: boolean;
} = {},
- ): Promise<boolean> {
+ ): Promise<void> {
const pendingNextTurnMessages = this._pendingNextTurnMessages;
this._pendingNextTurnMessages = [];
+ // Preflight callbacks run outside the try: a throwing callback must not roll
+ // back queue state for an input that was in fact enqueued (its prefixMessages
+ // would be delivered twice).
+ let queued: boolean;
try {
- if (streamingBehavior === "followUp") {
- const queued = await this._queueFollowUp(text, undefined, {
- queueKey: options.queueKey,
- message,
- prefixMessages: pendingNextTurnMessages,
- previewLabel: options.previewLabel,
- suppressAutonomousContinuation: options.suppressAutonomousContinuation,
- resumeIfIdle: options.resumeIfIdle,
- });
- if (!queued) {
- this._pendingNextTurnMessages.unshift(...pendingNextTurnMessages);
- }
- return queued;
- }
- await this._queueSteer(text, undefined, {
- message,
+ queued = await this._queuePreparedPrompt(streamingBehavior, text, options.images, {
+ queueKey: options.queueKey,
+ agentMessageId: options.agentMessageId,
+ message: options.message,
prefixMessages: pendingNextTurnMessages,
previewLabel: options.previewLabel,
- queueKey: options.queueKey,
suppressAutonomousContinuation: options.suppressAutonomousContinuation,
resumeIfIdle: options.resumeIfIdle,
});
- return true;
+ if (!queued) {
+ this._pendingNextTurnMessages.unshift(...pendingNextTurnMessages);
+ }
} catch (error) {
this._pendingNextTurnMessages.unshift(...pendingNextTurnMessages);
throw error;
}
+ reportPreflight(queued, queued);
}
/**
* Internal: Queue a steering message (already expanded, no extension command check).
*/
- private async _queueSteer(
+ private _createPreparedPromptInput(
text: string,
- images?: ImageContent[],
+ images: ImageContent[] | undefined,
options: {
agentMessageId?: string;
queueKey?: string;
@@ -4623,43 +4941,74 @@ export class AgentSession {
previewLabel?: string;
suppressAutonomousContinuation?: boolean;
resumeIfIdle?: boolean;
- } = {},
- ): Promise<void> {
+ },
+ ): PreparedPromptInput {
const content = options.content ?? this._buildPromptContent(text, images);
- const message: QueuedAgentMessage =
+ const message =
options.message ??
({
role: "user",
- content,
+ content: content.map((block) => ({ ...block })),
timestamp: Date.now(),
} satisfies UserMessage);
- if (options.suppressAutonomousContinuation) {
- this._markAutonomousContinuationSuppressed(message);
- }
- this._steeringMessages.push({
+ return {
+ kind: "prompt",
text,
+ images: images?.map((image) => ({ ...image })),
+ content: content.map((block) => ({ ...block })),
+ customMessage: options.message?.role === "custom" ? cloneCustomMessage(options.message) : undefined,
previewLabel: options.previewLabel,
queueKey: options.queueKey,
agentMessageId: options.agentMessageId,
- prefixMessages: options.prefixMessages ?? [],
+ prefixMessages: options.prefixMessages?.map((message) => cloneCustomMessage(message)) ?? [],
+ suppressAutonomousContinuation: options.suppressAutonomousContinuation,
+ autoPump: options.resumeIfIdle === true,
message,
- });
- this.agent.steer(options.prefixMessages?.length ? [...options.prefixMessages, message] : message);
+ };
+ }
+
+ private _enqueueSessionInput(
+ input: QueuedSessionInput,
+ schedule: SessionInputSchedule,
+ options: { restore?: boolean } = {},
+ ): boolean {
+ const queue = schedule === "steer" ? this._steeringMessages : this._followUpMessages;
+ const coalescedOwner =
+ schedule === "followUp" && input.kind === "prompt" && input.queueKey
+ ? (queue.find((item) => item.queueKey === input.queueKey) ??
+ this._activePendingPromptWithQueueKey(input.queueKey))
+ : undefined;
+ if (coalescedOwner) {
+ if (input.agentMessageId !== coalescedOwner.agentMessageId) {
+ this._rejectAgentMessage(
+ input.agentMessageId,
+ new Error("Prompt was not queued because an equivalent follow-up is already pending."),
+ );
+ }
+ return false;
+ }
+ queue.push(input);
+ this._sessionInputArrivalEpoch++;
+ this._syncSteeringStopPending();
this._emitQueueUpdate();
- if (options.resumeIfIdle) {
- this._schedulePendingMessageResume(true);
+ if (
+ !options.restore &&
+ ((schedule === "steer" && this.isStreaming) || input.kind === "command" || input.autoPump)
+ ) {
+ if (input.kind === "prompt" && input.autoPump) this._sessionInputPumpSuspended = false;
+ this._scheduleSessionInputPump();
}
+ return true;
}
- /**
- * Internal: Queue a follow-up message (already expanded, no extension command check).
- */
- private async _queueFollowUp(
+ /** Queue a prepared prompt on one lane; steering always queues, follow-up may coalesce by queue key. */
+ private async _queuePreparedPrompt(
+ schedule: SessionInputSchedule,
text: string,
images?: ImageContent[],
options: {
- queueKey?: string;
agentMessageId?: string;
+ queueKey?: string;
content?: (TextContent | ImageContent)[];
message?: QueuedAgentMessage;
prefixMessages?: CustomMessage[];
@@ -4668,126 +5017,362 @@ export class AgentSession {
resumeIfIdle?: boolean;
} = {},
): Promise<boolean> {
- if (options.queueKey && this._followUpMessages.some((message) => message.queueKey === options.queueKey)) {
- return false;
- }
- const content = options.content ?? this._buildPromptContent(text, images);
- const message: QueuedAgentMessage =
- options.message ??
- ({
- role: "user",
- content,
- timestamp: Date.now(),
- } satisfies UserMessage);
+ const input = this._createPreparedPromptInput(text, images, options);
if (options.suppressAutonomousContinuation) {
- this._markAutonomousContinuationSuppressed(message);
- }
- this._followUpMessages.push({
- text,
- previewLabel: options.previewLabel,
- queueKey: options.queueKey,
- agentMessageId: options.agentMessageId,
- prefixMessages: options.prefixMessages ?? [],
- message,
- });
- this.agent.followUp(options.prefixMessages?.length ? [...options.prefixMessages, message] : message);
- this._emitQueueUpdate();
- if (options.resumeIfIdle) {
- this._schedulePendingMessageResume(true);
+ this._markAutonomousContinuationSuppressed(input.message);
}
- return true;
+ return this._enqueueSessionInput(input, schedule);
}
- private _schedulePendingMessageResume(request = false): void {
- if (request) {
- this._pendingMessageResumeRequested = true;
- }
- if (this._disposed || this._disposing || this.pendingMessageCount === 0) {
- if (this.pendingMessageCount === 0) {
- this._pendingMessageResumeRequested = false;
- }
- return;
- }
- if (!this._pendingMessageResumeRequested) {
+ private _scheduleSessionInputPump(): void {
+ if (this._sessionInputPumpSuspended || this._queuedWorkPauses.size > 0) return;
+ if (this._disposed || this._disposing || this._sessionInputPumpRequested || this.pendingMessageCount === 0) {
return;
}
- const epoch = this._pendingMessageResumeEpoch;
- const resume = () => this._resumePendingMessages(epoch);
- this._pendingMessageResumeQueue = this._pendingMessageResumeQueue.then(resume, resume);
- this._pendingMessageResumeQueue.catch(() => {});
+ this._sessionInputPumpRequested = true;
+ const epoch = this._sessionInputPumpEpoch;
+ const pump = async () => {
+ this._sessionInputPumpRequested = false;
+ await this._pumpSessionInputs(epoch);
+ };
+ this._sessionInputPump = this._sessionInputPump.then(pump, pump);
+ this._sessionInputPump.catch(() => {});
}
- private async _resumePendingMessages(epoch: number): Promise<void> {
+ private async _pumpSessionInputs(epoch: number): Promise<void> {
+ this._pumpingSessionInput = true;
+ let blocked = false;
try {
- while (
- !this._disposed &&
- !this._disposing &&
- this._pendingMessageResumeRequested &&
- epoch === this._pendingMessageResumeEpoch &&
- this.pendingMessageCount > 0
- ) {
- await this.agent.waitForIdle();
- await this._agentEventQueue;
- await this._waitForRefineIdle();
- if (epoch !== this._pendingMessageResumeEpoch) {
- return;
- }
+ while (!this._disposed && !this._disposing && this.pendingMessageCount > 0) {
+ const admission = await this._acquireTurnAdmission();
+ try {
+ await this.agent.waitForIdle();
+ if (epoch !== this._sessionInputPumpEpoch) return;
+ await this._agentEventQueue;
+ await this._waitForRefineIdle();
+ if (this._isSessionInputHandoffDeferred(epoch)) {
+ blocked = true;
+ return;
+ }
- const blockingOperations = [this._compactionOperation, this._branchSummaryOperation].filter(
- (operation): operation is Promise<void> => operation !== undefined,
- );
- if (blockingOperations.length > 0) {
- await Promise.allSettled(blockingOperations);
- continue;
- }
- if (this.isRetrying) {
- await this.waitForRetry();
- continue;
- }
- const acceptedPrompts = [...this._acceptedPromptCompletions];
- if (acceptedPrompts.length > 0) {
- await Promise.allSettled(acceptedPrompts);
- continue;
- }
+ const queue = this._steeringMessages.length > 0 ? this._steeringMessages : this._followUpMessages;
+ const mode = queue === this._steeringMessages ? this.steeringMode : this.followUpMode;
+ const first = queue[0];
+ if (!first) continue;
+ const lane: SessionInputSchedule = queue === this._steeringMessages ? "steer" : "followUp";
+ if (first.kind === "command") {
+ queue.shift();
+ this._activeSessionInput = { kind: "command", lane, item: first, phase: "executing" };
+ this._syncSteeringStopPending();
+ this._notifySessionInputCheckpointChange();
+ this._emitQueueUpdate();
+ try {
+ await this._executeQueuedSessionCommand(first);
+ this._settleAgentMessage(first.agentMessageId, "completion");
+ } catch (error) {
+ this._rejectAgentMessage(first.agentMessageId, this._asError(error));
+ } finally {
+ this._activeSessionInput = undefined;
+ this._syncSteeringStopPending();
+ this._notifySessionInputCheckpointChange();
+ this._emitQueueUpdate();
+ }
+ continue;
+ }
- if (
- this._disposed ||
- this._disposing ||
- epoch !== this._pendingMessageResumeEpoch ||
- this.pendingMessageCount === 0
- ) {
- return;
- }
- if (this.isBashRunning || this.isCompacting || this.isRetrying || this.hasAcceptedPromptInFlight) {
- return;
+ const prompts: PreparedPromptInput[] = [];
+ while (queue[0]?.kind === "prompt" && (mode === "all" || prompts.length === 0)) {
+ prompts.push(queue.shift() as PreparedPromptInput);
+ }
+ if (epoch !== this._sessionInputPumpEpoch) {
+ queue.unshift(...prompts);
+ this._syncSteeringStopPending();
+ return;
+ }
+ this._activeSessionInput = {
+ kind: "prompt",
+ lane,
+ items: prompts,
+ phase: "preparing",
+ };
+ this._syncSteeringStopPending();
+ this._notifySessionInputCheckpointChange();
+ this._emitQueueUpdate();
+ try {
+ await this._startPreparedPromptItems(prompts, epoch, admission.release);
+ for (const prompt of prompts) {
+ this._settleAgentMessage(prompt.agentMessageId, "completion");
+ }
+ } catch (error) {
+ const delivered = new Set(this.agent.state.messages);
+ const undelivered: PreparedPromptInput[] = [];
+ for (const prompt of prompts) {
+ prompt.prefixMessages = prompt.prefixMessages.filter((message) => !delivered.has(message));
+ if (!delivered.has(prompt.message)) undelivered.push(prompt);
+ }
+ if (this._isDeferredSessionInputError(error, epoch)) {
+ if (!this._activeSessionInput?.cancelled && undelivered.length > 0) {
+ queue.unshift(...undelivered);
+ // Clear ownership before emitting so the requeued items are not
+ // double-counted as both owned and queued.
+ this._activeSessionInput = undefined;
+ this._syncSteeringStopPending();
+ this._emitQueueUpdate();
+ }
+ blocked = true;
+ return;
+ }
+ const terminalError = this._asError(error);
+ for (const prompt of undelivered) {
+ this._settleAgentMessage(prompt.agentMessageId, "delivery", terminalError);
+ }
+ for (const prompt of prompts) {
+ this._settleAgentMessage(prompt.agentMessageId, "completion", terminalError);
+ }
+ this._surfaceSessionInputError(error);
+ } finally {
+ this._activeSessionInput = undefined;
+ this._syncSteeringStopPending();
+ this._notifySessionInputCheckpointChange();
+ }
+ } finally {
+ admission.release();
}
+ }
+ } finally {
+ this._pumpingSessionInput = false;
+ this._syncSteeringStopPending();
+ if (!blocked && epoch === this._sessionInputPumpEpoch && this.pendingMessageCount > 0) {
+ this._scheduleSessionInputPump();
+ }
+ }
+ }
- await this.agent.waitForIdle();
- if (epoch !== this._pendingMessageResumeEpoch || this.pendingMessageCount === 0) {
- return;
- }
- // Re-check adjacent to the handoff: background planning may have
- // completed and entered _applyRefine during the awaits above,
- // disconnecting event handling. Wait for it to finish so the
- // resumed turn's events are not lost.
- await this._waitForRefineIdle();
- if (epoch !== this._pendingMessageResumeEpoch || this.pendingMessageCount === 0) {
- return;
- }
- this._flushPendingBashMessages();
- if (this._pendingNextTurnMessages.length > 0) {
- await this._drainQueuedMessagesAfterBash();
- } else {
- await this.agent.continue();
+ /**
+ * Single busy truth table for turn-admission decision points:
+ * "preflight" is queueIfBusy backpressure before pre-prompt work (streaming checked separately),
+ * "handoff" re-checks adjacent to the agent.prompt() handoff (includes streaming),
+ * "pump" is session-input pump deferral (adds lifecycle and pause state).
+ */
+ private _isBusyForSessionInput(
+ point: "preflight" | "handoff" | "pump",
+ ignoreAcceptedPrompt?: AcceptedAgentMessagePrompt,
+ ): boolean {
+ const busy =
+ this.isCompacting ||
+ this.isRetrying ||
+ this.isBashRunning ||
+ this._acceptedPromptCompletions.size > 0 ||
+ (this._acceptedAgentMessagePrompt !== undefined && this._acceptedAgentMessagePrompt !== ignoreAcceptedPrompt);
+ if (point === "pump") {
+ return (
+ busy ||
+ this._disposed ||
+ this._disposing ||
+ this._sessionInputPumpSuspended ||
+ this._queuedWorkPauses.size > 0 ||
+ this._branchSummaryOperation !== undefined
+ );
+ }
+ return busy || this.pendingMessageCount > 0 || (point === "handoff" && this.isStreaming);
+ }
+
+ private _isSessionInputHandoffDeferred(epoch: number): boolean {
+ return epoch !== this._sessionInputPumpEpoch || this._isBusyForSessionInput("pump");
+ }
+
+ private _asError(error: unknown): Error {
+ return error instanceof Error ? error : new Error(String(error));
+ }
+
+ private _isDeferredSessionInputError(error: unknown, epoch: number): boolean {
+ return error instanceof DeferredSessionInputError || this._isSessionInputHandoffDeferred(epoch);
+ }
+
+ private _surfaceSessionInputError(error: unknown): void {
+ const normalized = this._asError(error);
+ this._extensionRunner.emitError({
+ extensionPath: "<session-input>",
+ event: "session_input",
+ error: normalized.message,
+ stack: normalized.stack,
+ });
+ }
+
+ private async _startPreparedPromptItems(
+ prompts: PreparedPromptInput[],
+ epoch: number,
+ releaseAdmission: () => void,
+ ): Promise<void> {
+ await this._validateCanStartAgentRun();
+ if (this._isSessionInputHandoffDeferred(epoch)) {
+ throw new DeferredSessionInputError("Session input paused before preflight");
+ }
+ this._flushPendingBashMessages();
+ const lastAssistant = this._findLastAssistantMessage();
+ if (lastAssistant) await this._checkCompaction(lastAssistant, false, false);
+ const pendingModelSelectEmit = this._pendingModelSelectEmit();
+ if (pendingModelSelectEmit) await pendingModelSelectEmit;
+
+ while (!prompts.every((prompt) => prompt.preparation !== undefined)) {
+ if (this._isSessionInputHandoffDeferred(epoch)) {
+ throw new DeferredSessionInputError("Session input paused before preparation");
+ }
+ const preparationPrompt = prompts.at(-1);
+ if (!preparationPrompt) return;
+ const basePromptSnapshot = this._baseSystemPrompt;
+ const result = await this._extensionRunner.emitBeforeAgentStart(
+ preparationPrompt.text,
+ preparationPrompt.images,
+ basePromptSnapshot,
+ this._baseSystemPromptOptions,
+ );
+ if (prompts.at(-1) !== preparationPrompt) continue;
+ const preparation = { result, basePromptSnapshot };
+ for (const prompt of prompts) prompt.preparation = preparation;
+ }
+ if (this._isSessionInputHandoffDeferred(epoch)) {
+ throw new DeferredSessionInputError("Session input paused before handoff");
+ }
+ if (prompts.length === 0) return;
+
+ // Re-check adjacent to the handoff: background refine planning may have
+ // completed and entered _applyRefine during the awaits above,
+ // disconnecting event handling. Wait for it to finish so the new
+ // turn's events are not lost.
+ await this._waitForRefineIdle();
+ if (this._isSessionInputHandoffDeferred(epoch)) {
+ throw new DeferredSessionInputError("Session input paused before handoff");
+ }
+ // Assemble the handoff snapshot only after the last await: a clear that runs
+ // during the waits above must still be able to remove prompts from
+ // active.items before they are captured for agent.prompt().
+ if (prompts.length === 0) return;
+ const messages: AgentMessage[] = [];
+ const nextTurnMessages = this._pendingNextTurnMessages;
+ this._pendingNextTurnMessages = [];
+ messages.push(...nextTurnMessages);
+ for (const prompt of prompts) {
+ messages.push(...prompt.prefixMessages, prompt.message);
+ if (prompt.suppressAutonomousContinuation) this._markAutonomousContinuationSuppressed(prompt.message);
+ }
+ const preparation = prompts[0]?.preparation;
+ const result = preparation?.result;
+ this._appendBeforeAgentStartMessages(messages, result);
+ // The base prompt may have changed (e.g. refine) since preparation; splice the
+ // current base into an extension-modified prompt exactly like the direct path.
+ this.agent.state.systemPrompt =
+ result?.systemPrompt !== undefined && preparation !== undefined
+ ? this._refreshExtensionSystemPrompt(result.systemPrompt, preparation.basePromptSnapshot)
+ : this._baseSystemPrompt;
+ try {
+ if (this.isStreaming) {
+ // agent.prompt() would reject with its already-processing error; defer instead.
+ throw new DeferredSessionInputError("Agent became active before session input handoff");
+ }
+ if (this._activeSessionInput?.kind === "prompt") {
+ this._activeSessionInput.phase = "handedOff";
+ this._syncSteeringStopPending();
+ this._notifySessionInputCheckpointChange();
+ this._emitQueueUpdate();
+ }
+ // The phase flipped to handedOff before dispatch; hold a checkpoint section
+ // until dispatch so a restart snapshot cannot miss the accepted messages.
+ const endHandoffSection = this._enterDirectPromptSection();
+ const dispatchObserver = this._observeDirectDispatch(prompts[prompts.length - 1]!.message);
+ const settleHandoffSection = () => {
+ dispatchObserver.stop();
+ endHandoffSection();
+ };
+ const promptPromise = this.agent.prompt(messages);
+ releaseAdmission();
+ void Promise.race([promptPromise.catch(() => undefined), dispatchObserver.observed]).then(
+ settleHandoffSection,
+ settleHandoffSection,
+ );
+ await promptPromise;
+ await this.waitForRetry();
+ await this._agentEventQueue;
+ this._forgetConsumedPostCompactionContinuations(prompts.map((prompt) => prompt.message));
+ } catch (error) {
+ const delivered = new Set(this.agent.state.messages);
+ this._pendingNextTurnMessages.unshift(...nextTurnMessages.filter((message) => !delivered.has(message)));
+ throw error;
+ }
+ }
+
+ private async _executeQueuedSessionCommand(input: PreparedCommandInput): Promise<void> {
+ this._appendDurableSessionCommandMessage(input.text, input.command, false);
+ this._settleAgentMessage(input.agentMessageId, "delivery");
+ try {
+ let resultText: string | undefined;
+ switch (input.command.name) {
+ case "compact":
+ await this.compact(input.command.args || undefined, { skipAbort: true });
+ break;
+ case "refine": {
+ const options = parseRefineCommandOptions(input.command.args);
+ const result = await this.refine(options, { skipAbort: true });
+ const applied = result.appliedEdits.filter((edit) => edit.applied).length;
+ resultText = `Refined continual harness state: ${applied} edit${applied === 1 ? "" : "s"} applied.`;
+ break;
}
+ case "goal":
+ await this._handleGoalSlashCommand(input.text, input.images);
+ resultText = this._goalState.objective
+ ? `Goal ${this._goalState.status}: ${this._goalState.objective}`
+ : "No active goal.";
+ break;
+ case "autonomous":
+ await this._handleAutonomousSlashCommand(input.text);
+ break;
}
- } finally {
- if (epoch === this._pendingMessageResumeEpoch && this.pendingMessageCount === 0) {
- this._pendingMessageResumeRequested = false;
+ if (resultText) this._appendDurableSessionCommandMessage(resultText, input.command, true, false);
+ } catch (error) {
+ // A skipped compaction is benign and already surfaced by compaction_end.
+ if (error instanceof CompactionSkippedError) return;
+ const commandError = error instanceof Error ? error : new Error(String(error));
+ try {
+ this._appendDurableSessionCommandMessage(
+ `Command failed: ${commandError.message}`,
+ input.command,
+ true,
+ true,
+ );
+ } catch {
+ // Surfacing the command failure matters more than persisting its row.
}
+ throw commandError;
}
}
+ private _appendDurableSessionCommandMessage(
+ content: string,
+ command: SessionSlashCommand,
+ isResult: boolean,
+ isError = false,
+ ): void {
+ const message: CustomMessage = isResult
+ ? createSessionSlashCommandResultMessage(content, {
+ command,
+ success: !isError,
+ severity: isError ? "error" : "info",
+ ...(isError ? { error: content.replace(/^Command failed:\s*/, "") } : {}),
+ })
+ : createSessionSlashCommandMessage(command);
+ // Persist before touching live state so a failed write cannot leave an
+ // unsaved leaf that the next entry would silently parent onto.
+ this.sessionManager.appendCustomMessageEntryWithRollback(
+ message.customType,
+ message.content,
+ message.display,
+ message.details,
+ );
+ this.agent.state.messages.push(message);
+ this._emit({ type: "message_start", message });
+ this._emit({ type: "message_end", message });
+ }
+
/**
* Throw an error if the text is an extension command.
*/
@@ -4830,14 +5415,43 @@ export class AgentSession {
if (options?.deliverAs === "nextTurn") {
this._pendingNextTurnMessages.push(appMessage);
} else if (this.isStreaming) {
+ const normalized = normalizeMessageContent(message.content);
if (options?.deliverAs === "followUp") {
- this.agent.followUp(appMessage);
+ await this._queuePreparedPrompt("followUp", normalized.text, normalized.images, {
+ message: appMessage,
+ resumeIfIdle: true,
+ });
} else {
- this.agent.steer(appMessage);
+ await this._queuePreparedPrompt("steer", normalized.text, normalized.images, {
+ message: appMessage,
+ resumeIfIdle: true,
+ });
}
} else if (options?.triggerTurn) {
- await this._waitForRefineIdle();
- await this.agent.prompt(appMessage);
+ const admission = await this._acquireDirectTurnAdmission();
+ // Hold a checkpoint section from admission until the turn dispatches so
+ // an update-restart snapshot cannot miss the admitted custom turn.
+ const endDirectPromptSection = this._enterDirectPromptSection();
+ const dispatchObserver = this._observeDirectDispatch(appMessage);
+ const settleSection = () => {
+ dispatchObserver.stop();
+ endDirectPromptSection();
+ };
+ try {
+ if (this.isStreaming) await this.agent.waitForIdle();
+ await this._waitForRefineIdle();
+ const promptPromise = this.agent.prompt(appMessage);
+ admission.release();
+ void Promise.race([promptPromise.catch(() => undefined), dispatchObserver.observed]).then(
+ settleSection,
+ settleSection,
+ );
+ await promptPromise;
+ } finally {
+ settleSection();
+ admission.release();
+ this._scheduleSessionInputPump();
+ }
} else {
this.agent.state.messages.push(appMessage);
this.sessionManager.appendCustomMessageEntry(
@@ -4898,67 +5512,107 @@ export class AgentSession {
* @returns Object with steering and followUp arrays
*/
clearQueue(): { steering: string[]; followUp: string[] } {
- const steering = this._steeringMessages.map((message) => message.text);
- const followUp = this._followUpMessages.map((message) => message.text);
+ const active =
+ this._activeSessionInput?.kind === "prompt" &&
+ this._activeSessionInput.phase === "preparing" &&
+ !this._activeSessionInput.cancelled
+ ? this._activeSessionInput
+ : undefined;
+ if (active) {
+ active.cancelled = true;
+ this._sessionInputPumpEpoch++;
+ const error = new Error("Queued prompt was cleared before delivery.");
+ for (const input of active.items) {
+ this._settleAgentMessage(input.agentMessageId, "delivery", error);
+ this._settleAgentMessage(input.agentMessageId, "completion", error);
+ }
+ }
+ const activeTexts = active?.items.map((message) => message.text) ?? [];
+ const steering = [
+ ...(active?.lane === "steer" ? activeTexts : []),
+ ...this._steeringMessages.map((message) => message.text),
+ ];
+ const followUp = [
+ ...(active?.lane === "followUp" ? activeTexts : []),
+ ...this._followUpMessages.map((message) => message.text),
+ ];
this._rejectQueuedAgentMessageDeliveries(new Error("Queued agent message was cleared before delivery."));
this._steeringMessages = [];
this._followUpMessages = [];
+ this._syncSteeringStopPending();
this.agent.clearAllQueues();
this._emitQueueUpdate();
return { steering, followUp };
}
+ private _invalidateQueuedPromptPreparation(): void {
+ for (const queue of [this._steeringMessages, this._followUpMessages]) {
+ for (const input of queue) {
+ if (input.kind === "prompt") input.preparation = undefined;
+ }
+ }
+ }
+
+ private _removeActivePreparingPrompts(predicate: (message: PreparedPromptInput) => boolean): {
+ steering: PreparedPromptInput[];
+ followUp: PreparedPromptInput[];
+ } {
+ const active = this._activeSessionInput;
+ if (active?.kind !== "prompt" || active.phase !== "preparing") return { steering: [], followUp: [] };
+ const removed = active.items.filter(predicate);
+ if (removed.length === 0) return { steering: [], followUp: [] };
+ const previousAnchor = active.items.at(-1);
+ const removedSet = new Set(removed);
+ active.items.splice(0, active.items.length, ...active.items.filter((message) => !removedSet.has(message)));
+ if (active.items.at(-1) !== previousAnchor) {
+ for (const message of active.items) message.preparation = undefined;
+ }
+ return active.lane === "steer" ? { steering: removed, followUp: [] } : { steering: [], followUp: removed };
+ }
+
clearQueuedUserMessagesMatching(predicate: (text: string) => boolean): { steering: string[]; followUp: string[] } {
const steering = this._steeringMessages.filter(
- (message) => message.agentMessageId !== undefined && predicate(message.text),
+ (message): message is PreparedPromptInput =>
+ message.kind === "prompt" && message.agentMessageId !== undefined && predicate(message.text),
);
const followUp = this._followUpMessages.filter(
+ (message): message is PreparedPromptInput =>
+ message.kind === "prompt" && message.agentMessageId !== undefined && predicate(message.text),
+ );
+ const active = this._removeActivePreparingPrompts(
(message) => message.agentMessageId !== undefined && predicate(message.text),
);
+ steering.push(...active.steering);
+ followUp.push(...active.followUp);
const accepted = this._acceptedAgentMessagePrompt;
const acceptedMatches =
accepted !== undefined && !accepted.turnStarted && !accepted.cleared && predicate(accepted.text);
- if (steering.length === 0 && followUp.length === 0 && !acceptedMatches) {
- return { steering: [], followUp: [] };
- }
- const steeringToRemove = new Set<AgentMessage>(steering.map((message) => message.message));
- const followUpToRemove = new Set<AgentMessage>(followUp.map((message) => message.message));
- const removedQueuedMessages = new Set(
- this.agent.removeQueuedMessages((message) => steeringToRemove.has(message) || followUpToRemove.has(message)),
+ if (steering.length === 0 && followUp.length === 0 && !acceptedMatches) return { steering: [], followUp: [] };
+ const steeringSet = new Set(steering);
+ const followUpSet = new Set(followUp);
+ this._steeringMessages = this._steeringMessages.filter(
+ (message) => !steeringSet.has(message as PreparedPromptInput),
);
- const removedSteeringMessages = steering.filter((message) => removedQueuedMessages.has(message.message));
- const removedFollowUpMessages = followUp.filter((message) => removedQueuedMessages.has(message.message));
- if (removedSteeringMessages.length === 0 && removedFollowUpMessages.length === 0 && !acceptedMatches) {
- return { steering: [], followUp: [] };
- }
- const removedSteeringSet = new Set(removedSteeringMessages.map((message) => message.message));
- const removedFollowUpSet = new Set(removedFollowUpMessages.map((message) => message.message));
- this._steeringMessages = this._steeringMessages.filter((message) => !removedSteeringSet.has(message.message));
- this._followUpMessages = this._followUpMessages.filter((message) => !removedFollowUpSet.has(message.message));
- const removedSteering = removedSteeringMessages.map((message) => message.text);
- const removedFollowUp = removedFollowUpMessages.map((message) => message.text);
- for (const message of removedSteeringMessages) {
- this._rejectAgentMessageDelivery(
- message.agentMessageId,
- new Error("Queued agent message was cleared before delivery."),
- );
- }
- for (const message of removedFollowUpMessages) {
- this._rejectAgentMessageDelivery(
+ this._followUpMessages = this._followUpMessages.filter(
+ (message) => !followUpSet.has(message as PreparedPromptInput),
+ );
+ this._syncSteeringStopPending();
+ for (const message of [...steering, ...followUp]) {
+ this._rejectAgentMessage(
message.agentMessageId,
new Error("Queued agent message was cleared before delivery."),
);
}
+ const removedSteering = steering.map((message) => message.text);
+ const removedFollowUp = followUp.map((message) => message.text);
if (acceptedMatches) {
accepted.cleared = true;
this.agent.state.messages = this.agent.state.messages.filter((message) => !accepted.messages.has(message));
- // Restore drained nextTurn messages the model never saw. Clones, so the cleared
- // run's late-event cleanup cannot strip the restored copies from a newer run.
this._pendingNextTurnMessages.unshift(
...undeliveredPendingNextTurnMessages(accepted).map((message) => ({ ...message })),
);
const error = new Error("Accepted agent message was cleared before delivery.");
- this._rejectAgentMessageDelivery(accepted.agentMessageId, error);
+ this._rejectAgentMessage(accepted.agentMessageId, error);
accepted.rejectAccepted(error);
this.agent.abort();
removedFollowUp.push(accepted.text);
@@ -4967,35 +5621,278 @@ export class AgentSession {
return { steering: removedSteering, followUp: removedFollowUp };
}
+ /**
+ * Items the pump moved out of the typed queues but has not yet delivered:
+ * prompts still preparing and commands still executing. Once a prompt hands
+ * off it reaches the transcript, so it stops counting as pending.
+ */
+ private _undeliveredActiveSessionInputs(lane: SessionInputSchedule): readonly QueuedSessionInput[] {
+ const active = this._activeSessionInput;
+ if (!active || active.lane !== lane) return [];
+ if (active.kind === "command") return [active.item];
+ return active.phase === "preparing" && !active.cancelled ? active.items : [];
+ }
+
+ private _pendingSessionInputs(lane: SessionInputSchedule): readonly QueuedSessionInput[] {
+ const queue = lane === "steer" ? this._steeringMessages : this._followUpMessages;
+ const owned = this._undeliveredActiveSessionInputs(lane);
+ return owned.length === 0 ? queue : [...owned, ...queue];
+ }
+
/** Number of pending messages (includes both steering and follow-up) */
get pendingMessageCount(): number {
- return this._steeringMessages.length + this._followUpMessages.length;
+ return this._pendingSessionInputs("steer").length + this._pendingSessionInputs("followUp").length;
}
/** Get pending steering messages (read-only) */
getSteeringMessages(): readonly string[] {
- return this._steeringMessages.map((message) => message.text);
+ return this._pendingSessionInputs("steer").map((message) => message.text);
}
getSteeringMessagePreviews(): readonly string[] {
- return this._steeringMessages.map(queuedAgentMessagePreview);
+ return this._pendingSessionInputs("steer").map(queuedAgentMessagePreview);
}
/** Get pending follow-up messages (read-only) */
getFollowUpMessages(): readonly string[] {
- return this._followUpMessages.map((message) => message.text);
+ return this._pendingSessionInputs("followUp").map((message) => message.text);
}
getFollowUpMessagePreviews(): readonly string[] {
- return this._followUpMessages.map(queuedAgentMessagePreview);
+ return this._pendingSessionInputs("followUp").map(queuedAgentMessagePreview);
}
getSteeringQueueSnapshots(): readonly QueuedAgentInputSnapshot[] {
- return this._steeringMessages.map((message) => createQueuedAgentInputSnapshot(message));
+ return this._pendingSessionInputs("steer").map((message) => createQueuedAgentInputSnapshot(message));
}
getFollowUpQueueSnapshots(): readonly QueuedAgentInputSnapshot[] {
- return this._followUpMessages.map((message) => createQueuedAgentInputSnapshot(message));
+ return this._pendingSessionInputs("followUp").map((message) => createQueuedAgentInputSnapshot(message));
+ }
+
+ private _notifySessionInputCheckpointChange(): void {
+ for (const resolve of this._sessionInputCheckpointWaiters) resolve();
+ this._sessionInputCheckpointWaiters.clear();
+ }
+
+ /**
+ * Marks a direct prompt as being between admission and its preflight outcome
+ * (queued, handed off to the agent, or failed). Restart checkpoints wait for
+ * these sections so an accepted input cannot fall between the queue snapshot
+ * and the transcript flush.
+ */
+ private _enterDirectPromptSection(): () => void {
+ this._directPromptSectionCount++;
+ let ended = false;
+ return () => {
+ if (ended) return;
+ ended = true;
+ this._directPromptSectionCount--;
+ this._notifySessionInputCheckpointChange();
+ };
+ }
+
+ async waitForSessionInputCheckpoint(signal?: AbortSignal): Promise<void> {
+ // An executing command was already shifted off the queue; the snapshot
+ // must wait for it or it vanishes from durable queued input.
+ while (
+ (this._activeSessionInput?.kind === "prompt" && this._activeSessionInput.phase === "preparing") ||
+ this._activeSessionInput?.kind === "command" ||
+ this._directPromptSectionCount > 0
+ ) {
+ if (signal?.aborted) throw new Error("Update restart preparation cancelled");
+ await new Promise<void>((resolve, reject) => {
+ const onChange = () => {
+ cleanup();
+ resolve();
+ };
+ const onAbort = () => {
+ cleanup();
+ reject(new Error("Update restart preparation cancelled"));
+ };
+ const cleanup = () => {
+ this._sessionInputCheckpointWaiters.delete(onChange);
+ signal?.removeEventListener("abort", onAbort);
+ };
+ this._sessionInputCheckpointWaiters.add(onChange);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+ }
+ if (signal?.aborted) throw new Error("Update restart preparation cancelled");
+ // Handed-off inputs reach the transcript through the event queue; drain the
+ // current snapshot so the flush below persists them before the snapshot is taken.
+ await waitForPromiseOrAbort(this._agentEventQueue, signal, "Update restart preparation cancelled");
+ if (signal?.aborted) throw new Error("Update restart preparation cancelled");
+ this.sessionManager.flushNow();
+ }
+
+ acquireQueuedWorkPause(): { release(): void } {
+ const token = Symbol("queued-work-pause");
+ this._queuedWorkPauses.add(token);
+ this._sessionInputPumpRequested = false;
+ this._sessionInputPumpEpoch++;
+ let released = false;
+ return {
+ release: () => {
+ if (released) return;
+ released = true;
+ this._queuedWorkPauses.delete(token);
+ if (this._queuedWorkPauses.size === 0) this._wakeQueuedWorkAdmissionWaiters();
+ this._scheduleSessionInputPump();
+ },
+ };
+ }
+
+ private _wakeQueuedWorkAdmissionWaiters(): void {
+ for (const resolve of this._queuedWorkAdmissionWaiters) resolve();
+ this._queuedWorkAdmissionWaiters.clear();
+ }
+
+ private _assertDirectTurnAdmissionAvailable(): void {
+ if (this._disposed || this._disposing) {
+ throw new Error("Cannot start a direct turn because the session is disposing or disposed.");
+ }
+ if (this.pendingMessageCount > 0 && this._sessionInputPumpSuspended) {
+ throw new Error("Cannot start a direct turn while queued session input is suspended.");
+ }
+ }
+
+ private async _acquireTurnAdmission(signal?: AbortSignal): Promise<{ owner: symbol; release(): void }> {
+ const inheritedOwner = this._turnAdmissionContext.getStore();
+ if (inheritedOwner !== undefined && inheritedOwner === this._turnAdmissionOwner) {
+ return { owner: inheritedOwner, release: () => {} };
+ }
+ const previous = this._turnAdmissionTail;
+ let resolve = () => {};
+ this._turnAdmissionTail = new Promise<void>((release) => {
+ resolve = release;
+ });
+ try {
+ await waitForPromptAdmission(previous, signal);
+ } catch (error) {
+ // Keep this cancelled waiter in the FIFO chain until its predecessor
+ // releases; resolving immediately would let a later caller bypass the
+ // current admission owner.
+ void previous.then(resolve, resolve);
+ throw error;
+ }
+ const owner = Symbol("turn-admission");
+ this._turnAdmissionOwner = owner;
+ let released = false;
+ return {
+ owner,
+ release: () => {
+ if (released) return;
+ released = true;
+ if (this._turnAdmissionOwner === owner) this._turnAdmissionOwner = undefined;
+ resolve();
+ },
+ };
+ }
+
+ private async _acquireDirectTurnAdmission(
+ options: { allowStreaming?: boolean; allowPendingQueue?: boolean; signal?: AbortSignal } = {},
+ ): Promise<{ owner: symbol; release(): void }> {
+ while (true) {
+ this._assertDirectTurnAdmissionAvailable();
+ await this._waitForQueuedWorkAdmission(options.signal);
+ this._assertDirectTurnAdmissionAvailable();
+ if (this.pendingMessageCount > 0) this._scheduleSessionInputPump();
+ const admission = await this._acquireTurnAdmission(options.signal);
+ try {
+ this._assertDirectTurnAdmissionAvailable();
+ if (this._queuedWorkPauses.size > 0) {
+ admission.release();
+ await this._waitForQueuedWorkAdmission(options.signal);
+ continue;
+ }
+ // queueIfBusy callers enqueue behind pending work at preflight; they need ownership, not a drained queue.
+ if (
+ (options.allowStreaming === true && this.isStreaming) ||
+ options.allowPendingQueue === true ||
+ (this.pendingMessageCount === 0 &&
+ this._activeSessionInput === undefined &&
+ !this._pumpingSessionInput &&
+ !this._sessionInputPumpRequested)
+ ) {
+ // This is the ownership commit point: no prompt/session state has
+ // been consumed yet, and from here the session owns delivery.
+ throwIfPromptAdmissionCancelled(options.signal);
+ return admission;
+ }
+ } catch (error) {
+ admission.release();
+ throw error;
+ }
+ admission.release();
+ await waitForPromptAdmission(this.waitForSessionInputIdle(), options.signal);
+ this._assertDirectTurnAdmissionAvailable();
+ }
+ }
+
+ private async _waitForQueuedWorkAdmission(signal?: AbortSignal): Promise<void> {
+ while (this._queuedWorkPauses.size > 0) {
+ this._assertDirectTurnAdmissionAvailable();
+ let wake = () => {};
+ const wait = new Promise<void>((resolve) => {
+ wake = resolve;
+ this._queuedWorkAdmissionWaiters.add(resolve);
+ });
+ try {
+ await waitForPromptAdmission(wait, signal);
+ } finally {
+ this._queuedWorkAdmissionWaiters.delete(wake);
+ }
+ this._assertDirectTurnAdmissionAvailable();
+ }
+ }
+
+ /** Compatibility wrapper for callers migrating to owned pause leases. */
+ pauseQueuedWork(): boolean {
+ if (this._legacyQueuedWorkPause) return false;
+ this._legacyQueuedWorkPause = this.acquireQueuedWorkPause();
+ return true;
+ }
+
+ /** Compatibility wrapper that releases only the pause acquired by pauseQueuedWork(). */
+ resumeQueuedWork(): boolean {
+ this._sessionInputPumpSuspended = false;
+ const pause = this._legacyQueuedWorkPause;
+ if (pause) {
+ this._legacyQueuedWorkPause = undefined;
+ pause.release();
+ } else {
+ this._scheduleSessionInputPump();
+ }
+ return this.pendingMessageCount > 0;
+ }
+
+ async waitForSessionInputIdle(): Promise<void> {
+ while (true) {
+ const pump = this._sessionInputPump;
+ await pump;
+ if (pump === this._sessionInputPump && !this._sessionInputPumpRequested && !this._pumpingSessionInput) return;
+ }
+ }
+
+ async waitForIdle(): Promise<void> {
+ while (true) {
+ const pump = this._sessionInputPump;
+ const acceptedPrompts = [...this._acceptedPromptCompletions];
+ await Promise.all([pump, ...acceptedPrompts]);
+ await this.agent.waitForIdle();
+ if (
+ pump === this._sessionInputPump &&
+ acceptedPrompts.length === this._acceptedPromptCompletions.size &&
+ acceptedPrompts.every((completion) => this._acceptedPromptCompletions.has(completion)) &&
+ !this._sessionInputPumpRequested &&
+ !this._pumpingSessionInput &&
+ !this.agent.state.isStreaming &&
+ this._acceptedAgentMessagePrompt === undefined
+ ) {
+ return;
+ }
+ }
}
getPendingNextTurnMessageSnapshots(): readonly CustomMessage[] {
@@ -5024,28 +5921,44 @@ export class AgentSession {
}
hasQueuedFollowUp(queueKey: string): boolean {
- return this._followUpMessages.some((message) => message.queueKey === queueKey);
+ return (
+ this._followUpMessages.some((message) => message.queueKey === queueKey) ||
+ this._activePendingPromptWithQueueKey(queueKey) !== undefined
+ );
+ }
+
+ /**
+ * The active-input prompt owning `queueKey` while it still counts as
+ * pending. Once handed off it belongs to the running turn, so a same-key
+ * follow-up must queue for the next turn instead of coalescing away.
+ */
+ private _activePendingPromptWithQueueKey(queueKey: string): PreparedPromptInput | undefined {
+ const active = this._activeSessionInput;
+ if (active?.kind !== "prompt" || active.phase !== "preparing" || active.cancelled) return undefined;
+ return active.items.find((item) => item.queueKey === queueKey);
}
removeQueuedFollowUp(queueKey: string): boolean {
- const removedSteering = this._steeringMessages.filter((message) => message.queueKey === queueKey);
- const removedFollowUp = this._followUpMessages.filter((message) => message.queueKey === queueKey);
- if (removedSteering.length === 0 && removedFollowUp.length === 0) {
- return false;
- }
- this._steeringMessages = this._steeringMessages.filter((message) => message.queueKey !== queueKey);
- this._followUpMessages = this._followUpMessages.filter((message) => message.queueKey !== queueKey);
- const removedMessages = new Set<AgentMessage>([
- ...removedSteering.map((message) => message.message),
- ...removedFollowUp.map((message) => message.message),
- ]);
- for (const message of [...removedSteering, ...removedFollowUp]) {
- this._rejectAgentMessageDelivery(
+ const removedSteering = this._steeringMessages.filter(
+ (message): message is PreparedPromptInput => message.kind === "prompt" && message.queueKey === queueKey,
+ );
+ const removedFollowUp = this._followUpMessages.filter(
+ (message): message is PreparedPromptInput => message.kind === "prompt" && message.queueKey === queueKey,
+ );
+ const active = this._removeActivePreparingPrompts((message) => message.queueKey === queueKey);
+ removedSteering.push(...active.steering);
+ removedFollowUp.push(...active.followUp);
+ if (removedSteering.length === 0 && removedFollowUp.length === 0) return false;
+ const removed = new Set<QueuedSessionInput>([...removedSteering, ...removedFollowUp]);
+ this._steeringMessages = this._steeringMessages.filter((message) => !removed.has(message));
+ this._followUpMessages = this._followUpMessages.filter((message) => !removed.has(message));
+ this._syncSteeringStopPending();
+ for (const message of removed) {
+ this._rejectAgentMessage(
message.agentMessageId,
new Error("Queued agent message was cleared before delivery."),
);
}
- this.agent.removeQueuedMessages((message) => removedMessages.has(message));
this._emitQueueUpdate();
return true;
}
@@ -5055,6 +5968,10 @@ export class AgentSession {
}
requestAbort(): void {
+ this._sessionInputPumpRequested = false;
+ this._sessionInputPumpEpoch++;
+ this._sessionInputPumpSuspended = true;
+ this._cancelPostCompactionContinue();
this.abortRetry();
this.abortCompaction();
this.abortBranchSummary();
@@ -5063,8 +5980,6 @@ export class AgentSession {
this._autoRefineBranchVersion++;
this._autoRefineReviewAbort?.abort();
this._refineAbortController?.abort();
- this._pendingMessageResumeRequested = false;
- this._pendingMessageResumeEpoch++;
this.agent.abort();
}
@@ -5090,9 +6005,13 @@ export class AgentSession {
}
abortForUpdateRestart(): void {
+ // Cancel scheduled pumps and suspend new ones: queued inputs must survive
+ // into the restart manifest instead of starting a turn during teardown.
+ this._sessionInputPumpRequested = false;
+ this._sessionInputPumpEpoch++;
+ this._sessionInputPumpSuspended = true;
+ this._cancelPostCompactionContinue();
this.abortRetry();
- this._pendingMessageResumeRequested = false;
- this._pendingMessageResumeEpoch++;
this._cancelActiveRlmChildRuns("Parent session aborted for update restart");
this._goalAbortInProgress = this._goalState.status === "active";
this.agent.abort();
@@ -5523,10 +6442,13 @@ export class AgentSession {
* Aborts current agent operation first.
* @param customInstructions Optional instructions for the compaction summary
*/
- async compact(customInstructions?: string): Promise<CompactionResult> {
+ async compact(customInstructions?: string, options: { skipAbort?: boolean } = {}): Promise<CompactionResult> {
+ if (options.skipAbort && this.isStreaming) {
+ throw new Error("Cannot compact without aborting while the agent is running.");
+ }
const hadPostCompactionContinue = this._postCompactionContinuationScheduled;
this._disconnectFromAgent();
- await this.abort();
+ if (!options.skipAbort) await this.abort();
let didCompact = false;
this._compactionAbortController = new AbortController();
let resolveCompactionOperation: () => void = () => {};
@@ -5585,13 +6507,17 @@ export class AgentSession {
this._compactionOperation = undefined;
}
resolveCompactionOperation();
- this._schedulePendingMessageResume();
+ this._scheduleSessionInputPump();
if (didCompact) {
this._discardPendingAutoRefine({ cancelPostCompactionContinue: true });
if (hadPostCompactionContinue) {
this._schedulePostCompactionContinue();
}
- this._scheduleAutoRefineAfterCompaction(hadPostCompactionContinue);
+ // 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,
+ );
}
}
}
@@ -5661,6 +6587,7 @@ export class AgentSession {
);
const newEntries = this.sessionManager.getEntries();
this.agent.state.messages = this.sessionManager.buildSessionContext().messages;
+ this._mergeUnpersistedCompactionOutcomes(this.agent.state.messages);
this._restoreLateIpythonSentAgentMessages();
// Get the saved compaction entry for the extension event
@@ -5704,6 +6631,7 @@ export class AgentSession {
this._postCompactionContinuationTimer = undefined;
}
this._postCompactionContinuationScheduled = false;
+ this._scheduledPostCompactionContinuationMessages = [];
}
private _discardPendingAutoRefine(options: { cancelPostCompactionContinue?: boolean } = {}): void {
@@ -5802,25 +6730,61 @@ export class AgentSession {
return;
}
this._postCompactionContinuationScheduled = true;
+ this._scheduledPostCompactionContinuationMessages = [...this._postCompactionContinuationMessages];
this._postCompactionContinuationTimer = setTimeout(() => {
this._postCompactionContinuationTimer = undefined;
void this._runScheduledPostCompactionContinue();
}, 100);
}
+ /** Whether any snapshot of scheduled continuation messages is still session-owned. */
+ private _sessionOwnsScheduledContinuations(continuationMessages: AgentMessage[]): boolean {
+ return continuationMessages.some((message) => this._postCompactionContinuationMessages.includes(message));
+ }
+
private async _runScheduledPostCompactionContinue(): Promise<void> {
await this._waitForRefineIdle();
if (!this._postCompactionContinuationScheduled) {
return;
}
- if (this.isStreaming || this.isCompacting) {
+ if (this.isStreaming || this.isCompacting || this.isRetrying || this._queuedWorkPauses.size > 0) {
this._postCompactionContinuationScheduled = false;
this._schedulePostCompactionContinue();
return;
}
+ const continuationMessages = [...this._scheduledPostCompactionContinuationMessages];
+ if (continuationMessages.length > 0 && !this._sessionOwnsScheduledContinuations(continuationMessages)) {
+ this._cancelPostCompactionContinue();
+ this._scheduleAutoRefineAfterAgentEnd();
+ return;
+ }
+ // An empty queue is not idle: the pump owns items moved into _activeSessionInput before handoff.
+ if (
+ this.pendingMessageCount > 0 ||
+ this._activeSessionInput !== undefined ||
+ this._pumpingSessionInput ||
+ this._sessionInputPumpRequested
+ ) {
+ this._scheduleSessionInputPump();
+ await this._sessionInputPump;
+ if (this._postCompactionContinuationScheduled) {
+ this._postCompactionContinuationScheduled = false;
+ const shouldReschedule =
+ continuationMessages.length === 0
+ ? this.pendingMessageCount > 0
+ : this._sessionOwnsScheduledContinuations(continuationMessages);
+ if (shouldReschedule) {
+ this._schedulePostCompactionContinue();
+ } else {
+ this._scheduledPostCompactionContinuationMessages = [];
+ this._scheduleAutoRefineAfterAgentEnd();
+ }
+ }
+ return;
+ }
+
this._postCompactionContinuationScheduled = false;
- const continuationMessages = [...this._postCompactionContinuationMessages];
try {
await this.agent.continue();
this._forgetConsumedPostCompactionContinuations(continuationMessages);
@@ -6061,7 +7025,15 @@ export class AgentSession {
*/
async refine(
options: { instructions?: string; rollbackId?: string; global?: boolean } = {},
+ internal: { skipAbort?: boolean } = {},
): Promise<RefinementResult> {
+ // Queued /refine executes from the session-input pump between turns;
+ // refine never aborts the agent (planning is backgrounded and the apply
+ // phase waits for quiescence), so skipAbort only asserts the pump's
+ // idle invariant instead of changing abort behavior.
+ if (internal.skipAbort && this.isStreaming) {
+ throw new Error("Cannot refine without aborting while the agent is running.");
+ }
// Wait for any existing refine (both planning and application) before
// starting a new run. This serializes concurrent /refine calls so two
// planning phases cannot race into concurrent _applyRefine calls that
@@ -6107,7 +7079,7 @@ export class AgentSession {
if (this._refineAbortController === refineAbort) {
this._refineAbortController = undefined;
}
- this._schedulePendingMessageResume();
+ this._scheduleSessionInputPump();
throw e;
} finally {
if (this._refinePlanInFlight === planSettled) {
@@ -6153,7 +7125,7 @@ export class AgentSession {
if (this._refineInFlight === applySettled) {
this._refineInFlight = undefined;
}
- this._schedulePendingMessageResume(true);
+ this._scheduleSessionInputPump();
}
}
@@ -6438,20 +7410,19 @@ export class AgentSession {
sameModel &&
isContextOverflow(assistantMessage, contextWindow)
) {
- if (this._overflowRecoveryAttempted) {
- this._emit({
- type: "compaction_end",
- reason: "overflow",
- result: undefined,
- aborted: false,
- willRetry: false,
- errorMessage:
+ if (this._overflowRecovery !== "idle") {
+ if (this._overflowRecovery === "attempted") {
+ this._overflowRecovery = "reported";
+ this._endCompactionUnsuccessfully(
+ "overflow",
+ "failed",
"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
- });
+ );
+ }
return false;
}
- this._overflowRecoveryAttempted = true;
+ this._overflowRecovery = "attempted";
// Remove the error message from agent state (it IS saved to session for history,
// but we don't want it in context for the retry)
const messages = this.agent.state.messages;
@@ -6489,6 +7460,54 @@ export class AgentSession {
* Internal: Run automatic (threshold/overflow) or model-requested compaction
* with events.
*/
+ /** Emit an unsuccessful compaction_end and durably record the outcome. */
+ private _endCompactionUnsuccessfully(
+ reason: CompactionOutcomeReason,
+ outcome: CompactionOutcome,
+ message: string,
+ options: { aborted?: boolean; errorSeverity?: "warning" | "error"; customInstructions?: string } = {},
+ ): void {
+ this._persistCompactionOutcome(reason, outcome, message);
+ this._emit({
+ type: "compaction_end",
+ reason,
+ result: undefined,
+ aborted: options.aborted ?? false,
+ willRetry: false,
+ // Aborts are user-initiated; they carry no error message on the event.
+ errorMessage: options.aborted ? undefined : message,
+ errorSeverity: options.errorSeverity,
+ customInstructions: options.customInstructions,
+ });
+ }
+
+ private _persistCompactionOutcome(
+ reason: CompactionOutcomeReason,
+ outcome: CompactionOutcome,
+ message: string,
+ ): void {
+ let outcomeMessage = createCompactionOutcomeMessage(message, { reason, outcome });
+ try {
+ this.sessionManager.appendCustomMessageEntryWithRollback(
+ outcomeMessage.customType,
+ outcomeMessage.content,
+ outcomeMessage.display,
+ outcomeMessage.details,
+ );
+ } catch (error) {
+ const persistenceError = error instanceof Error ? error.message : String(error);
+ outcomeMessage = createCompactionOutcomeMessage(
+ `${message}\n\nThis compaction outcome could not be saved to session history: ${persistenceError}`,
+ { reason, outcome },
+ );
+ // Not in the session file, so context rebuilds would drop the disclosure.
+ this._unpersistedCompactionOutcomes.push(outcomeMessage);
+ }
+ this.agent.state.messages.push(outcomeMessage);
+ this._emit({ type: "message_start", message: outcomeMessage });
+ this._emit({ type: "message_end", message: outcomeMessage });
+ }
+
private async _runAutoCompaction(
reason: "overflow" | "threshold" | "requested",
willRetry: boolean,
@@ -6508,7 +7527,10 @@ export class AgentSession {
// A requested compaction stopped the loop on purpose; don't stall if it fails.
const resumeAfterFailure = () => {
- if (reason === "requested" && (shouldContinueAfterCompaction || this.agent.hasQueuedMessages())) {
+ if (
+ reason === "requested" &&
+ (shouldContinueAfterCompaction || this.agent.hasQueuedMessages() || this.pendingMessageCount > 0)
+ ) {
this._schedulePostCompactionContinue();
}
};
@@ -6517,31 +7539,15 @@ export class AgentSession {
this._autoCompactionAbortController = new AbortController();
try {
- if (!this.model) {
- this._emit({
- type: "compaction_end",
- reason,
- result: undefined,
- aborted: false,
- willRetry: false,
- });
- this._clearQueuedAutonomousContinuationsAfterSkippedThresholdCompaction(
- reason === "threshold" && shouldContinueAfterCompaction,
- queuedAutonomousContinuationsForThisCompaction,
- );
- resumeAfterFailure();
- return false;
- }
-
- const authResult = await this._modelRegistry.getApiKeyAndHeaders(this.model);
- if (!authResult.ok || !authResult.apiKey) {
- this._emit({
- type: "compaction_end",
- reason,
- result: undefined,
- aborted: false,
- willRetry: false,
- });
+ const authResult = this.model ? await this._modelRegistry.getApiKeyAndHeaders(this.model) : undefined;
+ if (!this.model || !authResult || !authResult.ok || !authResult.apiKey) {
+ const detail =
+ !this.model || !authResult
+ ? "no model is selected"
+ : authResult.ok
+ ? "no API key is available"
+ : authResult.error;
+ this._endCompactionUnsuccessfully(reason, "failed", `Compaction failed: ${detail}`);
this._clearQueuedAutonomousContinuationsAfterSkippedThresholdCompaction(
reason === "threshold" && shouldContinueAfterCompaction,
queuedAutonomousContinuationsForThisCompaction,
@@ -6559,7 +7565,8 @@ export class AgentSession {
});
this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry, customInstructions });
- const hasQueuedMessages = this.agent.hasQueuedMessages();
+ // Queued work lives in both the agent queues and the session-owned queues.
+ const hasQueuedMessages = this.agent.hasQueuedMessages() || this.pendingMessageCount > 0;
const willContinueAfterCompaction = willRetry || shouldContinueAfterCompaction || hasQueuedMessages;
if (willRetry) {
@@ -6590,52 +7597,41 @@ export class AgentSession {
const aborted =
errorMessage === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError");
if (aborted) {
- this._emit({
- type: "compaction_end",
+ this._endCompactionUnsuccessfully(
reason,
- result: undefined,
- aborted: true,
- willRetry: false,
- customInstructions,
- });
+ "cancelled",
+ `${reason === "requested" ? "Requested c" : "C"}ompaction cancelled`,
+ { aborted: true, customInstructions },
+ );
return false;
}
if (error instanceof CompactionSkippedError) {
- this._emit({
- type: "compaction_end",
+ this._endCompactionUnsuccessfully(
reason,
- result: undefined,
- aborted: false,
- willRetry: false,
- errorMessage:
- reason === "requested"
- ? `Requested compaction skipped: ${errorMessage}`
- : `Auto-compaction skipped: ${errorMessage}`,
- errorSeverity: "warning",
- customInstructions,
- });
+ "skipped",
+ reason === "requested"
+ ? `Requested compaction skipped: ${errorMessage}`
+ : `Auto-compaction skipped: ${errorMessage}`,
+ { errorSeverity: "warning", customInstructions },
+ );
resumeAfterFailure();
return false;
}
- this._emit({
- type: "compaction_end",
+ this._endCompactionUnsuccessfully(
reason,
- result: undefined,
- aborted: false,
- willRetry: false,
- errorMessage:
- reason === "overflow"
- ? `Context overflow recovery failed: ${errorMessage}`
- : reason === "requested"
- ? `Requested compaction failed: ${errorMessage}`
- : `Auto-compaction failed: ${errorMessage}`,
- customInstructions,
- });
+ "failed",
+ reason === "overflow"
+ ? `Context overflow recovery failed: ${errorMessage}`
+ : reason === "requested"
+ ? `Requested compaction failed: ${errorMessage}`
+ : `Auto-compaction failed: ${errorMessage}`,
+ { customInstructions },
+ );
resumeAfterFailure();
return false;
} finally {
this._autoCompactionAbortController = undefined;
- this._schedulePendingMessageResume();
+ this._scheduleSessionInputPump();
}
}
@@ -8610,59 +9606,7 @@ export class AgentSession {
private async _drainQueuedMessagesAfterBash(): Promise<void> {
await this.agent.waitForIdle();
- if (
- this.isStreaming ||
- this.isCompacting ||
- this.isRetrying ||
- this.hasAcceptedPromptInFlight ||
- this.pendingMessageCount === 0
- ) {
- return;
- }
- await this._promptPendingMessagesWithNextTurnContext();
- }
-
- private async _promptPendingMessagesWithNextTurnContext(): Promise<void> {
- const steeringMessages = [...this._steeringMessages];
- const followUpMessages = [...this._followUpMessages];
- const drainedSteeringMessages = steeringMessages.length > 0 ? steeringMessages : [];
- const drainedFollowUpMessages = steeringMessages.length > 0 ? [] : followUpMessages;
- const queuedMessages = [...drainedSteeringMessages, ...drainedFollowUpMessages].flatMap((message) => [
- ...message.prefixMessages,
- message.message,
- ]);
- if (queuedMessages.length === 0) {
- return;
- }
-
- const queuedMessageSet = new Set<AgentMessage>(queuedMessages);
- this.agent.removeQueuedMessages((message) => queuedMessageSet.has(message));
- this._flushPendingBashMessages();
- const nextTurnMessages = this._pendingNextTurnMessages;
- this._pendingNextTurnMessages = [];
- try {
- await this.agent.prompt([...nextTurnMessages, ...queuedMessages]);
- await this.waitForRetry();
- } catch {
- const deliveredMessages = new Set(this.agent.state.messages);
- this._pendingNextTurnMessages.unshift(
- ...nextTurnMessages.filter((message) => !deliveredMessages.has(message)).map((message) => ({ ...message })),
- );
- const queuedSteering = new Set(this._steeringMessages.map((message) => message.message));
- const queuedFollowUps = new Set(this._followUpMessages.map((message) => message.message));
- for (const queued of drainedSteeringMessages) {
- queued.prefixMessages = queued.prefixMessages.filter((message) => !deliveredMessages.has(message));
- if (queuedSteering.has(queued.message) && !deliveredMessages.has(queued.message)) {
- this.agent.steer([...queued.prefixMessages, queued.message]);
- }
- }
- for (const queued of drainedFollowUpMessages) {
- queued.prefixMessages = queued.prefixMessages.filter((message) => !deliveredMessages.has(message));
- if (queuedFollowUps.has(queued.message) && !deliveredMessages.has(queued.message)) {
- this.agent.followUp([...queued.prefixMessages, queued.message]);
- }
- }
- }
+ this._scheduleSessionInputPump();
}
private async runUserBashLocked(
@@ -8830,17 +9774,29 @@ export class AgentSession {
* @param options.label Label to attach to the branch summary entry
* @returns Result with editorText (if user message) and cancelled status
*/
+ private _branchNavigationQueue: Promise<void> = Promise.resolve();
+
async navigateTree(
targetId: string,
options: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},
): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {
- const oldLeafId = this.sessionManager.getLeafId();
-
- // No-op if already at target
- if (targetId === oldLeafId) {
- return { cancelled: false };
+ const previous = this._branchNavigationQueue;
+ let release = () => {};
+ this._branchNavigationQueue = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ await previous;
+ try {
+ return await this._navigateTree(targetId, options);
+ } finally {
+ release();
}
+ }
+ private async _navigateTree(
+ targetId: string,
+ options: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},
+ ): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {
// Model required for summarization
if (options.summarize && !this.model) {
throw new Error("No model available for summarization");
@@ -8851,6 +9807,33 @@ export class AgentSession {
throw new Error(`Entry ${targetId} not found`);
}
+ const queuedWorkPause = this.acquireQueuedWorkPause();
+ let admission: { owner: symbol; release(): void } | undefined;
+ try {
+ admission = await this._acquireTurnAdmission();
+ return await this._turnAdmissionContext.run(admission.owner, async () => {
+ await this.agent.waitForIdle();
+ await this._agentEventQueue;
+ return this._navigateTreeUnderPause(targetId, targetEntry, options);
+ });
+ } finally {
+ queuedWorkPause.release();
+ admission?.release();
+ }
+ }
+
+ private async _navigateTreeUnderPause(
+ targetId: string,
+ targetEntry: NonNullable<ReturnType<SessionManager["getEntry"]>>,
+ options: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },
+ ): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {
+ const oldLeafId = this.sessionManager.getLeafId();
+
+ // No-op if already at target after admitted work has settled.
+ if (targetId === oldLeafId) {
+ return { cancelled: false };
+ }
+
// Do not switch branches while /refine has detached event handling and is
// about to persist harness/session entries for the current branch.
await this._invalidatePendingAutoRefineForBranchChange();
@@ -9007,8 +9990,10 @@ export class AgentSession {
// Update agent state
const sessionContext = this.sessionManager.buildSessionContext();
this.agent.state.messages = sessionContext.messages;
+ this._mergeUnpersistedCompactionOutcomes(this.agent.state.messages);
this._restoreLateIpythonSentAgentMessages();
this._reloadGoalStateFromBranch();
+ this._invalidateQueuedPromptPreparation();
// Emit session_tree event
await this._extensionRunner.emit({
@@ -9028,7 +10013,6 @@ export class AgentSession {
this._branchSummaryOperation = undefined;
}
resolveBranchSummaryOperation();
- this._schedulePendingMessageResume();
}
}
diff --git a/packages/coding-agent/src/core/cron-jobs.ts b/packages/coding-agent/src/core/cron-jobs.ts
index 9a2c177e42..783db5dac4 100644
--- a/packages/coding-agent/src/core/cron-jobs.ts
+++ b/packages/coding-agent/src/core/cron-jobs.ts
@@ -77,6 +77,7 @@ export interface AgentCronDispatch {
export interface AgentCronSchedulerHooks {
runJob: (job: AgentCronJob) => Promise<AgentCronJobRunResult | undefined>;
+ beginDispatch?: (dispatch: AgentCronDispatch) => (() => void) | undefined;
now?: () => Date;
onError?: (job: AgentCronJob, error: unknown) => void;
}
@@ -762,6 +763,16 @@ export class AgentCronJobStore {
return recovered;
}
+ recoverInterruptedDispatchesById(dispatchIds: readonly string[], now = new Date()): AgentCronJob[] {
+ const recovered: AgentCronJob[] = [];
+ const interruptedDispatchIds = new Set(dispatchIds);
+ this.mutateStates((state) => {
+ recoverInterruptedInState(state, now, recovered, interruptedDispatchIds);
+ return [];
+ });
+ return recovered;
+ }
+
getDueJob(id: string, now = new Date()): AgentCronJob | undefined {
return this.readJobs().find((job) => job.id === id && isDueJob(job, now));
}
@@ -956,48 +967,70 @@ export class AgentCronScheduler {
}
async runDue(now = this.now()): Promise<number> {
- if (this.running) {
+ if (this.running || (this.stopped && this.hasStarted)) {
return 0;
}
this.running = true;
- let dispatches: AgentCronDispatch[] = [];
+ const dispatches: Array<{ dispatch: AgentCronDispatch; endDispatch?: () => void }> = [];
+ let claimedDispatches: AgentCronDispatch[] | undefined;
try {
- dispatches = this.store.claimDue(now, this.now());
+ claimedDispatches = this.store.claimDue(now, this.now());
+ for (const dispatch of claimedDispatches) {
+ dispatches.push({ dispatch, endDispatch: this.hooks.beginDispatch?.(dispatch) });
+ }
+ } catch (error) {
+ for (const claimed of dispatches) claimed.endDispatch?.();
+ if (claimedDispatches) {
+ this.store.recoverInterruptedDispatchesById(
+ claimedDispatches.map((dispatch) => dispatch.id),
+ this.now(),
+ );
+ }
+ throw error;
} finally {
this.running = false;
if (!this.stopped) {
this.scheduleNext();
}
}
- const results = await Promise.all(dispatches.map((dispatch) => this.queueDispatch(dispatch)));
+ const results = await Promise.all(
+ dispatches.map(({ dispatch, endDispatch }) => this.queueDispatch(dispatch, endDispatch)),
+ );
return results.filter((result) => result !== "skipped").length;
}
- private queueDispatch(dispatch: AgentCronDispatch): Promise<AgentCronJobRunResult | undefined> {
+ private queueDispatch(
+ dispatch: AgentCronDispatch,
+ endDispatch?: () => void,
+ ): Promise<AgentCronJobRunResult | undefined> {
const laneKey = dispatch.job.activeSessionId;
const previous = this.dispatchLanes.get(laneKey) ?? Promise.resolve();
const task = previous
.catch(() => undefined)
.then(async (): Promise<AgentCronJobRunResult | undefined> => {
- const job = this.store.getClaimedJob(dispatch.job.id);
- if (!job) {
- this.store.recordDispatchResult(dispatch.id, { now: this.now(), outcome: "skipped" });
- return "skipped";
- }
- let runResult: AgentCronJobRunResult | undefined;
- let error: unknown;
try {
- runResult = await this.hooks.runJob(job);
- } catch (runError) {
- error = runError;
- this.hooks.onError?.(job, runError);
+ const job = this.store.getClaimedJob(dispatch.job.id);
+ if (!job) {
+ this.store.recordDispatchResult(dispatch.id, { now: this.now(), outcome: "skipped" });
+ return "skipped";
+ }
+ let runResult: AgentCronJobRunResult | undefined;
+ let error: unknown;
+ try {
+ runResult = await this.hooks.runJob(job);
+ } catch (runError) {
+ error = runError;
+ this.hooks.onError?.(job, runError);
+ }
+ this.store.recordDispatchResult(dispatch.id, {
+ now: this.now(),
+ outcome: runResult === "skipped" && error === undefined ? "skipped" : "ran",
+ error,
+ });
+ return runResult;
+ } finally {
+ endDispatch?.();
}
- this.store.recordDispatchResult(dispatch.id, {
- now: this.now(),
- outcome: runResult === "skipped" && error === undefined ? "skipped" : "ran",
- error,
- });
- return runResult;
});
const lane = task.then(
() => undefined,
@@ -1566,12 +1599,20 @@ function claimDueInState(state: CronJobsState, dueAt: Date, claimedAt: Date): Ag
return dispatches;
}
-function recoverInterruptedInState(state: CronJobsState, now: Date, recovered: AgentCronJob[]): void {
- if (state.dispatches.length === 0) {
+function recoverInterruptedInState(
+ state: CronJobsState,
+ now: Date,
+ recovered: AgentCronJob[],
+ dispatchIds?: ReadonlySet<string>,
+): void {
+ const interrupted = dispatchIds
+ ? state.dispatches.filter((dispatch) => dispatchIds.has(dispatch.id))
+ : state.dispatches;
+ if (interrupted.length === 0) {
return;
}
- const interruptedIds = new Set(state.dispatches.map((dispatch) => dispatch.jobId));
- state.dispatches = [];
+ const interruptedIds = new Set(interrupted.map((dispatch) => dispatch.jobId));
+ state.dispatches = dispatchIds ? state.dispatches.filter((dispatch) => !dispatchIds.has(dispatch.id)) : [];
state.jobs = state.jobs.map((job) => {
if (!interruptedIds.has(job.id) || job.status !== "active") {
return job;
diff --git a/packages/coding-agent/src/core/messages.ts b/packages/coding-agent/src/core/messages.ts
index 63f0695358..991d5a5122 100644
--- a/packages/coding-agent/src/core/messages.ts
+++ b/packages/coding-agent/src/core/messages.ts
@@ -8,6 +8,7 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { ImageContent, Message, TextContent } from "@earendil-works/pi-ai";
import type { AgentCronJob } from "./cron-jobs.js";
+import { isSessionSlashCommandName, parseSessionSlashCommand, type SessionSlashCommand } from "./slash-commands.js";
export const COMPACTION_SUMMARY_PREFIX = `The conversation history before this point was compacted into the following summary:
@@ -27,6 +28,48 @@ export const BRANCH_SUMMARY_SUFFIX = `</summary>`;
export const HEARTBEAT_PROMPT_CUSTOM_TYPE = "heartbeat_prompt";
export const HEARTBEAT_PROMPT_PREVIEW_LABEL = "Heartbeat prompt";
export const IPYTHON_STATE_RESTORED_CUSTOM_TYPE = "ipython_state_restored";
+export const SESSION_SLASH_COMMAND_CUSTOM_TYPE = "session_slash_command";
+export const SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE = "session_slash_command_result";
+export const COMPACTION_OUTCOME_CUSTOM_TYPE = "compaction_outcome";
+
+export interface SessionSlashCommandDetails {
+ command: SessionSlashCommand;
+ commandEntryId?: string;
+}
+
+export interface SessionSlashCommandResultDetails {
+ command: SessionSlashCommand;
+ success: boolean;
+ severity: "info" | "warning" | "error";
+ error?: string;
+ commandEntryId?: string;
+}
+
+export interface SessionSlashCommandMessage extends CustomMessage<SessionSlashCommandDetails> {
+ customType: typeof SESSION_SLASH_COMMAND_CUSTOM_TYPE;
+ content: string;
+ details: SessionSlashCommandDetails;
+}
+
+export interface SessionSlashCommandResultMessage extends CustomMessage<SessionSlashCommandResultDetails> {
+ customType: typeof SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE;
+ content: string;
+ details: SessionSlashCommandResultDetails;
+}
+
+export type CompactionOutcomeReason = "threshold" | "overflow" | "requested";
+export type CompactionOutcome = "skipped" | "cancelled" | "failed";
+
+export interface CompactionOutcomeDetails {
+ reason: CompactionOutcomeReason;
+ outcome: CompactionOutcome;
+}
+
+export interface CompactionOutcomeMessage extends CustomMessage<CompactionOutcomeDetails> {
+ customType: typeof COMPACTION_OUTCOME_CUSTOM_TYPE;
+ content: string;
+ details: CompactionOutcomeDetails;
+}
/**
* Message type for bash executions via the ! command.
@@ -81,6 +124,8 @@ export interface CompactionSummaryMessage {
role: "compactionSummary";
summary: string;
tokensBefore: number;
+ /** Number of retained messages that precede this summary in transcript presentation. */
+ retainedMessageCount?: number;
/** User instructions that guided the summary (from `/compact <instructions>`) */
customInstructions?: string;
timestamp: number;
@@ -148,11 +193,13 @@ export function createCompactionSummaryMessage(
tokensBefore: number,
timestamp: string,
customInstructions?: string,
+ retainedMessageCount?: number,
): CompactionSummaryMessage {
return {
role: "compactionSummary",
- summary: summary,
+ summary,
tokensBefore,
+ retainedMessageCount,
customInstructions,
timestamp: new Date(timestamp).getTime(),
};
@@ -176,6 +223,127 @@ export function createCustomMessage(
};
}
+export function createSessionSlashCommandMessage(
+ command: SessionSlashCommand,
+ details: Omit<SessionSlashCommandDetails, "command"> = {},
+ display = true,
+ timestamp = Date.now(),
+): SessionSlashCommandMessage {
+ return {
+ role: "custom",
+ customType: SESSION_SLASH_COMMAND_CUSTOM_TYPE,
+ content: command.text,
+ display,
+ details: { ...details, command: { ...command } },
+ timestamp,
+ };
+}
+
+export function createSessionSlashCommandResultMessage(
+ content: string,
+ details: SessionSlashCommandResultDetails,
+ display = true,
+ timestamp = Date.now(),
+): SessionSlashCommandResultMessage {
+ return {
+ role: "custom",
+ customType: SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE,
+ content,
+ display,
+ details: { ...details, command: { ...details.command } },
+ timestamp,
+ };
+}
+
+export function createCompactionOutcomeMessage(
+ content: string,
+ details: CompactionOutcomeDetails,
+ display = true,
+ timestamp = Date.now(),
+): CompactionOutcomeMessage {
+ return {
+ role: "custom",
+ customType: COMPACTION_OUTCOME_CUSTOM_TYPE,
+ content,
+ display,
+ details: { ...details },
+ timestamp,
+ };
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+function hasValidCustomMessageEnvelope(message: Record<string, unknown>, customType: string): boolean {
+ return (
+ message.role === "custom" &&
+ message.customType === customType &&
+ typeof message.content === "string" &&
+ typeof message.display === "boolean" &&
+ typeof message.timestamp === "number" &&
+ Number.isFinite(message.timestamp)
+ );
+}
+
+function isSessionSlashCommand(value: unknown): value is SessionSlashCommand {
+ if (
+ !isRecord(value) ||
+ !isSessionSlashCommandName(value.name) ||
+ typeof value.args !== "string" ||
+ typeof value.text !== "string"
+ ) {
+ return false;
+ }
+ const parsed = parseSessionSlashCommand(value.text);
+ return (
+ parsed !== undefined && parsed.name === value.name && parsed.args === value.args && parsed.text === value.text
+ );
+}
+
+function isValidCommandEntryId(value: unknown): value is string | undefined {
+ return value === undefined || (typeof value === "string" && value.length > 0);
+}
+
+export function isSessionSlashCommandMessage(message: unknown): message is SessionSlashCommandMessage {
+ if (
+ !isRecord(message) ||
+ !hasValidCustomMessageEnvelope(message, SESSION_SLASH_COMMAND_CUSTOM_TYPE) ||
+ typeof message.content !== "string"
+ ) {
+ return false;
+ }
+ if (!isRecord(message.details) || !isSessionSlashCommand(message.details.command)) return false;
+ return message.content === message.details.command.text && isValidCommandEntryId(message.details.commandEntryId);
+}
+
+export function isSessionSlashCommandResultMessage(message: unknown): message is SessionSlashCommandResultMessage {
+ if (!isRecord(message) || !hasValidCustomMessageEnvelope(message, SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE))
+ return false;
+ if (!isRecord(message.details) || !isSessionSlashCommand(message.details.command)) return false;
+ return (
+ typeof message.details.success === "boolean" &&
+ (message.details.severity === "info" ||
+ message.details.severity === "warning" ||
+ message.details.severity === "error") &&
+ (message.details.error === undefined || typeof message.details.error === "string") &&
+ isValidCommandEntryId(message.details.commandEntryId)
+ );
+}
+
+export function isCompactionOutcomeMessage(message: unknown): message is CompactionOutcomeMessage {
+ if (!isRecord(message) || !hasValidCustomMessageEnvelope(message, COMPACTION_OUTCOME_CUSTOM_TYPE)) return false;
+ if (!isRecord(message.details)) return false;
+ return (
+ (message.details.reason === "threshold" ||
+ message.details.reason === "overflow" ||
+ message.details.reason === "requested") &&
+ (message.details.outcome === "skipped" ||
+ message.details.outcome === "cancelled" ||
+ message.details.outcome === "failed")
+ );
+}
+
export function createHeartbeatPromptMessage(
job: AgentCronJob,
timestamp = Date.now(),
@@ -220,6 +388,13 @@ export function convertToLlm(messages: AgentMessage[]): Message[] {
timestamp: m.timestamp,
};
case "custom": {
+ if (
+ m.customType === SESSION_SLASH_COMMAND_CUSTOM_TYPE ||
+ m.customType === SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE ||
+ m.customType === COMPACTION_OUTCOME_CUSTOM_TYPE
+ ) {
+ return undefined;
+ }
const content = typeof m.content === "string" ? [{ type: "text" as const, text: m.content }] : m.content;
return {
role: "user",
diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.ts
index 1840af57dd..641a09c4b2 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -3,16 +3,21 @@ import type { AssistantMessage, ImageContent, Message, ServiceTier, TextContent,
import { randomUUID } from "crypto";
import {
appendFileSync,
+ chmodSync,
+ chownSync,
createReadStream,
existsSync,
mkdirSync,
readdirSync,
readFileSync,
+ realpathSync,
+ renameSync,
+ rmSync,
statSync,
writeFileSync,
} from "fs";
import { readdir, readFile, stat } from "fs/promises";
-import { dirname, join, resolve } from "path";
+import { basename, dirname, join, resolve } from "path";
import { createInterface } from "readline";
import { v7 as uuidv7 } from "uuid";
import { getAgentDir as getDefaultAgentDir, getSessionsDir } from "../config.js";
@@ -48,6 +53,25 @@ const CONTENT_ENTRY_TYPES = new Set([
"branch_summary",
]);
+function realpathIfPresent(path: string): string {
+ try {
+ return realpathSync(path);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return path;
+ throw error;
+ }
+}
+
+function statMetadataIfPresent(path: string): { mode: number; uid: number; gid: number } | undefined {
+ try {
+ const { mode, uid, gid } = statSync(path);
+ return { mode: mode & 0o777, uid, gid };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
+ throw error;
+ }
+}
+
export interface SessionHeader {
type: "session";
version?: number; // v1 sessions don't have this
@@ -501,39 +525,30 @@ export function buildSessionContext(
}
// Build messages and collect corresponding entries
- // When there's a compaction, we need to:
- // 1. Emit summary first (entry = compaction)
- // 2. Emit kept messages (from firstKeptEntryId up to compaction)
- // 3. Emit messages after compaction
+ // When there's a compaction, model context remains summary-first while the
+ // summary records where clients should present it among retained messages.
const messages: AgentMessage[] = [];
- const appendMessage = (entry: SessionEntry) => {
+ const appendMessage = (entry: SessionEntry, target = messages) => {
if (entry.type === "message") {
- messages.push(entry.message);
+ target.push(entry.message);
} else if (entry.type === "custom_message") {
- messages.push(
+ target.push(
createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp),
);
} else if (entry.type === "branch_summary" && entry.summary) {
- messages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));
+ target.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));
}
};
if (compaction) {
- // Emit summary first
- messages.push(
- createCompactionSummaryMessage(
- compaction.summary,
- compaction.tokensBefore,
- compaction.timestamp,
- compaction.customInstructions,
- ),
- );
-
// Find compaction index in path
const compactionIdx = path.findIndex((e) => e.type === "compaction" && e.id === compaction.id);
- // Emit kept messages (before compaction, starting from firstKeptEntryId)
+ // Collect kept messages (before compaction, starting from firstKeptEntryId).
+ // The context remains summary-first for the model; retainedMessageCount records
+ // the exact chronological presentation boundary for clients.
+ const retainedMessages: AgentMessage[] = [];
let foundFirstKept = false;
for (let i = 0; i < compactionIdx; i++) {
const entry = path[i];
@@ -541,10 +556,21 @@ export function buildSessionContext(
foundFirstKept = true;
}
if (foundFirstKept) {
- appendMessage(entry);
+ appendMessage(entry, retainedMessages);
}
}
+ messages.push(
+ createCompactionSummaryMessage(
+ compaction.summary,
+ compaction.tokensBefore,
+ compaction.timestamp,
+ compaction.customInstructions,
+ retainedMessages.length,
+ ),
+ ...retainedMessages,
+ );
+
// Emit messages after compaction
for (let i = compactionIdx + 1; i < path.length; i++) {
const entry = path[i];
@@ -1195,8 +1221,21 @@ export class SessionManager {
private _rewriteFile(): void {
if (!this.persist || !this.sessionFile) return;
const content = `${this.fileEntries.map((e) => JSON.stringify(e)).join("\n")}\n`;
- mkdirSync(dirname(this.sessionFile), { recursive: true });
- writeFileSync(this.sessionFile, content);
+ const targetPath = realpathIfPresent(this.sessionFile);
+ const directory = dirname(targetPath);
+ mkdirSync(directory, { recursive: true });
+ const tempPath = join(directory, `.${basename(targetPath)}.${process.pid}.${randomUUID()}.tmp`);
+ try {
+ const metadata = statMetadataIfPresent(targetPath);
+ writeFileSync(tempPath, content, metadata === undefined ? undefined : { mode: metadata.mode });
+ if (metadata !== undefined) {
+ chownSync(tempPath, metadata.uid, metadata.gid);
+ chmodSync(tempPath, metadata.mode);
+ }
+ renameSync(tempPath, targetPath);
+ } finally {
+ rmSync(tempPath, { force: true });
+ }
this._notifyPersistListeners();
}
@@ -1606,6 +1645,41 @@ export class SessionManager {
return entry.id;
}
+ /**
+ * Append a custom message, undoing the append if persistence fails so a
+ * best-effort record never leaves an unsaved leaf for later entries.
+ */
+ appendCustomMessageEntryWithRollback<T = unknown>(
+ customType: string,
+ content: string | (TextContent | ImageContent)[],
+ display: boolean,
+ details?: T,
+ ): string {
+ const previousLeafId = this.leafId;
+ try {
+ const entryId = this.appendCustomMessageEntry(customType, content, display, details);
+ this.flushNow();
+ return entryId;
+ } catch (error) {
+ // The append indexes the entry before persisting it; undo exactly that.
+ if (this.leafId !== null && this.leafId !== previousLeafId) {
+ this.byId.delete(this.leafId);
+ this.fileEntries.pop();
+ this.leafId = previousLeafId;
+ // The failed append may have left a torn line on disk. Restore the file
+ // from the rolled-back entries now; if that also fails (e.g. the disk is
+ // still full), fall back to forcing the next persist to rewrite.
+ this.flushed = false;
+ try {
+ this.flushNow();
+ } catch {
+ this.flushed = false;
+ }
+ }
+ throw error;
+ }
+ }
+
// =========================================================================
// Tree Traversal
// =========================================================================
diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.ts
index 015894733c..21504d4b54 100644
--- a/packages/coding-agent/src/core/slash-commands.ts
+++ b/packages/coding-agent/src/core/slash-commands.ts
@@ -10,9 +10,58 @@ export interface SlashCommandInfo {
sourceInfo: SourceInfo;
}
+export const SESSION_SLASH_COMMAND_NAMES = ["compact", "refine", "goal", "autonomous"] as const;
+
+export type SessionSlashCommandName = (typeof SESSION_SLASH_COMMAND_NAMES)[number];
+
+const SESSION_SLASH_COMMAND_NAME_SET: ReadonlySet<string> = new Set(SESSION_SLASH_COMMAND_NAMES);
+
+export function isSessionSlashCommandName(value: unknown): value is SessionSlashCommandName {
+ return typeof value === "string" && SESSION_SLASH_COMMAND_NAME_SET.has(value);
+}
+
+export interface SessionSlashCommand {
+ name: SessionSlashCommandName;
+ args: string;
+ text: string;
+}
+
+export interface RefineCommandOptions {
+ instructions?: string;
+ rollbackId?: string;
+ global?: boolean;
+}
+
+export function parseRefineCommandOptions(args: string): RefineCommandOptions {
+ let rest = args.trim();
+ let global = false;
+ if (/^--global(?=\s|$)/.test(rest)) {
+ global = true;
+ rest = rest.replace(/^--global(?=\s|$)/, "").trim();
+ }
+ if (rest === "rollback") throw new Error("Usage: /refine rollback <refinement-id>");
+ // Slash-command args keep their original separators (tabs, Unicode spaces);
+ // match the subcommand with the same class parseSlashCommand splits on.
+ const rollbackMatch = /^rollback[\t\p{Zs}]/u.exec(rest);
+ if (rollbackMatch) {
+ let rollbackId = rest.slice(rollbackMatch[0].length).trim();
+ if (rollbackId === "--global") {
+ throw new Error("Usage: /refine rollback <refinement-id>");
+ }
+ if (/\s--global$/.test(rollbackId)) {
+ global = true;
+ rollbackId = rollbackId.replace(/\s--global$/, "").trim();
+ }
+ if (!rollbackId) throw new Error("Usage: /refine rollback <refinement-id>");
+ return { rollbackId, global };
+ }
+ return { instructions: rest || undefined, global };
+}
+
export interface BuiltinSlashCommand {
name: string;
description: string;
+ execution?: "client" | "session";
/** Shown in autocomplete before the description, e.g. "[instructions]" */
argumentHint?: string;
/** Hidden names that resolve to this command without being shown as commands. */
@@ -91,13 +140,22 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [
description: "Compact the session context; optional instructions focus the summary",
argumentHint: "[instructions]",
},
- { name: "refine", description: "Refine continual harness prompt notes, skills, subagents, and memory" },
+ {
+ name: "refine",
+ description: "Refine continual harness prompt notes, skills, subagents, and memory",
+ },
{
name: "goal",
description: "Set or view a persistent goal; supports pause, resume, and clear",
argumentHint: "[objective]",
takesArgument: true,
},
+ {
+ name: "autonomous",
+ description: "Set or view autonomous mode",
+ argumentHint: "[status|on|off]",
+ takesArgument: true,
+ },
{
name: "heartbeat",
description:
@@ -142,6 +200,7 @@ function buildBuiltinSlashCommands(): ReadonlyArray<BuiltinSlashCommand> {
}
return CANONICAL_BUILTIN_SLASH_COMMANDS.map((command) => ({
...command,
+ ...(isSessionSlashCommandName(command.name) ? { execution: "session" as const } : {}),
...(aliasesByTarget.has(command.name) ? { aliases: aliasesByTarget.get(command.name) } : {}),
}));
}
@@ -183,3 +242,13 @@ export function resolveSlashCommand(command: ParsedSlashCommand): ResolvedSlashC
isAlias: name !== command.name,
};
}
+
+export function parseSessionSlashCommand(text: string): SessionSlashCommand | undefined {
+ if (/[\r\n\u2028\u2029]/u.test(text)) return undefined;
+ const parsed = parseSlashCommand(text);
+ if (!parsed) return undefined;
+ const name = resolveBuiltinSlashCommandName(parsed.name);
+ const command = BUILTIN_SLASH_COMMAND_BY_NAME.get(name);
+ if (command?.execution !== "session" || !isSessionSlashCommandName(name)) return undefined;
+ return { name, args: parsed.args, text };
+}
diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts
index 3b7c135716..72b26f7abc 100644
--- a/packages/coding-agent/src/index.ts
+++ b/packages/coding-agent/src/index.ts
@@ -316,6 +316,7 @@ export {
type DaemonResumeCursor,
type DaemonSessionSnapshot,
defaultDaemonSocketPath,
+ type InteractiveInitialPrompt,
InteractiveMode,
type InteractiveModeLocalSessionHost,
type InteractiveModeOptions,
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index 54aba961c8..5db722615f 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -22,7 +22,11 @@ import type { RefinementResult } from "../../core/refinement/index.js";
import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";
import { SessionAlreadyActiveError } from "../../core/session-lease.js";
import type { SessionStats } from "../../core/session-stats.js";
-import { type DaemonClient, getDaemonSocketCloseReason } from "../daemon/daemon-client.js";
+import {
+ DaemonCapabilityUnavailableError,
+ type DaemonClient,
+ getDaemonSocketCloseReason,
+} from "../daemon/daemon-client.js";
import { deserializeDaemonError } from "../daemon/daemon-errors.js";
import {
collectDaemonClientEnv,
@@ -78,6 +82,7 @@ import type {
AgentConnectionToolDefinition,
AgentConnectionUserMessage,
} from "./types.js";
+import { AgentConnectionPromptAdmissionError } from "./types.js";
type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
@@ -197,6 +202,7 @@ export class DaemonAgentConnection implements AgentConnection {
private readonly snapshotRecoveryPromises = new Map<string, Promise<void>>();
private readonly ignoredSnapshotIds = new Set<string>();
private reconnectPromise?: Promise<void>;
+ private readonly definitiveRequestErrors = new WeakSet<Error>();
private disposing = false;
private disposed = false;
@@ -723,28 +729,104 @@ export class DaemonAgentConnection implements AgentConnection {
}
async prompt(message: string, options?: AgentConnectionPromptOptions): Promise<void> {
- await this.requestOk({
- type: "prompt",
- activeSessionId: this.activeSessionId,
- message,
- images: options?.images,
- streamingBehavior: options?.streamingBehavior,
- source: options?.source,
- });
+ await this.promptWithAdmissionCancellation("prompt", message, options);
}
async promptAndWait(message: string, options?: AgentConnectionPromptOptions): Promise<void> {
- await this.requestData<unknown>(
- {
- type: "prompt_and_wait",
- activeSessionId: this.activeSessionId,
- message,
- images: options?.images,
- streamingBehavior: options?.streamingBehavior,
- source: options?.source,
+ await this.promptWithAdmissionCancellation("prompt_and_wait", message, options);
+ }
+
+ private async promptWithAdmissionCancellation(
+ type: "prompt" | "prompt_and_wait",
+ message: string,
+ options?: AgentConnectionPromptOptions,
+ ): Promise<void> {
+ const signal = options?.signal;
+ if (signal?.aborted) {
+ throw new AgentConnectionPromptAdmissionError("Prompt admission was cancelled.", "cancelled");
+ }
+ if (!signal) {
+ await this.requestData<unknown>(
+ {
+ type,
+ activeSessionId: this.activeSessionId,
+ message,
+ images: options?.images,
+ streamingBehavior: options?.streamingBehavior,
+ queueIfBusy: options?.queueIfBusy,
+ source: options?.source,
+ },
+ DAEMON_LONG_RUNNING_REQUEST_TIMEOUT_MS,
+ );
+ return;
+ }
+ const admissionId = `prompt-admission:${randomUUID()}`;
+ let resolveAbort = () => {};
+ const aborted = new Promise<"abort">((resolve) => {
+ resolveAbort = () => resolve("abort");
+ });
+ const onAbort = () => resolveAbort();
+ signal.addEventListener("abort", onAbort, { once: true });
+ // Close the listener-registration race before issuing the first request.
+ if (signal.aborted) {
+ signal.removeEventListener("abort", onAbort);
+ throw new AgentConnectionPromptAdmissionError("Prompt admission was cancelled.", "cancelled");
+ }
+ const command = {
+ type,
+ activeSessionId: this.activeSessionId,
+ message,
+ images: options.images,
+ streamingBehavior: options.streamingBehavior,
+ queueIfBusy: options.queueIfBusy,
+ source: options.source,
+ admissionId,
+ } as Extract<DaemonCommandBody, { type: typeof type }>;
+ let promptError: unknown;
+ const promptRequest = this.requestData<unknown>(command, DAEMON_LONG_RUNNING_REQUEST_TIMEOUT_MS).catch(
+ (error: unknown) => {
+ promptError =
+ error instanceof DaemonCapabilityUnavailableError && !error.afterReconnect
+ ? new AgentConnectionPromptAdmissionError(error.message, "unsupported", { cause: error })
+ : error;
+ return "failed" as const;
},
- DAEMON_LONG_RUNNING_REQUEST_TIMEOUT_MS,
);
+ try {
+ const first = await Promise.race([promptRequest.then(() => "settled" as const), aborted]);
+ if (first === "settled" && promptError === undefined) return;
+ if (first === "settled" && promptError instanceof AgentConnectionPromptAdmissionError) throw promptError;
+ if (
+ first === "settled" &&
+ !signal.aborted &&
+ promptError instanceof Error &&
+ this.definitiveRequestErrors.has(promptError)
+ ) {
+ throw promptError;
+ }
+ let status: "cancelled" | "owned" | "unknown" = "unknown";
+ try {
+ const result = await this.requestData<{ status: "cancelled" | "owned" | "unknown" }>({
+ type: "cancel_prompt_admission",
+ activeSessionId: this.activeSessionId,
+ admissionId,
+ });
+ status = result.status;
+ } catch {
+ // Timeout/transport is indistinguishable from accepted ownership.
+ }
+ await promptRequest;
+ if (promptError instanceof AgentConnectionPromptAdmissionError) throw promptError;
+ const definitiveFailure = promptError instanceof Error && this.definitiveRequestErrors.has(promptError);
+ if (promptError === undefined || (status === "owned" && type === "prompt" && !definitiveFailure)) return;
+ throw new AgentConnectionPromptAdmissionError(
+ promptError instanceof Error ? promptError.message : "Prompt admission did not complete.",
+ status,
+ promptError === undefined ? undefined : { cause: promptError },
+ );
+ } finally {
+ signal.removeEventListener("abort", onAbort);
+ }
}
async startSideQuestion(
@@ -1292,10 +1374,16 @@ export class DaemonAgentConnection implements AgentConnection {
return response.data as T;
}
- private async requestData<T>(command: DaemonCommandBody, timeoutMs?: number): Promise<T> {
- const response = await this.client.request(command, timeoutMs);
+ private async requestData<T>(
+ command: DaemonCommandBody,
+ timeoutMs?: number,
+ options?: Parameters<DaemonClient["request"]>[2],
+ ): Promise<T> {
+ const response = await this.client.request(command, timeoutMs, options);
if (!response.success) {
- throw deserializeDaemonError(response);
+ const error = deserializeDaemonError(response);
+ this.definitiveRequestErrors.add(error);
+ throw error;
}
if (invalidatesCachedSnapshot(command.type)) {
this.latestSnapshotIsFresh = false;
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 10684b7c6d..75726e8c2b 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
@@ -294,37 +294,46 @@ export class InProcessAgentConnection implements AgentConnection {
async prompt(message: string, options?: AgentConnectionPromptOptions): Promise<void> {
await new Promise<void>((resolve, reject) => {
let settled = false;
+ let accepted = false;
const resolveOnce = () => {
- if (settled) return;
- settled = true;
- resolve();
+ if (!settled) {
+ settled = true;
+ resolve();
+ }
};
const rejectOnce = (error: unknown) => {
- if (settled) return;
- settled = true;
- reject(error);
+ if (!settled) {
+ settled = true;
+ reject(error);
+ }
};
const prompt = this.session.prompt(message, {
- images: options?.images,
- streamingBehavior: options?.streamingBehavior,
- source: options?.source,
+ ...(options?.images ? { images: options.images } : {}),
+ ...(options?.streamingBehavior ? { streamingBehavior: options.streamingBehavior, resumeIfIdle: true } : {}),
+ ...(options?.queueIfBusy !== undefined ? { queueIfBusy: options.queueIfBusy } : {}),
+ ...(options?.source ? { source: options.source } : {}),
+ ...(options?.signal ? { signal: options.signal } : {}),
preflightResult: (success) => {
- if (success) resolveOnce();
+ if (success) {
+ accepted = true;
+ resolveOnce();
+ }
},
});
- void prompt.then(resolveOnce, rejectOnce);
+ void prompt.then(() => {
+ if (accepted) resolveOnce();
+ else rejectOnce(new Error("Prompt was not accepted by the session."));
+ }, rejectOnce);
});
}
async promptAndWait(message: string, options?: AgentConnectionPromptOptions): Promise<void> {
- if (!options) {
- await this.session.prompt(message);
- return;
- }
- await this.session.prompt(message, {
- images: options.images,
- streamingBehavior: options.streamingBehavior,
- source: options.source,
+ await this.session.promptAndWait(message, {
+ ...(options?.images ? { images: options.images } : {}),
+ ...(options?.streamingBehavior ? { streamingBehavior: options.streamingBehavior, resumeIfIdle: true } : {}),
+ ...(options?.queueIfBusy !== undefined ? { queueIfBusy: options.queueIfBusy } : {}),
+ ...(options?.source ? { source: options.source } : {}),
+ ...(options?.signal ? { signal: options.signal } : {}),
});
}
@@ -376,7 +385,7 @@ export class InProcessAgentConnection implements AgentConnection {
}
async waitForIdle(): Promise<void> {
- await this.session.agent.waitForIdle();
+ await this.session.waitForIdle();
}
async waitForHeadlessCompletion(): Promise<AgentAutonomousStatus> {
diff --git a/packages/coding-agent/src/modes/agent-connection/index.ts b/packages/coding-agent/src/modes/agent-connection/index.ts
index f89e1a30eb..f8247c12ba 100644
--- a/packages/coding-agent/src/modes/agent-connection/index.ts
+++ b/packages/coding-agent/src/modes/agent-connection/index.ts
@@ -73,3 +73,4 @@ export type {
AgentConnectionToolDefinition,
AgentConnectionUserMessage,
} from "./types.js";
+export { AgentConnectionPromptAdmissionError } from "./types.js";
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 9ee61958fc..9d27a1320a 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -425,10 +425,28 @@ export interface AgentConnectionToolDefinition {
replayBuiltInToolName?: ReplayBuiltInToolName;
}
+/** Prompt admission failure; only a confirmed cancellation is retry-safe. */
+export class AgentConnectionPromptAdmissionError extends Error {
+ readonly cancelled: boolean;
+
+ constructor(
+ message: string,
+ readonly status: "cancelled" | "owned" | "unknown" | "unsupported",
+ options?: ErrorOptions,
+ ) {
+ super(message, options);
+ this.cancelled = status === "cancelled";
+ this.name = "AgentConnectionPromptAdmissionError";
+ }
+}
+
export interface AgentConnectionPromptOptions {
images?: ImageContent[];
streamingBehavior?: "steer" | "followUp";
+ queueIfBusy?: boolean;
source?: InputSource;
+ /** Cancel admission while it is still waiting; accepted prompts remain session-owned. */
+ signal?: AbortSignal;
}
export interface AgentConnectionSideQuestionEvent {
diff --git a/packages/coding-agent/src/modes/daemon/command-recovery-journal.ts b/packages/coding-agent/src/modes/daemon/command-recovery-journal.ts
index 88d22cf6a6..05fcec0644 100644
--- a/packages/coding-agent/src/modes/daemon/command-recovery-journal.ts
+++ b/packages/coding-agent/src/modes/daemon/command-recovery-journal.ts
@@ -59,15 +59,21 @@ export class CommandRecoveryJournal {
this.load();
}
- begin(clientId: DaemonClientId, commandId: DaemonCommandId, commandType: string): CommandJournalBeginResult {
- const key = createCommandIdempotencyKey(clientId, commandId);
- const existing = this.entries.get(key);
+ lookup(
+ clientId: DaemonClientId,
+ commandId: DaemonCommandId,
+ ): Exclude<CommandJournalBeginResult, { status: "new" }> | undefined {
+ const existing = this.entries.get(createCommandIdempotencyKey(clientId, commandId));
if (existing?.response) {
return { status: "complete", response: existing.response };
}
- if (existing) {
- return { status: "pending" };
- }
+ return existing ? { status: "pending" } : undefined;
+ }
+
+ begin(clientId: DaemonClientId, commandId: DaemonCommandId, commandType: string): CommandJournalBeginResult {
+ const key = createCommandIdempotencyKey(clientId, commandId);
+ const existing = this.lookup(clientId, commandId);
+ if (existing) return existing;
const received: ReceivedRecord = {
version: 1,
type: "received",
diff --git a/packages/coding-agent/src/modes/daemon/daemon-client.ts b/packages/coding-agent/src/modes/daemon/daemon-client.ts
index 112a2ca829..f87090f783 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-client.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-client.ts
@@ -4,11 +4,11 @@ import { getDaemonLogPath } from "../../config.js";
import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";
import {
createDaemonCommandEnvelope,
- DAEMON_COMMAND_COMPATIBILITY,
DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION,
DAEMON_PROTOCOL_VERSION,
type DaemonClosingReason,
type DaemonCommand,
+ type DaemonCommandCompatibility,
type DaemonCommandEnvelope,
type DaemonOutbound,
type DaemonProtocolVersion,
@@ -16,6 +16,7 @@ import {
type DaemonResponse,
type DaemonSavedSessionInfo,
type DaemonServerCapability,
+ getDaemonCommandCompatibilities,
isDaemonMutatingCommand,
} from "./daemon-protocol.js";
import type { DaemonWorkerCommand, DaemonWorkerCommandBody } from "./daemon-worker-protocol.js";
@@ -45,6 +46,8 @@ interface PendingDaemonRequest {
wireData: string;
awaitingReconnect: boolean;
acknowledgeResult: boolean;
+ /** Re-checked against the new hello before a reconnect replay. */
+ compatibilities: readonly DaemonCommandCompatibility[];
}
function daemonEndpointDetails(socketPath: string): string {
@@ -70,6 +73,7 @@ export class DaemonCapabilityUnavailableError extends Error {
constructor(
readonly command: DaemonCommand["type"],
readonly capability: DaemonServerCapability | undefined,
+ readonly afterReconnect = false,
) {
super(
capability
@@ -297,15 +301,12 @@ export class DaemonClient {
);
}
const hello = this.helloMessage ?? (await this.waitForHello());
- const compatibility = DAEMON_COMMAND_COMPATIBILITY[command.type];
- if (
- hello.protocol.version < compatibility.minProtocol ||
- ("capability" in compatibility && !this.supportsServerCapability(compatibility.capability))
- ) {
- throw new DaemonCapabilityUnavailableError(
- command.type,
- "capability" in compatibility ? compatibility.capability : undefined,
- );
+ const compatibilities = getDaemonCommandCompatibilities(command);
+ const missingCompatibility = compatibilities.find(
+ (compatibility) => !this.meetsCommandCompatibility(hello, compatibility),
+ );
+ if (missingCompatibility) {
+ throw new DaemonCapabilityUnavailableError(command.type, missingCompatibility.capability);
}
const envelopeProtocolVersion = Math.min(hello.protocol.version, DAEMON_PROTOCOL_VERSION);
return this.requestWire(
@@ -313,6 +314,17 @@ export class DaemonClient {
timeoutMs,
options,
envelopeProtocolVersion >= DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION ? envelopeProtocolVersion : undefined,
+ compatibilities,
+ );
+ }
+
+ private meetsCommandCompatibility(hello: DaemonHello, compatibility: DaemonCommandCompatibility): boolean {
+ return (
+ hello.protocol.version >= compatibility.minProtocol &&
+ (compatibility.minSchemaRevision === undefined ||
+ (hello.schemaRevision ?? 0) >= compatibility.minSchemaRevision) &&
+ (compatibility.capability === undefined ||
+ hello.serverCapabilities?.includes(compatibility.capability) === true)
);
}
@@ -342,6 +354,7 @@ export class DaemonClient {
timeoutMs: number,
options: DaemonClientRequestOptions = {},
publicEnvelopeProtocolVersion?: DaemonProtocolVersion,
+ compatibilities: readonly DaemonCommandCompatibility[] = [],
): Promise<DaemonResponse> {
if (!this.socket || this.socket.destroyed) {
throw new Error(
@@ -373,6 +386,7 @@ export class DaemonClient {
wireData,
awaitingReconnect: false,
acknowledgeResult,
+ compatibilities,
};
this.pendingRequests.set(id, pending);
this.armPendingRequestTimeout(id, pending);
@@ -436,6 +450,20 @@ export class DaemonClient {
continue;
}
pending.awaitingReconnect = false;
+ const missingCompatibility = pending.compatibilities.find(
+ (compatibility) => !this.meetsCommandCompatibility(message, compatibility),
+ );
+ if (missingCompatibility) {
+ this.pendingRequests.delete(id);
+ pending.reject(
+ new DaemonCapabilityUnavailableError(
+ pending.commandType as DaemonCommand["type"],
+ missingCompatibility.capability,
+ true,
+ ),
+ );
+ continue;
+ }
this.armPendingRequestTimeout(id, pending);
this.socket.write(pending.wireData);
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index b67f1162d5..874335e276 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -130,6 +130,7 @@ import {
DAEMON_DEFAULT_SERVER_CAPABILITIES,
DAEMON_PROTOCOL_INFO,
DAEMON_SCHEMA_ID,
+ DAEMON_SCHEMA_REVISION,
DAEMON_SUPPORTED_CLIENT_CAPABILITIES,
type DaemonAttachResult,
type DaemonClientCapability,
@@ -145,7 +146,9 @@ import {
failure,
isDaemonCommandEnvelope,
isDaemonDialogExtensionUiRequest,
+ isDaemonMutatingCommand,
success,
+ UPDATE_RESTART_DRAIN_COMMANDS,
} from "./daemon-protocol.js";
import { getDaemonRuntimeIdentity } from "./daemon-runtime-identity.js";
import {
@@ -176,6 +179,7 @@ import {
SESSION_LEASE_OWNER_ID_ENV,
SESSION_LEASES_ENABLED_ENV,
} from "./daemon-worker-protocol.js";
+import { MutationDrainLatch } from "./mutation-drain-latch.js";
import {
createSnapshotTranscriptChunks,
SNAPSHOT_TARGET_CHUNK_BYTES,
@@ -199,6 +203,7 @@ export { defaultDaemonSocketPath } from "./daemon-socket.js";
const structuredLog = getLogger("coding-agent.daemon");
const WORKER_SNAPSHOT_TERMINAL_DRAIN_TIMEOUT_MS = 1_000;
+const UPDATE_RESTART_PREPARE_TIMEOUT_MS = 90_000;
const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"ack_result",
@@ -210,6 +215,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"kill",
"rename",
"prompt",
+ "cancel_prompt_admission",
"prompt_and_wait",
"steer",
"follow_up",
@@ -322,6 +328,43 @@ function delay(ms: number): Promise<void> {
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
}
+class DaemonPromptAdmissionCancelledError extends Error {
+ constructor() {
+ super("Prompt admission was cancelled.");
+ this.name = "DaemonPromptAdmissionCancelledError";
+ }
+}
+
+export function waitForDaemonPromptAdmission<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
+ if (!signal) return promise;
+ if (signal.aborted) {
+ // The caller supplied already-running work. Observe its eventual rejection
+ // even though admission cancellation wins immediately.
+ void promise.catch(() => {});
+ return Promise.reject(new DaemonPromptAdmissionCancelledError());
+ }
+ return new Promise<T>((resolve, reject) => {
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
+ const onAbort = () => {
+ cleanup();
+ reject(new DaemonPromptAdmissionCancelledError());
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ // Close the registration-to-check race before observing the awaited work.
+ if (signal.aborted) return onAbort();
+ promise.then(
+ (value) => {
+ cleanup();
+ resolve(value);
+ },
+ (error: unknown) => {
+ cleanup();
+ reject(error);
+ },
+ );
+ });
+}
+
type RuntimeOpenGuard = () => boolean | Promise<boolean>;
type SupervisorGenerationClaim = Omit<Extract<DaemonWorkerCommand, { type: "worker_auth" }>, "id" | "type" | "token">;
@@ -364,8 +407,21 @@ export async function runDaemonMode(options: DaemonModeOptions): Promise<never>
export class AgentDaemon {
private server?: Server;
private shuttingDown = false;
- private updateRestartPreparing = false;
- private preparedUpdateRestartManifest?: DaemonUpdateRestartManifest;
+ private readonly updateRestartQueuePauses = new Map<string, { release(): void }>();
+ private readonly mutationDrain = new MutationDrainLatch();
+ private updateRestart?: {
+ id: symbol;
+ owner?: DaemonSocketClient;
+ abort: AbortController;
+ deadline?: ReturnType<typeof setTimeout>;
+ phase: "preparing" | "fencing" | "prepared" | "publishing";
+ manifest?: DaemonUpdateRestartManifest;
+ deferredClientEnv: Array<{
+ client: DaemonSocketClient;
+ state: ActiveSessionState;
+ env: Record<string, string>;
+ }>;
+ };
private ownsSocketPath = false;
private socketIdentity?: DaemonSocketIdentity;
private readonly clients = new Set<DaemonSocketClient>();
@@ -380,6 +436,16 @@ export class AgentDaemon {
string,
{ run: SideQuestionRun; client: DaemonSocketClient; activeSessionId: string }
>();
+ /** Live prompt admissions, keyed by session and caller-generated admission id. */
+ private readonly promptAdmissions = new Map<
+ string,
+ {
+ activeSessionId: string;
+ admissionId: string;
+ controller?: AbortController;
+ status: "waiting" | "owned" | "cancelled";
+ }
+ >();
private readonly signalCleanupHandlers: Array<() => void> = [];
private readonly cronStore: AgentCronJobStore;
private readonly agentDir: string;
@@ -436,6 +502,10 @@ export class AgentDaemon {
}
this.cronScheduler = new AgentCronScheduler(this.cronStore, {
runJob: (job) => this.runCronJob(job),
+ beginDispatch: () => {
+ this.mutationDrain.begin();
+ return () => this.mutationDrain.end();
+ },
onError: (job, error) => {
this.log(`Cron job ${job.id} failed: ${error instanceof Error ? error.message : String(error)}`);
},
@@ -564,6 +634,15 @@ export class AgentDaemon {
return this.supervisorClaims.size > 0;
}
+ private revokeSupervisorClaim(client: DaemonSocketClient, expected?: BoundSupervisorGenerationClaim): boolean {
+ if (expected && this.supervisorClaims.get(client) !== expected) return false;
+ if (!this.supervisorClaims.delete(client)) return false;
+ if (this.options.worker && this.updateRestart?.owner === client) {
+ this.cancelPreparedUpdateRestart(this.updateRestart.id);
+ }
+ return true;
+ }
+
private clearSupervisorAvailabilityCheck(): void {
if (this.supervisorMonitorTimer) {
clearTimeout(this.supervisorMonitorTimer);
@@ -593,7 +672,7 @@ export class AgentDaemon {
boundClaim.ownerFingerprint,
);
} catch {
- client.socket.end();
+ if (this.revokeSupervisorClaim(client, boundClaim)) client.socket.end();
}
}
this.scheduleSupervisorFenceCheck();
@@ -1173,9 +1252,6 @@ export class AgentDaemon {
}
private async runCronJob(job: AgentCronJob): Promise<"skipped" | undefined> {
- if (this.updateRestartPreparing) {
- return "skipped";
- }
const requirePersistedJob = this.cronStore.list().some((candidate) => candidate.id === job.id);
const dueJob = requirePersistedJob ? this.getRunnableCronJob(job.id) : job;
if (!dueJob) {
@@ -1183,12 +1259,7 @@ export class AgentDaemon {
}
const state = await this.getOrCreateCronJobSession(dueJob, requirePersistedJob);
const runnableJob = requirePersistedJob ? this.getRunnableCronJob(job.id) : dueJob;
- if (
- !state ||
- !runnableJob ||
- this.updateRestartPreparing ||
- !this.isCronJobRunnableForState(runnableJob, state, requirePersistedJob)
- ) {
+ if (!state || !runnableJob || !this.isCronJobRunnableForState(runnableJob, state, requirePersistedJob)) {
return "skipped";
}
const session = state.runtime.session;
@@ -1243,6 +1314,7 @@ export class AgentDaemon {
source: "rpc",
},
canPrompt,
+ false,
);
return didPrompt ? undefined : "skipped";
}
@@ -1260,25 +1332,29 @@ export class AgentDaemon {
message: string,
options?: PromptOptions,
canPrompt?: () => boolean,
+ waitForCompletion = true,
): Promise<boolean> {
return this.withAgentMessagePreparingGuard(
state,
(session, clearPreparing) => {
const prompt =
- options?.agentMessageId === undefined
- ? session.prompt.bind(session)
- : session.acceptAgentMessagePrompt.bind(session);
+ options?.agentMessageId !== undefined && options.expandPromptTemplates === false
+ ? session.acceptAgentMessagePrompt.bind(session)
+ : waitForCompletion
+ ? (session.promptAndWait ?? session.prompt).bind(session)
+ : (session.promptUntilAccepted ?? session.prompt).bind(session);
return prompt(message, {
...options,
- preflightResult: (didSucceed) => {
+ preflightResult: (didSucceed, queued) => {
if (didSucceed && session.isStreaming) {
clearPreparing();
}
- options?.preflightResult?.(didSucceed);
+ options?.preflightResult?.(didSucceed, queued);
},
});
},
canPrompt,
+ options?.signal,
);
}
@@ -1319,6 +1395,7 @@ export class AgentDaemon {
state: ActiveSessionState,
run: (session: AgentSession, clearPreparing: () => void) => Promise<void>,
canRun?: () => boolean,
+ signal?: AbortSignal,
): Promise<boolean> {
const activeSessionId = state.activeSessionId;
this.agentMessagePreparingTargets.set(
@@ -1339,7 +1416,12 @@ export class AgentDaemon {
}
};
try {
- await this.agentMessageTargetLocks.get(activeSessionId)?.catch(() => undefined);
+ const targetLock = this.agentMessageTargetLocks.get(activeSessionId);
+ if (targetLock)
+ await waitForDaemonPromptAdmission(
+ targetLock.catch(() => undefined),
+ signal,
+ );
if (this.sessions.get(activeSessionId) !== state || this.closingSessions.has(activeSessionId)) {
throw new Error("Target session is closing before prompt delivery");
}
@@ -1589,9 +1671,6 @@ export class AgentDaemon {
job: AgentCronJob,
requirePersistedJob: boolean,
): Promise<ActiveSessionState | undefined> {
- if (this.updateRestartPreparing) {
- return undefined;
- }
const dueJob = requirePersistedJob ? this.getRunnableCronJob(job.id) : job;
if (!dueJob) {
return undefined;
@@ -2296,6 +2375,7 @@ export class AgentDaemon {
socketPath: this.socketPath,
protocol: DAEMON_PROTOCOL_INFO,
schemaId: DAEMON_SCHEMA_ID,
+ schemaRevision: DAEMON_SCHEMA_REVISION,
appVersion: VERSION,
runtime: getDaemonRuntimeIdentity(),
clientId: client.id,
@@ -2345,9 +2425,10 @@ export class AgentDaemon {
this.detachClient(client);
client.detachInput();
this.clients.delete(client);
- this.supervisorClaims.delete(client);
+ const wasAuthenticated = client.authenticated === true;
+ this.revokeSupervisorClaim(client);
const supervisorSocketPath = process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];
- if (this.options.worker && client.authenticated === true && supervisorSocketPath) {
+ if (this.options.worker && wasAuthenticated && supervisorSocketPath) {
this.scheduleSupervisorAvailabilityCheck(supervisorSocketPath, 100);
}
};
@@ -2363,13 +2444,49 @@ export class AgentDaemon {
});
}
+ private promptAdmissionKey(activeSessionId: string, admissionId: string): string {
+ return `${activeSessionId}\0${admissionId}`;
+ }
+
+ /**
+ * Parse and synchronously register prompt admission before returning a promise.
+ * This method is intentionally non-async: handleLine invokes it before its first await.
+ */
+ private parseCommandAndRegisterPromptAdmission(client: DaemonSocketClient, line: string): unknown {
+ const wireValue = JSON.parse(line) as unknown;
+ if (isDaemonCommandEnvelope(wireValue) && wireValue.clientId) client.id = wireValue.clientId;
+ const parsed = (isDaemonCommandEnvelope(wireValue) ? { ...wireValue.command, id: wireValue.id } : wireValue) as {
+ type?: unknown;
+ activeSessionId?: unknown;
+ admissionId?: unknown;
+ };
+ if (parsed.type === "prompt" || parsed.type === "prompt_and_wait") {
+ if (parsed.admissionId !== undefined) {
+ if (typeof parsed.activeSessionId !== "string" || typeof parsed.admissionId !== "string") {
+ throw new Error("Prompt admission requires string activeSessionId and admissionId");
+ }
+ if (parsed.admissionId === "") throw new Error("admissionId must not be empty");
+ const key = this.promptAdmissionKey(parsed.activeSessionId, parsed.admissionId);
+ if (this.promptAdmissions.has(key)) {
+ throw new Error(`Prompt admission id is already in use: ${parsed.admissionId}`);
+ }
+ this.promptAdmissions.set(key, {
+ activeSessionId: parsed.activeSessionId,
+ admissionId: parsed.admissionId,
+ controller: new AbortController(),
+ status: "waiting",
+ });
+ }
+ }
+ return parsed;
+ }
+
private async handleLine(client: DaemonSocketClient, line: string): Promise<void> {
let command: DaemonCommand;
+ let clearParsedAdmission = () => {};
+ let promptHandlerOwnsAdmission = false;
try {
- const wireValue = JSON.parse(line) as unknown;
- const parsed = (
- isDaemonCommandEnvelope(wireValue) ? { ...wireValue.command, id: wireValue.id } : wireValue
- ) as {
+ const parsed = this.parseCommandAndRegisterPromptAdmission(client, line) as {
id?: unknown;
type?: unknown;
token?: unknown;
@@ -2378,13 +2495,28 @@ export class AgentDaemon {
supervisorProcessStartId?: unknown;
supervisorSocketPath?: unknown;
activeSessionId?: unknown;
+ admissionId?: unknown;
capabilities?: unknown;
supportsExtensionUi?: unknown;
job?: unknown;
};
- if (isDaemonCommandEnvelope(wireValue) && wireValue.clientId) {
- client.id = wireValue.clientId;
- }
+ const parsedAdmission =
+ (parsed.type === "prompt" || parsed.type === "prompt_and_wait") &&
+ typeof parsed.activeSessionId === "string" &&
+ typeof (parsed as { admissionId?: unknown }).admissionId === "string"
+ ? this.promptAdmissions.get(
+ this.promptAdmissionKey(parsed.activeSessionId, (parsed as { admissionId: string }).admissionId),
+ )
+ : undefined;
+ clearParsedAdmission = () => {
+ if (!parsedAdmission) return;
+ const key = this.promptAdmissionKey(parsedAdmission.activeSessionId, parsedAdmission.admissionId);
+ if (this.promptAdmissions.get(key) === parsedAdmission) {
+ this.promptAdmissions.delete(key);
+ }
+ };
+ // Envelope client identity is irrelevant to worker-local prompt admission.
+ // Public supervisor authentication has already bound this socket's identity.
if (this.options.worker && client.authenticated !== true) {
const commandId = typeof parsed.id === "string" ? parsed.id : undefined;
if (
@@ -2396,6 +2528,7 @@ export class AgentDaemon {
(parsed.supervisorProcessStartId !== undefined && typeof parsed.supervisorProcessStartId !== "string") ||
typeof parsed.supervisorSocketPath !== "string"
) {
+ clearParsedAdmission();
this.write(client, failure(commandId, "worker_auth", "Worker authentication failed"));
client.socket.end();
return;
@@ -2418,6 +2551,7 @@ export class AgentDaemon {
}
for (const previous of this.supervisorClaims.keys()) {
if (previous !== client) {
+ this.revokeSupervisorClaim(previous);
previous.socket.end();
}
}
@@ -2431,6 +2565,7 @@ export class AgentDaemon {
if (this.options.worker) {
const boundClaim = this.supervisorClaims.get(client);
if (!boundClaim) {
+ clearParsedAdmission();
this.write(
client,
failure(
@@ -2442,28 +2577,69 @@ export class AgentDaemon {
client.socket.end();
return;
}
+ const claimCheck = this.assertSupervisorClaimCurrent(boundClaim.claim, boundClaim.ownerFingerprint);
+ // Observe the already-running fence check even if admission cancellation
+ // wins the command wait below.
+ void claimCheck.catch(() => {});
try {
- boundClaim.ownerFingerprint = await this.assertSupervisorClaimCurrent(
- boundClaim.claim,
- boundClaim.ownerFingerprint,
+ const ownerFingerprint = await waitForDaemonPromptAdmission(
+ claimCheck,
+ parsedAdmission?.controller?.signal,
);
- } catch {
+ if (this.supervisorClaims.get(client) !== boundClaim || client.socket.destroyed) {
+ clearParsedAdmission();
+ return;
+ }
+ boundClaim.ownerFingerprint = ownerFingerprint;
+ } catch (error) {
+ const admissionCancelled = error instanceof DaemonPromptAdmissionCancelledError;
+ if (admissionCancelled) {
+ // The fence check remains authoritative after cancellation. Its rejection
+ // revokes only the exact binding that initiated it; replacements survive.
+ void claimCheck.catch(() => {
+ if (this.revokeSupervisorClaim(client, boundClaim)) client.socket.end();
+ });
+ }
+ clearParsedAdmission();
+ if (this.supervisorClaims.get(client) !== boundClaim || client.socket.destroyed) return;
this.write(
client,
failure(
typeof parsed.id === "string" ? parsed.id : undefined,
typeof parsed.type === "string" ? parsed.type : "worker_auth",
- "supervisor_generation_stale",
+ admissionCancelled ? error : "supervisor_generation_stale",
),
);
- client.socket.end();
+ // Cancelling this prompt only abandons its admission wait. A genuine
+ // stale supervisor claim fences only the binding that it checked.
+ if (!admissionCancelled && this.revokeSupervisorClaim(client, boundClaim)) {
+ client.socket.end();
+ }
return;
}
}
if (this.options.worker && typeof parsed.type === "string" && parsed.type.startsWith("worker_")) {
- await this.handleWorkerCommand(client, parsed as DaemonWorkerCommand);
+ const workerCommand = parsed as DaemonWorkerCommand;
+ const updateLifecycle =
+ workerCommand.type === "worker_prepare_update" ||
+ workerCommand.type === "worker_commit_update" ||
+ workerCommand.type === "worker_cancel_update";
+ if (this.updateRestart && !updateLifecycle) {
+ this.write(
+ client,
+ failure(workerCommand.id, workerCommand.type, "Daemon is preparing an update restart"),
+ );
+ return;
+ }
+ if (!updateLifecycle) this.mutationDrain.begin();
+ try {
+ await this.handleWorkerCommand(client, workerCommand);
+ } finally {
+ if (!updateLifecycle) this.mutationDrain.end();
+ }
return;
}
+
if (typeof parsed.type !== "string" || !DAEMON_COMMAND_TYPES.has(parsed.type)) {
const commandName = typeof parsed.type === "string" ? parsed.type : "unknown";
const commandId = typeof parsed.id === "string" ? parsed.id : undefined;
@@ -2476,8 +2652,25 @@ export class AgentDaemon {
return;
}
+ const mutation = command.type !== "prepare_update_restart" && isDaemonMutatingCommand(command);
+ const restartPhase = this.updateRestart?.phase;
+ // Mirror the supervisor's drain/fence split: abort-style commands stay
+ // admitted only while mutations drain; once the checkpoint is being
+ // captured they could race the snapshot and are rejected too.
+ const restartRejected =
+ restartPhase === "preparing"
+ ? !UPDATE_RESTART_DRAIN_COMMANDS.has(command.type)
+ : restartPhase !== undefined && command.type !== "shutdown";
+ if (mutation && restartRejected) {
+ clearParsedAdmission();
+ this.write(client, failure(command.id, command.type, "Daemon is preparing an update restart"));
+ return;
+ }
+ if (mutation) this.mutationDrain.begin();
try {
- const response = await this.handleCommand(client, command);
+ const response = await this.handleCommand(client, command, () => {
+ promptHandlerOwnsAdmission = true;
+ });
if (response) {
this.write(client, response);
}
@@ -2489,9 +2682,22 @@ export class AgentDaemon {
`daemon command "${command.type}" failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
);
this.write(client, failure(command.id, command.type, error, serializeDaemonError(error)));
+ } finally {
+ if (!promptHandlerOwnsAdmission) clearParsedAdmission();
+ if (mutation) this.mutationDrain.end();
}
}
+ private writeWorkerSuccess(client: DaemonSocketClient, command: DaemonWorkerCommand, data?: unknown): void {
+ this.write(client, {
+ id: command.id,
+ type: "response",
+ command: command.type,
+ success: true,
+ ...(data !== undefined ? { data } : {}),
+ });
+ }
+
private async handleWorkerCommand(client: DaemonSocketClient, command: DaemonWorkerCommand): Promise<void> {
try {
switch (command.type) {
@@ -2521,23 +2727,13 @@ export class AgentDaemon {
for (const peer of command.peers) {
this.remoteAgentPeers.set(peer.activeSessionId, peer);
}
- this.write(client, {
- id: command.id,
- type: "response",
- command: command.type,
- success: true,
- });
+ this.writeWorkerSuccess(client, command);
return;
case "worker_archive_and_shutdown": {
for (const state of [...this.sessions.values()]) {
await this.closeSession(state, "killed");
}
- this.write(client, {
- id: command.id,
- type: "response",
- command: command.type,
- success: true,
- });
+ this.writeWorkerSuccess(client, command);
setImmediate(() => void this.shutdown(0));
return;
}
@@ -2550,46 +2746,54 @@ export class AgentDaemon {
deliveryMode: command.deliveryMode,
origin: "agent",
});
- this.write(client, {
- id: command.id,
- type: "response",
- command: command.type,
- success: true,
- data: receipt,
- });
+ this.writeWorkerSuccess(client, command, receipt);
return;
}
case "worker_prepare_update": {
- const manifest = this.prepareUpdateRestartCheckpoint();
- this.write(client, {
- id: command.id,
- type: "response",
- command: command.type,
- success: true,
- data: manifest,
- });
+ const transaction = this.beginUpdateRestartTransaction(client);
+ const manifest = await this.runUpdateRestartPreparation(transaction);
+ this.writeWorkerSuccess(client, command, manifest);
return;
}
case "worker_commit_update": {
- const manifest = await this.commitPreparedUpdateRestart();
- this.write(client, {
- id: command.id,
- type: "response",
- command: command.type,
- success: true,
- data: manifest,
- });
+ const transaction = this.updateRestart;
+ if (!transaction || transaction.phase === "preparing" || transaction.phase === "fencing") {
+ throw new Error("Daemon has no prepared update checkpoint");
+ }
+ if (transaction.phase === "publishing") {
+ throw new Error("Daemon update checkpoint is already committing");
+ }
+ if (transaction.owner !== client)
+ throw new Error("Daemon update checkpoint belongs to another supervisor");
+ if (transaction.deadline) clearTimeout(transaction.deadline);
+ transaction.deadline = undefined;
+ transaction.phase = "publishing";
+ let manifest: DaemonUpdateRestartManifest;
+ try {
+ manifest = await this.commitPreparedUpdateRestart(transaction.id);
+ } catch (error) {
+ if (this.updateRestart === transaction) transaction.phase = "prepared";
+ if (transaction.abort.signal.aborted) this.cancelPreparedUpdateRestart(transaction.id);
+ throw error;
+ }
+ this.writeWorkerSuccess(client, command, manifest);
+ if (!this.supervisorClaims.has(client)) {
+ setImmediate(() => void this.shutdown(0));
+ }
return;
}
- case "worker_cancel_update":
- this.cancelPreparedUpdateRestart();
- this.write(client, {
- id: command.id,
- type: "response",
- command: command.type,
- success: true,
- });
+ case "worker_cancel_update": {
+ const transaction = this.updateRestart;
+ if (transaction && transaction.owner !== client) {
+ throw new Error("Daemon update checkpoint belongs to another supervisor");
+ }
+ if (transaction?.phase === "publishing") {
+ throw new Error("Daemon update checkpoint is already committing");
+ }
+ if (transaction) this.cancelPreparedUpdateRestart(transaction.id);
+ this.writeWorkerSuccess(client, command);
return;
+ }
}
} catch (error) {
this.write(client, failure(command.id, command.type, error, serializeDaemonError(error)));
@@ -2599,9 +2803,23 @@ export class AgentDaemon {
private async handleCommand(
client: DaemonSocketClient,
command: DaemonCommand,
+ onPromptHandlerOwnsAdmission: () => void = () => {},
): Promise<DaemonResponse | undefined> {
- if (this.updateRestartPreparing && command.type !== "shutdown" && command.type !== "ack_result") {
- throw new Error("Daemon is preparing an update restart");
+ if ("agentMessageId" in command && command.agentMessageId === "") {
+ throw new Error("agentMessageId must not be empty");
+ }
+ if ("admissionId" in command && command.admissionId === "") {
+ throw new Error("admissionId must not be empty");
+ }
+ if ((command.type === "steer" || command.type === "follow_up") && command.expandPromptTemplates !== false) {
+ const replayFields = (["content", "customMessage", "prefixMessages"] as const).filter(
+ (field) => command[field] !== undefined,
+ );
+ if (replayFields.length > 0) {
+ throw new Error(
+ `${command.type} replay fields (${replayFields.join(", ")}) require expandPromptTemplates=false`,
+ );
+ }
}
switch (command.type) {
case "ack_result":
@@ -2694,7 +2912,12 @@ export class AgentDaemon {
const streamsSnapshot =
client.transport === "private-framed" &&
daemonClientCapabilitiesForSession(client, state.activeSessionId).has("chunked_snapshot");
- this.adoptClientEnv(state, filterClientEnv(command.env));
+ // Attach is admitted during update-restart preparation as a read. Env
+ // adoption remains safe while mutations are only draining; after fencing,
+ // defer it until rollback so the checkpoint never omits a live identity.
+ const clientEnv = filterClientEnv(command.env);
+ const deferClientEnv = this.updateRestart && this.updateRestart.phase !== "preparing";
+ if (!deferClientEnv) this.adoptClientEnv(state, clientEnv);
const snapshotSignal = streamsSnapshot
? markClientSnapshotStreaming(client, state.activeSessionId)
: undefined;
@@ -2712,6 +2935,9 @@ export class AgentDaemon {
}
throw error;
}
+ if (deferClientEnv && clientEnv) {
+ this.updateRestart?.deferredClientEnv.push({ client, state, env: clientEnv });
+ }
if (streamsSnapshot) {
const snapshotId = `${state.activeSessionId}-${state.eventGeneration}-${state.lastEventSequence}`;
let transcript: SnapshotTranscriptChunkSource;
@@ -2827,34 +3053,109 @@ export class AgentDaemon {
return success(command.id, "delete_saved_session", result);
}
- case "prompt": {
- const state = this.getBoundSessionState(command.activeSessionId);
- let responseSent = false;
- const sendSuccessResponse = () => {
- if (responseSent) {
- return;
+ case "cancel_prompt_admission": {
+ const admission = this.promptAdmissions.get(
+ this.promptAdmissionKey(command.activeSessionId, command.admissionId),
+ );
+ if (!admission) {
+ return success(command.id, command.type, { status: "unknown" as const });
+ }
+ if (admission.status === "owned") {
+ return success(command.id, command.type, { status: "owned" as const });
+ }
+ if (admission.status === "waiting") {
+ admission.status = "cancelled";
+ admission.controller?.abort();
+ }
+ return success(command.id, command.type, { status: "cancelled" as const });
+ }
+
+ case "prompt":
+ case "prompt_and_wait": {
+ onPromptHandlerOwnsAdmission();
+ const admissionKey = command.admissionId
+ ? this.promptAdmissionKey(command.activeSessionId, command.admissionId)
+ : undefined;
+ const admission = admissionKey ? this.promptAdmissions.get(admissionKey) : undefined;
+ if (command.admissionId && !admission) {
+ throw new Error("Prompt admission was not registered during command parsing");
+ }
+ const clearAdmission = () => {
+ if (admissionKey && this.promptAdmissions.get(admissionKey) === admission) {
+ this.promptAdmissions.delete(admissionKey);
}
- responseSent = true;
- this.write(client, success(command.id, "prompt"));
};
- void this.promptWithAgentMessagePreparingGuard(state, command.message, {
+ const commitAdmission = () => {
+ if (admission?.status === "waiting") admission.status = "owned";
+ };
+ let state: ActiveSessionState;
+ try {
+ if (admission?.status === "cancelled") throw new Error("Prompt admission was cancelled.");
+ state = this.getBoundSessionState(command.activeSessionId);
+ } catch (error) {
+ clearAdmission();
+ throw error;
+ }
+ const options: PromptOptions = {
content: command.content,
images: command.images,
streamingBehavior: command.streamingBehavior,
+ queueIfBusy: command.queueIfBusy ?? command.streamingBehavior !== undefined,
+ resumeIfIdle: command.streamingBehavior !== undefined,
expandPromptTemplates: command.expandPromptTemplates,
- agentMessageId: command.agentMessageId,
- customMessage: command.customMessage,
skipInputHandlers: command.expandPromptTemplates === false ? true : undefined,
source: command.source,
- preflightResult: (didSucceed) => {
- if (didSucceed) {
- this.recordWorkerRecoveryState(state, "prompt_accepted", true);
- sendSuccessResponse();
- }
+ ...(admission?.controller
+ ? { signal: admission.controller.signal, admissionCommitted: commitAdmission }
+ : {}),
+ };
+ if (command.type === "prompt_and_wait") {
+ try {
+ await this.promptWithAgentMessagePreparingGuard(state, command.message, {
+ ...options,
+ preflightResult: (didSucceed) => {
+ if (didSucceed) this.recordWorkerRecoveryState(state, "prompt_accepted", true);
+ },
+ });
+ return success(command.id, command.type);
+ } finally {
+ clearAdmission();
+ }
+ }
+
+ let responseSent = false;
+ let preflightRejected = false;
+ const sendSuccessResponse = () => {
+ if (responseSent) return;
+ responseSent = true;
+ this.write(client, success(command.id, "prompt"));
+ };
+ void this.promptWithAgentMessagePreparingGuard(
+ state,
+ command.message,
+ {
+ ...options,
+ agentMessageId: command.agentMessageId,
+ customMessage: command.customMessage,
+ preflightResult: (didSucceed) => {
+ if (didSucceed) {
+ this.recordWorkerRecoveryState(state, "prompt_accepted", true);
+ sendSuccessResponse();
+ } else {
+ preflightRejected = true;
+ }
+ },
},
- })
+ undefined,
+ false,
+ )
.then(() => {
- sendSuccessResponse();
+ if (preflightRejected) {
+ const error = new Error("Prompt was not accepted by the session.");
+ this.write(client, failure(command.id, "prompt", error, serializeDaemonError(error)));
+ } else {
+ sendSuccessResponse();
+ }
})
.catch((error) => {
if (responseSent) {
@@ -2862,28 +3163,11 @@ export class AgentDaemon {
} else {
this.write(client, failure(command.id, "prompt", error, serializeDaemonError(error)));
}
- });
+ })
+ .finally(clearAdmission);
return undefined;
}
- case "prompt_and_wait": {
- const state = this.getBoundSessionState(command.activeSessionId);
- await this.promptWithAgentMessagePreparingGuard(state, command.message, {
- content: command.content,
- images: command.images,
- streamingBehavior: command.streamingBehavior,
- expandPromptTemplates: command.expandPromptTemplates,
- skipInputHandlers: command.expandPromptTemplates === false ? true : undefined,
- source: command.source,
- preflightResult: (didSucceed) => {
- if (didSucceed) {
- this.recordWorkerRecoveryState(state, "prompt_accepted", true);
- }
- },
- });
- return success(command.id, command.type);
- }
-
case "steer": {
const state = this.getBoundSessionState(command.activeSessionId);
if (command.expandPromptTemplates === false) {
@@ -2907,7 +3191,8 @@ export class AgentDaemon {
case "follow_up": {
const state = this.getBoundSessionState(command.activeSessionId);
- let queued: boolean;
+ let queued = true;
+ let admitted = true;
if (command.expandPromptTemplates === false) {
queued = await state.runtime.session.restoreFollowUpMessage(command.message, command.images, {
queueKey: command.queueKey,
@@ -2916,14 +3201,16 @@ export class AgentDaemon {
customMessage: command.customMessage,
prefixMessages: command.prefixMessages,
});
+ admitted = queued;
} else {
queued = await state.runtime.session.followUp(command.message, command.images, {
queueKey: command.queueKey,
agentMessageId: command.agentMessageId,
resumeIfIdle: true,
});
+ admitted = queued;
}
- if (queued) {
+ if (admitted) {
this.recordWorkerRecoveryState(state, "follow_up_queued", true);
}
return success(command.id, "follow_up", { queued });
@@ -2943,23 +3230,9 @@ export class AgentDaemon {
case "resume_queue": {
const state = this.getSessionState(command.activeSessionId);
- let checkedStart = false;
- let startError: unknown;
- void state.runtime.session.agent.continue().then(undefined, (error: unknown) => {
- if (checkedStart) {
- this.broadcastToSession(
- state,
- failure(undefined, "resume_queue", error, serializeDaemonError(error)),
- );
- } else {
- startError = error;
- }
- });
- // Self-update restore must acknowledge that queued work restarted without waiting for it to finish.
- await Promise.resolve();
- checkedStart = true;
- if (startError !== undefined) {
- return failure(command.id, "resume_queue", startError, serializeDaemonError(startError));
+ if (!state.runtime.session.resumeQueuedWork()) {
+ const error = new Error("No queued work to resume");
+ return failure(command.id, "resume_queue", error, serializeDaemonError(error));
}
return success(command.id, "resume_queue");
}
@@ -3104,7 +3377,7 @@ export class AgentDaemon {
case "wait_for_idle": {
const state = this.getSessionState(command.activeSessionId);
- await state.runtime.session.agent.waitForIdle();
+ await state.runtime.session.waitForIdle();
return success(command.id, "wait_for_idle");
}
@@ -4337,47 +4610,109 @@ export class AgentDaemon {
return depth;
}
- private prepareUpdateRestartCheckpoint(): DaemonUpdateRestartManifest {
- if (this.updateRestartPreparing) {
- throw new Error("Daemon is already preparing an update restart");
+ private assertUpdateRestartNotCancelled(transaction: { id: symbol; abort: AbortController }): void {
+ if (transaction.abort.signal.aborted || this.updateRestart?.id !== transaction.id) {
+ throw new Error("Update restart preparation cancelled");
}
- this.updateRestartPreparing = true;
- // Keep persisted jobs for the replacement daemon, but stop this process
- // from accepting another scheduled mutation while its checkpoint is held.
+ }
+
+ private beginUpdateRestartTransaction(owner?: DaemonSocketClient): NonNullable<AgentDaemon["updateRestart"]> {
+ if (this.updateRestart) throw new Error("Daemon is already preparing an update restart");
+ const transaction: NonNullable<AgentDaemon["updateRestart"]> = {
+ id: Symbol("update-restart"),
+ ...(owner ? { owner } : {}),
+ abort: new AbortController(),
+ phase: "preparing",
+ deferredClientEnv: [],
+ };
+ this.updateRestart = transaction;
this.cronScheduler.stop();
+ transaction.deadline = setTimeout(() => {
+ transaction.abort.abort();
+ this.cancelPreparedUpdateRestart(transaction.id);
+ }, UPDATE_RESTART_PREPARE_TIMEOUT_MS);
+ transaction.deadline.unref();
+ return transaction;
+ }
+
+ private async runUpdateRestartPreparation(
+ transaction: NonNullable<AgentDaemon["updateRestart"]>,
+ ): Promise<DaemonUpdateRestartManifest> {
+ try {
+ await this.mutationDrain.waitForDrain(0, transaction.abort.signal, "Update restart preparation cancelled");
+ this.assertUpdateRestartNotCancelled(transaction);
+ transaction.phase = "fencing";
+ await this.mutationDrain.waitForDrain(0, transaction.abort.signal, "Update restart preparation cancelled");
+ this.assertUpdateRestartNotCancelled(transaction);
+ const manifest = await this.prepareUpdateRestartCheckpoint(transaction);
+ this.assertUpdateRestartNotCancelled(transaction);
+ transaction.manifest = manifest;
+ transaction.phase = "prepared";
+ return manifest;
+ } catch (error) {
+ this.cancelPreparedUpdateRestart(transaction.id);
+ throw error;
+ }
+ }
+
+ private async prepareUpdateRestartCheckpoint(
+ transaction: NonNullable<AgentDaemon["updateRestart"]>,
+ ): Promise<DaemonUpdateRestartManifest> {
+ const signal = transaction.abort.signal;
try {
const states = [...this.sessions.values()];
+ this.updateRestartQueuePauses.clear();
+ for (const state of states) {
+ this.updateRestartQueuePauses.set(state.activeSessionId, state.runtime.session.acquireQueuedWorkPause());
+ }
+ await Promise.all(states.map((state) => state.runtime.session.waitForSessionInputCheckpoint(signal)));
+ this.assertUpdateRestartNotCancelled(transaction);
+ const snapshottedIds = new Set(states.map((state) => state.activeSessionId));
+ const addedSession = [...this.sessions.keys()].find((activeSessionId) => !snapshottedIds.has(activeSessionId));
+ if (addedSession) throw new Error(`Session ${addedSession} became resident during update preparation`);
+
const restartSessions = states
+ .filter((state) => this.sessions.get(state.activeSessionId) === state)
.map((state) => this.createUpdateRestartSession(state))
.filter((session): session is DaemonUpdateRestartSession => session !== undefined)
- .sort(
- (left, right) =>
- this.getUpdateRestartSessionDepth(this.getSessionState(left.activeSessionId)) -
- this.getUpdateRestartSessionDepth(this.getSessionState(right.activeSessionId)),
- );
- const manifest = {
+ .sort((left, right) => {
+ const leftState = this.sessions.get(left.activeSessionId);
+ const rightState = this.sessions.get(right.activeSessionId);
+ return (
+ (leftState ? this.getUpdateRestartSessionDepth(leftState) : 0) -
+ (rightState ? this.getUpdateRestartSessionDepth(rightState) : 0)
+ );
+ });
+ this.assertUpdateRestartNotCancelled(transaction);
+ const includedActiveSessionIds = new Set(restartSessions.map((session) => session.activeSessionId));
+ const discardedActiveSessionIds = states
+ .filter(
+ (state) =>
+ this.sessions.get(state.activeSessionId) === state &&
+ !includedActiveSessionIds.has(state.activeSessionId),
+ )
+ .map((state) => state.activeSessionId);
+ return {
createdAt: new Date().toISOString(),
sessions: restartSessions,
+ ...(discardedActiveSessionIds.length > 0 ? { discardedActiveSessionIds } : {}),
};
- this.preparedUpdateRestartManifest = manifest;
- return manifest;
} catch (error) {
- this.cancelPreparedUpdateRestart();
+ this.cancelPreparedUpdateRestart(transaction.id);
throw error;
}
}
- private async commitPreparedUpdateRestart(): Promise<DaemonUpdateRestartManifest> {
- const manifest = this.preparedUpdateRestartManifest;
- if (!this.updateRestartPreparing || !manifest) {
+ private async commitPreparedUpdateRestart(transactionId: symbol): Promise<DaemonUpdateRestartManifest> {
+ const transaction = this.updateRestart;
+ if (transaction?.id !== transactionId || !transaction.manifest) {
throw new Error("Daemon has no prepared update checkpoint");
}
+ const manifest = transaction.manifest;
const restartByActiveSessionId = new Map(manifest.sessions.map((session) => [session.activeSessionId, session]));
for (const state of this.sessions.values()) {
const restartSession = restartByActiveSessionId.get(state.activeSessionId);
- if (restartSession) {
- this.appendUpdateRestartMarker(state, restartSession);
- }
+ if (restartSession) this.appendUpdateRestartMarker(state, restartSession);
}
const closeStates = [...this.sessions.values()].sort(
(left, right) => this.getUpdateRestartSessionDepth(right) - this.getUpdateRestartSessionDepth(left),
@@ -4387,27 +4722,47 @@ export class AgentDaemon {
await this.closeSession(state, restartByActiveSessionId.has(state.activeSessionId) ? "update" : "killed");
}
}
- for (const state of [...this.sessions.values()]) {
- await this.closeSession(state, "killed");
- }
+ for (const state of [...this.sessions.values()]) await this.closeSession(state, "killed");
return manifest;
}
- private cancelPreparedUpdateRestart(): void {
- this.preparedUpdateRestartManifest = undefined;
- this.updateRestartPreparing = false;
- if (!this.shuttingDown) {
- this.cronScheduler.start();
+ private cancelPreparedUpdateRestart(transactionId?: symbol): void {
+ const transaction = this.updateRestart;
+ if (!transaction || (transactionId && transaction.id !== transactionId)) return;
+ if (transaction.deadline) clearTimeout(transaction.deadline);
+ transaction.deadline = undefined;
+ transaction.abort.abort();
+ if (transaction.phase === "publishing") return;
+ this.updateRestart = undefined;
+ for (const deferred of transaction.deferredClientEnv) {
+ if (
+ this.sessions.get(deferred.state.activeSessionId) === deferred.state &&
+ deferred.state.clients.has(deferred.client) &&
+ deferred.client.attachedActiveSessionIds.has(deferred.state.activeSessionId)
+ ) {
+ this.adoptClientEnv(deferred.state, deferred.env);
+ }
}
+ transaction.deferredClientEnv.length = 0;
+ for (const pause of this.updateRestartQueuePauses.values()) pause.release();
+ this.updateRestartQueuePauses.clear();
+ if (!this.shuttingDown) this.cronScheduler.start();
}
private async prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest> {
- const manifest = this.prepareUpdateRestartCheckpoint();
+ const transaction = this.beginUpdateRestartTransaction();
try {
+ const manifest = await this.runUpdateRestartPreparation(transaction);
+ if (transaction.deadline) clearTimeout(transaction.deadline);
+ transaction.deadline = undefined;
+ transaction.phase = "publishing";
this.writeUpdateRestartManifest(manifest);
- return await this.commitPreparedUpdateRestart();
+ return await this.commitPreparedUpdateRestart(transaction.id);
} catch (error) {
- this.cancelPreparedUpdateRestart();
+ if (this.updateRestart === transaction && transaction.phase === "publishing") {
+ transaction.phase = "prepared";
+ }
+ this.cancelPreparedUpdateRestart(transaction.id);
throw error;
}
}
@@ -4442,11 +4797,21 @@ export class AgentDaemon {
return undefined;
}
+ private abortWaitingPromptAdmissionsForSession(activeSessionId: string): void {
+ for (const admission of this.promptAdmissions.values()) {
+ if (admission.activeSessionId === activeSessionId && admission.status === "waiting") {
+ admission.status = "cancelled";
+ admission.controller?.abort();
+ }
+ }
+ }
+
private async closeSession(
state: ActiveSessionState,
reason: DaemonSessionClosedReason,
waitForAbort = true,
): Promise<void> {
+ this.abortWaitingPromptAdmissionsForSession(state.activeSessionId);
for (const client of state.clients) {
this.abortSideQuestionsFor(client, state.activeSessionId);
}
@@ -4970,6 +5335,10 @@ export class AgentDaemon {
this.signalCleanupHandlers.push(() => process.off("exit", exitHandler));
}
+ private getShutdownClosingReason(): DaemonClosingReason {
+ return this.updateRestart?.phase === "publishing" ? "update" : "shutdown";
+ }
+
private async shutdown(exitCode: number): Promise<never> {
if (this.shuttingDown) {
process.exit(exitCode);
@@ -4984,7 +5353,7 @@ export class AgentDaemon {
this.supervisorFenceTimer = undefined;
}
this.log(`shutting down (exit ${exitCode}); closing ${this.sessions.size} active session(s)`);
- const closingReason: DaemonClosingReason = this.updateRestartPreparing ? "update" : "shutdown";
+ const closingReason = this.getShutdownClosingReason();
for (const client of this.clients) {
abortClientSnapshotStreaming(client);
this.write(client, { type: "daemon_closing", reason: closingReason });
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 7639b44388..bf84adf971 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -48,17 +48,11 @@ import type { SessionSummary } from "./daemon-session-list.js";
*/
export const DAEMON_PROTOCOL_NAME = "prime-agent.daemon";
-export const DAEMON_PROTOCOL_VERSION = 4;
+export const DAEMON_PROTOCOL_VERSION = 5;
export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 2;
-// Revision 5: transient + runId on execute_bash (echoed with a transient
-// marker on the run's bash_start/bash_end session events) + transient_bash
-// capability.
-// Revision 4: side_question_transcript capability. The digest only covers the
-// command/outbound type source, so capability-list and session-event changes
-// must bump this revision by hand — otherwise a retained older daemon passes
-// the staleness probe and clients gate features against it forever.
-export const DAEMON_SCHEMA_REVISION = 5;
-export const DAEMON_SCHEMA_ID = "protocol-4-schema-5-4c17c4fb3f00";
+// Revision 6 combines prompt-admission cancellation with side-question transcripts and transient bash.
+export const DAEMON_SCHEMA_REVISION = 6;
+export const DAEMON_SCHEMA_ID = "protocol-5-schema-6-48a562b9bffe";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -77,6 +71,10 @@ export type DaemonClientCapability =
| "slim_attach"
| "chunked_snapshot"
| "client_owned_sessions";
+export type DaemonPromptAdmissionCancellationStatus = "cancelled" | "owned" | "unknown";
+export interface DaemonPromptAdmissionCancellationResult {
+ status: DaemonPromptAdmissionCancellationStatus;
+}
export type DaemonServerCapability =
| DaemonClientCapability
| "heartbeat_catalog"
@@ -89,7 +87,10 @@ export type DaemonServerCapability =
// bash: never recorded into the session, and its bash_start/bash_end events
// carry the transient marker and echoed runId so clients correlate runs by
// identity). Clients must check before sending.
- | "transient_bash";
+ | "transient_bash"
+ | "session_input_admission"
+ | "prompt_admission_cancellation";
+
export type DaemonReplayStatus = "complete" | "partial" | "unavailable";
export interface DaemonProtocolInfo {
@@ -123,6 +124,8 @@ export const DAEMON_DEFAULT_SERVER_CAPABILITIES: readonly DaemonServerCapability
"model_catalog",
"side_question_transcript",
"transient_bash",
+ "session_input_admission",
+ "prompt_admission_cancellation",
];
export interface DaemonRuntimeIdentity {
@@ -328,6 +331,7 @@ export interface DaemonUpdateRestartSession {
export interface DaemonUpdateRestartManifest {
createdAt: string;
sessions: DaemonUpdateRestartSession[];
+ discardedActiveSessionIds?: string[];
}
export type DaemonSavedSessionListCommand =
@@ -395,10 +399,19 @@ export type DaemonCommand =
content?: (TextContent | ImageContent)[];
images?: ImageContent[];
streamingBehavior?: "steer" | "followUp";
+ queueIfBusy?: boolean;
expandPromptTemplates?: boolean;
source?: InputSource;
agentMessageId?: string;
customMessage?: CustomMessage;
+ /** Unique only when the caller needs cancellable pre-ownership admission. */
+ admissionId?: string;
+ }
+ | {
+ id?: string;
+ type: "cancel_prompt_admission";
+ activeSessionId: string;
+ admissionId: string;
}
| {
id?: string;
@@ -408,8 +421,11 @@ export type DaemonCommand =
content?: (TextContent | ImageContent)[];
images?: ImageContent[];
streamingBehavior?: "steer" | "followUp";
+ queueIfBusy?: boolean;
expandPromptTemplates?: boolean;
source?: InputSource;
+ /** Unique only when the caller needs cancellable pre-ownership admission. */
+ admissionId?: string;
}
| {
id?: string;
@@ -590,13 +606,23 @@ type DaemonCommandName = DaemonCommand["type"];
export interface DaemonCommandCompatibility {
minProtocol: number;
+ minSchemaRevision?: number;
capability?: DaemonServerCapability;
}
const LEGACY_DAEMON_COMMAND = { minProtocol: 1 } as const;
-const CURRENT_DAEMON_COMMAND = { minProtocol: DAEMON_PROTOCOL_VERSION } as const;
+const CURRENT_DAEMON_COMMAND = { minProtocol: 4 } as const;
+const SESSION_INPUT_ADMISSION_COMMAND = {
+ minProtocol: 4,
+ capability: "session_input_admission",
+} as const;
+const PROMPT_ADMISSION_CANCELLATION_COMMAND = {
+ minProtocol: 5,
+ minSchemaRevision: 6,
+ capability: "prompt_admission_cancellation",
+} as const;
const CLIENT_OWNED_DAEMON_COMMAND = {
- minProtocol: DAEMON_PROTOCOL_VERSION,
+ minProtocol: 4,
capability: "client_owned_sessions",
} as const;
@@ -612,13 +638,14 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
promote_owned_session: CLIENT_OWNED_DAEMON_COMMAND,
kill: LEGACY_DAEMON_COMMAND,
rename: LEGACY_DAEMON_COMMAND,
- prompt: LEGACY_DAEMON_COMMAND,
- prompt_and_wait: CURRENT_DAEMON_COMMAND,
- steer: LEGACY_DAEMON_COMMAND,
- follow_up: LEGACY_DAEMON_COMMAND,
+ prompt: SESSION_INPUT_ADMISSION_COMMAND,
+ cancel_prompt_admission: PROMPT_ADMISSION_CANCELLATION_COMMAND,
+ prompt_and_wait: SESSION_INPUT_ADMISSION_COMMAND,
+ steer: SESSION_INPUT_ADMISSION_COMMAND,
+ follow_up: SESSION_INPUT_ADMISSION_COMMAND,
restore_next_turn: LEGACY_DAEMON_COMMAND,
append_custom_message: LEGACY_DAEMON_COMMAND,
- resume_queue: LEGACY_DAEMON_COMMAND,
+ resume_queue: SESSION_INPUT_ADMISSION_COMMAND,
send_message: LEGACY_DAEMON_COMMAND,
agent_messages_status: LEGACY_DAEMON_COMMAND,
agent_messages_pause: LEGACY_DAEMON_COMMAND,
@@ -695,6 +722,14 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
shutdown: LEGACY_DAEMON_COMMAND,
} as const satisfies Record<DaemonCommandName, DaemonCommandCompatibility>;
+export function getDaemonCommandCompatibilities(command: DaemonCommand): readonly DaemonCommandCompatibility[] {
+ const compatibility = DAEMON_COMMAND_COMPATIBILITY[command.type];
+ if ((command.type === "prompt" || command.type === "prompt_and_wait") && command.admissionId !== undefined) {
+ return [PROMPT_ADMISSION_CANCELLATION_COMMAND, compatibility];
+ }
+ return [compatibility];
+}
+
export type DaemonResponse =
| { id?: string; type: "response"; command: string; success: true; data?: unknown }
| {
@@ -781,6 +816,8 @@ export type DaemonOutbound =
socketPath: string;
protocol: DaemonProtocolInfo;
schemaId?: string;
+ /** Monotonic wire-schema revision for field-sensitive compatibility checks. */
+ schemaRevision?: number;
/** App version of the daemon process, used to detect stale daemons after self-update. */
appVersion?: string;
runtime?: DaemonRuntimeIdentity;
@@ -970,6 +1007,15 @@ export function isDaemonMutatingCommand(command: Pick<DaemonCommand, "type">): b
return !READ_ONLY_DAEMON_COMMANDS.has(command.type);
}
+export const UPDATE_RESTART_DRAIN_COMMANDS: ReadonlySet<DaemonCommand["type"]> = new Set([
+ "extension_ui_response",
+ "abort",
+ "abort_bash",
+ "abort_branch_summary",
+ "abort_compaction",
+ "abort_retry",
+]);
+
export function createDaemonEventEnvelope<TEvent extends DaemonOutbound>(
event: TEvent,
meta: DaemonEventMeta,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 9f4c23beba..54c906618c 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -45,6 +45,7 @@ import {
DAEMON_DEFAULT_SERVER_CAPABILITIES,
DAEMON_PROTOCOL_INFO,
DAEMON_SCHEMA_ID,
+ DAEMON_SCHEMA_REVISION,
type DaemonAttachResult,
type DaemonClientCapability,
type DaemonClosingReason,
@@ -57,6 +58,7 @@ import {
isDaemonCommandEnvelope,
isDaemonMutatingCommand,
success,
+ UPDATE_RESTART_DRAIN_COMMANDS,
} from "./daemon-protocol.js";
import { getDaemonRuntimeIdentity } from "./daemon-runtime-identity.js";
import { matchesSessionIdSuffix } from "./daemon-session-id.js";
@@ -92,6 +94,7 @@ import {
SESSION_LEASE_OWNER_ID_ENV,
SESSION_LEASES_ENABLED_ENV,
} from "./daemon-worker-protocol.js";
+import { MutationDrainLatch } from "./mutation-drain-latch.js";
import { SNAPSHOT_TARGET_CHUNK_BYTES, SnapshotTranscriptCache } from "./snapshot-transcript-cache.js";
import { WorkerRecoveryJournal } from "./worker-recovery-journal.js";
@@ -101,6 +104,12 @@ type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
const structuredLog = getLogger("coding-agent.daemon-supervisor");
const WORKER_CONNECT_TIMEOUT_MS = 30_000;
const WORKER_REQUEST_TIMEOUT_MS = 24 * 60 * 60 * 1000;
+const UPDATE_RESTART_MUTATION_DRAIN_TIMEOUT_MS = 80_000;
+const UPDATE_RESTART_WORKER_REQUEST_TIMEOUT_MS = 90_000;
+// The whole pre-commit prepare (drain + worker fencing) must finish inside the
+// caller's 120s prepare_update_restart request timeout, or roll back; otherwise
+// an abandoned prepare leaves the daemon permanently fenced with workers stopped.
+const UPDATE_RESTART_PREPARE_DEADLINE_MS = 100_000;
const WORKER_RETRY_DELAYS_MS = [250, 1000, 5000] as const;
const DEFERRED_RECOVERY_RECHECK_MS = 5000;
const OWNED_WORKER_DISCONNECT_GRACE_MS = 30_000;
@@ -120,6 +129,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"kill",
"rename",
"prompt",
+ "cancel_prompt_admission",
"prompt_and_wait",
"steer",
"follow_up",
@@ -220,6 +230,7 @@ interface ResidentWorker {
launchEnv?: Record<string, string>;
ownerCleanupTimer?: ReturnType<typeof setTimeout>;
promotedOwnerClientId?: string;
+ updateRestartPrepareClient?: DaemonWorkerClient;
}
interface SnapshotDuplicateValidation {
@@ -264,6 +275,17 @@ interface WorkerAttachData {
releaseTranscript?: () => void;
}
+interface SupervisorPromptAdmission {
+ client: DaemonSocketClient;
+ activeSessionId: string;
+ publicAdmissionId: string;
+ workerAdmissionId: string;
+ status: "waiting" | "owned" | "cancelled";
+ controller: AbortController;
+ worker?: ResidentWorker;
+ workerActiveSessionId?: string;
+}
+
class SupervisorRecoveryCancelledError extends Error {
readonly code = "supervisor_recovery_cancelled" as const;
}
@@ -295,6 +317,33 @@ function delay(ms: number): Promise<void> {
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
}
+export function waitForSupervisorPromptAdmission<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
+ if (!signal) return promise;
+ if (signal.aborted) {
+ void promise.catch(() => {});
+ return Promise.reject(new Error("Prompt admission was cancelled."));
+ }
+ return new Promise<T>((resolve, reject) => {
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
+ const onAbort = () => {
+ cleanup();
+ reject(new Error("Prompt admission was cancelled."));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ if (signal.aborted) return onAbort();
+ promise.then(
+ (value) => {
+ cleanup();
+ resolve(value);
+ },
+ (error: unknown) => {
+ cleanup();
+ reject(error);
+ },
+ );
+ });
+}
+
function unrefDelay(ms: number): Promise<void> {
return new Promise((resolveDelay) => setTimeout(resolveDelay, ms).unref());
}
@@ -537,10 +586,14 @@ export class DaemonSupervisor {
private ownership?: Awaited<ReturnType<typeof acquireDaemonSupervisorOwnership>>;
private cleanupPromise?: Promise<void>;
private shuttingDown = false;
+ private updateRestartPhase?: "draining" | "fencing" | "prepared";
+ private readonly mutationDrain = new MutationDrainLatch();
private readonly clients = new Set<DaemonSocketClient>();
private readonly protocolClientIds = new WeakMap<DaemonSocketClient, string>();
private readonly workers = new Map<string, ResidentWorker>();
private readonly openingWorkers = new Map<string, Promise<ResidentWorker>>();
+ /** Public admission ids are scoped to the socket that registered them. */
+ private readonly promptAdmissions = new Map<DaemonSocketClient, Map<string, SupervisorPromptAdmission>>();
private readonly signalCleanupHandlers: Array<() => void> = [];
private readonly descriptorDir: string;
private readonly generation = randomUUID();
@@ -822,6 +875,7 @@ export class DaemonSupervisor {
socketPath: this.socketPath,
protocol: DAEMON_PROTOCOL_INFO,
schemaId: DAEMON_SCHEMA_ID,
+ schemaRevision: DAEMON_SCHEMA_REVISION,
appVersion: VERSION,
runtime: getDaemonRuntimeIdentity(),
supervisorGeneration: this.generation,
@@ -846,6 +900,7 @@ export class DaemonSupervisor {
cleaned = true;
client.detachInput();
this.clients.delete(client);
+ this.cancelWaitingPromptAdmissionsForClient(client);
for (const activeSessionId of [...client.attachedActiveSessionIds]) {
client.attachedActiveSessionIds.delete(activeSessionId);
void this.syncWorkerExtensionUi(activeSessionId);
@@ -914,61 +969,198 @@ export class DaemonSupervisor {
worker.ownerCleanupTimer.unref();
}
+ private promptAdmissionKey(activeSessionId: string, publicAdmissionId: string): string {
+ return `${activeSessionId}\0${publicAdmissionId}`;
+ }
+
+ private promptAdmissionsFor(client: DaemonSocketClient): Map<string, SupervisorPromptAdmission> {
+ let admissions = this.promptAdmissions.get(client);
+ if (!admissions) {
+ admissions = new Map();
+ this.promptAdmissions.set(client, admissions);
+ }
+ return admissions;
+ }
+
+ private getPromptAdmission(
+ client: DaemonSocketClient,
+ activeSessionId: string,
+ publicAdmissionId: string,
+ ): SupervisorPromptAdmission | undefined {
+ return this.promptAdmissions.get(client)?.get(this.promptAdmissionKey(activeSessionId, publicAdmissionId));
+ }
+
+ private deletePromptAdmission(admission: SupervisorPromptAdmission): void {
+ const admissions = this.promptAdmissions.get(admission.client);
+ const key = this.promptAdmissionKey(admission.activeSessionId, admission.publicAdmissionId);
+ if (admissions?.get(key) !== admission) return;
+ admissions.delete(key);
+ if (admissions.size === 0) this.promptAdmissions.delete(admission.client);
+ }
+
+ private cancelWaitingPromptAdmissionsForClient(client: DaemonSocketClient): void {
+ for (const admission of this.promptAdmissions.get(client)?.values() ?? []) {
+ if (admission.status !== "waiting") continue;
+ if (!admission.worker || !admission.workerActiveSessionId) {
+ admission.status = "cancelled";
+ admission.controller.abort();
+ continue;
+ }
+ const worker = admission.worker;
+ const workerActiveSessionId = admission.workerActiveSessionId;
+ void this.forwardToWorker(worker, {
+ type: "cancel_prompt_admission",
+ activeSessionId: workerActiveSessionId,
+ admissionId: admission.workerAdmissionId,
+ })
+ .then((response) => {
+ if (admission.status !== "waiting") return;
+ const status =
+ response.success && response.data && typeof response.data === "object" && "status" in response.data
+ ? (response.data as { status?: unknown }).status
+ : undefined;
+ if (status === "owned") admission.status = "owned";
+ else if (status === "cancelled") admission.status = "cancelled";
+ })
+ .catch((error: unknown) => {
+ this.log(
+ `Could not cancel prompt admission ${admission.workerAdmissionId} on disconnected client: ${String(error)}`,
+ );
+ });
+ }
+ }
+
+ /** Non-async by design: prompt registration completes before handleLine's first await. */
+ private parseCommandAndRegisterPromptAdmission(
+ client: DaemonSocketClient,
+ line: string,
+ ): {
+ command: DaemonCommand;
+ envelopeClientId?: string;
+ admission?: SupervisorPromptAdmission;
+ } {
+ const parsed = JSON.parse(line) as unknown;
+ const command = (
+ isDaemonCommandEnvelope(parsed) ? { ...parsed.command, id: parsed.id } : parsed
+ ) 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") {
+ throw new Error("Prompt admission requires string activeSessionId and admissionId");
+ }
+ if (command.admissionId === "") throw new Error("admissionId must not be empty");
+ const admissions = this.promptAdmissionsFor(client);
+ const key = this.promptAdmissionKey(command.activeSessionId, command.admissionId);
+ if (admissions.has(key)) {
+ throw new Error(`Prompt admission id is already in use: ${command.admissionId}`);
+ }
+ admission = {
+ client,
+ activeSessionId: command.activeSessionId,
+ publicAdmissionId: command.admissionId,
+ workerAdmissionId: `supervisor-admission:${randomUUID()}`,
+ status: "waiting",
+ controller: new AbortController(),
+ };
+ admissions.set(key, admission);
+ }
+ return {
+ command,
+ envelopeClientId: isDaemonCommandEnvelope(parsed) ? (parsed.clientId ?? client.id) : undefined,
+ admission,
+ };
+ }
+
private async handleLine(client: DaemonSocketClient, line: string): Promise<void> {
+ let preParsed: ReturnType<DaemonSupervisor["parseCommandAndRegisterPromptAdmission"]>;
try {
- await this.ready;
- } catch {
+ preParsed = this.parseCommandAndRegisterPromptAdmission(client, line);
+ } catch (error) {
+ this.write(client, failure(undefined, "parse", error));
return;
}
- let command: DaemonCommand;
- let envelopeClientId: string | undefined;
+ const command = preParsed.command;
+ const parsedAdmission = preParsed.admission;
+ if (command.type === "cancel_prompt_admission" && this.updateRestartPhase !== undefined) {
+ this.write(client, failure(command.id, command.type, "Daemon is preparing an update restart"));
+ return;
+ }
+ const cancellationAdmission =
+ command.type === "cancel_prompt_admission"
+ ? this.getPromptAdmission(client, command.activeSessionId, command.admissionId)
+ : undefined;
+ if (cancellationAdmission?.status === "waiting" && !cancellationAdmission.worker) {
+ cancellationAdmission.status = "cancelled";
+ cancellationAdmission.controller.abort();
+ }
try {
- const parsed = JSON.parse(line) as unknown;
- const candidate = isDaemonCommandEnvelope(parsed)
- ? { ...parsed.command, id: parsed.id }
- : (parsed as { id?: unknown; type?: unknown });
- if (isDaemonCommandEnvelope(parsed)) {
- envelopeClientId = parsed.clientId ?? client.id;
- this.protocolClientIds.set(client, envelopeClientId);
- client.id = envelopeClientId;
- }
- this.cancelOwnedWorkerCleanup(client.id);
- if (typeof candidate.type !== "string" || !DAEMON_COMMAND_TYPES.has(candidate.type)) {
- const commandName = typeof candidate.type === "string" ? candidate.type : "unknown";
- this.write(
- client,
- failure(
- typeof candidate.id === "string" ? candidate.id : undefined,
- commandName,
- `Unknown daemon command: ${commandName}`,
- ),
- );
- return;
- }
- command = candidate as DaemonCommand;
+ await waitForSupervisorPromptAdmission(this.ready, parsedAdmission?.controller.signal);
} catch (error) {
- this.write(client, failure(undefined, "parse", error));
+ if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);
+ this.write(client, failure(command.id, command.type, error));
+ return;
+ }
+ const envelopeClientId = preParsed.envelopeClientId;
+ if (envelopeClientId) {
+ this.protocolClientIds.set(client, envelopeClientId);
+ client.id = envelopeClientId;
+ }
+ this.cancelOwnedWorkerCleanup(client.id);
+ if (!DAEMON_COMMAND_TYPES.has(command.type)) {
+ this.write(client, failure(command.id, command.type, `Unknown daemon command: ${command.type}`));
return;
}
try {
- await this.assertCurrentOwnership();
+ await waitForSupervisorPromptAdmission(this.assertCurrentOwnership(), parsedAdmission?.controller.signal);
} catch (error) {
+ if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);
this.write(client, failure(command.id, command.type, error));
return;
}
+ const mutation = isDaemonMutatingCommand(command);
const journalIdentity =
- envelopeClientId && command.id && isDaemonMutatingCommand(command)
- ? { clientId: envelopeClientId, commandId: command.id }
- : undefined;
+ envelopeClientId && command.id && mutation ? { clientId: envelopeClientId, commandId: command.id } : undefined;
+ const existing = journalIdentity
+ ? this.commandJournal.lookup(journalIdentity.clientId, journalIdentity.commandId)
+ : undefined;
+ if (existing?.status === "complete") {
+ if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);
+ this.write(client, existing.response);
+ return;
+ }
+ if (existing?.status === "pending" && journalIdentity) {
+ if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);
+ this.write(
+ client,
+ failure(command.id, command.type, "The previous command result is uncertain and was not replayed", {
+ code: "command_result_uncertain",
+ ...journalIdentity,
+ }),
+ );
+ return;
+ }
+
+ const phase = this.updateRestartPhase;
+ const restartRejected =
+ phase === "draining"
+ ? !UPDATE_RESTART_DRAIN_COMMANDS.has(command.type)
+ : phase !== undefined && !(phase === "prepared" && command.type === "shutdown");
+ if (restartRejected && mutation) {
+ if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);
+ this.write(client, failure(command.id, command.type, "Daemon is preparing an update restart"));
+ return;
+ }
if (journalIdentity) {
- const existing = this.commandJournal.begin(journalIdentity.clientId, journalIdentity.commandId, command.type);
- if (existing.status === "complete") {
- this.write(client, existing.response);
+ const admitted = this.commandJournal.begin(journalIdentity.clientId, journalIdentity.commandId, command.type);
+ if (admitted.status === "complete") {
+ if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);
+ this.write(client, admitted.response);
return;
}
- if (existing.status === "pending") {
+ if (admitted.status === "pending") {
+ if (parsedAdmission) this.deletePromptAdmission(parsedAdmission);
this.write(
client,
failure(command.id, command.type, "The previous command result is uncertain and was not replayed", {
@@ -980,8 +1172,9 @@ export class DaemonSupervisor {
}
}
+ if (mutation) this.mutationDrain.begin();
try {
- const response = await this.handleCommand(client, command);
+ const response = await this.handleCommand(client, command, cancellationAdmission);
if (response) {
if (journalIdentity) {
await this.assertCurrentOwnership();
@@ -1001,14 +1194,47 @@ export class DaemonSupervisor {
}
}
this.write(client, response);
+ } finally {
+ if (mutation) this.mutationDrain.end();
}
}
private async handleCommand(
client: DaemonSocketClient,
command: DaemonCommand,
+ cancellationAdmission?: SupervisorPromptAdmission,
): Promise<DaemonResponse | undefined> {
switch (command.type) {
+ case "cancel_prompt_admission": {
+ const admission =
+ cancellationAdmission ?? this.getPromptAdmission(client, command.activeSessionId, command.admissionId);
+ if (!admission) return success(command.id, command.type, { status: "unknown" as const });
+ if (admission.status === "owned") return success(command.id, command.type, { status: "owned" as const });
+ // A definitive cancellation never downgrades to unknown/waiting.
+ if (admission.status === "cancelled") {
+ return success(command.id, command.type, { status: "cancelled" as const });
+ }
+ if (!admission.worker || !admission.workerActiveSessionId) {
+ admission.status = "cancelled";
+ admission.controller.abort();
+ return success(command.id, command.type, { status: "cancelled" as const });
+ }
+ const response = await this.forwardToWorker(admission.worker, {
+ ...command,
+ activeSessionId: admission.workerActiveSessionId,
+ admissionId: admission.workerAdmissionId,
+ });
+ const status =
+ response.success && response.data && typeof response.data === "object" && "status" in response.data
+ ? (response.data as { status: "cancelled" | "owned" | "unknown" }).status
+ : "unknown";
+ // Re-read: a socket close may have cancelled during the round-trip (cast widens TS's pre-await narrowing).
+ const current = (admission as SupervisorPromptAdmission).status;
+ if (status === "owned") admission.status = "owned";
+ else if (status === "cancelled") admission.status = "cancelled";
+ else if (current !== "cancelled") admission.status = "waiting";
+ return { ...response, id: command.id };
+ }
case "ack_result":
this.commandJournal.acknowledge(client.id, command.commandId);
return undefined;
@@ -1386,25 +1612,47 @@ export class DaemonSupervisor {
if (!("activeSessionId" in command) || typeof command.activeSessionId !== "string") {
throw new Error(`Supervisor cannot route daemon command: ${command.type}`);
}
- const match = await this.findWorkerForClient(client, command.activeSessionId);
- const resolvedCommand = {
- ...command,
- activeSessionId: match.summary.activeSessionId ?? match.summary.id,
- } as DaemonCommand;
- const isRootKill =
- command.type === "kill" &&
- (match.summary.activeSessionId ?? match.summary.id) === match.worker.descriptor.rootActiveSessionId;
- if (!isRootKill) {
- return this.forwardToWorker(match.worker, resolvedCommand);
- }
- this.persistWorkerStopTombstone(match.worker, true);
- let response: DaemonResponse;
+ const admission =
+ (command.type === "prompt" || command.type === "prompt_and_wait") && command.admissionId
+ ? this.getPromptAdmission(client, command.activeSessionId, command.admissionId)
+ : undefined;
try {
- response = await this.forwardToWorker(match.worker, resolvedCommand);
+ if (admission?.status === "cancelled") throw new Error("Prompt admission was cancelled.");
+ const match = await waitForSupervisorPromptAdmission(
+ this.findWorkerForClient(client, command.activeSessionId),
+ admission?.controller.signal,
+ );
+ if ((admission as { status: string } | undefined)?.status === "cancelled") {
+ throw new Error("Prompt admission was cancelled.");
+ }
+ const resolvedCommand = {
+ ...command,
+ activeSessionId: match.summary.activeSessionId ?? match.summary.id,
+ ...(admission ? { admissionId: admission.workerAdmissionId } : {}),
+ } as DaemonCommand;
+ if (admission) {
+ admission.worker = match.worker;
+ admission.workerActiveSessionId = match.summary.activeSessionId ?? match.summary.id;
+ }
+ const isRootKill =
+ command.type === "kill" &&
+ (match.summary.activeSessionId ?? match.summary.id) === match.worker.descriptor.rootActiveSessionId;
+ if (!isRootKill) {
+ const response = await this.forwardToWorker(match.worker, resolvedCommand);
+ if (admission && response.success) admission.status = "owned";
+ return response;
+ }
+ this.persistWorkerStopTombstone(match.worker, true);
+ let response: DaemonResponse;
+ try {
+ response = await this.forwardToWorker(match.worker, resolvedCommand);
+ } finally {
+ await this.stopWorker(match.worker, true, false, true);
+ }
+ return response;
} finally {
- await this.stopWorker(match.worker, true, false, true);
+ if (admission) this.deletePromptAdmission(admission);
}
- return response;
}
private async handleList(
@@ -3557,73 +3805,161 @@ export class DaemonSupervisor {
}
private async prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest> {
- const workers = [...this.workers.values()].filter(
- (worker): worker is ResidentWorker & { client: DaemonWorkerClient } => worker.client !== undefined,
+ if (this.updateRestartPhase !== undefined) throw new Error("Daemon is already preparing an update restart");
+ this.updateRestartPhase = "draining";
+ try {
+ const deadline = Date.now() + UPDATE_RESTART_PREPARE_DEADLINE_MS;
+ const abort = AbortSignal.timeout(Math.min(UPDATE_RESTART_MUTATION_DRAIN_TIMEOUT_MS, deadline - Date.now()));
+ await this.mutationDrain.waitForDrain(1, abort, "Timed out draining daemon mutations for update restart");
+ this.updateRestartPhase = "fencing";
+ await this.mutationDrain.waitForDrain(1, abort, "Timed out draining daemon mutations for update restart");
+ const manifest = await this.prepareUpdateRestartFenced(deadline);
+ this.updateRestartPhase = "prepared";
+ return manifest;
+ } catch (error) {
+ this.updateRestartPhase = undefined;
+ throw error;
+ }
+ }
+
+ private async prepareUpdateRestartFenced(deadline: number): Promise<DaemonUpdateRestartManifest> {
+ const residents = [...this.workers.values()];
+ const unavailable = residents.find(
+ (worker) => worker.descriptor.lifecycle !== "ready" || worker.client === undefined,
);
- const prepared: Array<ResidentWorker & { client: DaemonWorkerClient }> = [];
+ if (unavailable) {
+ throw new Error(
+ `Cannot prepare update restart while resident worker ${unavailable.descriptor.workerId} is ${unavailable.descriptor.lifecycle}${unavailable.client ? "" : " and disconnected"}`,
+ );
+ }
+ const workers = residents as Array<ResidentWorker & { client: DaemonWorkerClient }>;
+ const acknowledged: ResidentWorker[] = [];
const preparationResults = await Promise.allSettled(
workers.map(async (worker) => {
- const response = await worker.client.requestWorker(
+ const client = worker.client;
+ const response = await client.requestWorker(
{ type: "worker_prepare_update" },
- WORKER_REQUEST_TIMEOUT_MS,
+ Math.max(1, Math.min(UPDATE_RESTART_WORKER_REQUEST_TIMEOUT_MS, deadline - Date.now())),
);
- if (!response.success || !response.data || typeof response.data !== "object") {
- throw new Error(response.success ? "Worker returned an invalid update manifest" : response.error);
+ if (!response.success) throw new Error(response.error);
+ worker.updateRestartPrepareClient = client;
+ acknowledged.push(worker);
+ if (!response.data || typeof response.data !== "object") {
+ throw new Error("Worker returned an invalid update manifest");
+ }
+ if (worker.client !== client || worker.descriptor.lifecycle !== "ready") {
+ throw new Error(`Worker ${worker.descriptor.workerId} disconnected during update preparation`);
}
- return { worker, manifest: response.data as DaemonUpdateRestartManifest };
+ const manifest = response.data as DaemonUpdateRestartManifest;
+ if (
+ !manifest.sessions.some(
+ (session) => session.activeSessionId === worker.descriptor.rootActiveSessionId,
+ ) &&
+ !manifest.discardedActiveSessionIds?.includes(worker.descriptor.rootActiveSessionId)
+ ) {
+ throw new Error(
+ `Worker ${worker.descriptor.workerId} omitted its root disposition from the update manifest`,
+ );
+ }
+ return { worker, manifest };
}),
);
- for (const result of preparationResults) {
- if (result.status === "fulfilled") {
- prepared.push(result.value.worker);
- }
- }
+ const cancelAcknowledged = async () => {
+ await Promise.all(
+ acknowledged.map(async (worker) => {
+ const prepareClient = worker.updateRestartPrepareClient;
+ worker.updateRestartPrepareClient = undefined;
+ if (!prepareClient) return;
+ try {
+ const response = await prepareClient.requestWorker({ type: "worker_cancel_update" }, 5000);
+ if (!response.success) throw new Error(response.error);
+ } catch (error) {
+ this.log(
+ `Could not cancel prepared worker ${worker.descriptor.workerId}; reconnecting it: ${String(error)}`,
+ );
+ prepareClient.close();
+ if (worker.client && worker.client !== prepareClient) worker.client.close();
+ }
+ }),
+ );
+ };
const preparationFailure = preparationResults.find(
(result): result is PromiseRejectedResult => result.status === "rejected",
);
if (preparationFailure) {
- await Promise.all(
- prepared.map((worker) =>
- worker.client.requestWorker({ type: "worker_cancel_update" }, 5000).catch(() => undefined),
- ),
- );
+ await cancelAcknowledged();
throw preparationFailure.reason;
}
+ const prepared = preparationResults.flatMap((result) =>
+ result.status === "fulfilled" ? [result.value.worker] : [],
+ );
const responses = preparationResults.flatMap((result) =>
result.status === "fulfilled" ? [result.value.manifest] : [],
);
+ const discardedActiveSessionIds = responses.flatMap((manifest) => manifest.discardedActiveSessionIds ?? []);
const manifest = {
createdAt: new Date().toISOString(),
sessions: responses.flatMap((manifest) => manifest.sessions),
+ ...(discardedActiveSessionIds.length > 0 ? { discardedActiveSessionIds } : {}),
};
+ // A worker that disconnected after preparing cancelled its checkpoint with
+ // the old client; a recovered replacement may have admitted inputs past the
+ // captured manifest. Abort before the manifest is persisted so the caller's
+ // fallback cannot restore from the stale checkpoint.
+ const staleWorker = prepared.find((worker) => worker.client !== worker.updateRestartPrepareClient);
+ if (staleWorker) {
+ await cancelAcknowledged();
+ throw new Error(
+ `Worker ${staleWorker.descriptor.workerId} reconnected during update preparation; its checkpoint is stale`,
+ );
+ }
try {
this.validateAndPersistUpdateManifest(manifest);
} catch (error) {
- await Promise.all(
- prepared.map((worker) =>
- worker.client.requestWorker({ type: "worker_cancel_update" }, 5000).catch(() => undefined),
- ),
- );
+ await cancelAcknowledged();
throw error;
}
- await Promise.all(
+ // Commit through the connection that owns the prepared transaction; a client
+ // swapped in after the check above must fail the commit rather than reach a
+ // worker that no longer holds the checkpoint.
+ const commitClients = new Map(prepared.map((worker) => [worker, worker.updateRestartPrepareClient]));
+ for (const worker of prepared) worker.updateRestartPrepareClient = undefined;
+ const commitResults = await Promise.allSettled(
prepared.map(async (worker) => {
- const response = await worker.client.requestWorker(
+ const client = commitClients.get(worker);
+ if (!client) throw new Error(`Worker ${worker.descriptor.workerId} disconnected before update commit`);
+ const response = await client.requestWorker(
{ type: "worker_commit_update" },
- WORKER_REQUEST_TIMEOUT_MS,
+ UPDATE_RESTART_WORKER_REQUEST_TIMEOUT_MS,
);
- if (!response.success) {
- throw new Error(response.error);
- }
+ if (!response.success) throw new Error(response.error);
}),
);
- await Promise.all(prepared.map((worker) => this.stopWorker(worker, false)));
+ const commitFailure = commitResults.find(
+ (result): result is PromiseRejectedResult => result.status === "rejected",
+ );
+ if (commitFailure) {
+ this.log(`Update restart commit response failed; forcing restart completion: ${String(commitFailure.reason)}`);
+ await Promise.allSettled(prepared.map((worker) => this.stopWorker(worker, false, true)));
+ return manifest;
+ }
+ const stopResults = await Promise.allSettled(prepared.map((worker) => this.stopWorker(worker, false)));
+ if (stopResults.some((result) => result.status === "rejected")) {
+ this.log("A committed update worker did not stop gracefully; forcing restart completion");
+ await Promise.allSettled(prepared.map((worker) => this.stopWorker(worker, false, true)));
+ }
return manifest;
}
private validateAndPersistUpdateManifest(manifest: DaemonUpdateRestartManifest): void {
const activeSessionIds = new Set<string>();
const sessionFiles = new Set<string>();
+ for (const discardedActiveSessionId of manifest.discardedActiveSessionIds ?? []) {
+ if (!discardedActiveSessionId || activeSessionIds.has(discardedActiveSessionId)) {
+ throw new Error("Update manifest contains an invalid discarded session disposition");
+ }
+ activeSessionIds.add(discardedActiveSessionId);
+ }
for (const session of manifest.sessions) {
if (!session.activeSessionId || !session.sessionFile) {
throw new Error("Update manifest contains an incomplete session checkpoint");
@@ -3631,7 +3967,7 @@ export class DaemonSupervisor {
if (activeSessionIds.has(session.activeSessionId)) {
throw new Error(`Update manifest contains duplicate active session ${session.activeSessionId}`);
}
- const sessionFile = resolve(session.sessionFile);
+ const sessionFile = canonicalSessionPath(session.sessionFile);
if (sessionFiles.has(sessionFile)) {
throw new Error(`Update manifest contains duplicate session file ${sessionFile}`);
}
diff --git a/packages/coding-agent/src/modes/daemon/mutation-drain-latch.ts b/packages/coding-agent/src/modes/daemon/mutation-drain-latch.ts
new file mode 100644
index 0000000000..3188e964df
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/mutation-drain-latch.ts
@@ -0,0 +1,37 @@
+/** Counts in-flight mutating commands so update-restart preparation can wait for them to drain. */
+export class MutationDrainLatch {
+ private active = 0;
+ private readonly waiters = new Set<() => void>();
+
+ begin(): void {
+ this.active++;
+ }
+
+ end(): void {
+ this.active--;
+ for (const resolve of this.waiters) resolve();
+ this.waiters.clear();
+ }
+
+ async waitForDrain(remaining: number, signal: AbortSignal, abortMessage: string): Promise<void> {
+ if (signal.aborted) throw new Error(abortMessage);
+ while (this.active > remaining) {
+ await new Promise<void>((resolve, reject) => {
+ let settled = false;
+ const settle = (error?: Error) => {
+ if (settled) return;
+ settled = true;
+ this.waiters.delete(onDrained);
+ signal.removeEventListener("abort", onAbort);
+ if (error) reject(error);
+ else resolve();
+ };
+ const onDrained = () => settle();
+ const onAbort = () => settle(new Error(abortMessage));
+ this.waiters.add(onDrained);
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+ if (signal.aborted) throw new Error(abortMessage);
+ }
+ }
+}
diff --git a/packages/coding-agent/src/modes/headless-completion.ts b/packages/coding-agent/src/modes/headless-completion.ts
index 803e9b656a..f082a45d58 100644
--- a/packages/coding-agent/src/modes/headless-completion.ts
+++ b/packages/coding-agent/src/modes/headless-completion.ts
@@ -1,3 +1,4 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { AssistantMessage } from "@earendil-works/pi-ai";
import type { AgentSession } from "../core/agent-session.js";
import {
@@ -5,11 +6,51 @@ import {
autonomousLimitReason,
buildAutonomousGateFailureContinuation,
} from "../core/autonomous.js";
+import {
+ COMPACTION_OUTCOME_CUSTOM_TYPE,
+ type CompactionOutcomeMessage,
+ isCompactionOutcomeMessage,
+ isSessionSlashCommandResultMessage,
+ type SessionSlashCommandResultMessage,
+} from "../core/messages.js";
export function latestAutonomousGateAttempt(status: AgentAutonomousStatus): number {
return Math.max(status.lastGateFailure?.attempt ?? 0, 0, ...Object.values(status.gateAttempts));
}
+export type HeadlessTerminalResultMessage = AssistantMessage | SessionSlashCommandResultMessage;
+
+export interface HeadlessTerminalResult {
+ primary?: HeadlessTerminalResultMessage;
+ compactionOutcomes: CompactionOutcomeMessage[];
+}
+
+export function selectHeadlessTerminalResult(messages: readonly AgentMessage[]): HeadlessTerminalResult {
+ let index = messages.length - 1;
+ const compactionOutcomes: CompactionOutcomeMessage[] = [];
+ while (index >= 0) {
+ const message = messages[index];
+ if (isCompactionOutcomeMessage(message)) {
+ compactionOutcomes.unshift(message);
+ index--;
+ continue;
+ }
+ // A corrupt outcome is still part of the terminal outcome suffix. Skip it
+ // without letting it hide earlier valid outcomes or their failure status.
+ if (message.role === "custom" && message.customType === COMPACTION_OUTCOME_CUSTOM_TYPE) {
+ index--;
+ continue;
+ }
+ break;
+ }
+ const precedingMessage = messages[index];
+ const primary =
+ precedingMessage?.role === "assistant" || isSessionSlashCommandResultMessage(precedingMessage)
+ ? precedingMessage
+ : undefined;
+ return { primary, compactionOutcomes };
+}
+
function shouldContinueAutonomousGates(status: AgentAutonomousStatus): boolean {
return (
status.enabled &&
@@ -63,10 +104,9 @@ export async function waitForHeadlessCompletion(session: AgentSession): Promise<
);
await session.agent.waitForIdle();
await session.refreshAutonomousGates();
- const lastMessage = session.state.messages.at(-1);
- if (lastMessage?.role === "assistant") {
- const assistantMessage = lastMessage as AssistantMessage;
- if (assistantMessage.stopReason === "error" || assistantMessage.stopReason === "aborted") {
+ const { primary } = selectHeadlessTerminalResult(session.state.messages);
+ if (primary?.role === "assistant") {
+ if (primary.stopReason === "error" || primary.stopReason === "aborted") {
const postErrorStatus = session.getAutonomousStatus();
if (shouldContinueAutonomousGates(postErrorStatus) && postErrorStatus.lastGateFailure) {
continue;
diff --git a/packages/coding-agent/src/modes/index.ts b/packages/coding-agent/src/modes/index.ts
index dd3ef26296..933a2d24e8 100644
--- a/packages/coding-agent/src/modes/index.ts
+++ b/packages/coding-agent/src/modes/index.ts
@@ -69,6 +69,7 @@ export { resolveAttachModelFallbackMessage } from "./daemon/daemon-session-list.
export { defaultDaemonSocketPath } from "./daemon/daemon-socket.js";
export { runDaemonSupervisorMode } from "./daemon/daemon-supervisor.js";
export {
+ type InteractiveInitialPrompt,
InteractiveMode,
type InteractiveModeOptions,
type InteractiveModeRunResult,
diff --git a/packages/coding-agent/src/modes/interactive/components/compaction-outcome-message.ts b/packages/coding-agent/src/modes/interactive/components/compaction-outcome-message.ts
new file mode 100644
index 0000000000..8772901833
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/components/compaction-outcome-message.ts
@@ -0,0 +1,27 @@
+import { Box, Container, Text } from "@earendil-works/pi-tui";
+import type { CompactionOutcomeMessage } from "../../../core/messages.js";
+import { theme } from "../theme/theme.js";
+
+/** Renders a durable unsuccessful automatic-compaction outcome. */
+export class CompactionOutcomeMessageComponent extends Container {
+ constructor(message: CompactionOutcomeMessage) {
+ super();
+ const color = message.details.outcome === "skipped" ? "warning" : "error";
+ const contentBox = new Box(2, 1, (text: string) => theme.getUserMessageBackgroundColor()(text));
+ contentBox.addChild(new Text(theme.fg(color, message.content), 0, 0));
+ this.addChild(contentBox);
+ }
+
+ setExpanded(_expanded: boolean): void {}
+}
+
+export class MalformedCompactionOutcomeMessageComponent extends Container {
+ constructor() {
+ super();
+ const contentBox = new Box(2, 1, (text: string) => theme.getUserMessageBackgroundColor()(text));
+ contentBox.addChild(new Text(theme.fg("error", "[Malformed compaction outcome message]"), 0, 0));
+ this.addChild(contentBox);
+ }
+
+ setExpanded(_expanded: boolean): void {}
+}
diff --git a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
index 1c60d83c86..7505932329 100644
--- a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
+++ b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
@@ -1,9 +1,23 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { Component, MarkdownTheme, TUI } from "@earendil-works/pi-tui";
import { isAgentSessionMessage } from "../../../core/agent-messages.js";
+import {
+ COMPACTION_OUTCOME_CUSTOM_TYPE,
+ isCompactionOutcomeMessage,
+ isSessionSlashCommandMessage,
+ isSessionSlashCommandResultMessage,
+ SESSION_SLASH_COMMAND_CUSTOM_TYPE,
+ SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE,
+} from "../../../core/messages.js";
import { AgentMessageComponent } from "./agent-message.js";
import { AssistantMessageComponent } from "./assistant-message.js";
+import {
+ CompactionOutcomeMessageComponent,
+ MalformedCompactionOutcomeMessageComponent,
+} from "./compaction-outcome-message.js";
import { InjectedPromptMessageComponent, isInjectedPromptMessage } from "./injected-prompt-message.js";
+import { SlashCommandMessageComponent } from "./slash-command-message.js";
+import { SlashCommandResultMessageComponent } from "./slash-command-result-message.js";
import {
selectLatestToolExpandHint,
ToolExecutionComponent,
@@ -88,6 +102,26 @@ export function buildConversationComponents(
} else if (message.role === "toolResult") {
pendingTools.get(message.toolCallId)?.updateResult(message);
pendingTools.delete(message.toolCallId);
+ } else if (
+ message.role === "custom" &&
+ (message.customType === SESSION_SLASH_COMMAND_CUSTOM_TYPE ||
+ message.customType === SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE)
+ ) {
+ if (!message.display) continue;
+ if (isSessionSlashCommandMessage(message)) {
+ components.push(new SlashCommandMessageComponent(message.content));
+ } else if (isSessionSlashCommandResultMessage(message)) {
+ components.push(new SlashCommandResultMessageComponent(message));
+ } else {
+ components.push(new UserMessageComponent("[Malformed session command message]", options.markdownTheme));
+ }
+ } else if (message.role === "custom" && message.customType === COMPACTION_OUTCOME_CUSTOM_TYPE) {
+ if (!message.display) continue;
+ components.push(
+ isCompactionOutcomeMessage(message)
+ ? new CompactionOutcomeMessageComponent(message)
+ : new MalformedCompactionOutcomeMessageComponent(),
+ );
} else if (isAgentSessionMessage(message) && message.display) {
const component = new AgentMessageComponent(message, options.markdownTheme);
component.setExpanded(expanded);
diff --git a/packages/coding-agent/src/modes/interactive/components/index.ts b/packages/coding-agent/src/modes/interactive/components/index.ts
index 7284761f82..6b5bc16d2c 100644
--- a/packages/coding-agent/src/modes/interactive/components/index.ts
+++ b/packages/coding-agent/src/modes/interactive/components/index.ts
@@ -12,6 +12,10 @@ export {
type ChildAgentStatus,
ChildAgentSummaryComponent,
} from "./child-agent-inspector.js";
+export {
+ CompactionOutcomeMessageComponent,
+ MalformedCompactionOutcomeMessageComponent,
+} from "./compaction-outcome-message.js";
export { CompactionSummaryMessageComponent } from "./compaction-summary-message.js";
export {
ConfigurationMenuComponent,
diff --git a/packages/coding-agent/src/modes/interactive/components/slash-command-message.ts b/packages/coding-agent/src/modes/interactive/components/slash-command-message.ts
new file mode 100644
index 0000000000..41af912a70
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/components/slash-command-message.ts
@@ -0,0 +1,35 @@
+import { Box, Container, Text } from "@earendil-works/pi-tui";
+import { theme } from "../theme/theme.js";
+
+const OSC133_ZONE_START = "\x1b]133;A\x07";
+const OSC133_ZONE_END = "\x1b]133;B\x07";
+const OSC133_ZONE_FINAL = "\x1b]133;C\x07";
+
+export function styleSlashCommandText(text: string): string {
+ const space = text.search(/\s/);
+ const command = space === -1 ? text : text.slice(0, space);
+ const rest = space === -1 ? "" : text.slice(space);
+ return `${theme.fg("accent", command)}${rest}`;
+}
+
+/** Renders a durable session command with the same layout as a user message. */
+export class SlashCommandMessageComponent extends Container {
+ private readonly contentBox: Box;
+
+ constructor(text: string) {
+ super();
+ this.contentBox = new Box(2, 1, (content: string) => theme.getUserMessageBackgroundColor()(content));
+ this.contentBox.addChild(new Text(styleSlashCommandText(text), 0, 0));
+ this.addChild(this.contentBox);
+ }
+
+ setExpanded(_expanded: boolean): void {}
+
+ override render(width: number): string[] {
+ const lines = super.render(width);
+ if (lines.length === 0) return lines;
+ lines[0] = OSC133_ZONE_START + lines[0];
+ lines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1];
+ return lines;
+ }
+}
diff --git a/packages/coding-agent/src/modes/interactive/components/slash-command-result-message.ts b/packages/coding-agent/src/modes/interactive/components/slash-command-result-message.ts
new file mode 100644
index 0000000000..9b91bc4a14
--- /dev/null
+++ b/packages/coding-agent/src/modes/interactive/components/slash-command-result-message.ts
@@ -0,0 +1,15 @@
+import { Box, Container, Text } from "@earendil-works/pi-tui";
+import type { SessionSlashCommandResultMessage } from "../../../core/messages.js";
+import { theme } from "../theme/theme.js";
+
+/** Renders a durable session-command outcome with user-message spacing. */
+export class SlashCommandResultMessageComponent extends Container {
+ constructor(message: SessionSlashCommandResultMessage) {
+ super();
+ const contentBox = new Box(2, 1, (text: string) => theme.getUserMessageBackgroundColor()(text));
+ contentBox.addChild(new Text(message.content, 0, 0));
+ this.addChild(contentBox);
+ }
+
+ setExpanded(_expanded: boolean): void {}
+}
diff --git a/packages/coding-agent/src/modes/interactive/image-markers.ts b/packages/coding-agent/src/modes/interactive/image-markers.ts
index ca4c618038..48ac05790f 100644
--- a/packages/coding-agent/src/modes/interactive/image-markers.ts
+++ b/packages/coding-agent/src/modes/interactive/image-markers.ts
@@ -16,7 +16,17 @@ export function formatImageMarker(id: number): string {
/** Marker ids that appear in `text`, in order of appearance. */
export function imageMarkerIds(text: string): number[] {
- return [...text.matchAll(IMAGE_MARKER_REGEX)].map((match) => Number(match[1]));
+ return [...text.matchAll(IMAGE_MARKER_REGEX)]
+ .map((match) => Number(match[1]))
+ .filter((id) => Number.isSafeInteger(id));
+}
+
+/** Replace every image-marker spelling whose numeric id appears in `remaps`. */
+export function remapImageMarkers(text: string, remaps: ReadonlyMap<number, number>): string {
+ return text.replace(IMAGE_MARKER_REGEX, (marker, id: string) => {
+ const replacement = remaps.get(Number(id));
+ return replacement === undefined ? marker : formatImageMarker(replacement);
+ });
}
/**
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index d5c664bfc7..7b5c8672b0 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -99,10 +99,13 @@ import type { KernelSentAgentMessage } from "../../core/kernel/index.js";
import { type AppKeybinding, KeybindingsManager } from "../../core/keybindings.js";
import {
bashOutputToText,
- createCompactionSummaryMessage,
+ COMPACTION_OUTCOME_CUSTOM_TYPE,
createHeartbeatPromptMessage,
HEARTBEAT_PROMPT_CUSTOM_TYPE,
HEARTBEAT_PROMPT_PREVIEW_LABEL,
+ isCompactionOutcomeMessage,
+ isSessionSlashCommandMessage,
+ isSessionSlashCommandResultMessage,
} from "../../core/messages.js";
import { findExactModelReferenceMatch, resolveModelScopeFromModels } from "../../core/model-resolver.js";
import { parseNewSessionCommand } from "../../core/new-session-command.js";
@@ -152,6 +155,7 @@ import type {
AgentConnectionState,
AgentConnectionToolDefinition,
} from "../agent-connection/index.js";
+import { AgentConnectionPromptAdmissionError } from "../agent-connection/index.js";
import { getModelArgumentCompletions } from "../model-autocomplete.js";
import {
checkForPackageUpdates,
@@ -173,6 +177,10 @@ import {
type ChildAgentInspectorNode,
ChildAgentSummaryComponent,
} from "./components/child-agent-inspector.js";
+import {
+ CompactionOutcomeMessageComponent,
+ MalformedCompactionOutcomeMessageComponent,
+} from "./components/compaction-outcome-message.js";
import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js";
import { ConfigurationMenuComponent, type ConfigurationMenuTab } from "./components/configuration-menu.js";
import { formatContextTree } from "./components/context-tree-format.js";
@@ -200,6 +208,8 @@ import { SessionSelectorComponent } from "./components/session-selector.js";
import { SettingsSelectorComponent } from "./components/settings-selector.js";
import { SideQuestionComponent } from "./components/side-question.js";
import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
+import { SlashCommandMessageComponent } from "./components/slash-command-message.js";
+import { SlashCommandResultMessageComponent } from "./components/slash-command-result-message.js";
import { ThinkingSelectorComponent } from "./components/thinking-selector.js";
import {
selectLatestToolExpandHint,
@@ -211,7 +221,13 @@ import { UserMessageComponent } from "./components/user-message.js";
import { UserMessageSelectorComponent } from "./components/user-message-selector.js";
import { FeatureHintDeck } from "./feature-hints.js";
import { scopeHeartbeatsToSession } from "./heartbeat-scope.js";
-import { collectMarkedImages, evictImagesToBudget, formatImageMarker, imageMarkerIds } from "./image-markers.js";
+import {
+ collectMarkedImages,
+ evictImagesToBudget,
+ formatImageMarker,
+ imageMarkerIds,
+ remapImageMarkers,
+} from "./image-markers.js";
import type {
InteractiveModeLocalSessionHost,
InteractiveModeLocalToolRendererDefinition,
@@ -470,10 +486,7 @@ export class BrandSplashHeader implements Component {
}
}
-type CompactionQueuedMessage = {
- text: string;
- mode: "steer" | "followUp";
-};
+type StartupPromptBarrierOutcome = "admitted" | "retained" | "lifecycle-cancelled";
type GoalAnnouncementSnapshot = {
goalId?: string;
@@ -740,6 +753,11 @@ export function resolveInteractiveUpdateDaemonSocketPath(
/**
* Options for InteractiveMode initialization.
*/
+export interface InteractiveInitialPrompt {
+ text: string;
+ images?: ImageContent[];
+}
+
export interface InteractiveModeOptions {
/** Providers that were migrated to auth.json (shows warning) */
migratedProviders?: string[];
@@ -751,8 +769,10 @@ export interface InteractiveModeOptions {
initialMessage?: string;
/** Images to attach to the initial message */
initialImages?: ImageContent[];
- /** Additional messages to send after the initial message */
+ /** Additional text-only messages to send after the initial message. */
initialMessages?: string[];
+ /** Additional image-bearing prompts to send after the initial messages. */
+ initialPrompts?: InteractiveInitialPrompt[];
/** Force verbose startup (overrides quietStartup setting) */
verbose?: boolean;
/** Agent execution boundary. InteractiveMode never talks directly to AgentSession for core execution. */
@@ -831,6 +851,14 @@ export class InteractiveMode {
private readonly startHint = getRandomStartHint();
private isInitialized = false;
private onInputCallback?: (text: string | undefined) => void;
+ private submittedInputBehavior: "steer" | "followUp" = "steer";
+ private latestEditorPromptStash: PromptStash | undefined;
+ private pendingSubmittedPromptStash: PromptStash | undefined;
+ private inputSubmissionGeneration = 0;
+ private inputSubmissionsPending = 0;
+ private pendingPromptStashReleases: { sessionId: string; state: PromptStashState }[] = [];
+ private readonly retainedSubmissionGenerations = new WeakMap<PromptStash, number>();
+ private admitPendingStartupPrompts: (() => Promise<StartupPromptBarrierOutcome>) | undefined;
private returnToAgentsViewRequested = false;
private loadingAnimation: Loader | undefined = undefined;
private workingMessage: string | undefined = undefined;
@@ -852,6 +880,8 @@ export class InteractiveMode {
// activityTracker token count already folded into the context snapshot; only output beyond
// this counts as live in-flight (keeps auto-retries from re-adding a failed attempt).
private contextUsageTokenBaseline = 0;
+ // Refresh ordering: a stale failure must never clobber a newer success.
+ private contextUsageRefresh = { generation: 0, lastSuccessGeneration: 0 };
private readonly defaultHiddenThinkingLabel = "Thinking...";
private hiddenThinkingLabel = this.defaultHiddenThinkingLabel;
@@ -970,8 +1000,7 @@ export class InteractiveMode {
private retryCountdown: CountdownTimer | undefined = undefined;
private traceUploadAllAbortController: AbortController | undefined = undefined;
- // Messages queued while compaction is running
- private compactionQueuedMessages: CompactionQueuedMessage[] = [];
+ // Session-owned queued messages mirrored from connection events.
private connectionQueue: AgentConnectionQueueState = { steering: [], followUp: [] };
// Shutdown state
@@ -1123,15 +1152,15 @@ export class InteractiveMode {
}
private hydratePromptStash(): void {
- const stash = this.promptStash;
- if (!stash) {
- return;
- }
- for (const [markerId, image] of stash.images ?? []) {
- this.pastedImages.set(markerId, image);
- }
- for (const markerId of imageMarkerIds(stash.text)) {
- this.nextImageMarkerId = Math.max(this.nextImageMarkerId, markerId + 1);
+ for (const stash of [this.promptStash, ...(this.promptStashState?.queuedStashes ?? [])]) {
+ if (!stash) continue;
+ for (const [markerId, image] of stash.images ?? []) {
+ this.pastedImages.set(markerId, image);
+ this.nextImageMarkerId = Math.max(this.nextImageMarkerId, markerId + 1);
+ }
+ for (const markerId of imageMarkerIds(stash.text)) {
+ this.nextImageMarkerId = Math.max(this.nextImageMarkerId, markerId + 1);
+ }
}
}
@@ -1146,11 +1175,41 @@ export class InteractiveMode {
}
private releasePromptStashSession(): void {
- if (this.promptStashStore && this.promptStashSessionId) {
+ if (this.inputSubmissionsPending > 0) {
+ // Capture the pair: a rebind may repoint the fields before the deferred
+ // release fires, and repeated rebinds/teardowns each defer their own pair.
+ if (
+ this.promptStashSessionId &&
+ !this.pendingPromptStashReleases.some((pending) => pending.sessionId === this.promptStashSessionId)
+ ) {
+ this.pendingPromptStashReleases.push({
+ sessionId: this.promptStashSessionId,
+ state: this.promptStashState,
+ });
+ }
+ return;
+ }
+ const pending = this.pendingPromptStashReleases;
+ this.pendingPromptStashReleases = [];
+ if (!this.promptStashStore) return;
+ for (const release of pending) {
+ this.promptStashStore.release(release.sessionId, release.state);
+ }
+ if (this.promptStashSessionId) {
this.promptStashStore.release(this.promptStashSessionId, this.promptStashState);
}
}
+ private completeDeferredPromptStashRelease(): void {
+ const pending = this.pendingPromptStashReleases;
+ if (pending.length === 0) return;
+ this.pendingPromptStashReleases = [];
+ if (!this.promptStashStore) return;
+ for (const release of pending) {
+ this.promptStashStore.release(release.sessionId, release.state);
+ }
+ }
+
private getAutocompleteSourceTag(sourceInfo?: AgentConnectionSourceInfo): string | undefined {
if (!sourceInfo) {
return undefined;
@@ -1463,7 +1522,14 @@ export class InteractiveMode {
const tmuxKeyboardWarningPromise = ownsGlobalStartupNotices ? checkTmuxKeyboardSetup() : undefined;
// Show startup warnings
- const { migratedProviders, modelFallbackMessage, initialMessage, initialImages, initialMessages } = this.options;
+ const {
+ migratedProviders,
+ modelFallbackMessage,
+ initialMessage,
+ initialImages,
+ initialMessages,
+ initialPrompts,
+ } = this.options;
if (migratedProviders && migratedProviders.length > 0) {
this.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(", ")}`);
@@ -1478,40 +1544,87 @@ export class InteractiveMode {
this.showError(`models.json error: ${modelsJsonError}`);
}
- let initialPromptsSent = false;
- const sendInitialPrompts = async () => {
- if (initialPromptsSent) {
- return;
- }
- if (!initialMessage && !initialMessages?.length) {
- initialPromptsSent = true;
- return;
- }
- if (!this.getCurrentModel()) {
- return;
- }
- initialPromptsSent = true;
-
- if (initialMessage) {
+ const startupPrompts: InteractiveInitialPrompt[] = [
+ ...(initialMessage ? [{ text: initialMessage, images: initialImages }] : []),
+ ...(initialMessages ?? []).map((text) => ({ text })),
+ ...(initialPrompts ?? []),
+ ];
+ // One drive loop owns startup-prompt delivery: it retries on a 250ms cadence
+ // while a model is missing or admission fails transiently, shows every
+ // admission error, and skips a prompt after three failed attempts.
+ // `startupPromptsSettled` is the user-submission barrier (startup prompts
+ // stay ahead of user prompts). Its outcome distinguishes completed admission
+ // from lifecycle cancellation so a resumed submit does not mutate torn-down
+ // editor state or consume the client-owned durable stash.
+ let startupPromptsDone = false;
+ const startupAdmissionAbort = new AbortController();
+ let settleStartupPrompts = (_outcome: StartupPromptBarrierOutcome) => {};
+ const startupPromptsSettled = new Promise<StartupPromptBarrierOutcome>((resolve) => {
+ settleStartupPrompts = (outcome) => {
+ startupPromptsDone = true;
+ resolve(outcome);
+ };
+ });
+ /** Resolves false when the run lifecycle ended before the 250ms retry delay elapsed. */
+ const startupRetryDelay = () =>
+ new Promise<boolean>((resolve) => {
+ const timer = setTimeout(() => resolve(true), 250);
+ timer.unref?.();
+ void startupPromptsSettled.then(() => {
+ clearTimeout(timer);
+ resolve(false);
+ });
+ });
+ const deliverStartupPrompts = async () => {
+ let failures = 0;
+ for (let next = 0; next < startupPrompts.length; ) {
+ // The run lifecycle can settle the barrier while a prompt is being
+ // admitted; stop instead of prompting a session we already left.
+ if (startupPromptsDone) return;
+ if (!this.getCurrentModel()) {
+ if (!(await startupRetryDelay())) return;
+ continue;
+ }
+ const prompt = startupPrompts[next]!;
try {
- await this.agentConnection.prompt(initialMessage, { images: initialImages });
- } catch (error: unknown) {
+ await this.agentConnection.prompt(prompt.text, {
+ images: prompt.images,
+ streamingBehavior: next === 0 ? "steer" : "followUp",
+ queueIfBusy: true,
+ signal: startupAdmissionAbort.signal,
+ });
+ failures = 0;
+ next++;
+ } catch (error) {
+ if (startupPromptsDone || startupAdmissionAbort.signal.aborted) return;
+ // An uncertain daemon admission may already be session-owned. Retrying
+ // would duplicate it; only an acknowledged pre-ownership cancellation is safe.
+ if (error instanceof AgentConnectionPromptAdmissionError && error.status === "owned") {
+ failures = 0;
+ next++;
+ continue;
+ }
+ if (error instanceof AgentConnectionPromptAdmissionError && !error.cancelled) {
+ // This attempt may already be session-owned, so never retry it. Preserve
+ // it and every not-yet-attempted startup prompt in original order.
+ this.retainStartupPromptDrafts(startupPrompts.slice(next));
+ this.showError(error.message);
+ settleStartupPrompts("retained");
+ return;
+ }
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
- this.showError(errorMessage);
- }
- }
-
- if (initialMessages) {
- for (const message of initialMessages) {
- try {
- await this.agentConnection.prompt(message);
- } catch (error: unknown) {
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
+ if (++failures < 3) {
this.showError(errorMessage);
+ if (!(await startupRetryDelay())) return;
+ continue;
}
+ this.showError(`Skipping startup prompt after 3 failed attempts: ${errorMessage}`);
+ failures = 0;
+ next++;
}
}
};
+ this.admitPendingStartupPrompts = startupPrompts.length > 0 ? () => startupPromptsSettled : undefined;
let deferredStartupNotificationsShown = false;
const showDeferredStartupNotifications = () => {
@@ -1568,28 +1681,21 @@ export class InteractiveMode {
showDeferredStartupNotifications();
showModelFallbackWarning();
void this.maybeWarnAboutAnthropicSubscriptionAuth();
- await sendInitialPrompts();
-
- // Main interactive loop
- while (true) {
- const userInput = await this.getUserInput();
- if (userInput === undefined || this.returnToAgentsViewRequested) {
- return "agents_view";
- }
- showDeferredStartupNotifications();
- showModelFallbackWarning();
- await sendInitialPrompts();
- // Collect images from the markers in the submitted text. The registry
- // still holds them (it is not cleared on submit), so this works even after
- // the text was restored to the editor by onboarding, history, or a retry.
- const images = this.collectImagesFor(userInput);
- try {
- await this.agentConnection.prompt(userInput, { streamingBehavior: "steer", images });
- } catch (error: unknown) {
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
- this.showError(errorMessage);
- }
+ void deliverStartupPrompts().then(
+ () => settleStartupPrompts("admitted"),
+ () => settleStartupPrompts("admitted"),
+ );
+
+ // Enter/Alt+Enter submit directly through AgentConnection. Keep run alive
+ // until shutdown or a return to the agents view resolves the lifecycle wait.
+ try {
+ await this.getUserInput();
+ } finally {
+ startupAdmissionAbort.abort();
+ settleStartupPrompts("lifecycle-cancelled");
+ this.admitPendingStartupPrompts = undefined;
}
+ return "agents_view";
}
private getModelFallbackWarningAction(modelFallbackMessage: string | undefined): ModelFallbackWarningAction {
@@ -2510,13 +2616,20 @@ export class InteractiveMode {
/** Refresh the tray's context usage from the session after a turn or compaction completes. */
private async refreshConnectionContextUsage(): Promise<void> {
+ const generation = ++this.contextUsageRefresh.generation;
const connection = this.agentConnection;
const sessionId = this.connectionState?.sessionId;
const stats = await connection?.getSessionStats?.().catch(() => undefined);
if (!stats) return;
- // Drop the result if the user switched sessions or the connection was rebound while the
- // async call was in flight — otherwise stale stats would overwrite the new session.
- if (this.agentConnection !== connection || this.connectionState?.sessionId !== sessionId) return;
+ // Drop results superseded by a newer successful refresh as well as results for a replaced session.
+ if (
+ generation < this.contextUsageRefresh.lastSuccessGeneration ||
+ this.agentConnection !== connection ||
+ this.connectionState?.sessionId !== sessionId
+ ) {
+ return;
+ }
+ this.contextUsageRefresh.lastSuccessGeneration = generation;
// Anything counted so far is now reflected in the snapshot; only later output is in-flight.
this.contextUsageTokenBaseline = this.activityTracker.getStatus().tokens;
this.patchConnectionState({ contextUsage: stats.contextUsage });
@@ -2700,11 +2813,11 @@ export class InteractiveMode {
this.shortcutGuideContainer.clear();
this.pendingMessagesContainer.clear();
this.queuedMessagesContainer.clear();
- this.compactionQueuedMessages = [];
this.connectionQueue = { steering: [], followUp: [] };
this.featureHintSuppressedByQueue = false;
if (options?.clearPromptStash) {
this.promptStash = undefined;
+ if (this.promptStashState) this.promptStashState.queuedStashes = undefined;
}
// Clear every editor's prompt history, draft text, and queues, then prune
// any pasted images no longer referenced by the remaining stashed draft.
@@ -2753,7 +2866,6 @@ export class InteractiveMode {
}
private async renderResyncedSession(snapshot: AgentConnectionSnapshot): Promise<void> {
- const compactionFinished = this.isAgentCompacting() && !snapshot.state.isCompacting;
const bashFinished = this.isBashRunning() && !snapshot.state.isBashRunning;
this.applyConnectionStateSnapshot(snapshot.state);
this.streamingComponent = undefined;
@@ -2765,9 +2877,6 @@ export class InteractiveMode {
});
await this.restoreStreamingMessageFromSnapshot(snapshot.streamingMessage);
await this.refreshConnectionQueue();
- if (compactionFinished) {
- await this.flushCompactionQueue({ willRetry: false });
- }
if (bashFinished) {
if (this.activeBashComponent) {
this.activeBashComponent.setComplete(undefined, false);
@@ -3222,7 +3331,42 @@ export class InteractiveMode {
// Reconcile the loader with current state for transitions that fire no live
// agent_start edge (returning from agents view, resuming mid-stream).
+ private startCompactionLoader(
+ reason: "manual" | "requested" | "overflow" | "threshold",
+ customInstructions?: string,
+ ): void {
+ if (this.settingsManager.getShowTerminalProgress()) {
+ this.ui.terminal.setProgress(true);
+ }
+ // Keep editor active; submissions are queued during compaction.
+ // Fully stop the working loader (not just detach) so it isn't orphaned.
+ this.stopWorkingLoader();
+ this.statusContainer.clear();
+ const cancelHint = `(${keyText("app.clear")} to cancel)`;
+ const focus = customInstructions ? ` (focus: ${truncateToWidth(customInstructions, 60, "…")})` : "";
+ const label =
+ reason === "manual"
+ ? `Compacting context${focus}... ${cancelHint}`
+ : reason === "requested"
+ ? `Agent requested compaction, compacting context${focus}... ${cancelHint}`
+ : `${reason === "overflow" ? "Context overflow detected, " : ""}Auto-compacting... ${cancelHint}`;
+ this.autoCompactionLoader = new Loader(
+ this.ui,
+ (spinner) => theme.fg("muted", spinner),
+ (text) => theme.fg("muted", text),
+ label,
+ );
+ this.statusContainer.addChild(this.autoCompactionLoader);
+ this.ui.requestRender();
+ }
+
private syncWorkingLoader(): void {
+ // A compaction that started before this client attached (or while another
+ // view was open) has no start-event edge; restore its loader from state.
+ if (!this.autoCompactionLoader && this.isAgentCompacting()) {
+ this.startCompactionLoader("manual");
+ return;
+ }
// Compaction/retry own the status container while active; don't fight them.
if (this.autoCompactionLoader || this.retryLoader) {
return;
@@ -3757,8 +3901,10 @@ export class InteractiveMode {
}
this.childAgentSummary.setHidden(false);
- // Save text from current editor before switching
- const currentText = this.editor.getText();
+ // Snapshot the current editor before replacing it. Paste markers are only
+ // meaningful while their originating editor still owns the paste snapshot.
+ const currentEditor = this.editor;
+ const currentPromptStash = this.snapshotPromptStashFrom(currentEditor, currentEditor.getText());
this.editorContainer.clear();
@@ -3766,13 +3912,25 @@ export class InteractiveMode {
// Create the custom editor with tui, theme, and keybindings
const newEditor = factory(this.ui, getEditorTheme(), this.keybindings);
- // Wire up callbacks from the default editor
+ // Restore before wiring the shared onChange callback: setText may emit a
+ // change, and an empty custom editor cannot reconstruct the old snapshot.
+ const canRestorePasteSnapshot =
+ currentPromptStash.pasteSnapshot === undefined || newEditor.restorePasteSnapshot !== undefined;
+ newEditor.setText(
+ canRestorePasteSnapshot
+ ? currentPromptStash.text
+ : (currentPromptStash.expandedText ?? currentPromptStash.text),
+ );
+ if (currentPromptStash.pasteSnapshot && newEditor.restorePasteSnapshot) {
+ newEditor.restorePasteSnapshot(currentPromptStash.pasteSnapshot);
+ }
+
+ // Wire up callbacks from the default editor. onChange snapshots the
+ // active editor while it still owns paste markers and attachments, so
+ // submit remains exact even when an editor clears before calling onSubmit.
newEditor.onSubmit = this.defaultEditor.onSubmit;
newEditor.onChange = this.defaultEditor.onChange;
- // Copy text from previous editor
- newEditor.setText(currentText);
-
// Copy appearance settings if supported
if (newEditor.borderColor !== undefined) {
newEditor.borderColor = this.defaultEditor.borderColor;
@@ -3816,10 +3974,21 @@ export class InteractiveMode {
this.editor = newEditor;
} else {
- // Restore default editor with text from custom editor
- this.defaultEditor.setText(currentText);
+ // Restore the default editor with the same rich snapshot (or expanded
+ // fallback text if this editor implementation cannot restore it).
+ const canRestorePasteSnapshot =
+ currentPromptStash.pasteSnapshot === undefined || this.defaultEditor.restorePasteSnapshot !== undefined;
+ this.defaultEditor.setText(
+ canRestorePasteSnapshot
+ ? currentPromptStash.text
+ : (currentPromptStash.expandedText ?? currentPromptStash.text),
+ );
+ if (currentPromptStash.pasteSnapshot && this.defaultEditor.restorePasteSnapshot) {
+ this.defaultEditor.restorePasteSnapshot(currentPromptStash.pasteSnapshot);
+ }
this.editor = this.defaultEditor;
}
+ this.latestEditorPromptStash = currentPromptStash;
this.editorContainer.addChild(this.editor as Component);
this.ui.setFocus(this.editor as Component);
@@ -3994,6 +4163,9 @@ export class InteractiveMode {
this.defaultEditor.onMoveBelowPrompt = () => this.focusChildAgentSummary();
this.defaultEditor.onChange = (text: string) => {
+ if (text.length > 0) {
+ this.latestEditorPromptStash = this.snapshotPromptStashFrom(this.editor, text);
+ }
if (this.escapeRepeatAction && !this.isRestoringQueuedEditorText) {
this.clearEscapeRepeat();
}
@@ -4008,6 +4180,21 @@ export class InteractiveMode {
};
}
+ private snapshotPromptStashFrom(editor: EditorComponent, text: string): PromptStash {
+ const pasteSnapshot = editor.getPasteSnapshot?.();
+ const images = this.getPromptStashImages(text);
+ return {
+ text,
+ expandedText: pasteSnapshot ? (editor.getExpandedText?.() ?? text) : undefined,
+ pasteSnapshot,
+ ...(images.length > 0 ? { images } : {}),
+ };
+ }
+
+ private snapshotPromptStash(text: string): PromptStash {
+ return this.snapshotPromptStashFrom(this.editor, text);
+ }
+
private handlePromptStash(): void {
const text = this.editor.getText();
if (!text.trim()) {
@@ -4020,14 +4207,7 @@ export class InteractiveMode {
this.showStatus("Prompt stash already has a draft");
return;
}
- const pasteSnapshot = this.editor.getPasteSnapshot?.();
- const images = this.getPromptStashImages(text);
- this.promptStash = {
- text,
- expandedText: pasteSnapshot ? (this.editor.getExpandedText?.() ?? text) : undefined,
- pasteSnapshot,
- ...(images.length > 0 ? { images } : {}),
- };
+ this.promptStash = this.snapshotPromptStash(text);
this.editor.setText("");
this.showStatus("Stashed prompt");
}
@@ -4039,17 +4219,95 @@ export class InteractiveMode {
if (this.promptStash !== stash) {
return false;
}
- this.promptStash = undefined;
+ this.promptStash = this.promptStashState?.queuedStashes?.shift();
+ if (this.promptStashState?.queuedStashes?.length === 0) this.promptStashState.queuedStashes = undefined;
const canRestorePasteSnapshot =
stash.pasteSnapshot === undefined || this.editor.restorePasteSnapshot !== undefined;
this.editor.setText(canRestorePasteSnapshot ? stash.text : (stash.expandedText ?? stash.text));
if (stash.pasteSnapshot && this.editor.restorePasteSnapshot) {
this.editor.restorePasteSnapshot(stash.pasteSnapshot);
}
+ this.latestEditorPromptStash = this.snapshotPromptStash(this.editor.getText());
this.showStatus("Restored stashed prompt");
return true;
}
+ private retainSubmittedDraft(
+ stash: PromptStash,
+ submissionGeneration: number,
+ state: PromptStashState = this.promptStashState,
+ ): void {
+ this.retainedSubmissionGenerations.set(stash, submissionGeneration);
+ const ordered = [state.stash, ...(state.queuedStashes ?? [])].filter(
+ (candidate): candidate is PromptStash => candidate !== undefined,
+ );
+ const insertAt = ordered.findIndex((candidate) => {
+ const generation = this.retainedSubmissionGenerations.get(candidate);
+ return generation !== undefined && generation > submissionGeneration;
+ });
+ ordered.splice(insertAt === -1 ? ordered.length : insertAt, 0, stash);
+ state.stash = ordered.shift();
+ state.queuedStashes = ordered.length > 0 ? ordered : undefined;
+ }
+
+ private retainStartupPromptDrafts(prompts: readonly InteractiveInitialPrompt[]): void {
+ // Reserve every marker visible anywhere in the retained batch before assigning
+ // any image. This prevents an early prompt's attachment from making a literal
+ // marker in a later prompt resolve to the wrong image.
+ const reserved = new Set(this.pastedImages.keys());
+ for (const stash of [this.promptStash, ...(this.promptStashState.queuedStashes ?? [])]) {
+ if (stash) for (const markerId of imageMarkerIds(stash.text)) reserved.add(markerId);
+ }
+ for (const prompt of prompts) {
+ for (const markerId of imageMarkerIds(prompt.text)) reserved.add(markerId);
+ }
+ for (const markerId of reserved) {
+ this.nextImageMarkerId = Math.max(this.nextImageMarkerId, markerId + 1);
+ }
+ const allocateMarker = () => {
+ while (reserved.has(this.nextImageMarkerId)) this.nextImageMarkerId++;
+ const markerId = this.nextImageMarkerId++;
+ reserved.add(markerId);
+ return markerId;
+ };
+
+ const retained: PromptStash[] = [];
+ for (const prompt of prompts) {
+ let text = prompt.text;
+ // A startup prompt owns only the images passed with it. Remap literal
+ // markers that already name registry data so restoring this draft cannot
+ // accidentally attach an old or another prompt's image.
+ const literalRemaps = new Map<number, number>();
+ for (const markerId of imageMarkerIds(text)) {
+ if (this.pastedImages.has(markerId) && !literalRemaps.has(markerId)) {
+ literalRemaps.set(markerId, allocateMarker());
+ }
+ }
+ text = remapImageMarkers(text, literalRemaps);
+
+ const images: Array<readonly [number, ImageContent]> = [];
+ for (const image of prompt.images ?? []) {
+ const markerId = allocateMarker();
+ images.push([markerId, image]);
+ text += `${text.length > 0 && !/\s$/.test(text) ? " " : ""}${formatImageMarker(markerId)}`;
+ }
+ retained.push({
+ text,
+ ...(images.length > 0 ? { images } : {}),
+ });
+ for (const [markerId, image] of images) this.pastedImages.set(markerId, image);
+ }
+
+ // Startup drafts form the head of the durable queue. Preserve any older
+ // client draft after them, and let submissions released by the barrier append.
+ const existing = [this.promptStashState.stash, ...(this.promptStashState.queuedStashes ?? [])].filter(
+ (stash): stash is PromptStash => stash !== undefined,
+ );
+ const ordered = [...retained, ...existing];
+ this.promptStashState.stash = ordered.shift();
+ this.promptStashState.queuedStashes = ordered.length > 0 ? ordered : undefined;
+ }
+
private getPromptStashImages(text: string): readonly (readonly [number, ImageContent])[] {
const images: Array<readonly [number, ImageContent]> = [];
for (const markerId of imageMarkerIds(text)) {
@@ -4124,15 +4382,12 @@ export class InteractiveMode {
}
};
add(this.editor.getText());
- if (this.promptStash !== undefined) {
- add(this.promptStash.text);
+ for (const stash of [this.promptStash, ...(this.promptStashState?.queuedStashes ?? [])]) {
+ if (stash) add(stash.text);
}
for (const entry of this.editor.getHistory?.() ?? []) {
add(entry);
}
- for (const msg of this.compactionQueuedMessages) {
- add(msg.text);
- }
for (const msg of [...this.connectionQueue.steering, ...this.connectionQueue.followUp]) {
add(msg);
}
@@ -4313,16 +4568,28 @@ export class InteractiveMode {
this.editor.setText(result.editorText);
}
this.showStatus("Navigated to selected point");
- void this.flushCompactionQueue({ willRetry: false });
}
private setupEditorSubmitHandler(): void {
this.defaultEditor.onSubmit = async (text: string) => {
+ const streamingBehavior = this.submittedInputBehavior;
+ this.submittedInputBehavior = "steer";
text = text.trim();
if (!text) return;
+ const submissionGeneration = ++this.inputSubmissionGeneration;
+ this.inputSubmissionsPending++;
this.clearShortcutGuide();
+ // A barrier wait can resume after /new repointed the live session fields.
+ const submissionStashState = this.promptStashState;
+ const submissionSessionId = this.promptStashSessionId;
const promptStashToRestore = this.promptStash;
+ const liveEditorText = this.editor.getText();
+ const submittedDraft =
+ this.pendingSubmittedPromptStash ??
+ (liveEditorText.trim() ? this.snapshotPromptStash(liveEditorText) : this.latestEditorPromptStash);
+ this.pendingSubmittedPromptStash = undefined;
let restorePromptStashAfterSubmit = true;
+ let submissionOutcome: StartupPromptBarrierOutcome = "admitted";
try {
const slashCommand = parseSlashCommand(text);
@@ -4443,12 +4710,6 @@ export class InteractiveMode {
this.editor.setText("");
return;
}
- if (commandName === "goal" && (!commandArgs || commandArgs === "status")) {
- this.echoLocalCommand(text);
- this.handleGoalStatusCommand();
- this.editor.setText("");
- return;
- }
if (commandName === "heartbeat") {
await this.handleHeartbeatCommand(canonicalCommandText);
this.editor.setText("");
@@ -4525,18 +4786,6 @@ export class InteractiveMode {
await this.handleClearCommand(options);
return;
}
- if (commandName === "compact") {
- const customInstructions = commandArgs || undefined;
- this.editor.setText("");
- await this.handleCompactCommand(customInstructions);
- return;
- }
- if (commandName === "refine") {
- const refineArgs = commandArgs || undefined;
- this.editor.setText("");
- await this.handleRefineCommand(refineArgs);
- return;
- }
if (commandName === "reload" && !commandArgs) {
this.editor.setText("");
await this.handleReloadCommand();
@@ -4694,43 +4943,84 @@ export class InteractiveMode {
}
this.clearSideQuestion({ abort: true });
-
- // Queue input during compaction (extension commands execute immediately)
- if (this.isAgentCompacting()) {
- if (this.isExtensionCommand(text)) {
- this.editor.addToHistory?.(text);
- this.editor.setText("");
- await this.agentConnection.prompt(text, { images: this.collectImagesFor(text) });
- } else {
- this.queueCompactionMessage(text, "steer");
- }
+ this.flushPendingBashComponents();
+ const images = this.collectImagesFor(text);
+ this.editor.addToHistory?.(text);
+ this.editor.setText("");
+ const promptStashAfterClear = this.promptStash;
+ submissionOutcome = (await this.admitPendingStartupPrompts?.()) ?? "admitted";
+ // Retention is not admission. Startup drafts were inserted synchronously
+ // before the barrier settled, so append this blocked submission behind them
+ // and never let it prompt or overtake them.
+ if (submissionOutcome === "retained") {
+ this.retainSubmittedDraft(submittedDraft ?? { text }, submissionGeneration);
return;
}
-
- // If streaming, use prompt() with steer behavior
- // This handles extension commands (execute immediately), prompt template expansion, and queueing
- if (this.isAgentStreaming()) {
- const images = this.collectImagesFor(text);
- this.editor.addToHistory?.(text);
- this.editor.setText("");
- await this.agentConnection.prompt(text, { streamingBehavior: "steer", images });
- this.updatePendingMessagesDisplay();
- this.ui.requestRender();
+ // The barrier also settles when the run lifecycle ends; a submit resumed
+ // by teardown must neither prompt nor mutate the editor/durable stash.
+ if (
+ submissionOutcome === "lifecycle-cancelled" ||
+ this.isShuttingDown ||
+ this.returnToAgentsViewRequested ||
+ this.promptStashSessionId !== submissionSessionId
+ ) {
+ // The editor is already torn down, but its shared session stash outlives
+ // this view. Preserve the submitted draft in the stash of the session it
+ // was typed for, without overwriting an explicit older stash.
+ this.retainSubmittedDraft(submittedDraft ?? { text }, submissionGeneration, submissionStashState);
+ submissionOutcome = "lifecycle-cancelled";
return;
}
-
- // Normal message submission
- // First, move any pending bash components to chat
- this.flushPendingBashComponents();
-
- if (this.onInputCallback) {
- this.onInputCallback(text);
+ try {
+ await this.agentConnection.prompt(text, {
+ streamingBehavior,
+ queueIfBusy: true,
+ images,
+ });
+ } catch (error) {
+ // Generation guards editor ownership, not draft durability: a stale
+ // rejection must be retained rather than overwrite newer input or vanish.
+ const rejectedDraft = submittedDraft ?? { text };
+ const canRestore =
+ !this.isShuttingDown &&
+ !this.returnToAgentsViewRequested &&
+ submissionGeneration === this.inputSubmissionGeneration &&
+ this.editor.getText().length === 0;
+ if (canRestore) {
+ const canRestorePasteSnapshot =
+ rejectedDraft.pasteSnapshot === undefined || this.editor.restorePasteSnapshot !== undefined;
+ this.editor.setText(
+ canRestorePasteSnapshot ? rejectedDraft.text : (rejectedDraft.expandedText ?? rejectedDraft.text),
+ );
+ if (rejectedDraft.pasteSnapshot && this.editor.restorePasteSnapshot) {
+ this.editor.restorePasteSnapshot(rejectedDraft.pasteSnapshot);
+ }
+ this.latestEditorPromptStash = this.snapshotPromptStash(this.editor.getText());
+ if (this.promptStash === promptStashAfterClear) this.promptStash = promptStashToRestore;
+ } else {
+ this.retainSubmittedDraft(rejectedDraft, submissionGeneration, submissionStashState);
+ }
+ this.showError(error instanceof Error ? error.message : String(error));
+ return;
}
- this.editor.addToHistory?.(text);
+ this.updatePendingMessagesDisplay();
+ this.ui.requestRender();
} finally {
- if (restorePromptStashAfterSubmit && promptStashToRestore !== undefined) {
+ if (this.isShuttingDown || this.returnToAgentsViewRequested) {
+ submissionOutcome = "lifecycle-cancelled";
+ }
+ if (
+ submissionOutcome === "admitted" &&
+ restorePromptStashAfterSubmit &&
+ promptStashToRestore !== undefined &&
+ submissionGeneration === this.inputSubmissionGeneration
+ ) {
this.restorePromptStashIfEditorEmpty(promptStashToRestore);
}
+ this.inputSubmissionsPending--;
+ if (this.inputSubmissionsPending === 0 && this.pendingPromptStashReleases.length > 0) {
+ this.completeDeferredPromptStashRelease();
+ }
}
};
}
@@ -5253,7 +5543,9 @@ export class InteractiveMode {
this.renderRecap();
this.applyOptimisticContextUsage();
- await this.refreshConnectionContextUsage();
+ // Auto-compaction can start server-side while this event is being handled.
+ // Do not hold its start event behind a stats RPC; stale refreshes are discarded.
+ void this.refreshConnectionContextUsage();
await this.checkShutdownRequested();
@@ -5261,31 +5553,7 @@ export class InteractiveMode {
break;
case "compaction_start": {
- if (this.settingsManager.getShowTerminalProgress()) {
- this.ui.terminal.setProgress(true);
- }
- // Keep editor active; submissions are queued during compaction.
- // Fully stop the working loader (not just detach) so it isn't orphaned.
- this.stopWorkingLoader();
- this.statusContainer.clear();
- const cancelHint = `(${keyText("app.clear")} to cancel)`;
- const focus = event.customInstructions
- ? ` (focus: ${truncateToWidth(event.customInstructions, 60, "…")})`
- : "";
- const label =
- event.reason === "manual"
- ? `Compacting context${focus}... ${cancelHint}`
- : event.reason === "requested"
- ? `Agent requested compaction, compacting context${focus}... ${cancelHint}`
- : `${event.reason === "overflow" ? "Context overflow detected, " : ""}Auto-compacting... ${cancelHint}`;
- this.autoCompactionLoader = new Loader(
- this.ui,
- (spinner) => theme.fg("muted", spinner),
- (text) => theme.fg("muted", text),
- label,
- );
- this.statusContainer.addChild(this.autoCompactionLoader);
- this.ui.requestRender();
+ this.startCompactionLoader(event.reason, event.customInstructions);
break;
}
@@ -5301,35 +5569,20 @@ export class InteractiveMode {
// Restore the working loader if streaming/subagents still warrant it.
this.syncWorkingLoader();
if (event.aborted) {
- if (event.reason === "manual") {
- this.showError("Compaction cancelled");
- } else {
- this.showStatus("Auto-compaction cancelled");
- }
+ if (event.reason === "manual") this.showError("Compaction cancelled");
} else if (event.result) {
- this.chatContainer.clear();
- await this.rebuildChatFromMessages();
- this.addMessageToChat(
- createCompactionSummaryMessage(
- event.result.summary,
- event.result.tokensBefore,
- new Date().toISOString(),
- event.customInstructions,
- ),
- );
+ try {
+ await this.rebuildChatFromMessages();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.showError(`Compaction succeeded, but the transcript could not be refreshed: ${message}`);
+ }
await this.refreshConnectionContextUsage();
this.footer.invalidate();
- } else if (event.errorMessage) {
- if (event.errorSeverity === "warning") {
- this.showWarning(event.errorMessage);
- } else if (event.reason === "manual") {
- this.showError(event.errorMessage);
- } else {
- this.chatContainer.addChild(new Spacer(1));
- this.chatContainer.addChild(new Text(theme.fg("error", event.errorMessage), 1, 0));
- }
+ } else if (event.errorMessage && event.reason === "manual") {
+ if (event.errorSeverity === "warning") this.showWarning(event.errorMessage);
+ else this.showError(event.errorMessage);
}
- void this.flushCompactionQueue({ willRetry: event.willRetry });
this.ui.requestRender();
break;
}
@@ -6191,18 +6444,31 @@ export class InteractiveMode {
}
case "custom": {
if (message.display) {
- const component = isAgentSessionMessage(message)
- ? new AgentMessageComponent(message, this.getMarkdownThemeWithSettings())
- : isInjectedPromptMessage(message)
- ? new InjectedPromptMessageComponent(message, this.getMarkdownThemeWithSettings())
- : new CustomMessageComponent(
- message,
- this.bindLocalSessionExtensions
- ? this.getLocalSessionHost().getExtensionRunner().getMessageRenderer(message.customType)
- : undefined,
- this.getMarkdownThemeWithSettings(),
- );
+ const component = isSessionSlashCommandMessage(message)
+ ? new SlashCommandMessageComponent(message.content)
+ : isSessionSlashCommandResultMessage(message)
+ ? new SlashCommandResultMessageComponent(message)
+ : isCompactionOutcomeMessage(message)
+ ? new CompactionOutcomeMessageComponent(message)
+ : message.customType === COMPACTION_OUTCOME_CUSTOM_TYPE
+ ? new MalformedCompactionOutcomeMessageComponent()
+ : isAgentSessionMessage(message)
+ ? new AgentMessageComponent(message, this.getMarkdownThemeWithSettings())
+ : isInjectedPromptMessage(message)
+ ? new InjectedPromptMessageComponent(message, this.getMarkdownThemeWithSettings())
+ : new CustomMessageComponent(
+ message,
+ this.bindLocalSessionExtensions
+ ? this.getLocalSessionHost()
+ .getExtensionRunner()
+ .getMessageRenderer(message.customType)
+ : undefined,
+ this.getMarkdownThemeWithSettings(),
+ );
component.setExpanded(this.toolOutputExpanded);
+ if (isSessionSlashCommandMessage(message) && this.chatContainer.children.length > 0) {
+ this.chatContainer.addChild(new Spacer(1));
+ }
this.chatContainer.addChild(component);
}
break;
@@ -6300,6 +6566,26 @@ export class InteractiveMode {
* @param options.clearChat Clear the current transcript immediately before rendering
* @param options.limitTranscript Limit transcript replay to the recent tail
*/
+ private orderMessagesForTranscript(messages: AgentMessage[]): AgentMessage[] {
+ const summaryIndex = messages.findIndex((message) => message.role === "compactionSummary");
+ if (summaryIndex === -1) return messages;
+ const summary = messages[summaryIndex];
+ if (summary.role !== "compactionSummary") return messages;
+ const remaining = messages.filter((_, index) => index !== summaryIndex);
+ if (Number.isSafeInteger(summary.retainedMessageCount) && summary.retainedMessageCount! >= 0) {
+ const boundary = Math.min(summary.retainedMessageCount!, remaining.length);
+ return [...remaining.slice(0, boundary), summary, ...remaining.slice(boundary)];
+ }
+
+ // Compatibility for summaries created before retainedMessageCount was added.
+ const retained: AgentMessage[] = [];
+ const later: AgentMessage[] = [];
+ for (const message of remaining) {
+ (message.timestamp < summary.timestamp ? retained : later).push(message);
+ }
+ return [...retained, summary, ...later];
+ }
+
private async renderSessionContext(
sessionContext: AgentConnectionSessionContext,
options: {
@@ -6310,9 +6596,8 @@ export class InteractiveMode {
} = {},
): Promise<void> {
this.resetPendingToolState();
- const messagesToRender = options.limitTranscript
- ? initialRenderMessages(sessionContext.messages)
- : sessionContext.messages;
+ const transcriptMessages = this.orderMessagesForTranscript(sessionContext.messages);
+ const messagesToRender = options.limitTranscript ? initialRenderMessages(transcriptMessages) : transcriptMessages;
this.ipythonToolComponents.clear();
this.lateIpythonSentAgentMessages.clear();
const renderedPendingTools = new Map<string, ToolExecutionComponent>();
@@ -6790,55 +7075,28 @@ export class InteractiveMode {
}
private async handleFollowUp(): Promise<void> {
- const text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();
- if (!text) return;
- const promptStashToRestore = this.promptStash;
- let clearedSubmittedText: string | undefined;
+ const editorText = this.editor.getText();
+ const text = (this.editor.getExpandedText?.() ?? editorText).trim();
+ if (!text || !this.editor.onSubmit) return;
+ // Unlike Enter, Alt+Enter does not go through Editor.submitValue(), so
+ // capture and clear synchronously before an async/local handler can yield.
+ this.pendingSubmittedPromptStash = this.snapshotPromptStash(editorText);
+ this.editor.setText("");
+ this.submittedInputBehavior = "followUp";
+ // onSubmit consumes the behavior flag and bumps the generation synchronously;
+ // capture the generation so an older failed submit never clobbers newer
+ // typing or submissions.
+ const submission = this.editor.onSubmit(text);
+ this.submittedInputBehavior = "steer";
+ const submissionGeneration = this.inputSubmissionGeneration;
try {
- // Queue input during compaction (extension commands execute immediately)
- if (this.isAgentCompacting()) {
- if (this.isExtensionCommand(text)) {
- this.editor.addToHistory?.(text);
- clearedSubmittedText = text;
- this.editor.setText("");
- await this.agentConnection.prompt(text, { images: this.collectImagesFor(text) });
- clearedSubmittedText = undefined;
- } else {
- this.queueCompactionMessage(text, "followUp");
- }
- return;
- }
-
- // Alt+Enter queues a follow-up message (waits until agent finishes)
- // This handles extension commands (execute immediately), prompt template expansion, and queueing
- if (this.isAgentStreaming()) {
- const images = this.collectImagesFor(text);
- this.editor.addToHistory?.(text);
- clearedSubmittedText = text;
- this.editor.setText("");
- await this.agentConnection.prompt(text, { streamingBehavior: "followUp", images });
- clearedSubmittedText = undefined;
- this.updatePendingMessagesDisplay();
- this.ui.requestRender();
- }
- // If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)
- else if (this.editor.onSubmit) {
- clearedSubmittedText = text;
- this.editor.setText("");
- await this.editor.onSubmit(text);
- clearedSubmittedText = undefined;
- }
+ await submission;
} catch (error) {
- if (clearedSubmittedText !== undefined) {
- this.editor.setText(clearedSubmittedText);
- this.promptStash = promptStashToRestore;
+ if (submissionGeneration === this.inputSubmissionGeneration && this.editor.getText().length === 0) {
+ this.editor.setText(text);
}
throw error;
- } finally {
- if (promptStashToRestore !== undefined && clearedSubmittedText === undefined) {
- this.restorePromptStashIfEditorEmpty(promptStashToRestore);
- }
}
}
@@ -6936,7 +7194,6 @@ export class InteractiveMode {
void (async () => {
// Rebuild chat from session messages
- this.chatContainer.clear();
await this.rebuildChatFromMessages();
// If streaming, re-add the streaming component with updated visibility and re-render
@@ -7046,27 +7303,15 @@ export class InteractiveMode {
this.ui.requestRender();
}
- /**
- * Get all queued messages (read-only).
- * Combines session queue and compaction queue.
- */
+ /** Get all queued messages from the session-owned connection queue. */
private getAllQueuedMessages(): { steering: string[]; followUp: string[] } {
return {
- steering: [
- ...this.connectionQueue.steering,
- ...this.compactionQueuedMessages.filter((msg) => msg.mode === "steer").map((msg) => msg.text),
- ],
- followUp: [
- ...this.connectionQueue.followUp,
- ...this.compactionQueuedMessages.filter((msg) => msg.mode === "followUp").map((msg) => msg.text),
- ],
+ steering: [...this.connectionQueue.steering],
+ followUp: [...this.connectionQueue.followUp],
};
}
- /**
- * Clear all queued messages and return their contents.
- * Clears both session queue and compaction queue.
- */
+ /** Clear all session-owned queued messages and return their contents. */
private async clearAllQueues(
options: { abort?: boolean } = {},
): Promise<{ steering: string[]; followUp: string[] }> {
@@ -7074,17 +7319,7 @@ export class InteractiveMode {
? await this.agentConnection.abortAndClearQueue()
: await this.agentConnection.clearQueue();
this.connectionQueue = { steering: [], followUp: [] };
- const compactionSteering = this.compactionQueuedMessages
- .filter((msg) => msg.mode === "steer")
- .map((msg) => msg.text);
- const compactionFollowUp = this.compactionQueuedMessages
- .filter((msg) => msg.mode === "followUp")
- .map((msg) => msg.text);
- this.compactionQueuedMessages = [];
- return {
- steering: [...steering, ...compactionSteering],
- followUp: [...followUp, ...compactionFollowUp],
- };
+ return { steering, followUp };
}
private updatePendingMessagesDisplay(): void {
@@ -7154,102 +7389,6 @@ export class InteractiveMode {
return allQueued.length;
}
- private queueCompactionMessage(text: string, mode: "steer" | "followUp"): void {
- this.compactionQueuedMessages.push({ text, mode });
- this.editor.addToHistory?.(text);
- this.editor.setText("");
- this.updatePendingMessagesDisplay();
- this.showStatus("Queued message for after compaction");
- }
-
- private isExtensionCommand(text: string): boolean {
- if (!text.startsWith("/")) return false;
-
- const spaceIndex = text.indexOf(" ");
- const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
- return this.connectionCommands.some((command) => command.source === "extension" && command.name === commandName);
- }
-
- private async flushCompactionQueue(options?: { willRetry?: boolean }): Promise<void> {
- if (this.compactionQueuedMessages.length === 0) {
- return;
- }
-
- const queuedMessages = [...this.compactionQueuedMessages];
- this.compactionQueuedMessages = [];
- this.updatePendingMessagesDisplay();
-
- const restoreQueue = async (error: unknown) => {
- await this.agentConnection.clearQueue().catch(() => undefined);
- this.connectionQueue = { steering: [], followUp: [] };
- this.compactionQueuedMessages = queuedMessages;
- this.updatePendingMessagesDisplay();
- this.showError(
- `Failed to send queued message${queuedMessages.length > 1 ? "s" : ""}: ${
- error instanceof Error ? error.message : String(error)
- }`,
- );
- };
-
- try {
- if (options?.willRetry) {
- // When retry is pending, queue messages for the retry turn
- for (const message of queuedMessages) {
- if (this.isExtensionCommand(message.text)) {
- await this.agentConnection.prompt(message.text, { images: this.collectImagesFor(message.text) });
- } else if (message.mode === "followUp") {
- await this.agentConnection.followUp(message.text, this.collectImagesFor(message.text));
- } else {
- await this.agentConnection.steer(message.text, this.collectImagesFor(message.text));
- }
- }
- this.updatePendingMessagesDisplay();
- return;
- }
-
- // Find first non-extension-command message to use as prompt
- const firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));
- if (firstPromptIndex === -1) {
- // All extension commands - execute them all
- for (const message of queuedMessages) {
- await this.agentConnection.prompt(message.text, { images: this.collectImagesFor(message.text) });
- }
- return;
- }
-
- // Execute any extension commands before the first prompt
- const preCommands = queuedMessages.slice(0, firstPromptIndex);
- const firstPrompt = queuedMessages[firstPromptIndex];
- const rest = queuedMessages.slice(firstPromptIndex + 1);
-
- for (const message of preCommands) {
- await this.agentConnection.prompt(message.text, { images: this.collectImagesFor(message.text) });
- }
-
- // Send first prompt (starts streaming)
- const promptPromise = this.agentConnection
- .prompt(firstPrompt.text, { images: this.collectImagesFor(firstPrompt.text) })
- .catch((error) => {
- void restoreQueue(error);
- });
-
- // Queue remaining messages
- for (const message of rest) {
- if (this.isExtensionCommand(message.text)) {
- await this.agentConnection.prompt(message.text, { images: this.collectImagesFor(message.text) });
- } else if (message.mode === "followUp") {
- await this.agentConnection.followUp(message.text, this.collectImagesFor(message.text));
- } else {
- await this.agentConnection.steer(message.text, this.collectImagesFor(message.text));
- }
- }
- this.updatePendingMessagesDisplay();
- void promptPromise;
- } catch (error) {
- await restoreQueue(error);
- }
- }
-
// =========================================================================
// Selectors
// =========================================================================
@@ -9264,41 +9403,6 @@ export class InteractiveMode {
this.ui.requestRender();
}
- private handleGoalStatusCommand(): void {
- const goal = this.getGoalState();
- if (goal.status === "idle" || !goal.objective) {
- this.showStatus("No active goal");
- return;
- }
-
- const lines = [
- theme.bold("Goal"),
- "",
- `${theme.fg("dim", "Status:")} ${goal.status}`,
- `${theme.fg("dim", "Objective:")} ${goal.objective}`,
- `${theme.fg("dim", "Time:")} ${this.formatGoalElapsed(goal.timeUsedSeconds)}`,
- `${theme.fg("dim", "Continuations:")} ${goal.continuationsUsed}`,
- `${theme.fg("dim", "Tokens:")} ${goal.tokensUsed.toLocaleString()}${
- goal.tokenBudget === undefined ? "" : ` / ${goal.tokenBudget.toLocaleString()}`
- }`,
- ];
- if (goal.tokenBudget !== undefined) {
- lines.push(
- `${theme.fg("dim", "Remaining:")} ${Math.max(0, goal.tokenBudget - goal.tokensUsed).toLocaleString()}`,
- );
- }
- if (goal.lastReason) {
- lines.push(`${theme.fg("dim", "Reason:")} ${goal.lastReason}`);
- }
- if (goal.lastError) {
- lines.push(`${theme.fg("dim", "Error:")} ${goal.lastError}`);
- }
-
- this.chatContainer.addChild(new Spacer(1));
- this.chatContainer.addChild(new Text(lines.join("\n"), 1, 0));
- this.ui.requestRender();
- }
-
private async handleHeartbeatCommand(text: string): Promise<void> {
try {
const command = parseHeartbeatCommand(text);
@@ -9789,94 +9893,6 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shor
}
}
- private async handleCompactCommand(customInstructions?: string): Promise<void> {
- let messageCount: number;
- try {
- const stats = await this.agentConnection.getSessionStats();
- messageCount = stats.totalMessages;
- } catch (error) {
- this.showError(error instanceof Error ? error.message : String(error));
- return;
- }
-
- if (messageCount < 2) {
- this.showWarning("Nothing to compact (no messages yet)");
- return;
- }
-
- this.stopWorkingLoader();
-
- try {
- await this.agentConnection.compact(customInstructions);
- } catch {
- // Ignore, will be emitted as an event
- }
- }
-
- private async handleRefineCommand(args?: string): Promise<void> {
- let trimmedArgs = args?.trim() ?? "";
- const globalOption: { global: boolean } = { global: false };
- if (/^--global(?=\s|$)/.test(trimmedArgs)) {
- globalOption.global = true;
- trimmedArgs = trimmedArgs.replace(/^--global(?=\s|$)/, "").trim();
- }
- const rollbackPrefix = "rollback ";
- let options: { instructions?: string; rollbackId?: string; global?: boolean };
-
- if (trimmedArgs === "rollback") {
- this.showWarning("Usage: /refine rollback <refinement-id>");
- return;
- }
-
- if (trimmedArgs?.startsWith(rollbackPrefix) && trimmedArgs.slice(rollbackPrefix.length).trim()) {
- // Rollback uses the global refinement history, not the current trajectory,
- // so it must work even in a fresh session with no messages yet.
- let rollbackId = trimmedArgs.slice(rollbackPrefix.length).trim();
- if (/\s--global$/.test(rollbackId)) {
- globalOption.global = true;
- rollbackId = rollbackId.replace(/\s--global$/, "").trim();
- }
- options = { rollbackId, ...globalOption };
- } else {
- let messageCount: number;
- try {
- const stats = await this.agentConnection.getSessionStats();
- messageCount = stats.totalMessages;
- } catch (error) {
- this.showError(error instanceof Error ? error.message : String(error));
- return;
- }
-
- if (messageCount < 2) {
- this.showWarning("Nothing to refine (no trajectory yet)");
- return;
- }
- options = { instructions: trimmedArgs || undefined, ...globalOption };
- }
-
- this.stopWorkingLoader();
- this.showStatus(
- options.rollbackId
- ? `Rolling back refinement ${options.rollbackId}...`
- : `Refining ${options.global ? "global" : "local"} continual harness state...`,
- );
-
- this.agentConnection
- .refine(options)
- .then((result) => {
- const applied = result.appliedEdits.filter((edit) => edit.applied).length;
- const failed = result.appliedEdits.length - applied;
- const failedSuffix = failed > 0 ? `, ${failed} failed` : "";
- this.showStatus(
- `Refined continual harness state: ${applied} edit${applied === 1 ? "" : "s"} applied${failedSuffix}`,
- );
- this.showStatus(`Harness state: ${result.harnessStatePath}`);
- })
- .catch((error) => {
- this.showError(`Refinement failed: ${error instanceof Error ? error.message : String(error)}`);
- });
- }
-
stop(options: { preserveAltScreen?: boolean } = {}): void {
this.unregisterSignalHandlers();
this.clearCtrlCExitHint({ render: false });
diff --git a/packages/coding-agent/src/modes/interactive/prompt-stash-state.ts b/packages/coding-agent/src/modes/interactive/prompt-stash-state.ts
index 87705eaa97..e8c99824f0 100644
--- a/packages/coding-agent/src/modes/interactive/prompt-stash-state.ts
+++ b/packages/coding-agent/src/modes/interactive/prompt-stash-state.ts
@@ -10,6 +10,7 @@ export interface PromptStash {
export interface PromptStashState {
stash?: PromptStash;
+ queuedStashes?: PromptStash[];
}
export class ClientPromptStashStore {
@@ -25,7 +26,11 @@ export class ClientPromptStashStore {
}
release(sessionId: string, state: PromptStashState): void {
- if (state.stash === undefined && this.states.get(sessionId) === state) {
+ if (
+ state.stash === undefined &&
+ (state.queuedStashes?.length ?? 0) === 0 &&
+ this.states.get(sessionId) === state
+ ) {
this.states.delete(sessionId);
}
}
diff --git a/packages/coding-agent/src/modes/print-mode.ts b/packages/coding-agent/src/modes/print-mode.ts
index ffcb7da8db..5435c6f166 100644
--- a/packages/coding-agent/src/modes/print-mode.ts
+++ b/packages/coding-agent/src/modes/print-mode.ts
@@ -6,14 +6,14 @@
* - `pi --mode json "prompt"` - JSON event stream
*/
-import type { AssistantMessage, ImageContent } from "@earendil-works/pi-ai";
+import type { ImageContent } from "@earendil-works/pi-ai";
import type { AgentSessionRuntime } from "../core/agent-session-runtime.js";
import { type AgentAutonomousStatus, type AutonomousLimitReason, autonomousLimitReason } from "../core/autonomous.js";
import { flushRawStdout, writeRawStdout } from "../core/output-guard.js";
import { killTrackedDetachedChildren } from "../utils/shell.js";
import { InProcessAgentConnection } from "./agent-connection/in-process-agent-connection.js";
import type { AgentConnection } from "./agent-connection/types.js";
-import { latestAutonomousGateAttempt } from "./headless-completion.js";
+import { latestAutonomousGateAttempt, selectHeadlessTerminalResult } from "./headless-completion.js";
/**
* Options for print mode.
@@ -115,19 +115,25 @@ async function runPrintModeWithConnectionInternal(
const autonomousStatus = await connection.waitForHeadlessCompletion();
if (mode === "text") {
- const lastMessage = (await connection.getMessages()).at(-1);
- if (lastMessage?.role === "assistant") {
- const assistantMessage = lastMessage as AssistantMessage;
- if (assistantMessage.stopReason === "error" || assistantMessage.stopReason === "aborted") {
- console.error(assistantMessage.errorMessage || `Request ${assistantMessage.stopReason}`);
+ const { primary, compactionOutcomes } = selectHeadlessTerminalResult(await connection.getMessages());
+ if (primary?.role === "assistant") {
+ if (primary.stopReason === "error" || primary.stopReason === "aborted") {
+ console.error(primary.errorMessage || `Request ${primary.stopReason}`);
exitCode = 1;
} else {
- for (const content of assistantMessage.content) {
+ for (const content of primary.content) {
if (content.type === "text") {
writeRawStdout(`${content.text}\n`);
}
}
}
+ } else if (primary) {
+ writeRawStdout(`${primary.content}\n`);
+ if (!primary.details.success || primary.details.severity === "error") exitCode = 1;
+ }
+ for (const outcome of compactionOutcomes) {
+ console.error(outcome.content);
+ if (outcome.details.outcome === "failed") exitCode = 1;
}
}
diff --git a/packages/coding-agent/src/package-manager-cli.ts b/packages/coding-agent/src/package-manager-cli.ts
index 6a64905515..d991734bb8 100644
--- a/packages/coding-agent/src/package-manager-cli.ts
+++ b/packages/coding-agent/src/package-manager-cli.ts
@@ -43,7 +43,11 @@ import {
} from "./config.js";
import { parseAgentSessionMessagePromptId } from "./core/agent-messages.js";
import type { AgentSessionRuntimeMetadata } from "./core/agent-session-runtime.js";
-import type { CustomMessage } from "./core/messages.js";
+import {
+ type CustomMessage,
+ isSessionSlashCommandMessage,
+ SESSION_SLASH_COMMAND_CUSTOM_TYPE,
+} 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";
@@ -622,11 +626,17 @@ function parseDaemonUpdateRestartQueuedMessage(value: unknown): DaemonUpdateRest
: isCustomMessage(value.customMessage)
? value.customMessage
: undefined;
- if (value.customMessage !== undefined && !customMessage) {
+ if (
+ value.customMessage !== undefined &&
+ (!customMessage ||
+ (customMessage.customType === SESSION_SLASH_COMMAND_CUSTOM_TYPE &&
+ (!isSessionSlashCommandMessage(customMessage) || message !== customMessage.details.command.text)))
+ ) {
throw new Error("Daemon update restart response contains an invalid custom queued message");
}
- const agentMessageId =
- readOptionalString(value.agentMessageId, "queue.agentMessageId") ?? parseAgentSessionMessagePromptId(message);
+ 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 } : {}),
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index 13c6edd4a1..b27f6adecb 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -14,6 +14,7 @@ import type {
} from "../src/modes/agent-connection/types.js";
import {
+ DaemonCapabilityUnavailableError,
type DaemonClient,
type DaemonClientCloseListener,
type DaemonClientMessageListener,
@@ -23,6 +24,7 @@ import {
} from "../src/modes/daemon/daemon-client.js";
import {
DAEMON_PROTOCOL_INFO,
+ DAEMON_SCHEMA_REVISION,
type DaemonAttachResult,
type DaemonCommand,
type DaemonOutbound,
@@ -47,10 +49,21 @@ class FakeDaemonClient {
abortBashUnknownCommand = false;
abortAndClearQueueUnknownCommand = false;
cronAddGate: Promise<void> | undefined;
+ promptGate: Promise<void> | undefined;
+ promptError: Error | undefined;
+ promptResponseError: string | undefined;
+ cancelPromptAdmissionStatus: "cancelled" | "owned" | "unknown" = "owned";
legacyHeartbeatCommandsSupported = false;
serverCapabilities = new Set<string>();
updateRestartSessions: Array<Record<string, unknown>> = [];
- hello: DaemonHello | undefined;
+ hello: DaemonHello | undefined = {
+ type: "daemon_hello",
+ socketPath: "/tmp/fake.sock",
+ protocol: DAEMON_PROTOCOL_INFO,
+ schemaRevision: DAEMON_SCHEMA_REVISION,
+ clientId: "fake-client",
+ serverCapabilities: ["prompt_admission_cancellation", "session_input_admission"],
+ };
private readonly messageListeners = new Set<DaemonClientMessageListener>();
private readonly closeListeners = new Set<DaemonClientCloseListener>();
@@ -62,6 +75,24 @@ class FakeDaemonClient {
this.requests.push(command);
this.requestTimeouts.push(timeoutMs);
switch (command.type) {
+ case "prompt":
+ if (this.promptGate) await this.promptGate;
+ if (this.promptError) throw this.promptError;
+ if (this.promptResponseError) {
+ return { type: "response", command: command.type, success: false, error: this.promptResponseError };
+ }
+ return { type: "response", command: command.type, success: true };
+ case "prompt_and_wait":
+ if (this.promptGate) await this.promptGate;
+ if (this.promptError) throw this.promptError;
+ return { type: "response", command: command.type, success: true };
+ case "cancel_prompt_admission":
+ return {
+ type: "response",
+ command: command.type,
+ success: true,
+ data: { status: this.cancelPromptAdmissionStatus },
+ };
case "list":
return {
type: "response",
@@ -488,7 +519,9 @@ class FakeDaemonClient {
this.connected = true;
}
- async waitForHello(): Promise<void> {}
+ async waitForHello(): Promise<DaemonHello> {
+ return this.hello!;
+ }
resetTransportForReconnect(): void {
this.resetTransportCount++;
@@ -673,6 +706,159 @@ function emitSequencedQueueUpdate(client: FakeDaemonClient, activeSessionId: str
}
describe("DaemonAgentConnection", () => {
+ it("forwards queueIfBusy for prompt admission", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+
+ await connection.prompt("queued input", { streamingBehavior: "followUp", queueIfBusy: true });
+
+ expect(fakeClient.requests.at(-1)).toMatchObject({
+ type: "prompt",
+ activeSessionId: "active-1",
+ message: "queued input",
+ streamingBehavior: "followUp",
+ queueIfBusy: true,
+ });
+ });
+
+ it("forwards signal-backed prompts with a unique cancellable admission id", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ const abort = new AbortController();
+
+ await connection.prompt("startup", { signal: abort.signal, queueIfBusy: true });
+
+ expect(fakeClient.requests.at(-1)).toMatchObject({
+ type: "prompt",
+ activeSessionId: "active-1",
+ message: "startup",
+ queueIfBusy: true,
+ admissionId: expect.stringMatching(/^prompt-admission:/),
+ });
+ });
+
+ it("cancels rejected signal-backed admission and removes its abort listener", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.promptError = new Error("transport failed");
+ fakeClient.cancelPromptAdmissionStatus = "cancelled";
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ const abort = new AbortController();
+ const add = vi.spyOn(abort.signal, "addEventListener");
+ const remove = vi.spyOn(abort.signal, "removeEventListener");
+
+ await expect(connection.prompt("startup", { signal: abort.signal })).rejects.toMatchObject({
+ message: "transport failed",
+ cancelled: true,
+ });
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["prompt", "cancel_prompt_admission"]);
+ expect(add).toHaveBeenCalledOnce();
+ expect(remove).toHaveBeenCalledOnce();
+ expect(remove.mock.calls[0]?.[1]).toBe(add.mock.calls[0]?.[1]);
+ });
+
+ it("preserves a definitive prompt rejection when the signal remains live", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.promptResponseError = "session rejected prompt";
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+
+ await expect(connection.prompt("startup", { signal: new AbortController().signal })).rejects.toEqual(
+ new Error("session rejected prompt"),
+ );
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["prompt"]);
+ });
+
+ it("sends zero requests for a pre-aborted prompt", async () => {
+ const fakeClient = new FakeDaemonClient();
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ const abort = new AbortController();
+ abort.abort();
+
+ await expect(connection.prompt("startup", { signal: abort.signal })).rejects.toMatchObject({
+ status: "cancelled",
+ });
+ expect(fakeClient.requests).toEqual([]);
+ });
+
+ it("accepts a successful prompt response when cancellation reports unknown", async () => {
+ const fakeClient = new FakeDaemonClient();
+ let releasePrompt = () => {};
+ fakeClient.promptGate = new Promise<void>((resolve) => {
+ releasePrompt = resolve;
+ });
+ fakeClient.cancelPromptAdmissionStatus = "unknown";
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ const abort = new AbortController();
+
+ const prompt = connection.prompt("startup", { signal: abort.signal });
+ abort.abort();
+ await vi.waitFor(() =>
+ expect(fakeClient.requests.map((request) => request.type)).toContain("cancel_prompt_admission"),
+ );
+ releasePrompt();
+
+ await expect(prompt).resolves.toBeUndefined();
+ });
+
+ it("preserves a definitive prompt rejection when cancellation reports owned", async () => {
+ const fakeClient = new FakeDaemonClient();
+ let releasePrompt = () => {};
+ fakeClient.promptGate = new Promise<void>((resolve) => {
+ releasePrompt = resolve;
+ });
+ fakeClient.promptResponseError = "post-ownership validation failed";
+ fakeClient.cancelPromptAdmissionStatus = "owned";
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+ const abort = new AbortController();
+
+ const prompt = connection.prompt("startup", { signal: abort.signal });
+ abort.abort();
+ await vi.waitFor(() =>
+ expect(fakeClient.requests.map((request) => request.type)).toContain("cancel_prompt_admission"),
+ );
+ releasePrompt();
+
+ await expect(prompt).rejects.toThrow("post-ownership validation failed");
+ });
+
+ it("treats a lost prompt response plus unknown cancellation as uncertain", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.promptError = new Error("lost response");
+ fakeClient.cancelPromptAdmissionStatus = "unknown";
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+
+ await expect(connection.prompt("startup", { signal: new AbortController().signal })).rejects.toMatchObject({
+ message: "lost response",
+ status: "unknown",
+ cancelled: false,
+ });
+ });
+
+ it("translates unsupported admission cancellation into an admission error", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.promptError = new DaemonCapabilityUnavailableError("prompt", "prompt_admission_cancellation");
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+
+ await expect(connection.prompt("startup", { signal: new AbortController().signal })).rejects.toMatchObject({
+ status: "unsupported",
+ });
+ expect(fakeClient.requests.map((request) => request.type)).toEqual(["prompt"]);
+ });
+
+ it("uses cancellable admission for promptAndWait", async () => {
+ const fakeClient = new FakeDaemonClient();
+ fakeClient.promptError = new Error("lost response");
+ fakeClient.cancelPromptAdmissionStatus = "cancelled";
+ const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1");
+
+ await expect(connection.promptAndWait("wait", { signal: new AbortController().signal })).rejects.toMatchObject({
+ status: "cancelled",
+ });
+ expect(fakeClient.requests.map((request) => request.type)).toEqual([
+ "prompt_and_wait",
+ "cancel_prompt_admission",
+ ]);
+ });
+
it("uses fleet heartbeat scope for residents and session scope for owned workers", async () => {
const residentClient = new FakeDaemonClient();
residentClient.serverCapabilities.add("heartbeat_catalog");
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 1c55dfc9cb..0a4c08061b 100644
--- a/packages/coding-agent/test/agent-connection-in-process.test.ts
+++ b/packages/coding-agent/test/agent-connection-in-process.test.ts
@@ -1,7 +1,7 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import { getModel } from "@earendil-works/pi-ai";
-import { describe, expect, it } from "vitest";
-import type { AgentSessionEvent, AgentSessionEventListener } from "../src/core/agent-session.js";
+import { describe, expect, it, vi } from "vitest";
+import type { AgentSessionEvent, AgentSessionEventListener, PromptOptions } from "../src/core/agent-session.js";
import type { AgentSessionRuntime } from "../src/core/agent-session-runtime.js";
import { emptyGoalState } from "../src/core/goals.js";
import { InProcessAgentConnection } from "../src/modes/agent-connection/in-process-agent-connection.js";
@@ -142,6 +142,61 @@ function createFakeSession(id: string, messages: AgentMessage[]): FakeSessionCon
}
describe("InProcessAgentConnection", () => {
+ it.each([
+ { accepted: true, promptResult: "pending", expectedError: undefined },
+ { accepted: false, promptResult: "resolve", expectedError: "Prompt was not accepted by the session." },
+ { accepted: false, promptResult: "reject", expectedError: "real session error" },
+ ] as const)(
+ "settles bare prompts from admission (accepted: $accepted, result: $promptResult)",
+ async ({ accepted, promptResult, expectedError }) => {
+ const session = createFakeSession("prompt-admission", []);
+ let finishTurn = () => {};
+ const turn = new Promise<void>((resolve) => {
+ finishTurn = resolve;
+ });
+ const prompt = vi.fn((_message: string, options?: PromptOptions) => {
+ options?.preflightResult?.(accepted);
+ if (promptResult === "pending") return turn;
+ if (promptResult === "reject") return Promise.reject(new Error("real session error"));
+ return Promise.resolve();
+ });
+ Object.assign(session.session, { prompt });
+ const connection = new InProcessAgentConnection(asRuntime(new FakeRuntime(session.session)));
+ const result = expect(connection.prompt("hello"));
+
+ if (expectedError) await result.rejects.toThrow(expectedError);
+ else await result.resolves.toBeUndefined();
+ expect(prompt).toHaveBeenCalledWith(
+ "hello",
+ expect.objectContaining({ preflightResult: expect.any(Function) }),
+ );
+ finishTurn();
+ },
+ );
+ it("forwards prompt admission cancellation to the session", async () => {
+ const session = createFakeSession("prompt-cancellation", []);
+ const prompt = vi.fn(
+ (_message: string, options?: PromptOptions) =>
+ new Promise<void>((_resolve, reject) => {
+ options?.signal?.addEventListener("abort", () => reject(new Error("Prompt admission was cancelled.")), {
+ once: true,
+ });
+ }),
+ );
+ Object.assign(session.session, { prompt });
+ const connection = new InProcessAgentConnection(asRuntime(new FakeRuntime(session.session)));
+ const controller = new AbortController();
+
+ const admission = connection.prompt("hello", { signal: controller.signal });
+ controller.abort();
+
+ await expect(admission).rejects.toThrow("Prompt admission was cancelled.");
+ expect(prompt).toHaveBeenCalledWith(
+ "hello",
+ expect.objectContaining({ signal: controller.signal, preflightResult: expect.any(Function) }),
+ );
+ });
+
it("loads the full model catalog through the connection boundary", async () => {
const session = createFakeSession("models", []);
const runtime = new FakeRuntime(session.session);
diff --git a/packages/coding-agent/test/command-recovery-journal.test.ts b/packages/coding-agent/test/command-recovery-journal.test.ts
index 6c1686333f..fabf6ad708 100644
--- a/packages/coding-agent/test/command-recovery-journal.test.ts
+++ b/packages/coding-agent/test/command-recovery-journal.test.ts
@@ -25,6 +25,13 @@ describe("CommandRecoveryJournal", () => {
expect(journal.begin("client-a", "command-a", "prompt")).toEqual({ status: "pending" });
});
+ it("looks up prior commands without inserting new receipts", () => {
+ const journal = new CommandRecoveryJournal(createPath());
+ expect(journal.lookup("client-a", "missing")).toBeUndefined();
+ expect(journal.begin("client-a", "pending", "prompt")).toEqual({ status: "new" });
+ expect(journal.lookup("client-a", "pending")).toEqual({ status: "pending" });
+ });
+
it("does not collide when client and command ids contain separators", () => {
const journal = new CommandRecoveryJournal(createPath());
expect(journal.begin("client:a", "command", "prompt")).toEqual({ status: "new" });
diff --git a/packages/coding-agent/test/compaction.test.ts b/packages/coding-agent/test/compaction.test.ts
index 0bd0a204ac..75bc7273c0 100644
--- a/packages/coding-agent/test/compaction.test.ts
+++ b/packages/coding-agent/test/compaction.test.ts
@@ -377,8 +377,11 @@ describe("buildSessionContext", () => {
const loaded = buildSessionContext(entries);
// summary + kept (u2, a2) + after (u3, a3) = 5
expect(loaded.messages.length).toBe(5);
- expect(loaded.messages[0].role).toBe("compactionSummary");
- expect((loaded.messages[0] as any).summary).toContain("Summary of 1,a,2,b");
+ expect(loaded.messages[0]).toMatchObject({
+ role: "compactionSummary",
+ summary: expect.stringContaining("Summary of 1,a,2,b"),
+ retainedMessageCount: 2,
+ });
});
it("should handle multiple compactions (only latest matters)", () => {
diff --git a/packages/coding-agent/test/cron-jobs.test.ts b/packages/coding-agent/test/cron-jobs.test.ts
index 00706cb16c..c7ea1e7220 100644
--- a/packages/coding-agent/test/cron-jobs.test.ts
+++ b/packages/coding-agent/test/cron-jobs.test.ts
@@ -1,7 +1,7 @@
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
type AgentCronJob,
AgentCronJobStore,
@@ -951,6 +951,78 @@ describe("AgentCronScheduler", () => {
expect(store.list()[0]).not.toHaveProperty("nextRunAt");
});
+ it("does not claim new jobs after a started scheduler is stopped", async () => {
+ const store = new AgentCronJobStore(makeStorePath(tempDirs));
+ const job = store.create({
+ activeSessionId: "active-1",
+ sessionId: "session-1",
+ sessionFile: "/tmp/session.jsonl",
+ cwd: "/tmp/project",
+ scheduleText: "in 1m",
+ prompt: "do not claim",
+ now: start,
+ });
+ const runJob = vi.fn(async () => undefined);
+ const scheduler = new AgentCronScheduler(store, { runJob });
+ scheduler.start();
+ scheduler.stop();
+
+ expect(await scheduler.runDue(new Date("2026-01-01T12:35:00.000Z"))).toBe(0);
+ expect(runJob).not.toHaveBeenCalled();
+ expect(store.list()[0]).toMatchObject({ id: job.id, status: "active", runCount: 0 });
+ });
+
+ it("releases leases and recovers the whole claimed batch when setup fails", async () => {
+ const store = new AgentCronJobStore(makeStorePath(tempDirs));
+ const unrelated = store.create({
+ activeSessionId: "unrelated",
+ sessionId: "unrelated",
+ sessionFile: "/tmp/unrelated.jsonl",
+ cwd: "/tmp/project",
+ scheduleText: "every 10s",
+ prompt: "unrelated",
+ now: start,
+ });
+ const [unrelatedDispatch] = store.claimDue(new Date("2026-01-01T12:34:10.000Z"));
+ if (!unrelatedDispatch) throw new Error("Expected unrelated dispatch");
+ const batch = ["active-1", "active-2", "active-3"].map((activeSessionId) =>
+ store.create({
+ activeSessionId,
+ sessionId: activeSessionId,
+ sessionFile: `/tmp/${activeSessionId}.jsonl`,
+ cwd: "/tmp/project",
+ scheduleText: "in 1m",
+ prompt: activeSessionId,
+ now: start,
+ }),
+ );
+ const endDispatch = vi.fn();
+ const beginDispatch = vi.fn((dispatch) => {
+ if (dispatch.job.activeSessionId === "active-2") throw new Error("lease setup failed");
+ return endDispatch;
+ });
+ const scheduler = new AgentCronScheduler(store, {
+ now: () => new Date("2026-01-01T12:35:00.000Z"),
+ runJob: vi.fn(async () => undefined),
+ beginDispatch,
+ });
+
+ await expect(scheduler.runDue(new Date("2026-01-01T12:35:00.000Z"))).rejects.toThrow("lease setup failed");
+ expect(beginDispatch).toHaveBeenCalledTimes(2);
+ expect(endDispatch).toHaveBeenCalledOnce();
+ for (const job of batch) {
+ expect(store.getClaimedJob(job.id)).toBeUndefined();
+ expect(store.list().find((candidate) => candidate.id === job.id)).toMatchObject({
+ status: "completed",
+ lastError: "Interrupted before scheduled operation completion",
+ });
+ }
+ expect(store.getClaimedJob(unrelated.id)).toMatchObject({ id: unrelated.id });
+ expect(store.recordDispatchResult(unrelatedDispatch.id, { outcome: "ran" })).toMatchObject({
+ id: unrelated.id,
+ });
+ });
+
it("reschedules recurring jobs after each run", async () => {
const store = new AgentCronJobStore(makeStorePath(tempDirs));
store.create({
diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.ts
index 086ab4acec..862e6b7140 100644
--- a/packages/coding-agent/test/daemon-client.test.ts
+++ b/packages/coding-agent/test/daemon-client.test.ts
@@ -1,6 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DaemonClient, getDaemonSocketCloseReason } from "../src/modes/daemon/daemon-client.js";
-import { DAEMON_PROTOCOL_VERSION } from "../src/modes/daemon/daemon-protocol.js";
+import {
+ DAEMON_COMMAND_COMPATIBILITY,
+ DAEMON_PROTOCOL_VERSION,
+ DAEMON_SCHEMA_REVISION,
+} from "../src/modes/daemon/daemon-protocol.js";
const netMock = vi.hoisted(() => {
type Listener = (...args: unknown[]) => void;
@@ -86,16 +90,22 @@ vi.mock("node:net", () => ({
createConnection: netMock.createConnection,
}));
-function emitHello(socket: (typeof netMock.sockets)[number], version = DAEMON_PROTOCOL_VERSION): void {
+function emitHello(
+ socket: (typeof netMock.sockets)[number],
+ version = DAEMON_PROTOCOL_VERSION,
+ serverCapabilities: string[] = ["session_input_admission"],
+ schemaRevision?: number,
+): void {
socket.emit(
"data",
`${JSON.stringify({
type: "daemon_hello",
socketPath: "/tmp/prime-agent.sock",
protocol: { name: "prime-agent.daemon", version },
+ schemaRevision,
appVersion: "9.9.9",
clientId: "client-1",
- serverCapabilities: [],
+ serverCapabilities,
})}\n`,
);
}
@@ -205,6 +215,61 @@ describe("DaemonClient", () => {
client.close();
});
+ it("rejects session input admission clearly when an old daemon lacks the capability", 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, DAEMON_PROTOCOL_VERSION, []);
+
+ await expect(
+ client.request({ type: "prompt", activeSessionId: "active-1", message: "hello", queueIfBusy: true }),
+ ).rejects.toThrow("does not support session_input_admission");
+ expect(socket.writes).toEqual([]);
+ client.close();
+ });
+
+ it("field-gates prompt admissionId before writing raw commands", 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, DAEMON_PROTOCOL_VERSION, ["session_input_admission", "prompt_admission_cancellation"], 3);
+
+ await expect(
+ client.request({ type: "prompt", activeSessionId: "active-1", message: "hello", admissionId: "a-1" }),
+ ).rejects.toThrow("does not support prompt_admission_cancellation");
+ expect(socket.writes).toEqual([]);
+ client.close();
+ });
+
+ it("accepts a newer compatible daemon schema for admission-gated prompts", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+ const compatibility = DAEMON_COMMAND_COMPATIBILITY.cancel_prompt_admission;
+ emitHello(
+ socket,
+ compatibility.minProtocol,
+ ["session_input_admission", "prompt_admission_cancellation"],
+ compatibility.minSchemaRevision + 1,
+ );
+
+ const request = client.request({
+ type: "prompt",
+ activeSessionId: "active-1",
+ message: "hello",
+ admissionId: "a-1",
+ });
+ await vi.waitFor(() => expect(socket.writes).toHaveLength(1));
+ client.close();
+ await expect(request).rejects.toThrow("closed before the operation completed");
+ });
+
it("isolates a message consumer failure from the rest of the client", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
const connect = client.connect();
@@ -706,7 +771,7 @@ describe("DaemonClient", () => {
socketPath: "/tmp/prime-agent.sock",
protocol: { name: "prime-agent.daemon", version: DAEMON_PROTOCOL_VERSION },
clientId: "server-client-2",
- serverCapabilities: [],
+ serverCapabilities: ["session_input_admission"],
})}\n`,
);
expect(secondSocket.writes).toEqual([firstWireData]);
@@ -758,6 +823,43 @@ describe("DaemonClient", () => {
client.close();
});
+ it("rejects a pending admission-gated prompt when the reconnected daemon is downgraded", async () => {
+ vi.useFakeTimers();
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ client.enableRequestRecovery();
+ const firstConnect = client.connect();
+ const firstSocket = netMock.sockets[0]!;
+ firstSocket.emit("connect");
+ await firstConnect;
+ emitHello(
+ firstSocket,
+ DAEMON_PROTOCOL_VERSION,
+ ["session_input_admission", "prompt_admission_cancellation"],
+ DAEMON_SCHEMA_REVISION,
+ );
+
+ const response = client.request({
+ type: "prompt",
+ activeSessionId: "active-1",
+ message: "hello",
+ admissionId: "a-1",
+ });
+ expect(firstSocket.writes).toHaveLength(1);
+ firstSocket.emit("close");
+
+ const secondConnect = client.connect();
+ const secondSocket = netMock.sockets[1]!;
+ secondSocket.emit("connect");
+ await secondConnect;
+ // The replacement daemon no longer supports admission cancellation, so
+ // replaying would silently drop admissionId and take ownership.
+ emitHello(secondSocket, DAEMON_PROTOCOL_VERSION, ["session_input_admission"], DAEMON_SCHEMA_REVISION);
+
+ await expect(response).rejects.toThrow("does not support prompt_admission_cancellation");
+ expect(secondSocket.writes).toEqual([]);
+ client.close();
+ });
+
it("reconnects raw clients and replays pending commands after supervisor replacement", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
const firstConnect = client.connect();
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index d9ac916a16..667a54f674 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -20,10 +20,39 @@ import {
markClientSnapshotStreaming,
setDaemonClientSessionCapabilities,
shouldSendDaemonOutboundToClient,
+ waitForDaemonPromptAdmission,
} from "../src/modes/daemon/daemon-mode.js";
-import type { DaemonAttachResult, DaemonCommand } from "../src/modes/daemon/daemon-protocol.js";
+import {
+ createDaemonCommandEnvelope,
+ type DaemonAttachResult,
+ type DaemonCommand,
+} from "../src/modes/daemon/daemon-protocol.js";
describe("daemon mode helpers", () => {
+ it("preserves envelope client identity while registering prompt admission", () => {
+ const daemon = new AgentDaemon("/tmp/unused-daemon.sock", {
+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },
+ createRuntime: vi.fn(),
+ });
+ const client = makeClient("worker-socket", "active");
+ const parse = Reflect.get(daemon, "parseCommandAndRegisterPromptAdmission").bind(daemon);
+
+ parse(client, JSON.stringify(createDaemonCommandEnvelope({ type: "list" }, "request-1", "public-client")));
+ expect(client.id).toBe("public-client");
+ });
+
+ it("observes supplied work when prompt admission is already aborted", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const work = Promise.reject(new Error("late claim failure"));
+
+ await expect(waitForDaemonPromptAdmission(work, controller.signal)).rejects.toThrow(
+ "Prompt admission was cancelled.",
+ );
+ // Let the observed work settle; an unhandled rejection would fail Vitest.
+ await Promise.resolve();
+ });
+
it("finds only direct child active sessions", () => {
const parent = makeState("parent");
const child = makeState("child", "parent");
@@ -2275,7 +2304,7 @@ describe("daemon mode helpers", () => {
expect(prompt).toHaveBeenCalledOnce();
});
- it("queues agent messages while a cron prompt prepares to stream", async () => {
+ it("releases cron preparing state after prompt admission", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
@@ -2290,6 +2319,7 @@ describe("daemon mode helpers", () => {
resolvePrompt = resolve;
}),
);
+ const promptUntilAccepted = vi.fn(async () => {});
const acceptAgentMessagePrompt = vi.fn(async () => {});
const queueAgentMessagePrompt = vi.fn(async (_message: string, _streamingBehavior: "steer" | "followUp") => true);
targetState.runtime = {
@@ -2302,6 +2332,7 @@ describe("daemon mode helpers", () => {
isBashRunning: false,
pendingMessageCount: 0,
prompt,
+ promptUntilAccepted,
acceptAgentMessagePrompt,
queueAgentMessagePrompt,
},
@@ -2322,7 +2353,8 @@ describe("daemon mode helpers", () => {
);
await Promise.resolve();
await Promise.resolve();
- expect(prompt).toHaveBeenCalledOnce();
+ expect(promptUntilAccepted).toHaveBeenCalledOnce();
+ expect(prompt).not.toHaveBeenCalled();
await internals.sendAgentSessionMessage({
targetSelector: targetState.activeSessionId,
@@ -2330,9 +2362,8 @@ describe("daemon mode helpers", () => {
origin: "agent",
});
- expect(acceptAgentMessagePrompt).not.toHaveBeenCalled();
- expect(queueAgentMessagePrompt).toHaveBeenCalledOnce();
- expect(queueAgentMessagePrompt.mock.calls[0]?.[1]).toBe("steer");
+ expect(acceptAgentMessagePrompt).toHaveBeenCalledOnce();
+ expect(queueAgentMessagePrompt).not.toHaveBeenCalled();
resolvePrompt();
await cronRun;
});
@@ -4487,582 +4518,617 @@ describe("daemon mode helpers", () => {
});
});
- it("defers busy heartbeat cron jobs instead of queueing a follow-up", async () => {
- const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
- defaultSessionConfig: {
- agentDir: "/tmp/prime-agent-test-agent",
- cwd: "/tmp",
- },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const prompt = vi.fn(async () => {});
- const followUp = vi.fn(async () => true);
- const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- isBashRunning: boolean;
- pendingMessageCount: number;
- prompt: typeof prompt;
- followUp: typeof followUp;
- };
- };
- };
- state.runtime.session = {
- isStreaming: true,
- isBashRunning: false,
- pendingMessageCount: 0,
- prompt,
- followUp,
- } as never;
- (
- daemon as unknown as {
- sessions: Map<string, ActiveSessionState>;
- }
- ).sessions.set(state.activeSessionId, state);
- const runCronJob = (
- daemon as unknown as {
- runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;
- }
- ).runCronJob.bind(daemon);
+ it.each([
+ {
+ name: "defers busy heartbeat cron jobs instead of queueing a follow-up",
+ activity: { isStreaming: true },
+ jobs: [{ id: "heartbeat-1", source: "heartbeat", deliveryMode: "follow_up" }],
+ acceptingAgentMessage: false,
+ assertQueuedHeartbeatUntouched: false,
+ },
+ {
+ name: "defers separate RLM heartbeat cron jobs while the session is busy",
+ activity: { isStreaming: true },
+ jobs: [
+ { id: "rlm-1", source: "rlm_heartbeat", deliveryMode: "follow_up" },
+ { id: "rlm-2", source: "rlm_heartbeat", deliveryMode: "follow_up" },
+ ],
+ acceptingAgentMessage: false,
+ assertQueuedHeartbeatUntouched: false,
+ },
+ {
+ name: "does not enqueue another heartbeat when one is already pending",
+ activity: { isStreaming: true, pendingMessageCount: 1 },
+ jobs: [{ id: "heartbeat-1", source: "heartbeat" }],
+ acceptingAgentMessage: false,
+ assertQueuedHeartbeatUntouched: true,
+ },
+ {
+ name: "defers heartbeat cron jobs while the target is accepting an agent message",
+ activity: {},
+ jobs: [{ id: "heartbeat-1", source: "heartbeat" }],
+ acceptingAgentMessage: true,
+ assertQueuedHeartbeatUntouched: false,
+ },
+ {
+ name: "defers heartbeat cron jobs while an accepted agent message prompt is in flight",
+ activity: { hasAcceptedPromptInFlight: true },
+ jobs: [{ id: "heartbeat-1", source: "heartbeat" }],
+ acceptingAgentMessage: false,
+ assertQueuedHeartbeatUntouched: false,
+ },
+ ] as const)("$name", async ({ activity, jobs, acceptingAgentMessage, assertQueuedHeartbeatUntouched }) => {
+ const fixture = makeCronAdmissionFixture(activity, { acceptingAgentMessage });
- const result = await runCronJob(
- makeCronJob({
- id: "heartbeat-1",
- source: "heartbeat",
- activeSessionId: state.activeSessionId,
- deliveryMode: "follow_up",
- }),
- );
+ const results = [];
+ for (const job of jobs) {
+ results.push(await fixture.runCronJob(makeCronJob({ ...job, activeSessionId: fixture.activeSessionId })));
+ }
- expect(result).toBe("skipped");
- expect(followUp).not.toHaveBeenCalled();
- expect(prompt).not.toHaveBeenCalled();
+ expect(results).toEqual(jobs.map(() => "skipped"));
+ expect(fixture.prompt).not.toHaveBeenCalled();
+ expect(fixture.promptHeartbeat).not.toHaveBeenCalled();
+ expect(fixture.followUp).not.toHaveBeenCalled();
+ if (assertQueuedHeartbeatUntouched) {
+ expect(fixture.removeQueuedFollowUp).not.toHaveBeenCalled();
+ }
});
- it("defers separate RLM heartbeat cron jobs while the session is busy", async () => {
- const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
- defaultSessionConfig: {
- agentDir: "/tmp/prime-agent-test-agent",
- cwd: "/tmp",
- },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const prompt = vi.fn(async () => {});
- const followUp = vi.fn(async () => true);
- const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- isBashRunning: boolean;
- pendingMessageCount: number;
- prompt: typeof prompt;
- followUp: typeof followUp;
- };
- };
- };
- state.runtime.session = {
- isStreaming: true,
- isBashRunning: false,
- pendingMessageCount: 0,
- prompt,
- followUp,
- } as never;
- (
- daemon as unknown as {
- sessions: Map<string, ActiveSessionState>;
- }
- ).sessions.set(state.activeSessionId, state);
- const runCronJob = (
- daemon as unknown as {
- runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;
- }
- ).runCronJob.bind(daemon);
+ it.each([
+ {
+ name: "queues generic cron jobs while the target is accepting an agent message",
+ activity: {},
+ acceptingAgentMessage: true,
+ },
+ {
+ name: "queues generic cron jobs behind accepted agent message prompts",
+ activity: { hasAcceptedPromptInFlight: true },
+ acceptingAgentMessage: false,
+ },
+ {
+ name: "queues generic cron jobs behind pending messages",
+ activity: { pendingMessageCount: 1 },
+ acceptingAgentMessage: false,
+ },
+ ] as const)("$name", async ({ activity, acceptingAgentMessage }) => {
+ const fixture = makeCronAdmissionFixture(activity, { acceptingAgentMessage });
- const first = await runCronJob(
- makeCronJob({
- id: "rlm-1",
- source: "rlm_heartbeat",
- activeSessionId: state.activeSessionId,
- deliveryMode: "follow_up",
- }),
- );
- const second = await runCronJob(
- makeCronJob({
- id: "rlm-2",
- source: "rlm_heartbeat",
- activeSessionId: state.activeSessionId,
- deliveryMode: "follow_up",
- }),
- );
+ await fixture.runCronJob(makeCronJob({ id: "cron-1", source: "cron", activeSessionId: fixture.activeSessionId }));
- expect(first).toBe("skipped");
- expect(second).toBe("skipped");
- expect(followUp).not.toHaveBeenCalled();
- expect(prompt).not.toHaveBeenCalled();
+ expect(fixture.followUp).toHaveBeenCalledWith("heartbeat prompt", undefined, { resumeIfIdle: true });
+ expect(fixture.prompt).not.toHaveBeenCalled();
+ expect(fixture.promptHeartbeat).not.toHaveBeenCalled();
});
- it("does not enqueue another heartbeat when one is already pending", async () => {
- const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
- defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- isBashRunning: boolean;
- pendingMessageCount: number;
- prompt: ReturnType<typeof vi.fn>;
- followUp: ReturnType<typeof vi.fn>;
- };
- };
- };
- const followUp = vi.fn(async () => false);
- const removeQueuedFollowUp = vi.fn(() => true);
- state.runtime.session = {
- isStreaming: true,
- isBashRunning: false,
- pendingMessageCount: 1,
- prompt: vi.fn(),
- followUp,
- removeQueuedFollowUp,
- } as never;
- (daemon as unknown as { sessions: Map<string, ActiveSessionState> }).sessions.set(state.activeSessionId, state);
- const result = await (
- daemon as unknown as { runCronJob(job: AgentCronJob): Promise<"skipped" | undefined> }
- ).runCronJob(makeCronJob({ id: "heartbeat-1", source: "heartbeat", activeSessionId: state.activeSessionId }));
+ it.each([
+ {
+ name: "delivers heartbeats with a steering behavior by default",
+ job: { id: "heartbeat-1", source: "heartbeat" },
+ streamingBehavior: "steer",
+ method: "promptHeartbeat",
+ },
+ {
+ name: "delivers follow-up heartbeats with a followUp behavior and coalescing key",
+ job: { id: "heartbeat-1", source: "heartbeat", deliveryMode: "follow_up" },
+ streamingBehavior: "followUp",
+ method: "promptHeartbeat",
+ },
+ {
+ name: "prompts idle generic cron jobs without a heartbeat coalescing key",
+ job: { id: "cron-1", source: "cron" },
+ streamingBehavior: "followUp",
+ method: "prompt",
+ },
+ ] as const)("$name", async ({ job, streamingBehavior, method }) => {
+ const fixture = makeCronAdmissionFixture();
- expect(result).toBe("skipped");
- expect(followUp).not.toHaveBeenCalled();
- expect(removeQueuedFollowUp).not.toHaveBeenCalled();
+ await fixture.runCronJob(makeCronJob({ ...job, activeSessionId: fixture.activeSessionId }));
+
+ const expectedOptions = expect.objectContaining({ streamingBehavior, source: "rpc" });
+ if (method === "promptHeartbeat") {
+ expect(fixture.promptHeartbeat).toHaveBeenCalledWith(
+ expect.objectContaining({ id: job.id, prompt: "heartbeat prompt" }),
+ expectedOptions,
+ );
+ expect(fixture.promptHeartbeat.mock.calls[0]?.[1]).toMatchObject({
+ followUpQueueKey: `heartbeat:${job.id}`,
+ });
+ expect(fixture.prompt).not.toHaveBeenCalled();
+ } else {
+ expect(fixture.prompt).toHaveBeenCalledWith("heartbeat prompt", expectedOptions);
+ expect(fixture.prompt.mock.calls[0]?.[1]).not.toHaveProperty("followUpQueueKey");
+ expect(fixture.promptHeartbeat).not.toHaveBeenCalled();
+ }
+ expect(fixture.followUp).not.toHaveBeenCalled();
});
- it("defers heartbeat cron jobs while the target is accepting an agent message", async () => {
+ it("delivers steer heartbeats after an RPC prompt finishes preflight while its turn is still streaming", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
throw new Error("unexpected runtime creation");
},
});
- const prompt = vi.fn(async () => {});
- const followUp = vi.fn(async () => true);
+ let releasePrompt = () => {};
+ const promptFinished = new Promise<void>((resolve) => {
+ releasePrompt = resolve;
+ });
+ let reportPromptStarted = () => {};
+ const promptStarted = new Promise<void>((resolve) => {
+ reportPromptStarted = resolve;
+ });
+ const sessionState = {
+ isStreaming: false,
+ isBashRunning: false,
+ pendingMessageCount: 0,
+ };
+ const prompt = vi.fn(async (_message: string, options?: { preflightResult?: (didSucceed: boolean) => void }) => {
+ sessionState.isStreaming = true;
+ options?.preflightResult?.(true);
+ reportPromptStarted();
+ await promptFinished;
+ });
+ const promptHeartbeat = vi.fn(
+ async (
+ _job: AgentCronJob,
+ options?: { streamingBehavior?: "steer" | "followUp"; preflightResult?: (didSucceed: boolean) => void },
+ ) => {
+ options?.preflightResult?.(true);
+ },
+ );
const state = makeState("active-1") as ActiveSessionState & {
runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- isBashRunning: boolean;
- pendingMessageCount: number;
+ session: typeof sessionState & {
prompt: typeof prompt;
- followUp: typeof followUp;
+ promptHeartbeat: typeof promptHeartbeat;
};
};
};
- state.runtime.session = {
- isStreaming: false,
- isBashRunning: false,
- pendingMessageCount: 0,
- prompt,
- followUp,
- } as never;
+ state.runtime.session = Object.assign(sessionState, { prompt, promptHeartbeat }) as never;
const internals = daemon as unknown as {
sessions: Map<string, ActiveSessionState>;
- agentMessageAcceptingTargets: Set<string>;
+ agentMessagePreparingTargets: Map<string, number>;
+ promptWithAgentMessagePreparingGuard(state: ActiveSessionState, message: string): Promise<void>;
runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;
};
internals.sessions.set(state.activeSessionId, state);
- internals.agentMessageAcceptingTargets.add(state.activeSessionId);
+ const promptPromise = internals.promptWithAgentMessagePreparingGuard(state, "long-running prompt");
+ await promptStarted;
+ const preparingReleased = !internals.agentMessagePreparingTargets.has(state.activeSessionId);
const result = await internals.runCronJob(
makeCronJob({ id: "heartbeat-1", source: "heartbeat", activeSessionId: state.activeSessionId }),
);
+ releasePrompt();
+ await promptPromise;
- expect(result).toBe("skipped");
- expect(prompt).not.toHaveBeenCalled();
- expect(followUp).not.toHaveBeenCalled();
+ expect(preparingReleased).toBe(true);
+ expect(result).toBeUndefined();
+ expect(promptHeartbeat).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "heartbeat-1" }),
+ expect.objectContaining({ streamingBehavior: "steer" }),
+ );
});
- it("queues generic cron jobs while the target is accepting an agent message", async () => {
- const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
+ it.each(["steer", "follow_up"] as const)(
+ "idle daemon %s inserts into its scheduler lane exactly once",
+ async (type) => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const steer = vi.fn(async () => {});
+ const followUp = vi.fn(async () => true);
+ const state = makeState("active-1") as ActiveSessionState & {
+ runtime: ActiveSessionState["runtime"] & {
+ session: { isStreaming: boolean; steer: typeof steer; followUp: typeof followUp };
+ };
+ };
+ state.runtime = { ...state.runtime, session: { isStreaming: false, steer, followUp } } as never;
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ recordWorkerRecoveryState: ReturnType<typeof vi.fn>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ internals.sessions.set(state.activeSessionId, state);
+ internals.recordWorkerRecoveryState = vi.fn();
+
+ await expect(
+ internals.handleCommand(makeClient("client-1", state.activeSessionId), {
+ id: "command-1",
+ type,
+ activeSessionId: state.activeSessionId,
+ message: "idle queued turn",
+ }),
+ ).resolves.toMatchObject({
+ success: true,
+ command: type,
+ ...(type === "follow_up" ? { data: { queued: true } } : {}),
+ });
+ const queue = type === "steer" ? steer : followUp;
+ expect(queue).toHaveBeenCalledOnce();
+ expect(queue).toHaveBeenCalledWith("idle queued turn", undefined, {
+ queueKey: undefined,
+ agentMessageId: undefined,
+ resumeIfIdle: true,
+ });
+ if (type === "follow_up") {
+ expect(internals.recordWorkerRecoveryState).toHaveBeenCalledWith(state, "follow_up_queued", true);
+ }
+ },
+ );
+
+ it("clears prompt admission registered before unauthenticated worker rejection", async () => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-worker-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
throw new Error("unexpected runtime creation");
},
+ worker: { authenticationToken: "worker-token" },
});
- const prompt = vi.fn(async () => {});
- const followUp = vi.fn(async () => true);
- const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- isBashRunning: boolean;
- pendingMessageCount: number;
- prompt: typeof prompt;
- followUp: typeof followUp;
- };
- };
- };
- state.runtime.session = {
- isStreaming: false,
- isBashRunning: false,
- pendingMessageCount: 0,
- prompt,
- followUp,
- } as never;
+ const client = makeClient("unauthenticated", "active-1");
+ const end = vi.fn();
+ client.socket = { destroyed: false, write: vi.fn(() => true), end } as unknown as Socket;
const internals = daemon as unknown as {
- sessions: Map<string, ActiveSessionState>;
- agentMessageAcceptingTargets: Set<string>;
- runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;
+ promptAdmissions: Map<string, unknown>;
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
};
- internals.sessions.set(state.activeSessionId, state);
- internals.agentMessageAcceptingTargets.add(state.activeSessionId);
- await internals.runCronJob(makeCronJob({ id: "cron-1", source: "cron", activeSessionId: state.activeSessionId }));
+ await internals.handleLine(
+ client,
+ JSON.stringify({
+ type: "prompt",
+ activeSessionId: "active-1",
+ message: "unauthorized",
+ admissionId: "leaked-admission",
+ }),
+ );
- expect(followUp).toHaveBeenCalledWith("heartbeat prompt", undefined, { resumeIfIdle: true });
- expect(prompt).not.toHaveBeenCalled();
+ expect(end).toHaveBeenCalledOnce();
+ expect(internals.promptAdmissions.size).toBe(0);
});
- it("defers heartbeat cron jobs while an accepted agent message prompt is in flight", async () => {
- const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
+ it("clears prompt admission when restart fencing rejects before dispatch", async () => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-worker-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
throw new Error("unexpected runtime creation");
},
});
- const prompt = vi.fn(async () => {});
- const followUp = vi.fn(async () => true);
- const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- isBashRunning: boolean;
- hasAcceptedPromptInFlight: boolean;
- pendingMessageCount: number;
- prompt: typeof prompt;
- followUp: typeof followUp;
- };
- };
+ const client = makeClient("client", "active-1");
+ client.socket = { destroyed: false, write: vi.fn(() => true), end: vi.fn() } as unknown as Socket;
+ const internals = daemon as unknown as {
+ promptAdmissions: Map<string, unknown>;
+ updateRestart: { phase: "fencing" };
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
};
- state.runtime.session = {
- isStreaming: false,
- isBashRunning: false,
- hasAcceptedPromptInFlight: true,
- pendingMessageCount: 0,
- prompt,
- followUp,
- } as never;
- (daemon as unknown as { sessions: Map<string, ActiveSessionState> }).sessions.set(state.activeSessionId, state);
+ internals.updateRestart = { phase: "fencing" };
- const result = await (
- daemon as unknown as { runCronJob(job: AgentCronJob): Promise<"skipped" | undefined> }
- ).runCronJob(makeCronJob({ id: "heartbeat-1", source: "heartbeat", activeSessionId: state.activeSessionId }));
+ await internals.handleLine(
+ client,
+ JSON.stringify({
+ id: "prompt-1",
+ type: "prompt",
+ activeSessionId: "active-1",
+ message: "blocked",
+ admissionId: "retryable-admission",
+ }),
+ );
- expect(result).toBe("skipped");
- expect(prompt).not.toHaveBeenCalled();
- expect(followUp).not.toHaveBeenCalled();
+ expect(internals.promptAdmissions.size).toBe(0);
});
- it("queues generic cron jobs behind accepted agent message prompts", async () => {
- const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
- defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const prompt = vi.fn(async () => {});
- const followUp = vi.fn(async () => true);
- const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- hasAcceptedPromptInFlight: boolean;
- pendingMessageCount: number;
- prompt: typeof prompt;
- followUp: typeof followUp;
- };
+ it.each(["success", "late-failure", "replacement"] as const)(
+ "handles cancellation followed by supervisor-claim %s without affecting the wrong socket binding",
+ async (outcome) => {
+ const daemon = new AgentDaemon("/tmp/prime-agent-worker-test.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ worker: { authenticationToken: "worker-token" },
+ });
+ const client = makeClient("authenticated", "active-1");
+ client.authenticated = true;
+ const end = vi.fn();
+ client.socket = { destroyed: false, write: vi.fn(() => true), end } as unknown as Socket;
+ const claim = {
+ supervisorGeneration: "generation",
+ supervisorPid: process.pid,
+ supervisorSocketPath: "/tmp/supervisor.sock",
};
- };
- state.runtime.session = {
- isStreaming: false,
- hasAcceptedPromptInFlight: true,
- pendingMessageCount: 0,
- prompt,
- followUp,
- } as never;
- (daemon as unknown as { sessions: Map<string, ActiveSessionState> }).sessions.set(state.activeSessionId, state);
+ let resolveClaim!: (fingerprint: string) => void;
+ let rejectClaim!: (error: Error) => void;
+ const claimCheck = new Promise<string>((resolve, reject) => {
+ resolveClaim = resolve;
+ rejectClaim = reject;
+ });
+ const internals = daemon as unknown as {
+ promptAdmissions: Map<string, { controller?: AbortController }>;
+ supervisorClaims: Map<DaemonSocketClient, { claim: typeof claim; ownerFingerprint: string }>;
+ assertSupervisorClaimCurrent: ReturnType<typeof vi.fn>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
+ };
+ const originalBinding = { claim, ownerFingerprint: "owner" };
+ internals.supervisorClaims.set(client, originalBinding);
+ internals.assertSupervisorClaimCurrent = vi.fn(() => claimCheck);
+
+ const handling = internals.handleLine(
+ client,
+ JSON.stringify({
+ type: "prompt",
+ activeSessionId: "active-1",
+ message: "cancel during claim check",
+ admissionId: "claim-admission",
+ }),
+ );
+ await vi.waitFor(() => expect(internals.promptAdmissions.size).toBe(1));
+ await internals.handleCommand(client, {
+ type: "cancel_prompt_admission",
+ activeSessionId: "active-1",
+ admissionId: "claim-admission",
+ });
+ await handling;
- await (daemon as unknown as { runCronJob(job: AgentCronJob): Promise<"skipped" | undefined> }).runCronJob(
- makeCronJob({ id: "cron-1", source: "cron", activeSessionId: state.activeSessionId }),
- );
+ expect(internals.promptAdmissions.size).toBe(0);
+ expect(end).not.toHaveBeenCalled();
+ if (outcome === "replacement") {
+ internals.supervisorClaims.set(client, { claim: { ...claim }, ownerFingerprint: "replacement" });
+ }
+ if (outcome === "success") resolveClaim("refreshed");
+ else rejectClaim(new Error("late stale claim"));
+ await Promise.resolve();
+ await Promise.resolve();
- expect(followUp).toHaveBeenCalledWith("heartbeat prompt", undefined, { resumeIfIdle: true });
- expect(prompt).not.toHaveBeenCalled();
- });
+ if (outcome === "late-failure") {
+ expect(end).toHaveBeenCalledOnce();
+ expect(internals.supervisorClaims.has(client)).toBe(false);
+ } else {
+ expect(end).not.toHaveBeenCalled();
+ }
+ if (outcome === "success") expect(originalBinding.ownerFingerprint).toBe("owner");
+ if (outcome === "replacement")
+ expect(internals.supervisorClaims.get(client)?.ownerFingerprint).toBe("replacement");
+ },
+ );
- it("queues generic cron jobs behind pending messages", async () => {
+ it("cancels only pre-ownership prompt admission and cleans up its controller", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
throw new Error("unexpected runtime creation");
},
});
- const prompt = vi.fn(async () => {});
- const followUp = vi.fn(async () => true);
+ let promptOptions: { signal?: AbortSignal; admissionCommitted?: () => void } | undefined;
+ let rejectPrompt: ((error: Error) => void) | undefined;
+ const promptUntilAccepted = vi.fn(
+ async (_message: string, options?: { signal?: AbortSignal; admissionCommitted?: () => void }) => {
+ promptOptions = options;
+ await new Promise<void>((_resolve, reject) => {
+ rejectPrompt = reject;
+ options?.signal?.addEventListener("abort", () => reject(new Error("cancelled")), { once: true });
+ });
+ },
+ );
const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- pendingMessageCount: number;
- prompt: typeof prompt;
- followUp: typeof followUp;
- };
- };
+ runtime: ActiveSessionState["runtime"] & { session: { promptUntilAccepted: typeof promptUntilAccepted } };
};
- state.runtime.session = { isStreaming: false, pendingMessageCount: 1, prompt, followUp } as never;
- (daemon as unknown as { sessions: Map<string, ActiveSessionState> }).sessions.set(state.activeSessionId, state);
+ state.runtime = { ...state.runtime, session: { promptUntilAccepted } } as never;
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ promptAdmissions: Map<string, unknown>;
+ parseCommandAndRegisterPromptAdmission(client: DaemonSocketClient, line: string): unknown;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown> | undefined;
+ };
+ internals.sessions.set(state.activeSessionId, state);
+ const client = makeClient("client-1", state.activeSessionId);
+ client.socket = { destroyed: false, write: vi.fn(() => true) } as unknown as Socket;
- await (daemon as unknown as { runCronJob(job: AgentCronJob): Promise<"skipped" | undefined> }).runCronJob(
- makeCronJob({ id: "cron-1", source: "cron", activeSessionId: state.activeSessionId }),
+ internals.parseCommandAndRegisterPromptAdmission(
+ client,
+ JSON.stringify({
+ type: "prompt",
+ activeSessionId: state.activeSessionId,
+ message: "blocked",
+ admissionId: "admission-1",
+ }),
);
-
- expect(followUp).toHaveBeenCalledWith("heartbeat prompt", undefined, { resumeIfIdle: true });
- expect(prompt).not.toHaveBeenCalled();
+ internals.handleCommand(client, {
+ id: "prompt-1",
+ type: "prompt",
+ activeSessionId: state.activeSessionId,
+ message: "blocked",
+ admissionId: "admission-1",
+ });
+ await vi.waitFor(() => expect(promptUntilAccepted).toHaveBeenCalledOnce());
+ await expect(
+ internals.handleCommand(client, {
+ id: "cancel-1",
+ type: "cancel_prompt_admission",
+ activeSessionId: state.activeSessionId,
+ admissionId: "admission-1",
+ }),
+ ).resolves.toMatchObject({ success: true, data: { status: "cancelled" } });
+ await vi.waitFor(() => expect(internals.promptAdmissions.size).toBe(0));
+
+ // Once ownership commits the same cancellation is a no-op.
+ internals.parseCommandAndRegisterPromptAdmission(
+ client,
+ JSON.stringify({
+ type: "prompt",
+ activeSessionId: state.activeSessionId,
+ message: "owned",
+ admissionId: "admission-2",
+ }),
+ );
+ internals.handleCommand(client, {
+ id: "prompt-2",
+ type: "prompt",
+ activeSessionId: state.activeSessionId,
+ message: "owned",
+ admissionId: "admission-2",
+ });
+ await vi.waitFor(() => expect(promptUntilAccepted).toHaveBeenCalledTimes(2));
+ promptOptions?.admissionCommitted?.();
+ await expect(
+ internals.handleCommand(client, {
+ id: "cancel-2",
+ type: "cancel_prompt_admission",
+ activeSessionId: state.activeSessionId,
+ admissionId: "admission-2",
+ }),
+ ).resolves.toMatchObject({ success: true, data: { status: "owned" } });
+ rejectPrompt?.(new Error("test cleanup"));
});
- it("delivers heartbeats with a steering behavior by default", async () => {
+ it("settles cancellation while prompt routing waits on the target lock", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
throw new Error("unexpected runtime creation");
},
});
- const prompt = vi.fn(async () => {});
- const promptHeartbeat = vi.fn(
- async (
- _job: AgentCronJob,
- _options?: { streamingBehavior?: "steer" | "followUp"; followUpQueueKey?: string },
- ) => {},
- );
- const followUp = vi.fn(async () => true);
- const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- isBashRunning: boolean;
- pendingMessageCount: number;
- prompt: typeof prompt;
- promptHeartbeat: typeof promptHeartbeat;
- followUp: typeof followUp;
- };
- };
+ const promptUntilAccepted = vi.fn(async () => {});
+ const state = makeState("active-lock") as ActiveSessionState;
+ state.runtime = { ...state.runtime, session: { promptUntilAccepted } } as never;
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ agentMessageTargetLocks: Map<string, Promise<void>>;
+ promptAdmissions: Map<string, unknown>;
+ parseCommandAndRegisterPromptAdmission(client: DaemonSocketClient, line: string): unknown;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown> | undefined;
};
- state.runtime.session = {
- isStreaming: false,
- isBashRunning: false,
- pendingMessageCount: 0,
- prompt,
- promptHeartbeat,
- followUp,
- } as never;
- (daemon as unknown as { sessions: Map<string, ActiveSessionState> }).sessions.set(state.activeSessionId, state);
-
- await (daemon as unknown as { runCronJob(job: AgentCronJob): Promise<"skipped" | undefined> }).runCronJob(
- makeCronJob({ id: "heartbeat-1", source: "heartbeat", activeSessionId: state.activeSessionId }),
- );
-
- // The preparing guard adds an internal preflightResult hook.
- expect(promptHeartbeat).toHaveBeenCalledWith(
- expect.objectContaining({ id: "heartbeat-1", prompt: "heartbeat prompt" }),
- expect.objectContaining({
- streamingBehavior: "steer",
- source: "rpc",
+ internals.sessions.set(state.activeSessionId, state);
+ internals.agentMessageTargetLocks.set(state.activeSessionId, new Promise(() => {}));
+ const client = makeClient("client-lock", state.activeSessionId);
+ client.socket = { destroyed: false, write: vi.fn(() => true) } as unknown as Socket;
+ internals.parseCommandAndRegisterPromptAdmission(
+ client,
+ JSON.stringify({
+ type: "prompt",
+ activeSessionId: state.activeSessionId,
+ message: "blocked",
+ admissionId: "lock-admission",
}),
);
- expect(promptHeartbeat.mock.calls[0]?.[1]).toMatchObject({ followUpQueueKey: "heartbeat:heartbeat-1" });
- expect(prompt).not.toHaveBeenCalled();
- expect(followUp).not.toHaveBeenCalled();
+ internals.handleCommand(client, {
+ type: "prompt",
+ activeSessionId: state.activeSessionId,
+ message: "blocked",
+ admissionId: "lock-admission",
+ });
+ await expect(
+ internals.handleCommand(client, {
+ type: "cancel_prompt_admission",
+ activeSessionId: state.activeSessionId,
+ admissionId: "lock-admission",
+ }),
+ ).resolves.toMatchObject({ data: { status: "cancelled" } });
+ await vi.waitFor(() => expect(internals.promptAdmissions.size).toBe(0));
+ expect(promptUntilAccepted).not.toHaveBeenCalled();
});
- it("delivers steer heartbeats after an RPC prompt finishes preflight while its turn is still streaming", async () => {
+ it("aborts waiting prompt admissions when their session closes", () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
throw new Error("unexpected runtime creation");
},
});
- let releasePrompt = () => {};
- const promptFinished = new Promise<void>((resolve) => {
- releasePrompt = resolve;
- });
- let reportPromptStarted = () => {};
- const promptStarted = new Promise<void>((resolve) => {
- reportPromptStarted = resolve;
- });
- const sessionState = {
- isStreaming: false,
- isBashRunning: false,
- pendingMessageCount: 0,
- };
- const prompt = vi.fn(async (_message: string, options?: { preflightResult?: (didSucceed: boolean) => void }) => {
- sessionState.isStreaming = true;
- options?.preflightResult?.(true);
- reportPromptStarted();
- await promptFinished;
- });
- const promptHeartbeat = vi.fn(
- async (
- _job: AgentCronJob,
- options?: { streamingBehavior?: "steer" | "followUp"; preflightResult?: (didSucceed: boolean) => void },
- ) => {
- options?.preflightResult?.(true);
- },
- );
- const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: typeof sessionState & {
- prompt: typeof prompt;
- promptHeartbeat: typeof promptHeartbeat;
- };
- };
- };
- state.runtime.session = Object.assign(sessionState, { prompt, promptHeartbeat }) as never;
const internals = daemon as unknown as {
- sessions: Map<string, ActiveSessionState>;
- agentMessagePreparingTargets: Map<string, number>;
- promptWithAgentMessagePreparingGuard(state: ActiveSessionState, message: string): Promise<void>;
- runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;
+ promptAdmissions: Map<string, { status: string; controller?: AbortController }>;
+ parseCommandAndRegisterPromptAdmission(client: DaemonSocketClient, line: string): unknown;
+ abortWaitingPromptAdmissionsForSession(activeSessionId: string): void;
};
- internals.sessions.set(state.activeSessionId, state);
-
- const promptPromise = internals.promptWithAgentMessagePreparingGuard(state, "long-running prompt");
- await promptStarted;
- const preparingReleased = !internals.agentMessagePreparingTargets.has(state.activeSessionId);
- const result = await internals.runCronJob(
- makeCronJob({ id: "heartbeat-1", source: "heartbeat", activeSessionId: state.activeSessionId }),
- );
- releasePrompt();
- await promptPromise;
-
- expect(preparingReleased).toBe(true);
- expect(result).toBeUndefined();
- expect(promptHeartbeat).toHaveBeenCalledWith(
- expect.objectContaining({ id: "heartbeat-1" }),
- expect.objectContaining({ streamingBehavior: "steer" }),
+ const client = makeClient("client-closing", "closing-session");
+ internals.parseCommandAndRegisterPromptAdmission(
+ client,
+ JSON.stringify({
+ type: "prompt",
+ activeSessionId: "closing-session",
+ message: "blocked",
+ admissionId: "closing-admission",
+ }),
);
+ const admission = [...internals.promptAdmissions.values()][0]!;
+ internals.abortWaitingPromptAdmissionsForSession("closing-session");
+ expect(admission.status).toBe("cancelled");
+ expect(admission.controller?.signal.aborted).toBe(true);
});
- it("delivers follow-up heartbeats with a followUp behavior and coalescing key", async () => {
+ it("uses the queued default lane for old-client prompts on a new daemon", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
throw new Error("unexpected runtime creation");
},
});
- const prompt = vi.fn(async () => {});
- const promptHeartbeat = vi.fn(async () => {});
- const followUp = vi.fn(async () => true);
+ const promptUntilAccepted = vi.fn(async () => {});
const state = makeState("active-1") as ActiveSessionState & {
- runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- isBashRunning: boolean;
- pendingMessageCount: number;
- prompt: typeof prompt;
- promptHeartbeat: typeof promptHeartbeat;
- followUp: typeof followUp;
- };
- };
+ runtime: ActiveSessionState["runtime"] & { session: { promptUntilAccepted: typeof promptUntilAccepted } };
};
- state.runtime.session = {
- isStreaming: false,
- isBashRunning: false,
- pendingMessageCount: 0,
- prompt,
- promptHeartbeat,
- followUp,
- } as never;
- (daemon as unknown as { sessions: Map<string, ActiveSessionState> }).sessions.set(state.activeSessionId, state);
+ state.runtime = { ...state.runtime, session: { promptUntilAccepted } } as never;
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown> | undefined;
+ };
+ internals.sessions.set(state.activeSessionId, state);
+ const client = makeClient("legacy-client", state.activeSessionId);
+ const write = vi.fn((_data: unknown) => true);
+ client.socket = { destroyed: false, write } as unknown as Socket;
- await (daemon as unknown as { runCronJob(job: AgentCronJob): Promise<"skipped" | undefined> }).runCronJob(
- makeCronJob({
- id: "heartbeat-1",
- source: "heartbeat",
- activeSessionId: state.activeSessionId,
- deliveryMode: "follow_up",
- }),
- );
+ internals.handleCommand(client, {
+ id: "command-1",
+ type: "prompt",
+ activeSessionId: state.activeSessionId,
+ message: "legacy prompt",
+ streamingBehavior: "followUp",
+ });
- // The preparing guard adds an internal preflightResult hook.
- expect(promptHeartbeat).toHaveBeenCalledWith(
- expect.objectContaining({ id: "heartbeat-1", prompt: "heartbeat prompt" }),
- expect.objectContaining({
- streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:heartbeat-1",
- source: "rpc",
- }),
+ await vi.waitFor(() => expect(write).toHaveBeenCalledOnce());
+ expect(JSON.parse(String(write.mock.calls[0]?.[0]))).toMatchObject({ success: true, command: "prompt" });
+ expect(promptUntilAccepted).toHaveBeenCalledWith(
+ "legacy prompt",
+ expect.objectContaining({ streamingBehavior: "followUp", queueIfBusy: true }),
);
- expect(prompt).not.toHaveBeenCalled();
- expect(followUp).not.toHaveBeenCalled();
});
- it("prompts idle generic cron jobs without a heartbeat coalescing key", async () => {
+ it("routes resume_queue through the session scheduler", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
throw new Error("unexpected runtime creation");
},
});
- const prompt = vi.fn(
- async (
- _message: string,
- _options?: { streamingBehavior?: "steer" | "followUp"; followUpQueueKey?: string; source?: string },
- ) => {},
- );
- const followUp = vi.fn(async () => true);
+ const resumeQueuedWork = vi.fn(() => true);
+ const continueAgent = vi.fn(async () => {});
const state = makeState("active-1") as ActiveSessionState & {
runtime: ActiveSessionState["runtime"] & {
- session: {
- isStreaming: boolean;
- isBashRunning: boolean;
- pendingMessageCount: number;
- prompt: typeof prompt;
- followUp: typeof followUp;
- };
+ session: { resumeQueuedWork: typeof resumeQueuedWork; agent: { continue: typeof continueAgent } };
};
};
- state.runtime.session = {
- isStreaming: false,
- isBashRunning: false,
- pendingMessageCount: 0,
- prompt,
- followUp,
- } as never;
- (daemon as unknown as { sessions: Map<string, ActiveSessionState> }).sessions.set(state.activeSessionId, state);
-
- await (daemon as unknown as { runCronJob(job: AgentCronJob): Promise<"skipped" | undefined> }).runCronJob(
- makeCronJob({ id: "cron-1", source: "cron", activeSessionId: state.activeSessionId }),
- );
+ state.runtime = { ...state.runtime, session: { resumeQueuedWork, agent: { continue: continueAgent } } } as never;
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
+ };
+ internals.sessions.set(state.activeSessionId, state);
- // The preparing guard adds an internal preflightResult hook.
- expect(prompt).toHaveBeenCalledWith(
- "heartbeat prompt",
- expect.objectContaining({
- streamingBehavior: "followUp",
- source: "rpc",
+ await expect(
+ internals.handleCommand(makeClient("client-1", state.activeSessionId), {
+ id: "command-1",
+ type: "resume_queue",
+ activeSessionId: state.activeSessionId,
}),
- );
- expect(prompt.mock.calls[0]?.[1]).not.toHaveProperty("followUpQueueKey");
- expect(followUp).not.toHaveBeenCalled();
+ ).resolves.toMatchObject({ success: true, command: "resume_queue" });
+ expect(resumeQueuedWork).toHaveBeenCalledOnce();
+ expect(continueAgent).not.toHaveBeenCalled();
});
- it("forwards queue keys when expanded daemon steer commands are queued", async () => {
+ it.each(["steer", "follow_up"] as const)("routes correlated daemon %s commands", async (type) => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
createRuntime: async () => {
@@ -5070,37 +5136,90 @@ describe("daemon mode helpers", () => {
},
});
const steer = vi.fn(async () => {});
+ const followUp = vi.fn(async () => true);
const restoreSteeringMessage = vi.fn(async () => {});
+ const restoreFollowUpMessage = vi.fn(async () => true);
const state = makeState("active-1") as ActiveSessionState & {
runtime: ActiveSessionState["runtime"] & {
session: {
steer: typeof steer;
+ followUp: typeof followUp;
restoreSteeringMessage: typeof restoreSteeringMessage;
+ restoreFollowUpMessage: typeof restoreFollowUpMessage;
};
};
};
- state.runtime.session = { steer, restoreSteeringMessage } as never;
+ state.runtime.session = { steer, followUp, restoreSteeringMessage, restoreFollowUpMessage } as never;
const internals = daemon as unknown as {
sessions: Map<string, ActiveSessionState>;
handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;
};
internals.sessions.set(state.activeSessionId, state);
+ const client = makeClient("client-1", state.activeSessionId);
+ const base = { type, activeSessionId: state.activeSessionId } as const;
- await internals.handleCommand(makeClient("client-1", state.activeSessionId), {
- id: "command-1",
- type: "steer",
- activeSessionId: state.activeSessionId,
- message: "queued heartbeat",
- queueKey: "heartbeat:job-1",
- agentMessageId: "agentmsg_steer",
+ await internals.handleCommand(client, {
+ ...base,
+ message: "expanded prompt",
+ queueKey: "heartbeat:expanded",
+ agentMessageId: `agentmsg_expanded_${type}`,
+ });
+ const queue = type === "steer" ? steer : followUp;
+ expect(queue).toHaveBeenCalledWith("expanded prompt", undefined, {
+ queueKey: "heartbeat:expanded",
+ agentMessageId: `agentmsg_expanded_${type}`,
+ resumeIfIdle: true,
});
- expect(steer).toHaveBeenCalledWith("queued heartbeat", undefined, {
+ const replayFields = {
+ content: [{ type: "text" as const, text: "restored content" }],
+ customMessage: {
+ role: "custom" as const,
+ customType: "restored",
+ content: "restored custom message",
+ display: false,
+ timestamp: 1,
+ },
+ prefixMessages: [
+ {
+ role: "custom" as const,
+ customType: "restored-prefix",
+ content: "restored prefix",
+ display: false,
+ timestamp: 1,
+ },
+ ],
+ };
+ for (const expandPromptTemplates of [undefined, true]) {
+ await expect(
+ internals.handleCommand(client, {
+ ...base,
+ message: "invalid replay",
+ expandPromptTemplates,
+ ...replayFields,
+ }),
+ ).rejects.toThrow("require expandPromptTemplates=false");
+ }
+
+ await internals.handleCommand(client, {
+ ...base,
+ message: "restored prompt",
queueKey: "heartbeat:job-1",
- agentMessageId: "agentmsg_steer",
- resumeIfIdle: true,
+ agentMessageId: `agentmsg_${type}`,
+ expandPromptTemplates: false,
+ ...replayFields,
});
- expect(restoreSteeringMessage).not.toHaveBeenCalled();
+ const restore = type === "steer" ? restoreSteeringMessage : restoreFollowUpMessage;
+ expect(restore).toHaveBeenCalledWith("restored prompt", undefined, {
+ queueKey: "heartbeat:job-1",
+ agentMessageId: `agentmsg_${type}`,
+ ...replayFields,
+ });
+ expect(queue).toHaveBeenCalledOnce();
+
+ await expect(
+ internals.handleCommand(client, { ...base, message: "invalid", agentMessageId: "" }),
+ ).rejects.toThrow("agentMessageId must not be empty");
});
it("rejects invalid heartbeat delivery modes before persisting", async () => {
@@ -5597,6 +5716,79 @@ describe("daemon mode helpers", () => {
});
});
+type CronAdmissionActivity = Partial<{
+ isStreaming: boolean;
+ isCompacting: boolean;
+ isRetrying: boolean;
+ isBashRunning: boolean;
+ hasAcceptedPromptInFlight: boolean;
+ pendingMessageCount: number;
+}>;
+
+function makeCronAdmissionFixture(
+ activity: CronAdmissionActivity = {},
+ options: { acceptingAgentMessage?: boolean } = {},
+) {
+ const activeSessionId = "active-1";
+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const prompt = vi.fn(
+ async (
+ _message: string,
+ _options?: { streamingBehavior?: "steer" | "followUp"; followUpQueueKey?: string; source?: string },
+ ) => {},
+ );
+ const promptHeartbeat = vi.fn(
+ async (
+ _job: AgentCronJob,
+ _options?: { streamingBehavior?: "steer" | "followUp"; followUpQueueKey?: string; source?: string },
+ ) => {},
+ );
+ const followUp = vi.fn(async () => true);
+ const removeQueuedFollowUp = vi.fn(() => true);
+ const state = makeState(activeSessionId) as ActiveSessionState & {
+ runtime: ActiveSessionState["runtime"] & { session: Record<string, unknown> };
+ };
+ state.runtime = {
+ ...state.runtime,
+ session: {
+ isStreaming: false,
+ isCompacting: false,
+ isRetrying: false,
+ isBashRunning: false,
+ hasAcceptedPromptInFlight: false,
+ pendingMessageCount: 0,
+ ...activity,
+ prompt,
+ promptHeartbeat,
+ followUp,
+ removeQueuedFollowUp,
+ },
+ } as never;
+ const internals = daemon as unknown as {
+ sessions: Map<string, ActiveSessionState>;
+ agentMessageAcceptingTargets: Set<string>;
+ runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;
+ };
+ internals.sessions.set(activeSessionId, state);
+ if (options.acceptingAgentMessage) {
+ internals.agentMessageAcceptingTargets.add(activeSessionId);
+ }
+
+ return {
+ activeSessionId,
+ prompt,
+ promptHeartbeat,
+ followUp,
+ removeQueuedFollowUp,
+ runCronJob: internals.runCronJob.bind(daemon),
+ };
+}
+
function makeCronJob(input: {
id: string;
source: AgentCronJob["source"];
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index 15d23f6385..8509ec7426 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -36,7 +36,7 @@ describe("daemon protocol helpers", () => {
});
it("requires compatibility metadata for the heartbeat protocol surface", () => {
- expect(DAEMON_PROTOCOL_VERSION).toBe(4);
+ expect(DAEMON_PROTOCOL_VERSION).toBe(5);
expect(DAEMON_SCHEMA_ID).toContain(`protocol-${DAEMON_PROTOCOL_VERSION}`);
expect(DAEMON_COMMAND_COMPATIBILITY.heartbeats_list).toEqual({
minProtocol: 3,
@@ -47,7 +47,7 @@ describe("daemon protocol helpers", () => {
capability: "heartbeat_management",
});
expect(DAEMON_COMMAND_COMPATIBILITY.complete_owned_session).toEqual({
- minProtocol: DAEMON_PROTOCOL_VERSION,
+ minProtocol: 4,
capability: "client_owned_sessions",
});
expect(DAEMON_OUTBOUND_COMPATIBILITY.heartbeats_changed).toEqual({
@@ -67,6 +67,15 @@ describe("daemon protocol helpers", () => {
expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("model_catalog");
});
+ it("version- and capability-gates prompt admission cancellation", () => {
+ expect(DAEMON_COMMAND_COMPATIBILITY.cancel_prompt_admission).toEqual({
+ minProtocol: 5,
+ minSchemaRevision: 6,
+ capability: "prompt_admission_cancellation",
+ });
+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("prompt_admission_cancellation");
+ });
+
it("keeps refine failure events backward-compatible on the existing session event channel", () => {
const event: DaemonOutbound = {
type: "session_event",
@@ -74,8 +83,8 @@ describe("daemon protocol helpers", () => {
event: { type: "refine_failed", error: "disk full" },
};
- // Revision 3 introduced the refine events; later features moved it further.
- expect(DAEMON_SCHEMA_REVISION).toBeGreaterThanOrEqual(3);
+ // 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(event).toMatchObject({ event: { type: "refine_failed", error: "disk full" } });
});
diff --git a/packages/coding-agent/test/daemon-supervisor-admission.test.ts b/packages/coding-agent/test/daemon-supervisor-admission.test.ts
new file mode 100644
index 0000000000..784403e7a2
--- /dev/null
+++ b/packages/coding-agent/test/daemon-supervisor-admission.test.ts
@@ -0,0 +1,602 @@
+import type { Socket } from "node:net";
+import { PassThrough } from "node:stream";
+import { describe, expect, it, vi } from "vitest";
+import type { DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
+import {
+ createDaemonCommandEnvelope,
+ type DaemonCommand,
+ type DaemonResponse,
+ success,
+} from "../src/modes/daemon/daemon-protocol.js";
+import { DaemonSupervisor, waitForSupervisorPromptAdmission } from "../src/modes/daemon/daemon-supervisor.js";
+import { MutationDrainLatch } from "../src/modes/daemon/mutation-drain-latch.js";
+
+interface AdmissionRecord {
+ client: DaemonSocketClient;
+ activeSessionId: string;
+ publicAdmissionId: string;
+ workerAdmissionId: string;
+ status: "waiting" | "owned" | "cancelled";
+ controller: AbortController;
+ worker?: unknown;
+ workerActiveSessionId?: string;
+}
+
+interface SupervisorHarness {
+ handleConnection(socket: Socket): void;
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
+ clients: Set<DaemonSocketClient>;
+ promptAdmissions: Map<DaemonSocketClient, Map<string, AdmissionRecord>>;
+}
+
+interface Deferred<T> {
+ promise: Promise<T>;
+ resolve(value: T): void;
+ reject(error: unknown): void;
+}
+
+function deferred<T>(): Deferred<T> {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+function client(id: string): DaemonSocketClient {
+ return { id, attachedActiveSessionIds: new Set(), capabilities: new Set() } as DaemonSocketClient;
+}
+
+function admissionFor(supervisor: SupervisorHarness, owner: DaemonSocketClient): AdmissionRecord | undefined {
+ return [...(supervisor.promptAdmissions.get(owner)?.values() ?? [])][0];
+}
+
+async function waitFor(predicate: () => boolean): Promise<void> {
+ for (let index = 0; index < 50; index++) {
+ if (predicate()) return;
+ await Promise.resolve();
+ }
+ throw new Error("Condition was not reached");
+}
+
+function createHarness(
+ options: {
+ ready?: Promise<void>;
+ assertCurrent?: () => Promise<void>;
+ findWorker?: (client: DaemonSocketClient, selector: string) => Promise<unknown>;
+ forwardToWorker?: (worker: unknown, command: DaemonCommand) => Promise<DaemonResponse>;
+ commandJournal?: {
+ lookup: ReturnType<typeof vi.fn>;
+ begin: ReturnType<typeof vi.fn>;
+ recordResult: ReturnType<typeof vi.fn>;
+ acknowledge: ReturnType<typeof vi.fn>;
+ };
+ updateRestartPhase?: "draining" | "fencing" | "prepared";
+ } = {},
+): SupervisorHarness {
+ return Object.assign(Object.create(DaemonSupervisor.prototype), {
+ ready: options.ready ?? Promise.resolve(),
+ ownership: {
+ assertCurrent: options.assertCurrent ?? vi.fn(async () => undefined),
+ record: { token: "test-owner", processStartId: "test-process", socketPath: "/tmp/test.sock" },
+ },
+ workers: new Map(),
+ clients: new Set(),
+ protocolClientIds: new WeakMap(),
+ promptAdmissions: new Map(),
+ mutationDrain: new MutationDrainLatch(),
+ commandJournal: options.commandJournal ?? {
+ lookup: vi.fn(() => undefined),
+ begin: vi.fn(() => ({ status: "new" })),
+ recordResult: vi.fn(),
+ acknowledge: vi.fn(),
+ },
+ updateRestartPhase: options.updateRestartPhase,
+ findWorkerForClient: options.findWorker,
+ forwardToWorker: options.forwardToWorker,
+ write: vi.fn(),
+ log: vi.fn(),
+ }) as SupervisorHarness;
+}
+
+describe("daemon supervisor prompt admission ownership", () => {
+ it("observes an already-running promise when admission is pre-aborted", async () => {
+ const abort = new AbortController();
+ abort.abort();
+ const work = Promise.reject(new Error("late failure"));
+
+ await expect(waitForSupervisorPromptAdmission(work, abort.signal)).rejects.toThrow(
+ "Prompt admission was cancelled",
+ );
+ await Promise.resolve();
+ });
+
+ it("registers a prompt synchronously before readiness and ownership awaits", async () => {
+ const ready = deferred<void>();
+ const ownership = deferred<void>();
+ const workerLookup = deferred<unknown>();
+ const supervisor = createHarness({
+ ready: ready.promise,
+ assertCurrent: () => ownership.promise,
+ findWorker: vi.fn(() => workerLookup.promise),
+ });
+ const owner = client("connection-owner");
+ const prompt = {
+ id: "prompt-1",
+ type: "prompt",
+ activeSessionId: "session-1",
+ admissionId: "public-admission",
+ message: "hello",
+ } satisfies DaemonCommand;
+
+ const pendingPrompt = supervisor.handleLine(owner, JSON.stringify(prompt));
+ const admission = admissionFor(supervisor, owner);
+ expect(admission).toMatchObject({
+ client: owner,
+ activeSessionId: "session-1",
+ publicAdmissionId: "public-admission",
+ status: "waiting",
+ });
+
+ ready.resolve();
+ await Promise.resolve();
+ expect(admissionFor(supervisor, owner)).toBe(admission);
+ ownership.resolve();
+ await Promise.resolve();
+ expect(admissionFor(supervisor, owner)).toBe(admission);
+ workerLookup.reject(new Error("worker lookup stopped"));
+ await pendingPrompt;
+ expect(admissionFor(supervisor, owner)).toBeUndefined();
+ });
+
+ it("cleans up restart-fenced prompt admissions so the same id can retry", async () => {
+ const supervisor = createHarness();
+ (supervisor as unknown as { updateRestartPhase: "fencing" }).updateRestartPhase = "fencing";
+ const owner = client("connection-owner");
+ const prompt = {
+ id: "prompt-1",
+ type: "prompt",
+ activeSessionId: "session-1",
+ admissionId: "retryable-admission",
+ message: "hello",
+ } satisfies DaemonCommand;
+
+ await supervisor.handleLine(owner, JSON.stringify(prompt));
+ expect(supervisor.promptAdmissions.size).toBe(0);
+
+ await supervisor.handleLine(owner, JSON.stringify({ ...prompt, id: "prompt-2" }));
+ expect(supervisor.promptAdmissions.size).toBe(0);
+ });
+
+ it("rejects restart-fenced cancellation before mutating its admission", async () => {
+ const supervisor = createHarness({ updateRestartPhase: "fencing" });
+ const owner = client("connection-owner");
+ const admission: AdmissionRecord = {
+ client: owner,
+ activeSessionId: "session-1",
+ publicAdmissionId: "public-admission",
+ workerAdmissionId: "worker-admission",
+ status: "waiting",
+ controller: new AbortController(),
+ };
+ supervisor.promptAdmissions.set(owner, new Map([["session-1\0public-admission", admission]]));
+
+ await supervisor.handleLine(
+ owner,
+ JSON.stringify({
+ id: "cancel-1",
+ type: "cancel_prompt_admission",
+ activeSessionId: "session-1",
+ admissionId: "public-admission",
+ } satisfies DaemonCommand),
+ );
+
+ expect(admission.status).toBe("waiting");
+ expect(admission.controller.signal.aborted).toBe(false);
+ });
+
+ it("admits only one concurrent mutation with the same journal identity", async () => {
+ let begun = false;
+ const commandJournal = {
+ lookup: vi.fn(() => undefined),
+ begin: vi.fn(() => {
+ if (begun) return { status: "pending" as const };
+ begun = true;
+ return { status: "new" as const };
+ }),
+ recordResult: vi.fn(),
+ acknowledge: vi.fn(),
+ };
+ const forward = deferred<DaemonResponse>();
+ const supervisor = createHarness({
+ commandJournal,
+ findWorker: vi.fn(async () => ({
+ worker: { descriptor: { lifecycle: "ready", rootActiveSessionId: "session-1" } },
+ summary: { id: "session-1", activeSessionId: "session-1" },
+ })),
+ forwardToWorker: vi.fn(() => forward.promise),
+ });
+ const owner = client("connection-owner");
+ const command = createDaemonCommandEnvelope(
+ { id: "prompt-1", type: "prompt", activeSessionId: "session-1", message: "hello" },
+ "prompt-1",
+ "logical-client",
+ );
+
+ const first = supervisor.handleLine(owner, JSON.stringify(command));
+ const second = supervisor.handleLine(owner, JSON.stringify(command));
+ await waitFor(() => commandJournal.begin.mock.calls.length === 2);
+ expect(
+ (supervisor as unknown as { forwardToWorker: ReturnType<typeof vi.fn> }).forwardToWorker,
+ ).toHaveBeenCalledOnce();
+ forward.resolve({ type: "response", command: "prompt", success: true });
+ await Promise.all([first, second]);
+ });
+
+ it("lets the originating connection cancel before worker lookup starts", async () => {
+ const ready = deferred<void>();
+ const findWorker = vi.fn(async () => {
+ throw new Error("worker lookup should not run");
+ });
+ const supervisor = createHarness({ ready: ready.promise, findWorker });
+ const owner = client("connection-owner");
+ const pendingPrompt = supervisor.handleLine(
+ owner,
+ JSON.stringify({
+ id: "prompt-1",
+ type: "prompt",
+ activeSessionId: "session-1",
+ admissionId: "public-admission",
+ message: "hello",
+ } satisfies DaemonCommand),
+ );
+ const pendingCancel = supervisor.handleLine(
+ owner,
+ JSON.stringify({
+ id: "cancel-1",
+ type: "cancel_prompt_admission",
+ activeSessionId: "session-1",
+ admissionId: "public-admission",
+ } satisfies DaemonCommand),
+ );
+
+ await pendingPrompt;
+ expect(findWorker).not.toHaveBeenCalled();
+ ready.resolve();
+ await pendingCancel;
+ expect(admissionFor(supervisor, owner)).toBeUndefined();
+ });
+
+ it("returns the captured outcome when cancellation handling follows prompt cleanup", async () => {
+ const cancelOwnership = deferred<void>();
+ let ownershipChecks = 0;
+ const workerPrompt = deferred<DaemonResponse>();
+ const worker = { descriptor: { lifecycle: "ready", rootActiveSessionId: "worker-session" } };
+ const supervisor = createHarness({
+ assertCurrent: () => (++ownershipChecks === 1 ? Promise.resolve() : cancelOwnership.promise),
+ findWorker: vi.fn(async () => ({
+ worker,
+ summary: { id: "worker-session", activeSessionId: "worker-session" },
+ })),
+ forwardToWorker: vi.fn(async () => workerPrompt.promise),
+ });
+ const owner = client("connection-owner");
+ const pendingPrompt = supervisor.handleLine(
+ owner,
+ JSON.stringify({
+ id: "prompt-1",
+ type: "prompt",
+ activeSessionId: "session-1",
+ admissionId: "public-admission",
+ message: "hello",
+ } satisfies DaemonCommand),
+ );
+ await waitFor(() => admissionFor(supervisor, owner)?.worker !== undefined);
+ const pendingCancel = supervisor.handleLine(
+ owner,
+ JSON.stringify({
+ id: "cancel-1",
+ type: "cancel_prompt_admission",
+ activeSessionId: "session-1",
+ admissionId: "public-admission",
+ } satisfies DaemonCommand),
+ );
+ workerPrompt.resolve({ type: "response", command: "prompt", success: true });
+ await pendingPrompt;
+ expect(admissionFor(supervisor, owner)).toBeUndefined();
+ cancelOwnership.resolve();
+ await pendingCancel;
+
+ expect((supervisor as unknown as { write: ReturnType<typeof vi.fn> }).write).toHaveBeenLastCalledWith(
+ owner,
+ expect.objectContaining({ success: true, data: { status: "owned" } }),
+ );
+ });
+
+ it("never downgrades a cancelled admission on repeated cancels", async () => {
+ const worker = { descriptor: { lifecycle: "ready", rootActiveSessionId: "worker-session" } };
+ const forwardToWorker = vi.fn(async (_worker: unknown, command: DaemonCommand) => {
+ if (command.type === "cancel_prompt_admission") {
+ return success(command.id, command.type, { status: "unknown" as const });
+ }
+ return new Promise<DaemonResponse>(() => {});
+ });
+ const supervisor = createHarness({
+ findWorker: vi.fn(async () => ({
+ worker,
+ summary: { id: "worker-session", activeSessionId: "worker-session" },
+ })),
+ forwardToWorker,
+ });
+ const owner = client("connection-owner");
+ void supervisor.handleLine(
+ owner,
+ JSON.stringify({
+ id: "prompt-1",
+ type: "prompt",
+ activeSessionId: "session-1",
+ admissionId: "public-admission",
+ message: "hello",
+ } satisfies DaemonCommand),
+ );
+ await waitFor(() => admissionFor(supervisor, owner)?.worker !== undefined);
+ const admission = admissionFor(supervisor, owner);
+ expect(admission).toBeDefined();
+ if (!admission) throw new Error("admission not registered");
+ admission.status = "cancelled";
+
+ await supervisor.handleLine(
+ owner,
+ JSON.stringify({
+ id: "cancel-1",
+ type: "cancel_prompt_admission",
+ activeSessionId: "session-1",
+ admissionId: "public-admission",
+ } satisfies DaemonCommand),
+ );
+
+ expect(forwardToWorker).not.toHaveBeenCalledWith(
+ worker,
+ expect.objectContaining({ type: "cancel_prompt_admission" }),
+ );
+ expect(admission.status).toBe("cancelled");
+ expect((supervisor as unknown as { write: ReturnType<typeof vi.fn> }).write).toHaveBeenLastCalledWith(
+ owner,
+ expect.objectContaining({ success: true, data: { status: "cancelled" } }),
+ );
+ });
+
+ it("isolates public ids by connection and forwards only opaque worker ids", async () => {
+ const ownerA = client("connection-a");
+ const ownerB = client("connection-b");
+ const attacker = client("connection-attacker");
+ const worker = {
+ descriptor: { lifecycle: "ready", rootActiveSessionId: "worker-session" },
+ };
+ const promptResponses = new Map<string, Deferred<DaemonResponse>>();
+ const cancelResponses = new Map<string, Deferred<DaemonResponse>>();
+ const forwarded: DaemonCommand[] = [];
+ const supervisor = createHarness({
+ findWorker: vi.fn(async () => ({
+ worker,
+ summary: { id: "worker-session", activeSessionId: "worker-session" },
+ })),
+ forwardToWorker: vi.fn(async (_worker, command) => {
+ forwarded.push(command);
+ const admissionId = "admissionId" in command ? command.admissionId : undefined;
+ if (!admissionId) throw new Error("Expected an internal admission id");
+ const pending = deferred<DaemonResponse>();
+ if (command.type === "cancel_prompt_admission") cancelResponses.set(admissionId, pending);
+ else promptResponses.set(admissionId, pending);
+ return pending.promise;
+ }),
+ });
+ const makePrompt = (id: string) =>
+ ({
+ id,
+ type: "prompt",
+ activeSessionId: "public-session",
+ admissionId: "shared-public-id",
+ 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")));
+ await waitFor(() => promptResponses.size === 2);
+ const admissionA = admissionFor(supervisor, ownerA)!;
+ const admissionB = admissionFor(supervisor, ownerB)!;
+ expect(admissionA.workerAdmissionId).not.toBe(admissionB.workerAdmissionId);
+ expect([...promptResponses.keys()].sort()).toEqual(
+ [admissionA.workerAdmissionId, admissionB.workerAdmissionId].sort(),
+ );
+ expect(forwarded.filter((command) => command.type === "prompt")).toEqual([
+ expect.objectContaining({ admissionId: admissionA.workerAdmissionId }),
+ expect.objectContaining({ admissionId: admissionB.workerAdmissionId }),
+ ]);
+
+ const spoofedCancel = {
+ id: "spoofed-cancel",
+ type: "cancel_prompt_admission",
+ activeSessionId: "public-session",
+ admissionId: "shared-public-id",
+ } as const satisfies DaemonCommand;
+ await supervisor.handleLine(
+ attacker,
+ JSON.stringify(createDaemonCommandEnvelope(spoofedCancel, spoofedCancel.id, ownerA.id)),
+ );
+ expect(cancelResponses.size).toBe(0);
+ expect(admissionFor(supervisor, ownerA)).toBe(admissionA);
+ expect(admissionFor(supervisor, ownerB)).toBe(admissionB);
+
+ const pendingCancelA = supervisor.handleLine(ownerA, JSON.stringify({ ...spoofedCancel, id: "cancel-a" }));
+ await waitFor(() => cancelResponses.has(admissionA.workerAdmissionId));
+ expect(cancelResponses.has(admissionB.workerAdmissionId)).toBe(false);
+ expect(admissionFor(supervisor, ownerA)).toBe(admissionA);
+
+ cancelResponses.get(admissionA.workerAdmissionId)!.resolve({
+ id: "worker-cancel",
+ type: "response",
+ command: "cancel_prompt_admission",
+ success: true,
+ data: { status: "cancelled" },
+ });
+ await pendingCancelA;
+ // The cancel response must not discard the record while the original forward is unsettled.
+ expect(admissionFor(supervisor, ownerA)).toBe(admissionA);
+ expect(admissionA.status).toBe("cancelled");
+
+ promptResponses.get(admissionA.workerAdmissionId)!.resolve({
+ id: "worker-prompt-a",
+ type: "response",
+ command: "prompt",
+ success: false,
+ error: "Prompt admission was cancelled.",
+ });
+ await pendingA;
+ expect(admissionFor(supervisor, ownerA)).toBeUndefined();
+ expect(admissionFor(supervisor, ownerB)).toBe(admissionB);
+
+ promptResponses.get(admissionB.workerAdmissionId)!.resolve({
+ id: "worker-prompt-b",
+ type: "response",
+ command: "prompt",
+ success: true,
+ });
+ await pendingB;
+ expect(admissionFor(supervisor, ownerB)).toBeUndefined();
+ });
+
+ it("cancels a mapped waiting admission when its originating socket closes", async () => {
+ const worker = {
+ descriptor: { lifecycle: "ready", rootActiveSessionId: "worker-session" },
+ };
+ const promptResponse = deferred<DaemonResponse>();
+ const cancelResponse = deferred<DaemonResponse>();
+ const deliveredPrompt = vi.fn();
+ const forwarded: DaemonCommand[] = [];
+ const supervisor = createHarness({
+ findWorker: vi.fn(async () => ({
+ worker,
+ summary: { id: "worker-session", activeSessionId: "worker-session" },
+ })),
+ forwardToWorker: vi.fn(async (_worker, command) => {
+ forwarded.push(command);
+ if (command.type === "cancel_prompt_admission") {
+ const response = await cancelResponse.promise;
+ promptResponse.resolve({
+ type: "response",
+ command: "prompt",
+ success: false,
+ error: "Prompt admission was cancelled.",
+ });
+ return response;
+ }
+ return promptResponse.promise.then((response) => {
+ if (response.success) deliveredPrompt();
+ return response;
+ });
+ }),
+ });
+ const socket = new PassThrough() as unknown as Socket;
+ Object.assign(socket, { destroyed: false });
+ supervisor.handleConnection(socket);
+ const owner = [...supervisor.clients][0]!;
+ const pendingPrompt = supervisor.handleLine(
+ owner,
+ JSON.stringify({
+ id: "prompt-1",
+ type: "prompt",
+ activeSessionId: "public-session",
+ admissionId: "public-admission",
+ message: "must not arrive",
+ } satisfies DaemonCommand),
+ );
+ await waitFor(() => forwarded.some((command) => command.type === "prompt"));
+ const admission = admissionFor(supervisor, owner)!;
+
+ socket.emit("close");
+ await waitFor(() => forwarded.some((command) => command.type === "cancel_prompt_admission"));
+ expect(forwarded.at(-1)).toEqual({
+ type: "cancel_prompt_admission",
+ activeSessionId: "worker-session",
+ admissionId: admission.workerAdmissionId,
+ });
+ expect(admissionFor(supervisor, owner)).toBe(admission);
+
+ cancelResponse.resolve({
+ type: "response",
+ command: "cancel_prompt_admission",
+ success: true,
+ data: { status: "cancelled" },
+ });
+ await pendingPrompt;
+ expect(admission.status).toBe("cancelled");
+ expect(deliveredPrompt).not.toHaveBeenCalled();
+ expect(admissionFor(supervisor, owner)).toBeUndefined();
+ expect(forwarded.filter((command) => command.type === "prompt")).toHaveLength(1);
+ });
+
+ it("leaves an admission delivered when ownership wins before socket close", async () => {
+ const worker = {
+ descriptor: { lifecycle: "ready", rootActiveSessionId: "worker-session" },
+ };
+ const promptResponse = deferred<DaemonResponse>();
+ const deliveredPrompt = vi.fn();
+ let workerOwnsAdmission = false;
+ const forwarded: DaemonCommand[] = [];
+ const supervisor = createHarness({
+ findWorker: vi.fn(async () => ({
+ worker,
+ summary: { id: "worker-session", activeSessionId: "worker-session" },
+ })),
+ forwardToWorker: vi.fn(async (_worker, command) => {
+ forwarded.push(command);
+ if (command.type === "cancel_prompt_admission") {
+ return {
+ type: "response",
+ command: "cancel_prompt_admission",
+ success: true,
+ data: { status: workerOwnsAdmission ? "owned" : "cancelled" },
+ } satisfies DaemonResponse;
+ }
+ return promptResponse.promise.then((response) => {
+ if (response.success) deliveredPrompt();
+ return response;
+ });
+ }),
+ });
+ const socket = new PassThrough() as unknown as Socket;
+ Object.assign(socket, { destroyed: false });
+ supervisor.handleConnection(socket);
+ const owner = [...supervisor.clients][0]!;
+ const pendingPrompt = supervisor.handleLine(
+ owner,
+ JSON.stringify({
+ id: "prompt-1",
+ type: "prompt",
+ activeSessionId: "public-session",
+ admissionId: "public-admission",
+ message: "delivered",
+ } satisfies DaemonCommand),
+ );
+ await waitFor(() => forwarded.some((command) => command.type === "prompt"));
+ const admission = admissionFor(supervisor, owner)!;
+
+ workerOwnsAdmission = true;
+ socket.emit("close");
+ await waitFor(() => forwarded.some((command) => command.type === "cancel_prompt_admission"));
+ await waitFor(() => admission.status === "owned");
+ promptResponse.resolve({
+ type: "response",
+ command: "prompt",
+ success: true,
+ });
+ await pendingPrompt;
+ expect(admission.status).toBe("owned");
+ expect(deliveredPrompt).toHaveBeenCalledOnce();
+ expect(admissionFor(supervisor, owner)).toBeUndefined();
+ expect(forwarded.filter((command) => command.type === "prompt")).toHaveLength(1);
+ });
+});
diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
index 3ea552acb4..088fe32717 100644
--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
@@ -1,20 +1,28 @@
import type { ChildProcess, SpawnOptions } from "node:child_process";
+import { EventEmitter } from "node:events";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import type { Socket } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
+import { CommandRecoveryJournal } from "../src/modes/daemon/command-recovery-journal.js";
+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 type { DaemonAttachResult } from "../src/modes/daemon/daemon-protocol.js";
+import { createDaemonCommandEnvelope, 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 {
DAEMON_WORKER_STARTUP_GATE_COMMIT,
+ DAEMON_WORKER_SUPERVISOR_SOCKET_ENV,
type DaemonWorkerFrameHeader,
} from "../src/modes/daemon/daemon-worker-protocol.js";
+import { MutationDrainLatch } from "../src/modes/daemon/mutation-drain-latch.js";
import { WorkerRecoveryJournal } from "../src/modes/daemon/worker-recovery-journal.js";
import type { PrivateFrame } from "../src/modes/session-worker/private-framing.js";
+import { createDeferred } from "./suite/scheduling.js";
const workerLaunchTestState = vi.hoisted(() => ({
capture: false,
@@ -285,6 +293,214 @@ describe("daemon worker supervisor monitoring", () => {
}
});
+ it("schedules recovery when the sole supervisor fails a fence check", async () => {
+ const previousSocketPath = process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];
+ process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = "/tmp/supervisor.sock";
+ try {
+ const daemon = new AgentDaemon("/tmp/worker.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/agent", cwd: "/tmp" },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ worker: { authenticationToken: "token" },
+ });
+ const socket = Object.assign(new EventEmitter(), {
+ destroyed: false,
+ write: vi.fn(() => true),
+ end: vi.fn(function (this: EventEmitter) {
+ this.emit("close");
+ }),
+ }) as unknown as Socket;
+ const internals = daemon as unknown as {
+ clients: Set<DaemonSocketClient>;
+ supervisorClaims: Map<DaemonSocketClient, object>;
+ handleConnection(socket: Socket): void;
+ checkSupervisorFences(): Promise<void>;
+ assertSupervisorClaimCurrent: ReturnType<typeof vi.fn>;
+ scheduleSupervisorAvailabilityCheck: ReturnType<typeof vi.fn>;
+ };
+ internals.handleConnection(socket);
+ const client = [...internals.clients][0]!;
+ client.authenticated = true;
+ internals.supervisorClaims.set(client, {
+ claim: {},
+ ownerFingerprint: "old",
+ });
+ internals.assertSupervisorClaimCurrent = vi.fn(async () => {
+ throw new Error("stale fence");
+ });
+ internals.scheduleSupervisorAvailabilityCheck = vi.fn();
+
+ await internals.checkSupervisorFences();
+
+ expect(internals.supervisorClaims.has(client)).toBe(false);
+ expect(client.authenticated).toBe(true);
+ expect(internals.scheduleSupervisorAvailabilityCheck).toHaveBeenCalledOnce();
+ expect(internals.scheduleSupervisorAvailabilityCheck).toHaveBeenCalledWith("/tmp/supervisor.sock", 100);
+ } finally {
+ if (previousSocketPath === undefined) delete process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];
+ else process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSocketPath;
+ }
+ });
+
+ it("does not revoke a newer same-client claim when an older periodic fence fails", async () => {
+ const assertionReached = createDeferred<void>();
+ const assertionGate = createDeferred<void>();
+ const client = {
+ authenticated: true,
+ socket: { destroyed: false, end: vi.fn() },
+ } as unknown as DaemonSocketClient;
+ const oldClaim = { claim: {}, ownerFingerprint: "old" };
+ const newerClaim = { claim: {}, ownerFingerprint: "new" };
+ const transaction = {
+ id: Symbol("update-restart"),
+ owner: client,
+ abort: new AbortController(),
+ phase: "prepared",
+ };
+ const daemon = Object.assign(Object.create(AgentDaemon.prototype), {
+ options: { worker: { authenticationToken: "token" } },
+ supervisorClaims: new Map([[client, oldClaim]]),
+ updateRestart: transaction,
+ shuttingDown: false,
+ scheduleSupervisorFenceCheck: vi.fn(),
+ assertSupervisorClaimCurrent: vi.fn(async () => {
+ assertionReached.resolve();
+ await assertionGate.promise;
+ throw new Error("stale fence");
+ }),
+ }) as unknown as {
+ supervisorClaims: Map<DaemonSocketClient, object>;
+ updateRestart: object;
+ checkSupervisorFences(): Promise<void>;
+ };
+
+ const check = daemon.checkSupervisorFences();
+ await assertionReached.promise;
+ daemon.supervisorClaims.set(client, newerClaim);
+ assertionGate.resolve();
+ await check;
+
+ expect(daemon.supervisorClaims.get(client)).toBe(newerClaim);
+ expect(daemon.updateRestart).toBe(transaction);
+ expect(client.socket.end).not.toHaveBeenCalled();
+ });
+
+ it("does not revoke a newer same-client claim when an older command fence fails", async () => {
+ const assertionReached = createDeferred<void>();
+ const assertionGate = createDeferred<void>();
+ const client = {
+ id: "supervisor",
+ authenticated: true,
+ socket: { destroyed: false, write: vi.fn(() => true), end: vi.fn() },
+ attachedActiveSessionIds: new Set(),
+ detachInput: vi.fn(),
+ supportsExtensionUi: false,
+ capabilities: new Set(),
+ } as unknown as DaemonSocketClient;
+ const oldClaim = { claim: {}, ownerFingerprint: "old" };
+ const newerClaim = { claim: {}, ownerFingerprint: "new" };
+ const transaction = {
+ id: Symbol("update-restart"),
+ owner: client,
+ abort: new AbortController(),
+ phase: "prepared",
+ };
+ const daemon = Object.assign(Object.create(AgentDaemon.prototype), {
+ options: { worker: { authenticationToken: "token" } },
+ supervisorClaims: new Map([[client, oldClaim]]),
+ updateRestart: transaction,
+ handleWorkerCommand: vi.fn(async () => undefined),
+ assertSupervisorClaimCurrent: vi.fn(async () => {
+ assertionReached.resolve();
+ await assertionGate.promise;
+ throw new Error("stale fence");
+ }),
+ }) as unknown as {
+ supervisorClaims: Map<DaemonSocketClient, object>;
+ updateRestart: object;
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
+ };
+
+ const command = daemon.handleLine(
+ client,
+ JSON.stringify({ type: "worker_subscribe", activeSessionId: "active-1" }),
+ );
+ await assertionReached.promise;
+ daemon.supervisorClaims.set(client, newerClaim);
+ assertionGate.resolve();
+ await command;
+
+ expect(daemon.supervisorClaims.get(client)).toBe(newerClaim);
+ expect(daemon.updateRestart).toBe(transaction);
+ expect(client.socket.end).not.toHaveBeenCalled();
+ });
+
+ it("revokes an old supervisor before ending its socket when a replacement authenticates", async () => {
+ let markOldAssertionReached = () => {};
+ const oldAssertionReached = new Promise<void>((resolve) => {
+ markOldAssertionReached = resolve;
+ });
+ let releaseOldAssertion = () => {};
+ const oldAssertionGate = new Promise<void>((resolve) => {
+ releaseOldAssertion = resolve;
+ });
+ let assertionCount = 0;
+ const handleWorkerCommand = vi.fn(async () => undefined);
+ const daemon = Object.assign(Object.create(AgentDaemon.prototype), {
+ options: { worker: { authenticationToken: "token" } },
+ supervisorClaims: new Map(),
+ shuttingDown: false,
+ clearSupervisorAvailabilityCheck: vi.fn(),
+ scheduleSupervisorFenceCheck: vi.fn(),
+ handleWorkerCommand,
+ assertSupervisorClaimCurrent: vi.fn(async () => {
+ assertionCount++;
+ if (assertionCount === 2) {
+ markOldAssertionReached();
+ await oldAssertionGate;
+ }
+ return `fingerprint-${assertionCount}`;
+ }),
+ }) as unknown as {
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
+ };
+ const makeClient = () =>
+ ({
+ id: "supervisor",
+ authenticated: false,
+ socket: { destroyed: false, write: vi.fn(() => true), end: vi.fn() },
+ attachedActiveSessionIds: new Set(),
+ detachInput: vi.fn(),
+ supportsExtensionUi: false,
+ capabilities: new Set(),
+ }) as unknown as DaemonSocketClient;
+ const auth = (generation: string) =>
+ JSON.stringify({
+ type: "worker_auth",
+ token: "token",
+ supervisorGeneration: generation,
+ supervisorPid: 123,
+ supervisorSocketPath: "/tmp/supervisor.sock",
+ });
+ const oldClient = makeClient();
+ const replacementClient = makeClient();
+
+ await daemon.handleLine(oldClient, auth("old"));
+ const staleCommand = daemon.handleLine(
+ oldClient,
+ JSON.stringify({ type: "worker_subscribe", activeSessionId: "active-1" }),
+ );
+ await oldAssertionReached;
+ await daemon.handleLine(replacementClient, auth("replacement"));
+
+ expect(oldClient.authenticated).toBe(true);
+ expect(oldClient.socket.end).toHaveBeenCalledOnce();
+ releaseOldAssertion();
+ await staleCommand;
+ expect(handleWorkerCommand).not.toHaveBeenCalled();
+ });
+
it.each([
{
name: "first post-spawn ownership check",
@@ -1552,4 +1768,215 @@ describe("daemon worker supervisor monitoring", () => {
rmSync(root, { recursive: true, force: true });
}
});
+ it.each([
+ { name: "malformed data", data: undefined, error: /invalid update manifest/ },
+ { name: "missing root disposition", data: { createdAt: "now", sessions: [] }, error: /root disposition/ },
+ ])("cancels a prepare acknowledgement with $name", async ({ data, error }) => {
+ const client = {
+ requestWorker: vi.fn(async ({ type }: { type: string }) =>
+ type === "worker_prepare_update" ? { success: true, data } : { success: true },
+ ),
+ close: vi.fn(),
+ };
+ const worker = {
+ descriptor: { workerId: "worker", lifecycle: "ready", rootActiveSessionId: "root" },
+ client,
+ };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([["worker", worker]]),
+ }) as { prepareUpdateRestartFenced(): Promise<unknown> };
+ await expect(supervisor.prepareUpdateRestartFenced()).rejects.toThrow(error);
+ expect(client.requestWorker).toHaveBeenCalledWith({ type: "worker_cancel_update" }, 5000);
+ });
+
+ it("accepts an explicitly discarded empty root", async () => {
+ const client = {
+ requestWorker: vi.fn(async ({ type }: { type: string }) =>
+ type === "worker_prepare_update"
+ ? { success: true, data: { createdAt: "now", sessions: [], discardedActiveSessionIds: ["root"] } }
+ : { success: true },
+ ),
+ };
+ const worker = {
+ descriptor: { workerId: "worker", lifecycle: "ready", rootActiveSessionId: "root" },
+ client,
+ };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([["worker", worker]]),
+ validateAndPersistUpdateManifest: vi.fn(),
+ stopWorker: vi.fn(async () => undefined),
+ }) as { prepareUpdateRestartFenced(): Promise<{ discardedActiveSessionIds?: string[] }> };
+ await expect(supervisor.prepareUpdateRestartFenced()).resolves.toMatchObject({
+ discardedActiveSessionIds: ["root"],
+ });
+ });
+
+ it("replays completed journaled mutations during restart preparation without taking a mutation lease", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-supervisor-command-replay-"));
+ const commandJournal = new CommandRecoveryJournal(join(root, "commands.jsonl"));
+ const response = success("command-1", "kill");
+ commandJournal.begin("client-1", "command-1", "kill");
+ commandJournal.recordResult("client-1", "command-1", response);
+ const writes: string[] = [];
+ const client = {
+ id: "socket-client",
+ socket: {
+ destroyed: false,
+ write: vi.fn((chunk: string) => {
+ writes.push(chunk);
+ return true;
+ }),
+ },
+ } as unknown as DaemonSocketClient;
+ const mutationDrain = { begin: vi.fn(), end: vi.fn() };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ ready: Promise.resolve(),
+ workers: new Map(),
+ protocolClientIds: new WeakMap(),
+ commandJournal,
+ mutationDrain,
+ updateRestartPhase: "fencing",
+ assertCurrentOwnership: vi.fn(async () => undefined),
+ cancelOwnedWorkerCleanup: vi.fn(),
+ handleCommand: vi.fn(async () => {
+ throw new Error("completed command was dispatched again");
+ }),
+ }) as unknown as {
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
+ };
+
+ try {
+ await supervisor.handleLine(
+ client,
+ JSON.stringify(
+ createDaemonCommandEnvelope({ type: "kill", activeSessionId: "session-1" }, "command-1", "client-1"),
+ ),
+ );
+ expect(writes).toEqual([`${JSON.stringify(response)}\n`]);
+ expect(mutationDrain.begin).not.toHaveBeenCalled();
+ expect(mutationDrain.end).not.toHaveBeenCalled();
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it("rejects genuinely new mutations during restart preparation without journaling or leasing them", async () => {
+ const root = mkdtempSync(join(tmpdir(), "prime-supervisor-command-reject-"));
+ const commandJournal = new CommandRecoveryJournal(join(root, "commands.jsonl"));
+ const writes: string[] = [];
+ const client = {
+ id: "socket-client",
+ socket: {
+ destroyed: false,
+ write: vi.fn((chunk: string) => {
+ writes.push(chunk);
+ return true;
+ }),
+ },
+ } as unknown as DaemonSocketClient;
+ const mutationDrain = { begin: vi.fn(), end: vi.fn() };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ ready: Promise.resolve(),
+ workers: new Map(),
+ protocolClientIds: new WeakMap(),
+ commandJournal,
+ mutationDrain,
+ updateRestartPhase: "fencing",
+ assertCurrentOwnership: vi.fn(async () => undefined),
+ cancelOwnedWorkerCleanup: vi.fn(),
+ }) as unknown as {
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
+ };
+
+ try {
+ await supervisor.handleLine(
+ client,
+ JSON.stringify(
+ createDaemonCommandEnvelope({ type: "kill", activeSessionId: "session-1" }, "command-2", "client-1"),
+ ),
+ );
+ expect(writes.join(" ")).toContain("Daemon is preparing an update restart");
+ expect(commandJournal.lookup("client-1", "command-2")).toBeUndefined();
+ expect(mutationDrain.begin).not.toHaveBeenCalled();
+ expect(mutationDrain.end).not.toHaveBeenCalled();
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it("fences and drains a mutation admitted at the first drain boundary before worker prepare", async () => {
+ const mutationDrain = new MutationDrainLatch();
+ const firstDrain = createDeferred();
+ const originalWaitForDrain = mutationDrain.waitForDrain.bind(mutationDrain);
+ vi.spyOn(mutationDrain, "waitForDrain").mockImplementationOnce(async (...args) => {
+ await originalWaitForDrain(...args);
+ mutationDrain.begin();
+ firstDrain.resolve();
+ });
+ mutationDrain.begin(); // The prepare command itself remains in flight at the supervisor boundary.
+ const prepareFenced = vi.fn(async () => ({ createdAt: "now", sessions: [] }));
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ mutationDrain,
+ workers: new Map(),
+ prepareUpdateRestartFenced: prepareFenced,
+ }) as {
+ updateRestartPhase?: "draining" | "fencing" | "prepared";
+ prepareUpdateRestart(): Promise<unknown>;
+ };
+
+ const prepare = supervisor.prepareUpdateRestart();
+ await firstDrain.promise;
+ await Promise.resolve();
+
+ expect(supervisor.updateRestartPhase).toBe("fencing");
+ expect(prepareFenced).not.toHaveBeenCalled();
+
+ mutationDrain.end();
+ await prepare;
+ expect(prepareFenced).toHaveBeenCalledOnce();
+ mutationDrain.end();
+ });
+
+ it("limits abort admission to mutation drain", async () => {
+ const root = mkdtempSync(`/tmp/prime-update-drain-${process.pid}-`);
+ const socketPath = join(root, "supervisor.sock");
+ const supervisor = new DaemonSupervisor(socketPath, {
+ defaultSessionConfig: { cwd: root, agentDir: root },
+ descriptorDir: join(root, "workers"),
+ });
+ const client = new DaemonClient(socketPath);
+ vi.spyOn(DaemonCatalogClient.prototype, "start").mockResolvedValue();
+ try {
+ await supervisor.start();
+ await client.connect();
+ const prepare = client.request({ type: "prepare_update_restart" });
+ expect(await client.request({ type: "abort", activeSessionId: "missing" })).not.toMatchObject({
+ error: "Daemon is preparing an update restart",
+ });
+ await prepare;
+ await expect(client.request({ type: "abort", activeSessionId: "missing" })).resolves.toMatchObject({
+ error: "Daemon is preparing an update restart",
+ });
+ } finally {
+ client.close();
+ await Reflect.apply(Reflect.get(supervisor, "cleanupSupervisorResources"), supervisor, []);
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it("rejects update prepare when a resident worker is recovering or disconnected", async () => {
+ const requestWorker = vi.fn();
+ const worker = {
+ descriptor: { workerId: "resident-1", lifecycle: "recovering" },
+ client: undefined,
+ };
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ workers: new Map([["resident-1", worker]]),
+ }) as {
+ prepareUpdateRestartFenced(): Promise<unknown>;
+ };
+
+ await expect(supervisor.prepareUpdateRestartFenced()).rejects.toThrow(/resident-1.*recovering.*disconnected/);
+ expect(requestWorker).not.toHaveBeenCalled();
+ });
});
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 5005183dfc..3e4d3cb6fc 100644
--- a/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-side-question.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import type { DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
import type { DaemonCommand, 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";
interface SupervisorHarness {
handleLine(client: DaemonSocketClient, line: string): Promise<void>;
@@ -24,6 +25,7 @@ describe("daemon supervisor side-question routing", () => {
workers: new Map(),
clients: new Set(),
protocolClientIds: new WeakMap(),
+ mutationDrain: new MutationDrainLatch(),
handleCommand,
write,
log: vi.fn(),
diff --git a/packages/coding-agent/test/image-markers.test.ts b/packages/coding-agent/test/image-markers.test.ts
index 0969d309c8..32070278ab 100644
--- a/packages/coding-agent/test/image-markers.test.ts
+++ b/packages/coding-agent/test/image-markers.test.ts
@@ -5,6 +5,7 @@ import {
evictImagesToBudget,
formatImageMarker,
imageMarkerIds,
+ remapImageMarkers,
} from "../src/modes/interactive/image-markers.js";
describe("image markers", () => {
@@ -18,6 +19,16 @@ describe("image markers", () => {
expect(imageMarkerIds("no markers here")).toEqual([]);
});
+ test("imageMarkerIds ignores ids outside the safe integer range", () => {
+ expect(imageMarkerIds("[image #7] [image #9007199254740992]")).toEqual([7]);
+ });
+
+ test("remapImageMarkers replaces every spelling of the numeric id", () => {
+ expect(remapImageMarkers("[image #1] [image #01] [image #2]", new Map([[1, 7]]))).toBe(
+ "[image #7] [image #7] [image #2]",
+ );
+ });
+
test("collectMarkedImages returns images in paste order, not text order", () => {
const pending = new Map([
[1, "first"],
diff --git a/packages/coding-agent/test/interactive-mode-compaction.test.ts b/packages/coding-agent/test/interactive-mode-compaction.test.ts
index 130e1e6b28..f00bf9d1b3 100644
--- a/packages/coding-agent/test/interactive-mode-compaction.test.ts
+++ b/packages/coding-agent/test/interactive-mode-compaction.test.ts
@@ -1,101 +1,123 @@
-import { describe, expect, test, vi } from "vitest";
+import { Container } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeAll, describe, expect, test, vi } from "vitest";
import { AgentActivityTracker } from "../src/modes/interactive/agent-activity.js";
import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
+
+const handleEvent = Reflect.get(InteractiveMode.prototype, "handleEvent") as (
+ this: unknown,
+ event: Record<string, unknown>,
+) => Promise<void>;
+
+const startCompactionLoader = Reflect.get(InteractiveMode.prototype, "startCompactionLoader") as (
+ this: unknown,
+ reason: string,
+ customInstructions?: string,
+) => void;
+
+function createFakeThis(overrides: Record<string, unknown> = {}) {
+ return {
+ isInitialized: true,
+ footer: { invalidate: vi.fn() },
+ updateConnectionStateFromEvent: vi.fn(),
+ activityTracker: new AgentActivityTracker(),
+ updateWorkingLoaderMessage: vi.fn(),
+ autoCompactionLoader: undefined,
+ retryLoader: undefined,
+ startCompactionLoader(this: Record<string, unknown>, reason: string, customInstructions?: string) {
+ startCompactionLoader.call(this, reason, customInstructions);
+ },
+ workingVisible: true,
+ stopWorkingLoader: vi.fn(),
+ syncWorkingLoader: vi.fn(),
+ defaultEditor: {},
+ statusContainer: { clear: vi.fn() },
+ chatContainer: { clear: vi.fn() },
+ rebuildChatFromMessages: vi.fn(function (this: { chatContainer: { clear(): void } }) {
+ this.chatContainer.clear();
+ return Promise.resolve();
+ }),
+ addMessageToChat: vi.fn(),
+ refreshConnectionContextUsage: vi.fn().mockResolvedValue(undefined),
+ showError: vi.fn(),
+ showWarning: vi.fn(),
+ showStatus: vi.fn(),
+ settingsManager: { getShowTerminalProgress: () => false },
+ ui: { requestRender: vi.fn(), terminal: { setProgress: vi.fn() } },
+ ...overrides,
+ };
+}
describe("InteractiveMode compaction events", () => {
- test("rebuilds chat and appends a synthetic compaction summary at the bottom", async () => {
- const fakeThis = {
- isInitialized: true,
- footer: { invalidate: vi.fn() },
- updateConnectionStateFromEvent: vi.fn(),
- activityTracker: new AgentActivityTracker(),
- updateWorkingLoaderMessage: vi.fn(),
- autoCompactionLoader: undefined,
- retryLoader: undefined,
- syncWorkingLoader: vi.fn(),
- defaultEditor: {},
- statusContainer: { clear: vi.fn() },
- chatContainer: { clear: vi.fn() },
- rebuildChatFromMessages: vi.fn(),
- addMessageToChat: vi.fn(),
- refreshConnectionContextUsage: vi.fn().mockResolvedValue(undefined),
- showError: vi.fn(),
- showWarning: vi.fn(),
- showStatus: vi.fn(),
- flushCompactionQueue: vi.fn().mockResolvedValue(undefined),
- settingsManager: { getShowTerminalProgress: () => false },
- ui: { requestRender: vi.fn(), terminal: { setProgress: vi.fn() } },
- };
+ beforeAll(() => initTheme("dark"));
- const handleEvent = Reflect.get(InteractiveMode.prototype, "handleEvent") as (
- this: typeof fakeThis,
- event: {
- type: "compaction_end";
- reason: "manual" | "threshold" | "overflow";
- result: { tokensBefore: number; summary: string } | undefined;
- aborted: boolean;
- willRetry: boolean;
- errorMessage?: string;
- errorSeverity?: "warning" | "error";
- customInstructions?: string;
- },
- ) => Promise<void>;
+ test("shows an automatic compaction loader for the full operation", async () => {
+ const statusContainer = new Container();
+ const fakeThis = createFakeThis({ statusContainer });
+
+ await handleEvent.call(fakeThis, { type: "compaction_start", reason: "threshold" });
+
+ expect(stripAnsi(statusContainer.render(80).join("\n"))).toContain("Auto-compacting");
+ expect(fakeThis.ui.requestRender).toHaveBeenCalled();
await handleEvent.call(fakeThis, {
type: "compaction_end",
- reason: "manual",
- result: {
- tokensBefore: 123,
- summary: "summary",
- },
- aborted: false,
+ reason: "threshold",
+ result: undefined,
+ aborted: true,
willRetry: false,
});
+ expect(statusContainer.children).toHaveLength(0);
+ });
- expect(fakeThis.chatContainer.clear).toHaveBeenCalledTimes(1);
- expect(fakeThis.rebuildChatFromMessages).toHaveBeenCalledTimes(1);
- expect(fakeThis.addMessageToChat).toHaveBeenCalledTimes(1);
- expect(fakeThis.addMessageToChat).toHaveBeenCalledWith(
- expect.objectContaining({
- role: "compactionSummary",
- tokensBefore: 123,
- summary: "summary",
- }),
+ test.each([
+ { name: "rebuilds successful compaction from its single persisted summary", refresh: "succeeds" },
+ { name: "keeps stale chat and reports a failed post-compaction refresh", refresh: "fails" },
+ ] as const)("$name", async ({ refresh }) => {
+ const fakeThis = createFakeThis(
+ refresh === "fails"
+ ? { rebuildChatFromMessages: vi.fn().mockRejectedValue(new Error("context unavailable")) }
+ : {},
);
- expect(fakeThis.flushCompactionQueue).toHaveBeenCalledWith({ willRetry: false });
await handleEvent.call(fakeThis, {
type: "compaction_end",
- reason: "manual",
- result: {
- tokensBefore: 456,
- summary: "focused summary",
- },
+ reason: "requested",
+ result: { tokensBefore: 123, summary: "summary" },
aborted: false,
willRetry: false,
- customInstructions: "focus on xyz",
});
- expect(fakeThis.addMessageToChat).toHaveBeenLastCalledWith(
- expect.objectContaining({
- role: "compactionSummary",
- tokensBefore: 456,
- summary: "focused summary",
- customInstructions: "focus on xyz",
- }),
- );
+ expect(fakeThis.chatContainer.clear).toHaveBeenCalledTimes(refresh === "succeeds" ? 1 : 0);
+ expect(fakeThis.rebuildChatFromMessages).toHaveBeenCalledOnce();
+ expect(fakeThis.addMessageToChat).not.toHaveBeenCalled();
+ if (refresh === "fails") {
+ expect(fakeThis.showError).toHaveBeenCalledWith(
+ "Compaction succeeded, but the transcript could not be refreshed: context unavailable",
+ );
+ } else {
+ expect(fakeThis.showError).not.toHaveBeenCalled();
+ }
+ });
- await handleEvent.call(fakeThis, {
- type: "compaction_end",
- reason: "manual",
- result: undefined,
- aborted: false,
- willRetry: false,
- errorMessage: "Session is too short to compact — try again once it grows",
- errorSeverity: "warning",
+ test("restores the compaction loader from state when no start event was seen", () => {
+ const statusContainer = new Container();
+ const fakeThis = createFakeThis({
+ statusContainer,
+ connectionState: { isCompacting: true },
+ isAgentCompacting() {
+ return true;
+ },
+ loadingAnimation: undefined,
+ workingVisible: true,
+ isAgentStreaming: () => false,
+ stopWorkingLoader: vi.fn(),
+ startWorkingLoader: vi.fn(),
});
- expect(fakeThis.showWarning).toHaveBeenCalledWith("Session is too short to compact — try again once it grows");
- expect(fakeThis.showError).not.toHaveBeenCalled();
+ (Reflect.get(InteractiveMode.prototype, "syncWorkingLoader") as (this: unknown) => void).call(fakeThis);
+
+ expect(stripAnsi(statusContainer.render(80).join("\n"))).toContain("Compacting context");
});
});
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 e22ca17a36..982ce6bb4e 100644
--- a/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
+++ b/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
@@ -26,7 +26,6 @@ type FakeInteractiveMode = {
retryAttempt: number;
};
connectionQueue: { steering: string[]; followUp: string[] };
- compactionQueuedMessages: Array<{ text: string; mode: "steer" | "followUp" }>;
agentConnection: {
abort: Mock;
clearQueue: Mock;
@@ -96,7 +95,6 @@ function createInteractiveFake(options: {
retryAttempt: options.retryAttempt ?? 0,
},
connectionQueue: { steering: [], followUp: [] },
- compactionQueuedMessages: [],
agentConnection: {
abort: vi.fn().mockResolvedValue(undefined),
clearQueue: vi.fn().mockResolvedValue({ steering: [], followUp: [] }),
diff --git a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
index 1b5c91cfe5..cfa875a352 100644
--- a/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
+++ b/packages/coding-agent/test/interactive-mode-prompt-stash.test.ts
@@ -35,13 +35,13 @@ type FakeEditor = {
type PromptStashHarness = {
promptStash?: PromptStash;
+ promptStashState: PromptStashState;
editor: FakeEditor;
showStatus: Mock;
clearShortcutGuide: Mock;
};
type PromptStashLiveMarkerHarness = PromptStashHarness & {
- compactionQueuedMessages: Array<{ text: string; mode: "steer" | "followUp" }>;
connectionQueue: { steering: string[]; followUp: string[] };
};
@@ -49,6 +49,7 @@ type SharedPromptStashHarness = PromptStashHarness & {
promptStashStore: ClientPromptStashStore;
promptStashSessionId: string;
promptStashState: PromptStashState;
+ pendingPromptStashReleases: { sessionId: string; state: unknown }[];
pastedImages: Map<number, ImageContent>;
nextImageMarkerId: number;
};
@@ -85,6 +86,17 @@ type SubmitHarness = PromptStashHarness & {
isAgentStreaming: () => boolean;
flushPendingBashComponents: Mock;
onInputCallback: Mock;
+ clearSideQuestion: Mock;
+ collectImagesFor: Mock;
+ agentConnection: { prompt: Mock };
+ updatePendingMessagesDisplay: Mock;
+ ui: { requestRender: Mock };
+ showError: Mock;
+ submittedInputBehavior: "steer" | "followUp";
+ inputSubmissionGeneration: number;
+ inputSubmissionsPending: number;
+ pendingPromptStashReleases: { sessionId: string; state: unknown }[];
+ retainedSubmissionGenerations: WeakMap<object, number>;
};
type PromptStashMethods = {
@@ -136,11 +148,26 @@ function createEditor(
return editor;
}
+type Deferred = { promise: Promise<void>; resolve: () => void; reject: (error: Error) => void };
+
+function createDeferred(): Deferred {
+ let resolve!: () => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<void>((nextResolve, nextReject) => {
+ resolve = nextResolve;
+ reject = nextReject;
+ });
+ return { promise, resolve, reject };
+}
+
function createPromptStashHarness(
options: { text?: string; expandedText?: string; stash?: string; pasteSnapshot?: FakePasteSnapshot } = {},
) {
const harness: PromptStashHarness = {
- promptStash: options.stash ? { text: options.stash, pasteSnapshot: options.pasteSnapshot } : undefined,
+ // promptStash reads/writes go through the prototype accessor onto this state.
+ promptStashState: {
+ stash: options.stash ? { text: options.stash, pasteSnapshot: options.pasteSnapshot } : undefined,
+ },
editor: createEditor({
text: options.text,
expandedText: options.expandedText,
@@ -153,6 +180,34 @@ function createPromptStashHarness(
return harness;
}
+function createSubmitHarness(
+ options: Parameters<typeof createPromptStashHarness>[0] & { prompt?: Mock } = {},
+): SubmitHarness {
+ const mode: SubmitHarness = {
+ ...createPromptStashHarness(options),
+ defaultEditor: {},
+ sideQuestionContainer: { clear: vi.fn() },
+ isAgentCompacting: () => false,
+ isAgentStreaming: () => false,
+ flushPendingBashComponents: vi.fn(),
+ onInputCallback: vi.fn(),
+ clearSideQuestion: vi.fn(),
+ collectImagesFor: vi.fn(() => []),
+ agentConnection: { prompt: options.prompt ?? vi.fn(async () => {}) },
+ updatePendingMessagesDisplay: vi.fn(),
+ ui: { requestRender: vi.fn() },
+ showError: vi.fn(),
+ submittedInputBehavior: "steer",
+ inputSubmissionGeneration: 0,
+ inputSubmissionsPending: 0,
+ pendingPromptStashReleases: [],
+ retainedSubmissionGenerations: new WeakMap(),
+ };
+ Object.setPrototypeOf(mode, InteractiveMode.prototype);
+ interactiveModeMethods.setupEditorSubmitHandler.call(mode);
+ return mode;
+}
+
function createSharedPromptStashHarness(
store: ClientPromptStashStore,
sessionId: string,
@@ -167,6 +222,7 @@ function createSharedPromptStashHarness(
promptStashStore: store,
promptStashSessionId: sessionId,
promptStashState: store.forSession(sessionId),
+ pendingPromptStashReleases: [],
editor: createEditor(options),
showStatus: vi.fn(),
clearShortcutGuide: vi.fn(),
@@ -228,6 +284,40 @@ describe("InteractiveMode prompt stash", () => {
expect(reopenedMode.promptStashState.stash).toBeUndefined();
});
+ it("restores retained startup image drafts in order and resubmits each image exactly once", async () => {
+ const store = new ClientPromptStashStore();
+ const state = store.forSession("session-a");
+ const firstImage: ImageContent = { type: "image", data: "first", mimeType: "image/png" };
+ const secondImage: ImageContent = { type: "image", data: "second", mimeType: "image/jpeg" };
+ state.stash = { text: "first [image #2]", images: [[2, firstImage]] };
+ state.queuedStashes = [{ text: "second [image #3]", images: [[3, secondImage]] }];
+ const mode = createSharedPromptStashHarness(store, "session-a", {
+ pastedImages: [[1, { type: "image", data: "existing", mimeType: "image/png" }]],
+ });
+ interactiveModeMethods.hydratePromptStash.call(mode);
+ const submitted: Array<{ text: string; images: ImageContent[] }> = [];
+
+ for (let index = 0; index < 2; index++) {
+ expect(interactiveModeMethods.restorePromptStashIfEditorEmpty.call(mode)).toBe(true);
+ const text = mode.editor.getText();
+ const ids = [...text.matchAll(/\[image #(\d+)\]/g)].map((match) => Number(match[1]));
+ submitted.push({
+ text,
+ images: ids.flatMap((id) => (mode.pastedImages.get(id) ? [mode.pastedImages.get(id)!] : [])),
+ });
+ mode.editor.setText("");
+ }
+
+ expect(submitted).toEqual([
+ { text: "first [image #2]", images: [firstImage] },
+ { text: "second [image #3]", images: [secondImage] },
+ ]);
+ expect(mode.pastedImages.get(1)?.data).toBe("existing");
+ expect(mode.nextImageMarkerId).toBe(4);
+ expect(state.stash).toBeUndefined();
+ expect(state.queuedStashes).toBeUndefined();
+ });
+
it("rebinds prompt stash state when the connected session changes", () => {
const store = new ClientPromptStashStore();
const firstState = store.forSession("session-a");
@@ -314,6 +404,36 @@ describe("InteractiveMode prompt stash", () => {
expect(mode.showStatus).not.toHaveBeenCalledWith("Restored stashed prompt");
});
+ it("restores both rich lifecycle-retained drafts in submission order", () => {
+ const store = new ClientPromptStashStore();
+ const mode = createSharedPromptStashHarness(store, "session-a");
+ const firstPaste: FakePasteSnapshot = { pastes: [[1, "first expanded"]], pasteCounter: 1 };
+ const secondPaste: FakePasteSnapshot = { pastes: [[2, "second expanded"]], pasteCounter: 2 };
+ mode.promptStashState.stash = {
+ text: "first [paste #1] [image #7]",
+ expandedText: "first expanded [image #7]",
+ pasteSnapshot: firstPaste,
+ };
+ mode.promptStashState.queuedStashes = [
+ {
+ text: "second [paste #2] [image #8]",
+ expandedText: "second expanded [image #8]",
+ pasteSnapshot: secondPaste,
+ },
+ ];
+
+ expect(interactiveModeMethods.restorePromptStashIfEditorEmpty.call(mode)).toBe(true);
+ expect(mode.editor.getText()).toBe("first [paste #1] [image #7]");
+ expect(mode.editor.restoredPasteSnapshot).toBe(firstPaste);
+
+ mode.editor.setText("");
+ expect(interactiveModeMethods.restorePromptStashIfEditorEmpty.call(mode)).toBe(true);
+ expect(mode.editor.getText()).toBe("second [paste #2] [image #8]");
+ expect(mode.editor.restoredPasteSnapshot).toBe(secondPaste);
+ expect(mode.promptStashState.stash).toBeUndefined();
+ expect(mode.promptStashState.queuedStashes).toBeUndefined();
+ });
+
it("does not overwrite an existing stash", () => {
const mode = createPromptStashHarness({ text: "second draft", stash: "first draft" });
@@ -325,42 +445,42 @@ describe("InteractiveMode prompt stash", () => {
});
it("restores a stashed prompt after normal message submission clears the editor", async () => {
- const mode: SubmitHarness = {
- ...createPromptStashHarness({ stash: "half-written draft" }),
- defaultEditor: {},
- sideQuestionContainer: { clear: vi.fn() },
- isAgentCompacting: () => false,
- isAgentStreaming: () => false,
- flushPendingBashComponents: vi.fn(),
- onInputCallback: vi.fn(),
- };
- Object.setPrototypeOf(mode, InteractiveMode.prototype);
- interactiveModeMethods.setupEditorSubmitHandler.call(mode);
+ const mode = createSubmitHarness({ stash: "half-written draft" });
await mode.defaultEditor.onSubmit?.("temporary prompt");
- expect(mode.onInputCallback).toHaveBeenCalledWith("temporary prompt");
+ expect(mode.agentConnection.prompt).toHaveBeenCalledWith("temporary prompt", {
+ streamingBehavior: "steer",
+ queueIfBusy: true,
+ images: [],
+ });
expect(mode.editor.addToHistory).toHaveBeenCalledWith("temporary prompt");
expect(mode.promptStash).toBeUndefined();
expect(mode.editor.getText()).toBe("half-written draft");
});
+ it("routes session-owned commands through canonical prompt admission", async () => {
+ const mode = Object.assign(createSubmitHarness(), { isAgentCompacting: () => true });
+
+ for (const command of ["/compact focus on tools", "/refine --global", "/goal ship it", "/autonomous on"]) {
+ await mode.defaultEditor.onSubmit?.(command);
+ }
+
+ for (const command of ["/compact focus on tools", "/refine --global", "/goal ship it", "/autonomous on"]) {
+ expect(mode.agentConnection.prompt).toHaveBeenCalledWith(command, {
+ streamingBehavior: "steer",
+ queueIfBusy: true,
+ images: [],
+ });
+ }
+ });
+
it("restores a stashed prompt after a session reset clears prompt state", async () => {
- let mode: SubmitHarness & { handleClearCommand: Mock<() => Promise<void>> };
- mode = {
- ...createPromptStashHarness({ stash: "half-written draft" }),
- defaultEditor: {},
- sideQuestionContainer: { clear: vi.fn() },
- isAgentCompacting: () => false,
- isAgentStreaming: () => false,
- flushPendingBashComponents: vi.fn(),
- onInputCallback: vi.fn(),
+ const mode = Object.assign(createSubmitHarness({ stash: "half-written draft" }), {
handleClearCommand: vi.fn(async () => {
mode.editor.setText("");
}),
- };
- Object.setPrototypeOf(mode, InteractiveMode.prototype);
- interactiveModeMethods.setupEditorSubmitHandler.call(mode);
+ });
await mode.defaultEditor.onSubmit?.("/new");
@@ -370,30 +490,17 @@ describe("InteractiveMode prompt stash", () => {
});
it("waits for async session selectors before restoring a stashed prompt", async () => {
- let resolveSelector: () => void = () => {};
- const selectorDone = new Promise<void>((resolve) => {
- resolveSelector = resolve;
- });
- let mode: SubmitHarness & { showUserMessageSelector: Mock<() => Promise<void>> };
- mode = {
- ...createPromptStashHarness({ stash: "half-written draft" }),
- defaultEditor: {},
- sideQuestionContainer: { clear: vi.fn() },
- isAgentCompacting: () => false,
- isAgentStreaming: () => false,
- flushPendingBashComponents: vi.fn(),
- onInputCallback: vi.fn(),
+ const selector = createDeferred();
+ const mode = Object.assign(createSubmitHarness({ stash: "half-written draft" }), {
showUserMessageSelector: vi.fn(async () => {
- await selectorDone;
+ await selector.promise;
mode.editor.setText("");
}),
- };
- Object.setPrototypeOf(mode, InteractiveMode.prototype);
- interactiveModeMethods.setupEditorSubmitHandler.call(mode);
+ });
const submit = mode.defaultEditor.onSubmit?.("/fork");
await Promise.resolve();
- resolveSelector();
+ selector.resolve();
await submit;
expect(mode.showUserMessageSelector).toHaveBeenCalled();
@@ -401,31 +508,26 @@ describe("InteractiveMode prompt stash", () => {
expect(mode.editor.getText()).toBe("half-written draft");
});
- it("restores a stashed prompt after idle follow-up slash commands clear the editor", async () => {
- let resolveSettings: () => void = () => {};
- const settingsDone = new Promise<void>((resolve) => {
- resolveSettings = resolve;
+ it("owns Alt+Enter /settings locally while preserving the stashed prompt", async () => {
+ const settings = createDeferred();
+ const admitPendingStartupPrompts = vi.fn(() => new Promise<void>(() => {}));
+ const mode = Object.assign(createSubmitHarness({ text: "/settings", stash: "half-written draft" }), {
+ admitPendingStartupPrompts,
+ showSettingsSelector: vi.fn(() => settings.promise),
});
- const mode: SubmitHarness & { showSettingsSelector: Mock<() => Promise<void>> } = {
- ...createPromptStashHarness({ text: "/settings", stash: "half-written draft" }),
- defaultEditor: {},
- sideQuestionContainer: { clear: vi.fn() },
- isAgentCompacting: () => false,
- isAgentStreaming: () => false,
- flushPendingBashComponents: vi.fn(),
- onInputCallback: vi.fn(),
- showSettingsSelector: vi.fn(() => settingsDone),
- };
- Object.setPrototypeOf(mode, InteractiveMode.prototype);
- interactiveModeMethods.setupEditorSubmitHandler.call(mode);
mode.editor.onSubmit = mode.defaultEditor.onSubmit;
const followUp = interactiveModeMethods.handleFollowUp.call(mode);
- await Promise.resolve();
- resolveSettings();
+ expect(mode.editor.getText()).toBe("");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(mode.showSettingsSelector).toHaveBeenCalledOnce();
+ await interactiveModeMethods.handleFollowUp.call(mode);
+ expect(mode.showSettingsSelector).toHaveBeenCalledOnce();
+ expect(admitPendingStartupPrompts).not.toHaveBeenCalled();
+
+ settings.resolve();
await followUp;
- expect(mode.showSettingsSelector).toHaveBeenCalled();
expect(mode.promptStash).toBeUndefined();
expect(mode.editor.getText()).toBe("half-written draft");
});
@@ -435,7 +537,6 @@ describe("InteractiveMode prompt stash", () => {
const mode: ResetHarness = {
...base,
defaultEditor: base.editor,
- compactionQueuedMessages: [],
connectionQueue: { steering: ["old [image #2]"], followUp: [] },
chatContainer: { clear: vi.fn() },
shortcutGuideContainer: { clear: vi.fn() },
@@ -474,7 +575,6 @@ describe("InteractiveMode prompt stash", () => {
const mode: ResetHarness = {
...base,
defaultEditor: base.editor,
- compactionQueuedMessages: [],
connectionQueue: { steering: [], followUp: [] },
chatContainer: { clear: vi.fn() },
shortcutGuideContainer: { clear: vi.fn() },
@@ -503,34 +603,116 @@ describe("InteractiveMode prompt stash", () => {
expect(mode.pastedImages.has(1)).toBe(false);
});
+ it("restores the exact rich draft after admission rejects", async () => {
+ const pasteSnapshot: FakePasteSnapshot = { pastes: [[1, "expanded paste"]], pasteCounter: 1 };
+ const mode = createSubmitHarness({
+ text: "draft [paste #1]",
+ expandedText: "draft expanded paste",
+ pasteSnapshot,
+ prompt: vi.fn(async () => {
+ throw new Error("admission failed");
+ }),
+ });
+ (mode as SubmitHarness & { latestEditorPromptStash: PromptStash }).latestEditorPromptStash = {
+ text: "draft [paste #1]",
+ expandedText: "draft expanded paste",
+ pasteSnapshot,
+ };
+ mode.editor.setText("");
+
+ await mode.defaultEditor.onSubmit?.("draft expanded paste");
+
+ expect(mode.editor.getText()).toBe("draft [paste #1]");
+ expect(mode.editor.restoredPasteSnapshot).toBe(pasteSnapshot);
+ });
+
+ it.each([
+ { newer: "draft and stash", stash: "older stash", firstError: "late rejection" },
+ { newer: "pending submission", stash: "stashed draft", firstError: undefined },
+ { newer: "accepted submission", stash: undefined, firstError: "late first rejection" },
+ ])("does not restore stale input over a newer $newer", async ({ newer, stash, firstError }) => {
+ const first = createDeferred();
+ const second = createDeferred();
+ const prompt = vi.fn().mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+ const mode = createSubmitHarness({ stash, prompt });
+ const newerStash = { text: "newer stash" };
+
+ const firstSubmission = mode.defaultEditor.onSubmit?.("first prompt");
+ await Promise.resolve();
+ const secondSubmission = newer === "draft and stash" ? undefined : mode.defaultEditor.onSubmit?.("second prompt");
+ if (newer === "draft and stash") {
+ mode.editor.setText("newer editor draft");
+ mode.promptStash = newerStash;
+ } else {
+ await Promise.resolve();
+ }
+ if (newer === "accepted submission") {
+ second.resolve();
+ await secondSubmission;
+ }
+ if (firstError) first.reject(new Error(firstError));
+ else first.resolve();
+ await firstSubmission;
+
+ if (firstError) expect(mode.showError).toHaveBeenCalledWith(firstError);
+ if (newer === "draft and stash") {
+ expect(mode.editor.getText()).toBe("newer editor draft");
+ expect(mode.promptStash).toBe(newerStash);
+ return;
+ }
+ expect(mode.editor.getText()).toBe("");
+ if (newer === "pending submission") {
+ // The stash restores only once the newest pending submission is accepted.
+ expect(mode.promptStash?.text).toBe("stashed draft");
+ second.resolve();
+ await secondSubmission;
+ expect(mode.editor.getText()).toBe("stashed draft");
+ expect(mode.promptStash).toBeUndefined();
+ } else {
+ expect(mode.promptStash).toEqual({ text: "first prompt" });
+ }
+ });
+
+ it.each(["typing", "submission"] as const)(
+ "does not restore an older failed Alt+Enter over newer %s",
+ async (newerInput) => {
+ const first = createDeferred();
+ const prompt = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValueOnce(undefined);
+ const mode = createSubmitHarness({ text: "stale follow-up", prompt });
+ mode.editor.onSubmit = mode.defaultEditor.onSubmit;
+
+ const firstSubmission = interactiveModeMethods.handleFollowUp.call(mode);
+ mode.editor.setText("newer input");
+ if (newerInput === "submission") await mode.defaultEditor.onSubmit?.("newer input");
+ first.reject(new Error("late follow-up rejection"));
+ await firstSubmission;
+
+ expect(mode.editor.getText()).toBe(newerInput === "typing" ? "newer input" : "");
+ expect(mode.showError).toHaveBeenCalledWith("late follow-up rejection");
+ },
+ );
+
it("restores failed follow-up text without dropping the stashed prompt", async () => {
- const error = new Error("send failed");
- const mode: SubmitHarness & {
- agentConnection: { prompt: Mock<() => Promise<void>> };
- collectImagesFor: Mock;
- updatePendingMessagesDisplay: Mock;
- ui: { requestRender: Mock };
- } = {
- ...createPromptStashHarness({ text: "quick follow-up", stash: "half-written draft" }),
- defaultEditor: {},
- sideQuestionContainer: { clear: vi.fn() },
- isAgentCompacting: () => false,
- isAgentStreaming: () => true,
- flushPendingBashComponents: vi.fn(),
- onInputCallback: vi.fn(),
- agentConnection: {
+ const mode = Object.assign(
+ createSubmitHarness({
+ text: "quick follow-up",
+ stash: "half-written draft",
prompt: vi.fn(async () => {
- throw error;
+ throw new Error("send failed");
}),
- },
- collectImagesFor: vi.fn(),
- updatePendingMessagesDisplay: vi.fn(),
- ui: { requestRender: vi.fn() },
- };
- Object.setPrototypeOf(mode, InteractiveMode.prototype);
+ }),
+ { isAgentStreaming: () => true },
+ );
+ mode.editor.onSubmit = mode.defaultEditor.onSubmit;
- await expect(interactiveModeMethods.handleFollowUp.call(mode)).rejects.toThrow(error);
+ await expect(interactiveModeMethods.handleFollowUp.call(mode)).resolves.toBeUndefined();
+ expect(mode.agentConnection.prompt).toHaveBeenCalledWith("quick follow-up", {
+ streamingBehavior: "followUp",
+ queueIfBusy: true,
+ images: [],
+ });
+ expect(mode.showError).toHaveBeenCalledWith("send failed");
expect(mode.editor.getText()).toBe("quick follow-up");
expect(mode.promptStash?.text).toBe("half-written draft");
});
@@ -538,7 +720,6 @@ describe("InteractiveMode prompt stash", () => {
it("keeps image markers in a stashed prompt live", () => {
const mode: PromptStashLiveMarkerHarness = {
...createPromptStashHarness({ stash: "look at [image #7]" }),
- compactionQueuedMessages: [],
connectionQueue: { steering: [], followUp: [] },
};
Object.setPrototypeOf(mode, InteractiveMode.prototype);
diff --git a/packages/coding-agent/test/interactive-mode-refine-command.test.ts b/packages/coding-agent/test/interactive-mode-refine-command.test.ts
deleted file mode 100644
index 88c2d49c9c..0000000000
--- a/packages/coding-agent/test/interactive-mode-refine-command.test.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import { describe, expect, test, vi } from "vitest";
-import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
-
-const handleRefineCommand = Reflect.get(InteractiveMode.prototype, "handleRefineCommand") as (
- this: {
- agentConnection: {
- getSessionStats: ReturnType<typeof vi.fn>;
- refine: ReturnType<typeof vi.fn>;
- };
- stopWorkingLoader: ReturnType<typeof vi.fn>;
- showStatus: ReturnType<typeof vi.fn>;
- showWarning: ReturnType<typeof vi.fn>;
- showError: ReturnType<typeof vi.fn>;
- },
- args?: string,
-) => Promise<void>;
-
-describe("InteractiveMode.handleRefineCommand", () => {
- test("requires a refinement id for rollback", async () => {
- const context = {
- agentConnection: {
- getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 2 }),
- refine: vi.fn(),
- },
- stopWorkingLoader: vi.fn(),
- showStatus: vi.fn(),
- showWarning: vi.fn(),
- showError: vi.fn(),
- };
-
- await handleRefineCommand.call(context, "rollback");
-
- expect(context.showWarning).toHaveBeenCalledWith("Usage: /refine rollback <refinement-id>");
- expect(context.agentConnection.refine).not.toHaveBeenCalled();
- expect(context.stopWorkingLoader).not.toHaveBeenCalled();
- });
-
- test("rolls back even when the session has no trajectory yet", async () => {
- const context = {
- agentConnection: {
- getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 0 }),
- refine: vi.fn().mockResolvedValue({ appliedEdits: [], harnessStatePath: "/tmp/harness_state.json" }),
- },
- stopWorkingLoader: vi.fn(),
- showStatus: vi.fn(),
- showWarning: vi.fn(),
- showError: vi.fn(),
- };
-
- await handleRefineCommand.call(context, "rollback refine_123");
-
- // Rollback uses global history, so the empty-trajectory guard must not block it.
- expect(context.agentConnection.getSessionStats).not.toHaveBeenCalled();
- expect(context.showWarning).not.toHaveBeenCalled();
- expect(context.agentConnection.refine).toHaveBeenCalledWith({ rollbackId: "refine_123", global: false });
- });
-
- test("parses --global after rollback id", async () => {
- const context = {
- agentConnection: {
- getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 0 }),
- refine: vi.fn().mockResolvedValue({ appliedEdits: [], harnessStatePath: "/tmp/harness_state.json" }),
- },
- stopWorkingLoader: vi.fn(),
- showStatus: vi.fn(),
- showWarning: vi.fn(),
- showError: vi.fn(),
- };
-
- await handleRefineCommand.call(context, "rollback refine_123 --global");
-
- expect(context.agentConnection.getSessionStats).not.toHaveBeenCalled();
- expect(context.agentConnection.refine).toHaveBeenCalledWith({ rollbackId: "refine_123", global: true });
- });
-
- test("parses --global before refinement instructions", async () => {
- const context = {
- agentConnection: {
- getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 2 }),
- refine: vi.fn().mockResolvedValue({ appliedEdits: [], harnessStatePath: "/tmp/harness_state.json" }),
- },
- stopWorkingLoader: vi.fn(),
- showStatus: vi.fn(),
- showWarning: vi.fn(),
- showError: vi.fn(),
- };
-
- await handleRefineCommand.call(context, "--global focus on validation");
-
- expect(context.showStatus).toHaveBeenCalledWith("Refining global continual harness state...");
- expect(context.agentConnection.refine).toHaveBeenCalledWith({
- instructions: "focus on validation",
- global: true,
- });
- });
-
- test("preserves trailing --global in ordinary refinement instructions", async () => {
- const context = {
- agentConnection: {
- getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 2 }),
- refine: vi.fn().mockResolvedValue({ appliedEdits: [], harnessStatePath: "/tmp/harness_state.json" }),
- },
- stopWorkingLoader: vi.fn(),
- showStatus: vi.fn(),
- showWarning: vi.fn(),
- showError: vi.fn(),
- };
-
- await handleRefineCommand.call(context, "update docs to explain --global");
-
- expect(context.showStatus).toHaveBeenCalledWith("Refining local continual harness state...");
- expect(context.agentConnection.refine).toHaveBeenCalledWith({
- instructions: "update docs to explain --global",
- global: false,
- });
- });
-
- test("shows local scope in status for default refinement", async () => {
- const context = {
- agentConnection: {
- getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 2 }),
- refine: vi.fn().mockResolvedValue({ appliedEdits: [], harnessStatePath: "/tmp/harness_state.json" }),
- },
- stopWorkingLoader: vi.fn(),
- showStatus: vi.fn(),
- showWarning: vi.fn(),
- showError: vi.fn(),
- };
-
- await handleRefineCommand.call(context, "focus on validation");
-
- expect(context.showStatus).toHaveBeenCalledWith("Refining local continual harness state...");
- expect(context.agentConnection.refine).toHaveBeenCalledWith({
- instructions: "focus on validation",
- global: false,
- });
- });
-
- test("blocks plain refinement when there is no trajectory", async () => {
- const context = {
- agentConnection: {
- getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 1 }),
- refine: vi.fn(),
- },
- stopWorkingLoader: vi.fn(),
- showStatus: vi.fn(),
- showWarning: vi.fn(),
- showError: vi.fn(),
- };
-
- await handleRefineCommand.call(context, "focus on validation");
-
- expect(context.showWarning).toHaveBeenCalledWith("Nothing to refine (no trajectory yet)");
- expect(context.agentConnection.refine).not.toHaveBeenCalled();
- });
-
- test("shows success status after refine resolves without blocking the caller", async () => {
- let resolveRefine: ((value: unknown) => void) | undefined;
- const refinePromise = new Promise((resolve) => {
- resolveRefine = resolve;
- });
- const context = {
- agentConnection: {
- getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 2 }),
- refine: vi.fn().mockReturnValue(refinePromise),
- },
- stopWorkingLoader: vi.fn(),
- showStatus: vi.fn(),
- showWarning: vi.fn(),
- showError: vi.fn(),
- };
-
- await handleRefineCommand.call(context, "focus on validation");
-
- // The "Refining..." status is shown synchronously.
- expect(context.showStatus).toHaveBeenCalledWith("Refining local continual harness state...");
- // The success status is NOT shown yet because refine has not resolved.
- expect(context.showStatus).not.toHaveBeenCalledWith("Refined continual harness state: 2 edits applied, 1 failed");
-
- // Resolve the refine promise and let the microtask queue drain.
- resolveRefine?.({
- appliedEdits: [{ applied: true }, { applied: true }, { applied: false, error: "entry not found" }],
- harnessStatePath: "/tmp/harness_state.json",
- });
- await vi.waitFor(() => {
- expect(context.showStatus).toHaveBeenCalledWith("Refined continual harness state: 2 edits applied, 1 failed");
- });
- expect(context.showStatus).toHaveBeenCalledWith("Harness state: /tmp/harness_state.json");
- });
-
- test("shows error status after refine rejects without blocking the caller", async () => {
- let rejectRefine: ((error: Error) => void) | undefined;
- const refinePromise = new Promise<never>((_, reject) => {
- rejectRefine = reject;
- });
- const context = {
- agentConnection: {
- getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 2 }),
- refine: vi.fn().mockReturnValue(refinePromise),
- },
- stopWorkingLoader: vi.fn(),
- showStatus: vi.fn(),
- showWarning: vi.fn(),
- showError: vi.fn(),
- };
-
- await handleRefineCommand.call(context, "focus on validation");
-
- // The "Refining..." status is shown synchronously.
- expect(context.showStatus).toHaveBeenCalledWith("Refining local continual harness state...");
- // The error is NOT shown yet because refine has not rejected.
- expect(context.showError).not.toHaveBeenCalled();
-
- rejectRefine?.(new Error("LLM timed out"));
- await vi.waitFor(() => {
- expect(context.showError).toHaveBeenCalledWith("Refinement failed: LLM timed out");
- });
- });
-});
diff --git a/packages/coding-agent/test/interactive-mode-session-command-rendering.test.ts b/packages/coding-agent/test/interactive-mode-session-command-rendering.test.ts
new file mode 100644
index 0000000000..85ce698975
--- /dev/null
+++ b/packages/coding-agent/test/interactive-mode-session-command-rendering.test.ts
@@ -0,0 +1,39 @@
+import { beforeAll, describe, expect, test, vi } from "vitest";
+import { createSessionSlashCommandMessage, createSessionSlashCommandResultMessage } from "../src/core/messages.js";
+import { SlashCommandMessageComponent } from "../src/modes/interactive/components/slash-command-message.js";
+import { SlashCommandResultMessageComponent } from "../src/modes/interactive/components/slash-command-result-message.js";
+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
+
+const command = { name: "compact" as const, args: "focus", text: "/compact focus" };
+
+describe("InteractiveMode session command rendering", () => {
+ beforeAll(() => initTheme("dark"));
+ test("uses specialized components for live command messages", () => {
+ const children: unknown[] = [];
+ const fakeThis = {
+ chatContainer: { children: [], addChild: vi.fn((child: unknown) => children.push(child)) },
+ toolOutputExpanded: false,
+ };
+ const add = Reflect.get(InteractiveMode.prototype, "addMessageToChat") as (
+ this: typeof fakeThis,
+ message:
+ | ReturnType<typeof createSessionSlashCommandMessage>
+ | ReturnType<typeof createSessionSlashCommandResultMessage>,
+ ) => void;
+
+ add.call(fakeThis, createSessionSlashCommandMessage(command));
+ add.call(
+ fakeThis,
+ createSessionSlashCommandResultMessage("Command failed", {
+ command,
+ success: false,
+ severity: "error",
+ error: "failed",
+ }),
+ );
+
+ expect(children[0]).toBeInstanceOf(SlashCommandMessageComponent);
+ expect(children[1]).toBeInstanceOf(SlashCommandResultMessageComponent);
+ });
+});
diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.ts
index 2da3dacf26..1df42211ed 100644
--- a/packages/coding-agent/test/interactive-mode-status.test.ts
+++ b/packages/coding-agent/test/interactive-mode-status.test.ts
@@ -38,6 +38,7 @@ import type {
AgentConnectionSourceInfo,
AgentConnectionState,
} from "../src/modes/agent-connection/types.js";
+import { AgentConnectionPromptAdmissionError } from "../src/modes/agent-connection/types.js";
import { AgentActivityTracker } from "../src/modes/interactive/agent-activity.js";
import type { AuthenticationResult } from "../src/modes/interactive/auth-flows.js";
import { BashExecutionComponent } from "../src/modes/interactive/components/bash-execution.js";
@@ -50,6 +51,7 @@ import {
mergeChildAgentSnapshots,
truncatePathMiddle,
} from "../src/modes/interactive/interactive-mode.js";
+import { ClientPromptStashStore, type PromptStashState } from "../src/modes/interactive/prompt-stash-state.js";
import { initTheme } from "../src/modes/interactive/theme/theme.js";
function renderLastLine(container: Container, width = 120): string {
@@ -483,6 +485,40 @@ describe("InteractiveMode.renderSessionContext", () => {
expect(renderAll(chatContainer)).toContain("Showing latest 400 of 405 messages for faster open.");
});
+ test("keeps equal-timestamp legacy messages after the compaction summary", async () => {
+ const { harness, addMessageToChat } = createRenderSessionContextHarness();
+ const earlier = userMessage("earlier", 4);
+ const summary = {
+ role: "compactionSummary",
+ summary: "legacy summary",
+ tokensBefore: 123,
+ timestamp: 5,
+ } as AgentMessage;
+ const equalLater = userMessage("equal later", 5);
+
+ await renderMessages(harness, [summary, earlier, equalLater]);
+ expect(addMessageToChat.mock.calls.map((call) => call[0])).toEqual([earlier, summary, equalLater]);
+ });
+
+ test("orders the compaction summary at its exact boundary before bounding the initial transcript", async () => {
+ const { harness, addMessageToChat } = createRenderSessionContextHarness();
+ const retained = Array.from({ length: 5 }, (_, index) => userMessage(`retained ${index}`, 5));
+ const summary = {
+ role: "compactionSummary",
+ summary: "summary",
+ tokensBefore: 123,
+ retainedMessageCount: retained.length,
+ timestamp: 5,
+ } as AgentMessage;
+ const later = Array.from({ length: 399 }, (_, index) => userMessage(`later ${index}`, 5));
+
+ await renderMessages(harness, [summary, ...retained, ...later], { limitTranscript: true });
+
+ expect(addMessageToChat).toHaveBeenCalledTimes(400);
+ expect(addMessageToChat.mock.calls[0]?.[0]).toBe(summary);
+ expect(addMessageToChat.mock.calls[1]?.[0]).toMatchObject({ content: "later 0" });
+ });
+
test("preserves the full transcript when rebuilding a cleared transcript", async () => {
const { harness, chatContainer, addMessageToChat } = createRenderSessionContextHarness();
chatContainer.addChild({ render: () => ["old transcript"], invalidate: () => {} });
@@ -598,8 +634,40 @@ describe("InteractiveMode.renderSessionContext", () => {
});
type SubmitHandlerHarness = {
- defaultEditor: { onSubmit?: (text: string) => Promise<void> };
- editor: { setText: (text: string) => void; addToHistory?: (text: string) => void };
+ defaultEditor: {
+ onSubmit?: (text: string) => Promise<void>;
+ };
+ editor: {
+ getText: () => string;
+ getExpandedText?: () => string;
+ getPasteSnapshot?: () => unknown;
+ setText: (text: string) => void;
+ addToHistory?: (text: string) => void;
+ onSubmit?: (text: string) => Promise<void>;
+ };
+ promptStash?: { text: string };
+ promptStashState: PromptStashState;
+ pastedImages: Map<number, unknown>;
+ getPromptStashImages: (text: string) => readonly (readonly [number, unknown])[];
+ retainStartupPromptDrafts?: (prompts: readonly { text: string; images?: readonly unknown[] }[]) => void;
+ nextImageMarkerId?: number;
+ admitPendingStartupPrompts?: () => Promise<"admitted" | "retained" | "lifecycle-cancelled">;
+ isShuttingDown?: boolean;
+ returnToAgentsViewRequested?: boolean;
+ submittedInputBehavior: "steer" | "followUp";
+ latestEditorPromptStash?: unknown;
+ pendingSubmittedPromptStash?: unknown;
+ snapshotPromptStash: (text: string) => unknown;
+ retainSubmittedDraft: (stash: unknown, submissionGeneration: number) => void;
+ inputSubmissionGeneration: number;
+ inputSubmissionsPending: number;
+ pendingPromptStashReleases: { sessionId: string; state: unknown }[];
+ retainedSubmissionGenerations: WeakMap<object, number>;
+ releasePromptStashSession?: () => void;
+ flushPendingBashComponents: () => void;
+ collectImagesFor: () => unknown[];
+ updatePendingMessagesDisplay: () => void;
+ ui: { requestRender: () => void };
clearSideQuestion: () => void;
clearShortcutGuide: () => void;
showWarning: (message: string) => void;
@@ -616,13 +684,36 @@ type SubmitHandlerHarness = {
function createSubmitHandlerHarness(overrides: Partial<SubmitHandlerHarness> = {}): SubmitHandlerHarness {
const fakeThis: SubmitHandlerHarness = {
defaultEditor: {},
- editor: { setText: vi.fn(), addToHistory: vi.fn() },
+ editor: { getText: vi.fn(() => ""), setText: vi.fn(), addToHistory: vi.fn() },
clearSideQuestion: vi.fn(),
clearShortcutGuide: vi.fn(),
showWarning: vi.fn(),
showError: vi.fn(),
isBashRunning: () => false,
patchConnectionState: vi.fn(),
+ promptStashState: {},
+ promptStash: undefined,
+ pastedImages: new Map(),
+ getPromptStashImages: vi.fn(() => []),
+ snapshotPromptStash: vi.fn((text) => ({ text })),
+ retainSubmittedDraft: (
+ InteractiveMode.prototype as unknown as { retainSubmittedDraft(stash: unknown, generation: number): void }
+ ).retainSubmittedDraft,
+ retainStartupPromptDrafts: (
+ InteractiveMode.prototype as unknown as {
+ retainStartupPromptDrafts(prompts: readonly { text: string; images?: readonly unknown[] }[]): void;
+ }
+ ).retainStartupPromptDrafts,
+ nextImageMarkerId: 1,
+ submittedInputBehavior: "steer",
+ inputSubmissionGeneration: 0,
+ inputSubmissionsPending: 0,
+ pendingPromptStashReleases: [],
+ retainedSubmissionGenerations: new WeakMap(),
+ flushPendingBashComponents: vi.fn(),
+ collectImagesFor: vi.fn(() => []),
+ updatePendingMessagesDisplay: vi.fn(),
+ ui: { requestRender: vi.fn() },
agentConnection: {
prompt: vi.fn(async () => {}),
executeBash: vi.fn(async () => {}),
@@ -639,6 +730,213 @@ function createSubmitHandlerHarness(overrides: Partial<SubmitHandlerHarness> = {
}
describe("InteractiveMode submit handling", () => {
+ test.each(["normal Enter", "installed custom editor"])("captures exact rich state for %s", async () => {
+ const image = { type: "image", data: "base64", mimeType: "image/png" };
+ const pasteSnapshot = { pastes: [[1, "expanded paste"]] as const, pasteCounter: 2 };
+ const rawText = "draft [paste #1] [image #7]";
+ let editorText = rawText;
+ const editor = {
+ getText: () => editorText,
+ getExpandedText: () => "draft expanded paste [image #7]",
+ getPasteSnapshot: () => pasteSnapshot,
+ setText: (text: string) => {
+ editorText = text;
+ },
+ onSubmit: undefined as ((text: string) => Promise<void>) | undefined,
+ };
+ const fakeThis = createSubmitHandlerHarness({
+ editor,
+ pastedImages: new Map([[7, image]]),
+ getPromptStashImages: () => [[7, image]],
+ admitPendingStartupPrompts: vi.fn(async (): Promise<"lifecycle-cancelled"> => "lifecycle-cancelled"),
+ });
+ delete fakeThis.promptStash;
+ fakeThis.snapshotPromptStash = (
+ InteractiveMode.prototype as unknown as { snapshotPromptStash(text: string): unknown }
+ ).snapshotPromptStash.bind({
+ editor,
+ snapshotPromptStashFrom: (
+ InteractiveMode.prototype as unknown as {
+ snapshotPromptStashFrom(editor: unknown, text: string): unknown;
+ }
+ ).snapshotPromptStashFrom,
+ getPromptStashImages: fakeThis.getPromptStashImages,
+ } as never);
+ fakeThis.latestEditorPromptStash = fakeThis.snapshotPromptStash(rawText);
+ editor.onSubmit = fakeThis.defaultEditor.onSubmit;
+
+ // Both pi-tui's normal editor and an installed extension editor call their
+ // wired onSubmit only after clearing their own state.
+ editorText = "";
+ await editor.onSubmit?.("draft expanded paste [image #7]");
+
+ expect(fakeThis.promptStashState.stash).toEqual({
+ text: rawText,
+ expandedText: "draft expanded paste [image #7]",
+ pasteSnapshot,
+ images: [[7, image]],
+ });
+ });
+
+ test.each([true, false])(
+ "custom editor replacement preserves the submitted rich draft through lifecycle cancellation (snapshot restore: %s)",
+ async (supportsSnapshotRestore) => {
+ initTheme("dark");
+ const image = { type: "image", data: "base64", mimeType: "image/png" };
+ const pasteSnapshot = { pastes: [[5, "expanded paste"]] as const, pasteCounter: 6 };
+ const rawText = "draft [paste #5] [image #7]";
+ const expandedText = "draft expanded paste [image #7]";
+ let oldText = rawText;
+ const oldEditor = {
+ onSubmit: undefined as ((text: string) => Promise<void>) | undefined,
+ onChange: undefined as ((text: string) => void) | undefined,
+ getText: () => oldText,
+ getExpandedText: () => expandedText,
+ getPasteSnapshot: () => pasteSnapshot,
+ setText: (text: string) => {
+ oldText = text;
+ },
+ handleInput: vi.fn(),
+ render: () => [],
+ };
+ let customText = "";
+ let restoredSnapshot: unknown;
+ const customEditor = {
+ getText: () => customText,
+ getExpandedText: () => (restoredSnapshot ? expandedText : customText),
+ getPasteSnapshot: () => restoredSnapshot,
+ restorePasteSnapshot: supportsSnapshotRestore
+ ? (snapshot: unknown) => {
+ restoredSnapshot = snapshot;
+ }
+ : undefined,
+ setText: (text: string) => {
+ customText = text;
+ customEditor.onChange?.(text);
+ },
+ handleInput: vi.fn(),
+ render: () => [],
+ onSubmit: undefined as ((text: string) => Promise<void>) | undefined,
+ onChange: undefined as ((text: string) => void) | undefined,
+ };
+ const lifecycleBarrier = createDeferred<"admitted" | "lifecycle-cancelled">();
+ const promptStashState: PromptStashState = {};
+ const fakeThis = createSubmitHandlerHarness({
+ defaultEditor: oldEditor,
+ editor: oldEditor,
+ promptStashState,
+ pastedImages: new Map([[7, image]]),
+ getPromptStashImages: (text) => (text.includes("[image #7]") ? [[7, image]] : []),
+ admitPendingStartupPrompts: () => lifecycleBarrier.promise,
+ });
+ Object.assign(fakeThis, {
+ editorContainer: new Container(),
+ childAgentPanelMode: undefined,
+ childAgentSummary: { setHidden: vi.fn() },
+ ui: { setFocus: vi.fn(), requestRender: vi.fn() },
+ keybindings: {},
+ autocompleteProvider: undefined,
+ showStatus: vi.fn(),
+ });
+ Object.defineProperty(fakeThis, "promptStash", {
+ configurable: true,
+ get: () => promptStashState.stash,
+ set: (stash) => {
+ promptStashState.stash = stash;
+ },
+ });
+ fakeThis.snapshotPromptStash = (
+ InteractiveMode.prototype as unknown as { snapshotPromptStash(text: string): unknown }
+ ).snapshotPromptStash.bind(fakeThis as never);
+ (
+ fakeThis as unknown as { snapshotPromptStashFrom(editor: unknown, text: string): unknown }
+ ).snapshotPromptStashFrom = (
+ InteractiveMode.prototype as unknown as {
+ snapshotPromptStashFrom(editor: unknown, text: string): unknown;
+ }
+ ).snapshotPromptStashFrom;
+ (
+ InteractiveMode.prototype as unknown as { setupEditorSubmitHandler(this: SubmitHandlerHarness): void }
+ ).setupEditorSubmitHandler.call(fakeThis);
+ oldEditor.onChange = (text: string) => {
+ if (text.length > 0) fakeThis.latestEditorPromptStash = fakeThis.snapshotPromptStash(text);
+ };
+
+ (
+ InteractiveMode.prototype as unknown as {
+ setCustomEditorComponent(this: unknown, factory: () => unknown): void;
+ }
+ ).setCustomEditorComponent.call(fakeThis, () => customEditor);
+
+ expect(customText).toBe(supportsSnapshotRestore ? rawText : expandedText);
+ expect(restoredSnapshot).toBe(supportsSnapshotRestore ? pasteSnapshot : undefined);
+ customEditor.setText("");
+ const submission = customEditor.onSubmit?.(expandedText);
+ await Promise.resolve();
+ expect(fakeThis.agentConnection.prompt).not.toHaveBeenCalled();
+ lifecycleBarrier.resolve("lifecycle-cancelled");
+ await submission;
+
+ expect(promptStashState.stash).toEqual({
+ text: rawText,
+ expandedText,
+ pasteSnapshot,
+ images: [[7, image]],
+ });
+ restoredSnapshot = undefined;
+ (
+ InteractiveMode.prototype as unknown as { restorePromptStashIfEditorEmpty(this: unknown): boolean }
+ ).restorePromptStashIfEditorEmpty.call(fakeThis);
+ expect(customText).toBe(supportsSnapshotRestore ? rawText : expandedText);
+ expect(restoredSnapshot).toBe(supportsSnapshotRestore ? pasteSnapshot : undefined);
+ expect(promptStashState.stash).toBeUndefined();
+ },
+ );
+
+ test("captures exact rich state for Alt+Enter before clearing", async () => {
+ const image = { type: "image", data: "base64", mimeType: "image/png" };
+ const pasteSnapshot = { pastes: [[3, "expanded paste"]] as const, pasteCounter: 4 };
+ let editorText = "alt [paste #3] [image #9]";
+ const fakeThis = createSubmitHandlerHarness({
+ editor: {
+ getText: () => editorText,
+ getExpandedText: () => "alt expanded paste [image #9]",
+ getPasteSnapshot: () => pasteSnapshot,
+ setText: (text: string) => {
+ editorText = text;
+ },
+ },
+ pastedImages: new Map([[9, image]]),
+ getPromptStashImages: () => [[9, image]],
+ admitPendingStartupPrompts: vi.fn(async (): Promise<"lifecycle-cancelled"> => "lifecycle-cancelled"),
+ });
+ delete fakeThis.promptStash;
+ fakeThis.editor.onSubmit = fakeThis.defaultEditor.onSubmit;
+ fakeThis.snapshotPromptStash = (
+ InteractiveMode.prototype as unknown as { snapshotPromptStash(text: string): unknown }
+ ).snapshotPromptStash.bind({
+ editor: fakeThis.editor,
+ snapshotPromptStashFrom: (
+ InteractiveMode.prototype as unknown as {
+ snapshotPromptStashFrom(editor: unknown, text: string): unknown;
+ }
+ ).snapshotPromptStashFrom,
+ getPromptStashImages: fakeThis.getPromptStashImages,
+ } as never);
+
+ await (
+ InteractiveMode.prototype as unknown as { handleFollowUp(this: SubmitHandlerHarness): Promise<void> }
+ ).handleFollowUp.call(fakeThis);
+
+ expect(editorText).toBe("");
+ expect(fakeThis.promptStashState.stash).toEqual({
+ text: "alt [paste #3] [image #9]",
+ expandedText: "alt expanded paste [image #9]",
+ pasteSnapshot,
+ images: [[9, image]],
+ });
+ });
+
test("routes ! shortcuts to executeBash on the agent connection", async () => {
const fakeThis = createSubmitHandlerHarness();
@@ -876,7 +1174,6 @@ describe("InteractiveMode pending bash components", () => {
shortcutGuideContainer: new Container(),
pendingMessagesContainer: new Container(),
queuedMessagesContainer: new Container(),
- compactionQueuedMessages: [],
pastedImages: new Map(),
liveImageMarkerIds: () => new Set(),
defaultEditor: editorStub,
@@ -1095,7 +1392,6 @@ describe("InteractiveMode connection events", () => {
});
test("preserves client-local work while rendering a resynchronized snapshot", async () => {
- const compactionQueue = [{ text: "send after compaction", mode: "followUp" as const }];
const sideQuestion = { id: "side-1", status: "running" };
const extensionRequests = new Map([["request-1", { cancelLocal: vi.fn() }]]);
const activeBashComponent = {};
@@ -1115,7 +1411,6 @@ describe("InteractiveMode connection events", () => {
}
});
const fakeThis = {
- compactionQueuedMessages: compactionQueue,
sideQuestionEvent: sideQuestion,
activeConnectionExtensionUiRequests: extensionRequests,
activeBashComponent,
@@ -1133,7 +1428,6 @@ describe("InteractiveMode connection events", () => {
renderSessionContext: vi.fn(async () => {}),
restoreStreamingMessageFromSnapshot,
refreshConnectionQueue: vi.fn(async () => {}),
- flushCompactionQueue: vi.fn(async () => {}),
flushPendingBashComponents: vi.fn(),
updateTerminalTitle: vi.fn(),
setGoalAnnouncementBaseline: vi.fn(),
@@ -1148,9 +1442,6 @@ describe("InteractiveMode connection events", () => {
}
).renderResyncedSession.call(fakeThis, snapshot);
- expect((fakeThis as unknown as { compactionQueuedMessages: unknown }).compactionQueuedMessages).toBe(
- compactionQueue,
- );
expect((fakeThis as unknown as { sideQuestionEvent: unknown }).sideQuestionEvent).toBe(sideQuestion);
expect(
(fakeThis as unknown as { activeConnectionExtensionUiRequests: unknown }).activeConnectionExtensionUiRequests,
@@ -1162,9 +1453,8 @@ describe("InteractiveMode connection events", () => {
expect(startAssistantStreamingMessage).toHaveBeenCalledWith(streamingMessage);
});
- test("finishes local compaction and bash UI when a resync proves the operations ended", async () => {
+ test("finishes local bash UI when a resync proves the operation ended", async () => {
const bashComponent = { setComplete: vi.fn() };
- const flushCompactionQueue = vi.fn(async () => {});
const flushPendingBashComponents = vi.fn();
const snapshot: AgentConnectionSnapshot = {
state: createConnectionState({ isCompacting: false, isBashRunning: false, isStreaming: false }),
@@ -1186,7 +1476,6 @@ describe("InteractiveMode connection events", () => {
renderSessionContext: vi.fn(async () => {}),
restoreStreamingMessageFromSnapshot: vi.fn(),
refreshConnectionQueue: vi.fn(async () => {}),
- flushCompactionQueue,
flushPendingBashComponents,
updateTerminalTitle: vi.fn(),
setGoalAnnouncementBaseline: vi.fn(),
@@ -1201,7 +1490,6 @@ describe("InteractiveMode connection events", () => {
}
).renderResyncedSession.call(fakeThis, snapshot);
- expect(flushCompactionQueue).toHaveBeenCalledWith({ willRetry: false });
expect(bashComponent.setComplete).toHaveBeenCalledWith(undefined, false);
expect((fakeThis as unknown as { activeBashComponent: unknown }).activeBashComponent).toBeUndefined();
expect(flushPendingBashComponents).toHaveBeenCalledOnce();
@@ -1397,16 +1685,22 @@ describe("InteractiveMode tool event rendering", () => {
});
describe("InteractiveMode transcript rebuild", () => {
- test("keeps existing chat visible when session context reload fails", async () => {
- type RebuildHarness = {
- chatContainer: Container;
- agentConnection: { getSessionContext(): Promise<never> };
- renderSessionContext(): Promise<void>;
- rebuildChatFromMessages(): Promise<void>;
- };
+ type RebuildHarness = {
+ chatContainer: Container;
+ agentConnection: { getSessionContext(): Promise<AgentConnectionSessionContext> };
+ renderSessionContext(context: AgentConnectionSessionContext, options: RenderSessionContextOptions): Promise<void>;
+ rebuildChatFromMessages(): Promise<void>;
+ };
+
+ function createRebuildHarness(): RebuildHarness {
const fakeThis = Object.create(InteractiveMode.prototype) as RebuildHarness;
fakeThis.chatContainer = new Container();
fakeThis.chatContainer.addChild(new Container());
+ return fakeThis;
+ }
+
+ test("keeps existing chat visible when session context reload fails", async () => {
+ const fakeThis = createRebuildHarness();
fakeThis.agentConnection = {
getSessionContext: vi.fn(async () => {
throw new Error("context unavailable");
@@ -1419,6 +1713,29 @@ describe("InteractiveMode transcript rebuild", () => {
expect(fakeThis.chatContainer.children).toHaveLength(1);
expect(fakeThis.renderSessionContext).not.toHaveBeenCalled();
});
+
+ test("replaces existing chat after session context reload succeeds", async () => {
+ const fakeThis = createRebuildHarness();
+ const staleChild = fakeThis.chatContainer.children[0];
+ const rebuiltChild = new Container();
+ const context: AgentConnectionSessionContext = {
+ messages: [],
+ thinkingLevel: "medium",
+ serviceTier: "default",
+ model: null,
+ };
+ fakeThis.agentConnection = { getSessionContext: vi.fn(async () => context) };
+ fakeThis.renderSessionContext = vi.fn(async (_context, options) => {
+ if (options.clearChat) fakeThis.chatContainer.clear();
+ fakeThis.chatContainer.addChild(rebuiltChild);
+ });
+
+ await fakeThis.rebuildChatFromMessages();
+
+ expect(fakeThis.renderSessionContext).toHaveBeenCalledWith(context, { clearChat: true });
+ expect(fakeThis.chatContainer.children).toEqual([rebuiltChild]);
+ expect(fakeThis.chatContainer.children).not.toContain(staleChild);
+ });
});
describe("InteractiveMode startup onboarding warnings", () => {
@@ -2381,6 +2698,24 @@ describe("InteractiveMode Prime CLI onboarding", () => {
const markOnboardingShown = (InteractiveMode.prototype as unknown as OnboardingHarness).markOnboardingShown;
const runStartupOnboarding = (InteractiveMode.prototype as unknown as OnboardingHarness).runStartupOnboarding;
const runOnboardingFlow = (InteractiveMode.prototype as unknown as OnboardingHarness).runOnboardingFlow;
+ function createStartupRunHarness(
+ options: Record<string, unknown>,
+ overrides: Record<string, unknown> = {},
+ ): Record<string, unknown> & { getUserInput: ReturnType<typeof vi.fn> } {
+ return {
+ init: vi.fn(async () => {}),
+ options: { agentsViewOwnsStartupNotices: true, ...options },
+ modelRegistry: { getError: vi.fn(() => undefined) },
+ runStartupOnboarding: vi.fn(async () => true),
+ getModelFallbackWarningAction: vi.fn(() => "suppress"),
+ maybeWarnAboutAnthropicSubscriptionAuth: vi.fn(),
+ getUserInput: vi.fn(() => new Promise<void>(() => {})),
+ showWarning: vi.fn(),
+ showError: vi.fn(),
+ sessionHasMessages: false,
+ ...overrides,
+ };
+ }
const primeModel: AgentConnectionModel = {
id: "openai/gpt-5.5",
@@ -2400,30 +2735,586 @@ describe("InteractiveMode Prime CLI onboarding", () => {
maxTokens: 128000,
} as AgentConnectionModel;
- test("defers CLI initial prompts until a model is selected after onboarding dismissal", async () => {
- let currentModel: AgentConnectionModel | undefined;
- const prompt = vi.fn(async () => {});
- const getUserInput = vi
- .fn<() => Promise<string | undefined>>()
- .mockImplementationOnce(async () => {
- currentModel = primeModel;
- return "interactive prompt";
- })
+ test("defers, retries transient startup failures, and skips a persistently failing prompt", async () => {
+ vi.useFakeTimers();
+ const inputDone = createDeferred<void>();
+ let model: AgentConnectionModel | undefined;
+ let firstAttempts = 0;
+ let secondAttempts = 0;
+ const prompt = vi.fn((message: string) => {
+ if (message === "first" && firstAttempts++ < 2) {
+ return Promise.reject(new Error(`transient failure ${firstAttempts}`));
+ }
+ if (message === "second") {
+ return Promise.reject(new Error(`admission failure ${++secondAttempts}`));
+ }
+ return Promise.resolve();
+ });
+ const showError = vi.fn();
+ const submitHarness = createSubmitHandlerHarness({
+ agentConnection: {
+ prompt,
+ executeBash: vi.fn(async () => {}),
+ getState: vi.fn(async () => ({ isBashRunning: false })),
+ },
+ });
+ const fakeThis = Object.assign(
+ submitHarness,
+ createStartupRunHarness(
+ { initialMessage: "first", initialMessages: ["second", "third"] },
+ {
+ getCurrentModel: () => model,
+ getUserInput: vi.fn(() => inputDone.promise),
+ agentConnection: submitHarness.agentConnection,
+ showError,
+ },
+ ),
+ );
+
+ try {
+ const run = InteractiveMode.prototype.run.call(fakeThis as never);
+ await vi.advanceTimersByTimeAsync(250);
+ expect(prompt).not.toHaveBeenCalled();
+
+ model = primeModel;
+ const userSubmission = fakeThis.defaultEditor.onSubmit?.("user");
+ await vi.advanceTimersByTimeAsync(1_250);
+ await userSubmission;
+
+ const steer = {
+ images: undefined,
+ streamingBehavior: "steer",
+ queueIfBusy: true,
+ signal: expect.any(AbortSignal),
+ };
+ const followUp = {
+ images: undefined,
+ streamingBehavior: "followUp",
+ queueIfBusy: true,
+ signal: expect.any(AbortSignal),
+ };
+ expect(prompt.mock.calls).toEqual([
+ ["first", steer],
+ ["first", steer],
+ ["first", steer],
+ ["second", followUp],
+ ["second", followUp],
+ ["second", followUp],
+ ["third", followUp],
+ ["user", { images: [], streamingBehavior: "steer", queueIfBusy: true }],
+ ]);
+ expect(showError.mock.calls).toEqual([
+ ["transient failure 1"],
+ ["transient failure 2"],
+ ["admission failure 1"],
+ ["admission failure 2"],
+ ["Skipping startup prompt after 3 failed attempts: admission failure 3"],
+ ]);
+
+ // Delivery settled: the retry cadence stops instead of re-prompting.
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(prompt).toHaveBeenCalledTimes(8);
+ inputDone.resolve(undefined);
+ await expect(run).resolves.toBe("agents_view");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test.each(["unsupported", "unknown"] as const)(
+ "reports %s startup admission once and retains every remaining prompt with collision-safe images",
+ async (status) => {
+ const inputDone = createDeferred<void>();
+ const firstImage = { type: "image", data: "first", mimeType: "image/png" } as const;
+ const secondImage = { type: "image", data: "second", mimeType: "image/jpeg" } as const;
+ let rejectStartup!: (error: Error) => void;
+ const startupAdmission = new Promise<void>((_resolve, reject) => {
+ rejectStartup = reject;
+ });
+ const prompt = vi.fn(() => startupAdmission);
+ const promptStashState: PromptStashState = { stash: { text: "existing draft [image #3]" } };
+ const submitHarness = createSubmitHandlerHarness({
+ promptStashState,
+ agentConnection: {
+ prompt,
+ executeBash: vi.fn(async () => {}),
+ getState: vi.fn(async () => ({ isBashRunning: false })),
+ },
+ pastedImages: new Map([[1, { type: "image", data: "existing", mimeType: "image/png" }]]),
+ nextImageMarkerId: 1,
+ });
+ const fakeThis = Object.assign(
+ submitHarness,
+ createStartupRunHarness(
+ {
+ initialMessage: "startup [image #1]",
+ initialImages: [firstImage],
+ initialPrompts: [{ text: "later [image #2]", images: [secondImage] }, { text: "last [image #4]" }],
+ },
+ {
+ getCurrentModel: () => primeModel,
+ getUserInput: vi.fn(() => inputDone.promise),
+ agentConnection: submitHarness.agentConnection,
+ },
+ ),
+ );
+
+ const run = InteractiveMode.prototype.run.call(fakeThis as never);
+ await vi.waitFor(() => expect(prompt).toHaveBeenCalledOnce());
+ const blockedSubmission = fakeThis.defaultEditor.onSubmit?.("blocked user");
+ rejectStartup(new AgentConnectionPromptAdmissionError("daemon admission uncertain", status));
+ await blockedSubmission;
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(prompt).toHaveBeenCalledOnce();
+ expect(fakeThis.showError).toHaveBeenCalledWith("daemon admission uncertain");
+ expect(fakeThis.promptStashState.stash).toEqual({
+ text: "startup [image #5] [image #6]",
+ images: [[6, firstImage]],
+ });
+ expect(fakeThis.promptStashState.queuedStashes).toEqual([
+ { text: "later [image #2] [image #7]", images: [[7, secondImage]] },
+ { text: "last [image #4]" },
+ { text: "existing draft [image #3]" },
+ { text: "blocked user" },
+ ]);
+ expect(fakeThis.pastedImages.get(1)).toEqual({ type: "image", data: "existing", mimeType: "image/png" });
+ expect(fakeThis.pastedImages.get(5)).toBeUndefined();
+ expect(fakeThis.pastedImages.get(6)).toBe(firstImage);
+ expect(fakeThis.pastedImages.get(7)).toBe(secondImage);
+ inputDone.resolve(undefined);
+ await expect(run).resolves.toBe("agents_view");
+ },
+ );
+
+ test("does not retain a startup prompt already owned by the session", async () => {
+ const inputDone = createDeferred<void>();
+ const prompt = vi
+ .fn()
+ .mockRejectedValueOnce(new AgentConnectionPromptAdmissionError("session owns prompt", "owned"))
.mockResolvedValueOnce(undefined);
+ const submitHarness = createSubmitHandlerHarness({
+ agentConnection: {
+ prompt,
+ executeBash: vi.fn(async () => {}),
+ getState: vi.fn(async () => ({ isBashRunning: false })),
+ },
+ });
+ const fakeThis = Object.assign(
+ submitHarness,
+ createStartupRunHarness(
+ { initialMessages: ["owned startup", "next startup"] },
+ {
+ getCurrentModel: () => primeModel,
+ getUserInput: vi.fn(() => inputDone.promise),
+ agentConnection: submitHarness.agentConnection,
+ },
+ ),
+ );
+
+ const run = InteractiveMode.prototype.run.call(fakeThis as never);
+ await vi.waitFor(() => expect(prompt).toHaveBeenCalledTimes(2));
+ expect(prompt.mock.calls.map(([message]) => message)).toEqual(["owned startup", "next startup"]);
+ expect(fakeThis.promptStashState.stash).toBeUndefined();
+ inputDone.resolve(undefined);
+ await expect(run).resolves.toBe("agents_view");
+ });
+
+ test.each(["typing", "Alt+Enter"] as const)(
+ "preserves %s during the startup admission barrier",
+ async (scenario) => {
+ vi.useFakeTimers();
+ let model: AgentConnectionModel | undefined;
+ let editorText = "first user prompt";
+ let startupAttempts = 0;
+ const startupAdmission = createDeferred<void>();
+ const inputDone = createDeferred<void>();
+ const prompt = vi.fn((message: string) => {
+ if (message !== "startup") return Promise.resolve();
+ startupAttempts++;
+ return startupAttempts === 1
+ ? Promise.reject(new Error("transient admission failure"))
+ : startupAdmission.promise;
+ });
+ const submitHarness = createSubmitHandlerHarness({
+ editor: {
+ getText: () => editorText,
+ getExpandedText: () => editorText,
+ setText: (text) => {
+ editorText = text;
+ },
+ },
+ agentConnection: {
+ prompt,
+ executeBash: vi.fn(async () => {}),
+ getState: vi.fn(async () => ({ isBashRunning: false })),
+ },
+ });
+ const fakeThis = Object.assign(
+ submitHarness,
+ createStartupRunHarness(
+ { initialMessage: "startup" },
+ {
+ getCurrentModel: () => model,
+ getUserInput: vi.fn(() => inputDone.promise),
+ agentConnection: submitHarness.agentConnection,
+ },
+ ),
+ );
+
+ try {
+ const run = InteractiveMode.prototype.run.call(fakeThis as never);
+ await vi.advanceTimersByTimeAsync(250);
+ fakeThis.editor.onSubmit = fakeThis.defaultEditor.onSubmit;
+ const submit = () =>
+ scenario === "typing"
+ ? fakeThis.defaultEditor.onSubmit?.(editorText)
+ : (
+ InteractiveMode.prototype as unknown as {
+ handleFollowUp(this: SubmitHandlerHarness): Promise<void>;
+ }
+ ).handleFollowUp.call(fakeThis);
+ const firstSubmission = submit();
+ await Promise.resolve();
+ expect(editorText).toBe("");
+ if (scenario === "typing") editorText = "typing during startup wait";
+ const duplicate = scenario === "Alt+Enter" ? submit() : undefined;
+ expect(prompt).not.toHaveBeenCalled();
+ model = primeModel;
+ await vi.advanceTimersByTimeAsync(250);
+ expect(prompt.mock.calls.map(([message]) => message)).toEqual(["startup"]);
+ await vi.advanceTimersByTimeAsync(249);
+ expect(prompt).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(prompt.mock.calls.map(([message]) => message)).toEqual(["startup", "startup"]);
+ startupAdmission.resolve(undefined);
+ await Promise.all([firstSubmission, duplicate]);
+ expect(prompt.mock.calls.map(([message]) => message)).toEqual(["startup", "startup", "first user prompt"]);
+ expect(editorText).toBe(scenario === "typing" ? "typing during startup wait" : "");
+ expect(prompt.mock.calls[0]).toEqual([
+ "startup",
+ {
+ images: undefined,
+ streamingBehavior: "steer",
+ queueIfBusy: true,
+ signal: expect.any(AbortSignal),
+ },
+ ]);
+ inputDone.resolve(undefined);
+ await expect(run).resolves.toBe("agents_view");
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
+ test("aborts an actually blocked startup admission when the run lifecycle ends", async () => {
+ const inputDone = createDeferred<void>();
+ let blockedSignal: AbortSignal | undefined;
+ const prompt = vi.fn((_message: string, options?: { signal?: AbortSignal }) => {
+ blockedSignal = options?.signal;
+ return new Promise<void>((_resolve, reject) => {
+ options?.signal?.addEventListener("abort", () => reject(new Error("admission aborted")), { once: true });
+ });
+ });
+ const fakeThis = Object.assign(
+ createSubmitHandlerHarness({
+ agentConnection: {
+ prompt,
+ executeBash: vi.fn(async () => {}),
+ getState: vi.fn(async () => ({ isBashRunning: false })),
+ },
+ }),
+ createStartupRunHarness(
+ { initialMessage: "startup" },
+ {
+ getCurrentModel: () => primeModel,
+ getUserInput: vi.fn(() => inputDone.promise),
+ },
+ ),
+ );
+
+ const run = InteractiveMode.prototype.run.call(fakeThis as never);
+ await vi.waitFor(() => expect(prompt).toHaveBeenCalledOnce());
+ expect(blockedSignal?.aborted).toBe(false);
+ inputDone.resolve(undefined);
+
+ await expect(run).resolves.toBe("agents_view");
+ expect(blockedSignal?.aborted).toBe(true);
+ expect(fakeThis.showError).not.toHaveBeenCalled();
+ });
+
+ test.each([false, true])(
+ "lifecycle cancellation retains the submitted draft with exact fidelity (existing stash: %s)",
+ async (hasExistingStash) => {
+ const inputDone = createDeferred<void>();
+ const store = new ClientPromptStashStore();
+ const promptStashState = store.forSession("session-a");
+ if (hasExistingStash) promptStashState.stash = { text: "older durable draft" };
+ const image = { type: "image", data: "base64", mimeType: "image/png" } as const;
+ const pasteSnapshot = { pastes: [[1, "expanded paste"]], pasteCounter: 2 } as const;
+ const submittedText = "submitted [paste #1] [image #7]";
+ let editorText = submittedText;
+ const submitHarness = createSubmitHandlerHarness({
+ editor: {
+ getText: () => editorText,
+ getExpandedText: () => "submitted expanded paste [image #7]",
+ getPasteSnapshot: () => pasteSnapshot,
+ setText: (text) => {
+ editorText = text;
+ },
+ },
+ promptStashState,
+ pastedImages: new Map([[7, image]]),
+ getPromptStashImages: () => [[7, image]],
+ });
+ delete submitHarness.promptStash;
+ const fakeThis = Object.assign(
+ submitHarness,
+ createStartupRunHarness(
+ { initialMessage: "startup" },
+ {
+ getCurrentModel: () => undefined,
+ getUserInput: vi.fn(() => inputDone.promise),
+ agentConnection: submitHarness.agentConnection,
+ },
+ ),
+ );
+
+ const run = InteractiveMode.prototype.run.call(fakeThis as never);
+ while (!fakeThis.admitPendingStartupPrompts) await Promise.resolve();
+ fakeThis.latestEditorPromptStash = {
+ text: submittedText,
+ expandedText: "submitted expanded paste [image #7]",
+ pasteSnapshot,
+ images: [[7, image]],
+ };
+ // pi-tui clears and emits onChange before invoking onSubmit.
+ editorText = "";
+ const submission = fakeThis.defaultEditor.onSubmit?.("submitted expanded paste [image #7]");
+ await Promise.resolve();
+ expect(editorText).toBe("");
+ fakeThis.returnToAgentsViewRequested = true;
+ fakeThis.isShuttingDown = true;
+ inputDone.resolve(undefined);
+
+ await expect(run).resolves.toBe("agents_view");
+ await submission;
+
+ expect(fakeThis.agentConnection.prompt).not.toHaveBeenCalled();
+ expect(editorText).toBe("");
+ const retained = hasExistingStash ? promptStashState.queuedStashes?.[0] : promptStashState.stash;
+ expect(promptStashState.stash?.text).toBe(hasExistingStash ? "older durable draft" : submittedText);
+ expect(retained).toEqual({
+ text: submittedText,
+ expandedText: "submitted expanded paste [image #7]",
+ pasteSnapshot,
+ images: [[7, image]],
+ });
+ },
+ );
+
+ test("a barrier-paused submit retains its draft in the original session's stash after a rebind", async () => {
+ const barrier = createDeferred<"admitted" | "lifecycle-cancelled">();
+ const oldState: PromptStashState = {};
+ const newState: PromptStashState = {};
+ const prompt = vi.fn(async () => {});
+ const fakeThis = createSubmitHandlerHarness({
+ promptStashState: oldState,
+ admitPendingStartupPrompts: () => barrier.promise,
+ agentConnection: {
+ prompt,
+ executeBash: vi.fn(async () => {}),
+ getState: vi.fn(async () => ({ isBashRunning: false })),
+ },
+ });
+ (fakeThis as unknown as { promptStashSessionId?: string }).promptStashSessionId = "session-old";
+
+ const submission = fakeThis.defaultEditor.onSubmit?.("typed for the old session");
+ await Promise.resolve();
+ // /new rebinds the live fields while the submit is paused on the barrier.
+ (fakeThis as unknown as { promptStashSessionId?: string }).promptStashSessionId = "session-new";
+ fakeThis.promptStashState = newState;
+ barrier.resolve("admitted");
+ await submission;
+
+ expect(prompt).not.toHaveBeenCalled();
+ expect(oldState.stash).toEqual({ text: "typed for the old session" });
+ expect(newState.stash).toBeUndefined();
+ });
+
+ test("defers stash-store release until lifecycle-retained submissions settle", () => {
+ const store = new ClientPromptStashStore();
+ const state = store.forSession("session-a");
const fakeThis = {
- init: vi.fn(async () => {}),
- options: {
- agentsViewOwnsStartupNotices: true,
- initialMessage: "initial prompt",
+ inputSubmissionsPending: 1,
+ pendingPromptStashReleases: [] as { sessionId: string; state: unknown }[],
+ promptStashStore: store,
+ promptStashSessionId: "session-a",
+ promptStashState: state,
+ retainedSubmissionGenerations: new WeakMap(),
+ };
+ const release = (InteractiveMode.prototype as unknown as { releasePromptStashSession(this: unknown): void })
+ .releasePromptStashSession;
+ const retain = (
+ InteractiveMode.prototype as unknown as {
+ retainSubmittedDraft(this: unknown, stash: { text: string }, generation: number): void;
+ }
+ ).retainSubmittedDraft;
+
+ release.call(fakeThis);
+ expect(fakeThis.pendingPromptStashReleases).toEqual([{ sessionId: "session-a", state }]);
+ expect(store.forSession("session-a")).toBe(state);
+ retain.call(fakeThis, { text: "retained" }, 1);
+ fakeThis.inputSubmissionsPending = 0;
+ release.call(fakeThis);
+ expect(store.forSession("session-a")).toBe(state);
+ expect(state.stash).toEqual({ text: "retained" });
+ });
+
+ test("a deferred release targets the session captured at deferral, not a rebound one", () => {
+ const store = new ClientPromptStashStore();
+ const oldState = store.forSession("session-old");
+ const fakeThis = {
+ inputSubmissionsPending: 1,
+ pendingPromptStashReleases: [] as { sessionId: string; state: unknown }[],
+ promptStashStore: store,
+ promptStashSessionId: "session-old",
+ promptStashState: oldState,
+ };
+ const methods = InteractiveMode.prototype as unknown as {
+ releasePromptStashSession(this: unknown): void;
+ completeDeferredPromptStashRelease(this: unknown): void;
+ };
+
+ methods.releasePromptStashSession.call(fakeThis);
+ const newState = store.forSession("session-new");
+ newState.stash = { text: "new session draft" };
+ fakeThis.promptStashSessionId = "session-new";
+ fakeThis.promptStashState = newState;
+
+ fakeThis.inputSubmissionsPending = 0;
+ methods.completeDeferredPromptStashRelease.call(fakeThis);
+
+ expect(store.forSession("session-old")).not.toBe(oldState);
+ expect(store.forSession("session-new")).toBe(newState);
+ expect(newState.stash).toEqual({ text: "new session draft" });
+ });
+
+ test("a teardown release after a rebind keeps both deferred session releases", () => {
+ const store = new ClientPromptStashStore();
+ const oldState = store.forSession("session-old");
+ const fakeThis = {
+ inputSubmissionsPending: 1,
+ pendingPromptStashReleases: [] as { sessionId: string; state: unknown }[],
+ promptStashStore: store,
+ promptStashSessionId: "session-old",
+ promptStashState: oldState,
+ };
+ const methods = InteractiveMode.prototype as unknown as {
+ releasePromptStashSession(this: unknown): void;
+ completeDeferredPromptStashRelease(this: unknown): void;
+ };
+
+ // /new rebind defers the old session's release...
+ methods.releasePromptStashSession.call(fakeThis);
+ const newState = store.forSession("session-new");
+ fakeThis.promptStashSessionId = "session-new";
+ fakeThis.promptStashState = newState;
+ // ...then teardown defers the rebound session's release while the same
+ // submission is still pending. The first pair must not be overwritten.
+ methods.releasePromptStashSession.call(fakeThis);
+ expect(fakeThis.pendingPromptStashReleases.map((pending) => pending.sessionId)).toEqual([
+ "session-old",
+ "session-new",
+ ]);
+
+ fakeThis.inputSubmissionsPending = 0;
+ methods.completeDeferredPromptStashRelease.call(fakeThis);
+
+ expect(store.forSession("session-old")).not.toBe(oldState);
+ expect(store.forSession("session-new")).not.toBe(newState);
+ });
+
+ test("orders retained drafts by submission rather than rejection", () => {
+ const state: PromptStashState = {};
+ const fakeThis = {
+ promptStashState: state,
+ retainedSubmissionGenerations: new WeakMap(),
+ };
+ Object.defineProperty(fakeThis, "promptStash", {
+ get: () => state.stash,
+ set: (stash) => {
+ state.stash = stash;
+ },
+ });
+ const retain = (
+ InteractiveMode.prototype as unknown as {
+ retainSubmittedDraft(this: unknown, stash: { text: string }, generation: number): void;
+ }
+ ).retainSubmittedDraft;
+
+ retain.call(fakeThis, { text: "second" }, 2);
+ retain.call(fakeThis, { text: "first" }, 1);
+ expect(state.stash).toEqual({ text: "first" });
+ expect(state.queuedStashes).toEqual([{ text: "second" }]);
+ });
+
+ test("retains every blocked submission in submission order on lifecycle cancellation", async () => {
+ const inputDone = createDeferred<void>();
+ const promptStashState: PromptStashState = {};
+ let editorText = "first rich draft";
+ const submitHarness = createSubmitHandlerHarness({
+ editor: {
+ getText: () => editorText,
+ setText: (text) => {
+ editorText = text;
+ },
},
+ promptStashState,
+ });
+ delete submitHarness.promptStash;
+ const fakeThis = Object.assign(
+ submitHarness,
+ createStartupRunHarness(
+ { initialMessage: "startup" },
+ {
+ getCurrentModel: () => undefined,
+ getUserInput: vi.fn(() => inputDone.promise),
+ agentConnection: submitHarness.agentConnection,
+ },
+ ),
+ );
+
+ const run = InteractiveMode.prototype.run.call(fakeThis as never);
+ while (!fakeThis.admitPendingStartupPrompts) await Promise.resolve();
+ fakeThis.latestEditorPromptStash = { text: "first rich draft", expandedText: "first expanded" };
+ editorText = "";
+ const first = fakeThis.defaultEditor.onSubmit?.("first rich draft");
+ fakeThis.latestEditorPromptStash = { text: "second rich draft", expandedText: "second expanded" };
+ const second = fakeThis.defaultEditor.onSubmit?.("second rich draft");
+ await Promise.resolve();
+
+ fakeThis.returnToAgentsViewRequested = true;
+ fakeThis.isShuttingDown = true;
+ inputDone.resolve(undefined);
+ await expect(run).resolves.toBe("agents_view");
+ await Promise.all([first, second]);
+
+ expect(promptStashState.stash).toEqual({ text: "first rich draft", expandedText: "first expanded" });
+ expect(promptStashState.queuedStashes).toEqual([{ text: "second rich draft", expandedText: "second expanded" }]);
+ });
+
+ test("keeps the TUI alive while direct editor submissions own prompt delivery", async () => {
+ const fakeThis = {
+ init: vi.fn(async () => {}),
+ options: { agentsViewOwnsStartupNotices: true },
modelRegistry: { getError: vi.fn(() => undefined) },
runStartupOnboarding: vi.fn(async () => true),
getModelFallbackWarningAction: vi.fn(() => "suppress"),
- getCurrentModel: vi.fn(() => currentModel),
+ getCurrentModel: vi.fn(() => primeModel),
maybeWarnAboutAnthropicSubscriptionAuth: vi.fn(),
- getUserInput,
- collectImagesFor: vi.fn(() => []),
- agentConnection: { prompt },
+ getUserInput: vi.fn(async () => undefined),
+ agentConnection: { prompt: vi.fn() },
showWarning: vi.fn(),
showError: vi.fn(),
returnToAgentsViewRequested: false,
@@ -2431,10 +3322,8 @@ describe("InteractiveMode Prime CLI onboarding", () => {
};
await expect(InteractiveMode.prototype.run.call(fakeThis as never)).resolves.toBe("agents_view");
-
- expect(prompt).toHaveBeenNthCalledWith(1, "initial prompt", { images: undefined });
- expect(prompt).toHaveBeenNthCalledWith(2, "interactive prompt", { streamingBehavior: "steer", images: [] });
- expect(prompt).toHaveBeenCalledTimes(2);
+ expect(fakeThis.getUserInput).toHaveBeenCalledOnce();
+ expect(fakeThis.agentConnection.prompt).not.toHaveBeenCalled();
});
function createPrimeCliHarness(shown: boolean): OnboardingFake {
@@ -2931,71 +3820,83 @@ describe("InteractiveMode live context usage", () => {
expect(prototype.getConnectionContextUsage.call(fakeThis)).toBeUndefined();
});
- test("refreshConnectionContextUsage drops stale stats after a session switch", async () => {
- type RefreshHarness = {
- agentConnection: { getSessionStats(): Promise<{ contextUsage: unknown }> };
- connectionState: { sessionId?: string; contextUsage?: unknown };
- activityTracker: { getStatus(): { tokens: number } };
- contextUsageTokenBaseline: number;
- patchConnectionState(patch: Record<string, unknown>): void;
- refreshConnectionContextUsage(): Promise<void>;
- };
- const refresh = (InteractiveMode.prototype as unknown as RefreshHarness).refreshConnectionContextUsage;
- const fakeThis = Object.create(InteractiveMode.prototype) as RefreshHarness;
- const patched: Record<string, unknown>[] = [];
+ type RefreshHarness = {
+ agentConnection: { getSessionStats(): Promise<{ contextUsage: unknown } | undefined> };
+ connectionState: { sessionId?: string; contextUsage?: unknown };
+ activityTracker: { getStatus(): { tokens: number } };
+ contextUsageTokenBaseline: number;
+ contextUsageRefresh: { generation: number; lastSuccessGeneration: number };
+ patchConnectionState(patch: Record<string, unknown>): void;
+ refreshConnectionContextUsage(): Promise<void>;
+ };
+ const refresh = (InteractiveMode.prototype as unknown as RefreshHarness).refreshConnectionContextUsage;
+
+ function createRefreshHarness(
+ getSessionStats: RefreshHarness["agentConnection"]["getSessionStats"],
+ ): RefreshHarness & { patched: Record<string, unknown>[] } {
+ const fakeThis = Object.create(InteractiveMode.prototype) as RefreshHarness & {
+ patched: Record<string, unknown>[];
+ };
+ fakeThis.patched = [];
fakeThis.activityTracker = { getStatus: () => ({ tokens: 0 }) };
fakeThis.contextUsageTokenBaseline = 0;
+ fakeThis.contextUsageRefresh = { generation: 0, lastSuccessGeneration: 0 };
fakeThis.connectionState = { sessionId: "session-A", contextUsage: undefined };
- fakeThis.patchConnectionState = (p) => patched.push(p);
- fakeThis.agentConnection = {
- getSessionStats: async () => {
- // User switches sessions while the stats call is in flight.
- fakeThis.connectionState = { sessionId: "session-B", contextUsage: undefined };
- return { contextUsage: { contextWindow: 100_000, tokens: 50_000, percent: 50 } };
- },
- };
+ fakeThis.patchConnectionState = (patch) => fakeThis.patched.push(patch);
+ fakeThis.agentConnection = { getSessionStats };
+ return fakeThis;
+ }
+
+ test("refreshConnectionContextUsage drops stale stats after a session switch", async () => {
+ let fakeThis: ReturnType<typeof createRefreshHarness>;
+ fakeThis = createRefreshHarness(async () => {
+ // User switches sessions while the stats call is in flight.
+ fakeThis.connectionState = { sessionId: "session-B", contextUsage: undefined };
+ return { contextUsage: { contextWindow: 100_000, tokens: 50_000, percent: 50 } };
+ });
await refresh.call(fakeThis);
// Stats belonged to session-A; must not overwrite session-B.
- expect(patched).toHaveLength(0);
+ expect(fakeThis.patched).toHaveLength(0);
});
-});
-describe("InteractiveMode.handleGoalStatusCommand", () => {
- test("prints current goal details without queuing through the agent", () => {
- type GoalStatusCommandHarness = {
- connectionState: { goal: GoalState };
- chatContainer: Container;
- ui: { requestRender(): void };
- handleGoalStatusCommand(): void;
- formatGoalElapsed(seconds: number): string;
- };
- const fakeThis = Object.create(InteractiveMode.prototype) as GoalStatusCommandHarness;
- fakeThis.connectionState = {
- goal: {
- active: true,
- status: "active",
- objective: "ship the feature",
- tokenBudget: 1000,
- tokensUsed: 125,
- timeUsedSeconds: 65,
- continuationsUsed: 2,
- },
- };
- fakeThis.chatContainer = new Container();
- fakeThis.ui = { requestRender: vi.fn() };
+ test("refreshConnectionContextUsage keeps a newer successful same-session response", async () => {
+ const first = createDeferred<{ contextUsage: unknown }>();
+ const second = createDeferred<{ contextUsage: unknown }>();
+ let request = 0;
+ const fakeThis = createRefreshHarness(() => (++request === 1 ? first.promise : second.promise));
- fakeThis.handleGoalStatusCommand();
+ const olderRefresh = refresh.call(fakeThis);
+ const newerRefresh = refresh.call(fakeThis);
+ second.resolve({ contextUsage: { tokens: 10, contextWindow: 100, percent: 10 } });
+ await newerRefresh;
+ first.resolve({ contextUsage: { tokens: 90, contextWindow: 100, percent: 90 } });
+ await olderRefresh;
- const rendered = normalizeRenderedOutput(fakeThis.chatContainer);
- expect(rendered).toContain("Goal");
- expect(rendered).toContain("Status: active");
- expect(rendered).toContain("Objective: ship the feature");
- expect(rendered).toContain("Time: 1m 05s");
- expect(rendered).toContain("Tokens: 125 / 1,000");
- expect(fakeThis.ui.requestRender).toHaveBeenCalledTimes(1);
+ expect(fakeThis.patched).toEqual([{ contextUsage: { tokens: 10, contextWindow: 100, percent: 10 } }]);
});
+
+ test.each(["failure", "no stats"] as const)(
+ "refreshConnectionContextUsage lets an older successful response survive a newer %s",
+ async (newerResult) => {
+ const first = createDeferred<{ contextUsage: unknown }>();
+ let request = 0;
+ const fakeThis = createRefreshHarness(() => {
+ if (++request === 1) return first.promise;
+ return newerResult === "failure"
+ ? Promise.reject(new Error("stats unavailable"))
+ : Promise.resolve(undefined);
+ });
+
+ const olderRefresh = refresh.call(fakeThis);
+ await refresh.call(fakeThis);
+ first.resolve({ contextUsage: { tokens: 90, contextWindow: 100, percent: 90 } });
+ await olderRefresh;
+
+ expect(fakeThis.patched).toEqual([{ contextUsage: { tokens: 90, contextWindow: 100, percent: 90 } }]);
+ },
+ );
});
describe("truncatePathMiddle", () => {
diff --git a/packages/coding-agent/test/interactive-mode-streaming.test.ts b/packages/coding-agent/test/interactive-mode-streaming.test.ts
index e7f860f68f..b104de2207 100644
--- a/packages/coding-agent/test/interactive-mode-streaming.test.ts
+++ b/packages/coding-agent/test/interactive-mode-streaming.test.ts
@@ -50,6 +50,8 @@ type HandleEventThis = {
stopWorkingLoader(): void;
resetPendingToolState(): void;
checkShutdownRequested(): Promise<void>;
+ applyOptimisticContextUsage(): void;
+ refreshConnectionContextUsage(): Promise<void>;
setSessionHasMessages(hasMessages: boolean): void;
clearShortcutGuide(): void;
addMessageToChat(): void;
@@ -100,6 +102,8 @@ function createFakeInteractiveModeThis(): HandleEventThis {
stopWorkingLoader: vi.fn(),
resetPendingToolState: vi.fn(),
checkShutdownRequested: vi.fn(async () => {}),
+ applyOptimisticContextUsage: vi.fn(),
+ refreshConnectionContextUsage: vi.fn(async () => {}),
setSessionHasMessages: vi.fn(),
clearShortcutGuide: vi.fn(),
addMessageToChat: vi.fn(),
@@ -171,6 +175,22 @@ describe("InteractiveMode streaming events", () => {
expect(fakeThis.streamingMessage).toBeUndefined();
});
+ test("does not block later compaction events on the agent-end stats refresh", async () => {
+ const fakeThis = createFakeInteractiveModeThis();
+ let resolveRefresh!: () => void;
+ fakeThis.refreshConnectionContextUsage = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveRefresh = resolve;
+ }),
+ );
+ const handleEvent = (InteractiveMode.prototype as unknown as { handleEvent: HandleEvent }).handleEvent;
+
+ await expect(handleEvent.call(fakeThis, { type: "agent_end", messages: [] })).resolves.toBeUndefined();
+ expect(fakeThis.refreshConnectionContextUsage).toHaveBeenCalledOnce();
+ resolveRefresh();
+ });
+
test("keeps attached partial assistant text when agent_end arrives without message_end", async () => {
const fakeThis = createFakeInteractiveModeThis();
const handleEvent = (InteractiveMode.prototype as unknown as { handleEvent: HandleEvent }).handleEvent;
diff --git a/packages/coding-agent/test/mutation-drain-latch.test.ts b/packages/coding-agent/test/mutation-drain-latch.test.ts
new file mode 100644
index 0000000000..4a8c67e3c3
--- /dev/null
+++ b/packages/coding-agent/test/mutation-drain-latch.test.ts
@@ -0,0 +1,33 @@
+import { getEventListeners } from "node:events";
+import { describe, expect, it, vi } from "vitest";
+import { MutationDrainLatch } from "../src/modes/daemon/mutation-drain-latch.js";
+
+describe("MutationDrainLatch", () => {
+ it("rejects an already-aborted wait even when no mutations are active", async () => {
+ const latch = new MutationDrainLatch();
+ const controller = new AbortController();
+ controller.abort();
+ const addEventListener = vi.spyOn(controller.signal, "addEventListener");
+
+ await expect(latch.waitForDrain(0, controller.signal, "drain cancelled")).rejects.toThrow("drain cancelled");
+ expect(addEventListener).not.toHaveBeenCalled();
+ });
+
+ it("keeps abort terminal when draining and aborting concurrently without leaking its listener", async () => {
+ const latch = new MutationDrainLatch();
+ const controller = new AbortController();
+ const addEventListener = vi.spyOn(controller.signal, "addEventListener");
+ const removeEventListener = vi.spyOn(controller.signal, "removeEventListener");
+ latch.begin();
+
+ const drained = latch.waitForDrain(0, controller.signal, "drain cancelled");
+ latch.end();
+ controller.abort();
+
+ await expect(drained).rejects.toThrow("drain cancelled");
+ expect(addEventListener).toHaveBeenCalledOnce();
+ expect(removeEventListener).toHaveBeenCalledWith("abort", expect.any(Function));
+ expect(removeEventListener).toHaveBeenCalledOnce();
+ expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);
+ });
+});
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 d80d3d3c1d..bb80e373b8 100644
--- a/packages/coding-agent/test/package-self-update-daemon.test.ts
+++ b/packages/coding-agent/test/package-self-update-daemon.test.ts
@@ -45,6 +45,7 @@ interface MockCustomMessage {
content: string;
display: boolean;
timestamp: number;
+ details?: unknown;
}
interface MockQueuedMessage {
@@ -1217,6 +1218,16 @@ 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 prefixMessage: MockCustomMessage = {
role: "custom",
customType: "ipython_state_restored",
@@ -1243,6 +1254,11 @@ describe("self-update daemon restart", () => {
customMessage,
prefixMessages: [prefixMessage],
},
+ {
+ message: "/autonomous on",
+ agentMessageId: "agentmsg_command",
+ customMessage: commandMessage,
+ },
],
nextTurn: [],
},
@@ -1273,6 +1289,31 @@ describe("self-update daemon restart", () => {
prefixMessages: [prefixMessage],
}),
);
+ expect(mockState.requestPayloads).toContainEqual(
+ expect.objectContaining({
+ type: "follow_up",
+ activeSessionId: "restored-active",
+ message: "/autonomous on",
+ agentMessageId: "agentmsg_command",
+ customMessage: commandMessage,
+ }),
+ );
+ mockState.prepareResponse = {
+ success: true,
+ data: {
+ ...mockState.prepareManifest,
+ sessions: mockState.prepareManifest.sessions.map((session) => ({
+ ...session,
+ queue: {
+ ...session.queue,
+ followUp: [{ message: "/autonomous off", customMessage: commandMessage }],
+ },
+ })),
+ },
+ };
+ await expect(prepareDaemonUpdateRestart(mockState.socketPath, agentDir)).rejects.toThrow(
+ "invalid custom queued message",
+ );
} 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 2149b1a251..4ef87094d0 100644
--- a/packages/coding-agent/test/print-mode.test.ts
+++ b/packages/coding-agent/test/print-mode.test.ts
@@ -1,9 +1,22 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { AssistantMessage, ImageContent } from "@earendil-works/pi-ai";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { AgentAutonomousStatus } from "../src/core/autonomous.js";
+import {
+ createCompactionOutcomeMessage,
+ createCustomMessage,
+ createSessionSlashCommandResultMessage,
+} from "../src/core/messages.js";
import type { SessionShutdownEvent } from "../src/index.js";
+import { selectHeadlessTerminalResult } from "../src/modes/headless-completion.js";
import { runPrintMode } from "../src/modes/print-mode.js";
+const output = vi.hoisted(() => ({ write: vi.fn(), flush: vi.fn(async () => {}) }));
+vi.mock("../src/core/output-guard.js", () => ({
+ writeRawStdout: output.write,
+ flushRawStdout: output.flush,
+}));
+
type EmitEvent = SessionShutdownEvent;
type FakeExtensionRunner = {
@@ -14,11 +27,13 @@ type FakeExtensionRunner = {
type FakeSession = {
sessionManager: { getHeader: () => object | undefined };
agent: { waitForIdle: ReturnType<typeof vi.fn<() => Promise<void>>> };
- state: { messages: AssistantMessage[] };
+ state: { messages: AgentMessage[] };
+ messages: AgentMessage[];
extensionRunner: FakeExtensionRunner;
bindExtensions: ReturnType<typeof vi.fn>;
subscribe: ReturnType<typeof vi.fn>;
prompt: ReturnType<typeof vi.fn>;
+ promptAndWait: ReturnType<typeof vi.fn>;
reload: ReturnType<typeof vi.fn>;
getAutonomousStatus: ReturnType<typeof vi.fn>;
recordHostAutonomousContinuation: ReturnType<typeof vi.fn>;
@@ -60,7 +75,7 @@ function createAssistantMessage(options?: {
}
function createRuntimeHost(
- assistantMessage: AssistantMessage,
+ assistantMessage: AgentMessage | AgentMessage[],
autonomousStatus: AgentAutonomousStatus = {
enabled: false,
continuationsUsed: 0,
@@ -76,16 +91,18 @@ function createRuntimeHost(
emit: vi.fn(async () => {}),
};
- const state = { messages: [assistantMessage] };
+ const state = { messages: Array.isArray(assistantMessage) ? assistantMessage : [assistantMessage] };
const session: FakeSession = {
sessionManager: { getHeader: () => undefined },
agent: { waitForIdle: vi.fn(async () => {}) },
state,
+ messages: state.messages,
extensionRunner,
bindExtensions: vi.fn(async () => {}),
subscribe: vi.fn(() => () => {}),
prompt: vi.fn(async () => {}),
+ promptAndWait: vi.fn(async () => {}),
reload: vi.fn(async () => {}),
getAutonomousStatus: vi.fn(() => autonomousStatus),
recordHostAutonomousContinuation: vi.fn(),
@@ -121,11 +138,101 @@ describe("runPrintMode", () => {
});
expect(exitCode).toBe(0);
- expect(session.prompt).toHaveBeenCalledWith("Say done", { images });
+ expect(session.promptAndWait).toHaveBeenCalledWith("Say done", { images });
expect(session.extensionRunner.emit).toHaveBeenCalledTimes(1);
expect(session.extensionRunner.emit).toHaveBeenCalledWith({ type: "session_shutdown", reason: "quit" });
});
+ it("prints successful session command results in text mode", async () => {
+ const result = createSessionSlashCommandResultMessage("No active goal.", {
+ command: { name: "goal", args: "status", text: "/goal status" },
+ success: true,
+ severity: "info",
+ });
+ const runtimeHost = createRuntimeHost(result);
+ output.write.mockClear();
+
+ const exitCode = await runPrintMode(runtimeHost as unknown as Parameters<typeof runPrintMode>[0], {
+ mode: "text",
+ });
+
+ expect(exitCode).toBe(0);
+ expect(output.write).toHaveBeenCalledWith("No active goal.\n");
+ });
+
+ it("prints a session command result before a trailing compaction outcome", async () => {
+ const result = createSessionSlashCommandResultMessage("No active goal.", {
+ command: { name: "goal", args: "status", text: "/goal status" },
+ success: true,
+ severity: "info",
+ });
+ const outcome = createCompactionOutcomeMessage("Requested compaction skipped", {
+ reason: "requested",
+ outcome: "skipped",
+ });
+ const runtimeHost = createRuntimeHost([result, outcome]);
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ output.write.mockClear();
+
+ const exitCode = await runPrintMode(runtimeHost as unknown as Parameters<typeof runPrintMode>[0], {
+ mode: "text",
+ });
+
+ expect(exitCode).toBe(0);
+ expect(output.write).toHaveBeenCalledWith("No active goal.\n");
+ expect(errorSpy).toHaveBeenCalledWith("Requested compaction skipped");
+ });
+
+ it("skips malformed terminal outcomes without hiding earlier valid failures", () => {
+ const failed = createCompactionOutcomeMessage("Compaction failed", {
+ reason: "requested",
+ outcome: "failed",
+ });
+ const malformed = { ...failed, details: { reason: "unknown", outcome: "failed" } } as AgentMessage;
+ const assistant = createAssistantMessage({ text: "done" });
+
+ expect(selectHeadlessTerminalResult([assistant, failed, malformed])).toEqual({
+ primary: assistant,
+ compactionOutcomes: [failed],
+ });
+ });
+
+ it("does not select a result across a message barrier", () => {
+ const outcome = createCompactionOutcomeMessage("Requested compaction skipped", {
+ reason: "requested",
+ outcome: "skipped",
+ });
+ const barriers: AgentMessage[] = [
+ { role: "user", content: "next request", timestamp: Date.now() },
+ createCustomMessage("extension.notice", "unrelated", true, undefined, new Date().toISOString()),
+ ];
+
+ for (const barrier of barriers) {
+ expect(selectHeadlessTerminalResult([createAssistantMessage({ text: "stale" }), barrier, outcome])).toEqual({
+ primary: undefined,
+ compactionOutcomes: [outcome],
+ });
+ }
+ });
+
+ it("returns non-zero for failed session command results in text mode", async () => {
+ const result = createSessionSlashCommandResultMessage("Command failed: bad arguments", {
+ command: { name: "refine", args: "rollback", text: "/refine rollback" },
+ success: false,
+ severity: "error",
+ error: "bad arguments",
+ });
+ const runtimeHost = createRuntimeHost(result);
+ output.write.mockClear();
+
+ const exitCode = await runPrintMode(runtimeHost as unknown as Parameters<typeof runPrintMode>[0], {
+ mode: "text",
+ });
+
+ expect(exitCode).toBe(1);
+ expect(output.write).toHaveBeenCalledWith("Command failed: bad arguments\n");
+ });
+
it("emits session_shutdown in json mode", async () => {
const runtimeHost = createRuntimeHost(createAssistantMessage({ text: "done" }));
const { session } = runtimeHost;
@@ -136,7 +243,7 @@ describe("runPrintMode", () => {
});
expect(exitCode).toBe(0);
- expect(session.prompt).toHaveBeenCalledWith("hello");
+ expect(session.promptAndWait).toHaveBeenCalledWith("hello", {});
expect(session.extensionRunner.emit).toHaveBeenCalledTimes(1);
expect(session.extensionRunner.emit).toHaveBeenCalledWith({ type: "session_shutdown", reason: "quit" });
});
@@ -158,6 +265,42 @@ describe("runPrintMode", () => {
expect(session.extensionRunner.emit).toHaveBeenCalledWith({ type: "session_shutdown", reason: "quit" });
});
+ it("prints assistant output and reports a trailing compaction outcome", async () => {
+ const outcome = createCompactionOutcomeMessage("Auto-compaction skipped: nothing to compact", {
+ reason: "threshold",
+ outcome: "skipped",
+ });
+ const runtimeHost = createRuntimeHost([createAssistantMessage({ text: "done" }), outcome]);
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ output.write.mockClear();
+
+ const exitCode = await runPrintMode(runtimeHost as unknown as Parameters<typeof runPrintMode>[0], {
+ mode: "text",
+ });
+
+ expect(exitCode).toBe(0);
+ expect(output.write).toHaveBeenCalledWith("done\n");
+ expect(errorSpy).toHaveBeenCalledWith("Auto-compaction skipped: nothing to compact");
+ });
+
+ it("reports an outcome-only failure and exits non-zero", async () => {
+ const outcome = createCompactionOutcomeMessage("Context overflow recovery failed", {
+ reason: "overflow",
+ outcome: "failed",
+ });
+ const runtimeHost = createRuntimeHost(outcome);
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ output.write.mockClear();
+
+ const exitCode = await runPrintMode(runtimeHost as unknown as Parameters<typeof runPrintMode>[0], {
+ mode: "text",
+ });
+
+ expect(exitCode).toBe(1);
+ expect(output.write).not.toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith("Context overflow recovery failed");
+ });
+
it("stops host-driven gate retries once gate maxRetries is exhausted", async () => {
const runtimeHost = createRuntimeHost(createAssistantMessage({ text: "still failing" }), {
enabled: true,
@@ -301,7 +444,10 @@ describe("runPrintMode", () => {
() => statuses[Math.min(statusIndex++, statuses.length - 1)] as AgentAutonomousStatus,
);
session.prompt.mockImplementationOnce(async () => {
- session.state.messages = [createAssistantMessage({ stopReason: "error", errorMessage: "provider down" })];
+ session.state.messages = [
+ createAssistantMessage({ stopReason: "error", errorMessage: "provider down" }),
+ createCompactionOutcomeMessage("Auto-compaction failed", { reason: "threshold", outcome: "failed" }),
+ ];
});
session.prompt.mockImplementationOnce(async () => {
session.state.messages = [createAssistantMessage({ text: "still failing" })];
diff --git a/packages/coding-agent/test/session-command-messages.test.ts b/packages/coding-agent/test/session-command-messages.test.ts
new file mode 100644
index 0000000000..eea3376a2b
--- /dev/null
+++ b/packages/coding-agent/test/session-command-messages.test.ts
@@ -0,0 +1,211 @@
+import type { TUI } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { beforeAll, describe, expect, test, vi } from "vitest";
+import {
+ COMPACTION_OUTCOME_CUSTOM_TYPE,
+ type CustomMessage,
+ convertToLlm,
+ createCompactionOutcomeMessage,
+ createSessionSlashCommandMessage,
+ createSessionSlashCommandResultMessage,
+ isCompactionOutcomeMessage,
+ isSessionSlashCommandMessage,
+ isSessionSlashCommandResultMessage,
+ SESSION_SLASH_COMMAND_CUSTOM_TYPE,
+ SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE,
+} from "../src/core/messages.js";
+import { parseSessionSlashCommand } from "../src/core/slash-commands.js";
+import { CompactionOutcomeMessageComponent } from "../src/modes/interactive/components/compaction-outcome-message.js";
+import { buildConversationComponents } from "../src/modes/interactive/components/conversation-components.js";
+import { SlashCommandMessageComponent } from "../src/modes/interactive/components/slash-command-message.js";
+import { SlashCommandResultMessageComponent } from "../src/modes/interactive/components/slash-command-result-message.js";
+import { initTheme } from "../src/modes/interactive/theme/theme.js";
+
+const componentOptions = {
+ ui: { requestRender: vi.fn() } as unknown as TUI,
+ cwd: "/tmp",
+ toolOptions: {},
+ getToolDefinition: () => undefined,
+};
+
+function customMessage(customType: string, details?: unknown): CustomMessage {
+ return {
+ role: "custom",
+ customType,
+ content: "durable display text",
+ display: true,
+ details,
+ timestamp: 123,
+ };
+}
+
+describe("session command messages", () => {
+ beforeAll(() => {
+ initTheme("dark");
+ });
+
+ test("creates and recognizes typed command and result messages", () => {
+ const command = parseSessionSlashCommand("/goal\tship it");
+ expect(command).toBeDefined();
+ const commandMessage = createSessionSlashCommandMessage(command!, { commandEntryId: "entry-1" }, true, 123);
+ const attemptedOverwrite = Reflect.apply(createSessionSlashCommandMessage, undefined, [
+ command!,
+ { command: { name: "compact", args: "", text: "/compact" } },
+ ]);
+ const resultMessage = createSessionSlashCommandResultMessage(
+ "Goal unavailable",
+ {
+ command: command!,
+ success: false,
+ severity: "warning",
+ error: "Goal unavailable",
+ commandEntryId: "entry-1",
+ },
+ true,
+ 124,
+ );
+
+ expect(commandMessage).toEqual({
+ role: "custom",
+ customType: SESSION_SLASH_COMMAND_CUSTOM_TYPE,
+ content: "/goal\tship it",
+ display: true,
+ details: {
+ command: { name: "goal", args: "ship it", text: "/goal\tship it" },
+ commandEntryId: "entry-1",
+ },
+ timestamp: 123,
+ });
+ expect(isSessionSlashCommandMessage(commandMessage)).toBe(true);
+ expect(attemptedOverwrite.details.command).toEqual(command);
+ expect(isSessionSlashCommandResultMessage(resultMessage)).toBe(true);
+ expect(
+ isSessionSlashCommandResultMessage({
+ ...resultMessage,
+ details: { ...resultMessage.details, command: { ...command!, text: "/compact" } },
+ }),
+ ).toBe(false);
+ expect(
+ isSessionSlashCommandResultMessage({
+ ...resultMessage,
+ details: { ...resultMessage.details, severity: "fatal" },
+ }),
+ ).toBe(false);
+ expect(
+ isSessionSlashCommandResultMessage({ ...resultMessage, details: { ...resultMessage.details, success: "no" } }),
+ ).toBe(false);
+ expect(
+ isSessionSlashCommandResultMessage({
+ ...resultMessage,
+ details: { ...resultMessage.details, commandEntryId: "" },
+ }),
+ ).toBe(false);
+ expect(
+ isSessionSlashCommandMessage({
+ ...commandMessage,
+ details: { command: { ...commandMessage.details.command, name: "compact" } },
+ }),
+ ).toBe(false);
+ expect(
+ isSessionSlashCommandMessage({
+ ...commandMessage,
+ details: { command: { ...commandMessage.details.command, args: "other" } },
+ }),
+ ).toBe(false);
+ expect(
+ isSessionSlashCommandMessage({
+ ...commandMessage,
+ details: { command: { ...commandMessage.details.command, text: "/goal other" } },
+ }),
+ ).toBe(false);
+ expect(isSessionSlashCommandMessage({ ...commandMessage, timestamp: Number.NaN })).toBe(false);
+ expect(
+ isSessionSlashCommandMessage({
+ ...commandMessage,
+ details: { ...commandMessage.details, commandEntryId: "" },
+ }),
+ ).toBe(false);
+ });
+
+ test("creates and validates typed compaction outcome messages", () => {
+ const outcome = createCompactionOutcomeMessage(
+ "Requested compaction skipped: too short",
+ { reason: "requested", outcome: "skipped" },
+ true,
+ 123,
+ );
+
+ expect(outcome).toEqual({
+ role: "custom",
+ customType: COMPACTION_OUTCOME_CUSTOM_TYPE,
+ content: "Requested compaction skipped: too short",
+ display: true,
+ details: { reason: "requested", outcome: "skipped" },
+ timestamp: 123,
+ });
+ expect(isCompactionOutcomeMessage(outcome)).toBe(true);
+ expect(isCompactionOutcomeMessage({ ...outcome, details: { reason: "manual", outcome: "skipped" } })).toBe(false);
+ expect(isCompactionOutcomeMessage({ ...outcome, details: { reason: "requested", outcome: "success" } })).toBe(
+ false,
+ );
+ expect(isCompactionOutcomeMessage({ ...outcome, timestamp: Number.NaN })).toBe(false);
+ });
+
+ test("excludes durable command, result, and compaction outcome entries from LLM context", () => {
+ const command = parseSessionSlashCommand("/compact");
+ expect(command).toBeDefined();
+
+ expect(
+ convertToLlm([
+ createSessionSlashCommandMessage(command!),
+ createSessionSlashCommandResultMessage("Skipped", {
+ command: command!,
+ success: false,
+ severity: "warning",
+ }),
+ customMessage(SESSION_SLASH_COMMAND_CUSTOM_TYPE),
+ customMessage(SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE),
+ customMessage(COMPACTION_OUTCOME_CUSTOM_TYPE),
+ ]),
+ ).toEqual([]);
+ });
+
+ test("continues to include ordinary custom messages", () => {
+ expect(convertToLlm([customMessage("extension_notice")])).toMatchObject([
+ { role: "user", content: [{ type: "text", text: "durable display text" }] },
+ ]);
+ });
+
+ test("dispatches valid messages and safely diagnoses malformed reserved entries", () => {
+ const command = parseSessionSlashCommand("/compact focus");
+ expect(command).toBeDefined();
+ const components = buildConversationComponents(
+ [
+ createSessionSlashCommandMessage(command!),
+ createSessionSlashCommandResultMessage("Compaction skipped", {
+ command: command!,
+ success: false,
+ severity: "warning",
+ }),
+ createCompactionOutcomeMessage("Auto-compaction skipped", {
+ reason: "threshold",
+ outcome: "skipped",
+ }),
+ customMessage(SESSION_SLASH_COMMAND_CUSTOM_TYPE, { command: "not-a-command" }),
+ customMessage(SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE, { severity: "fatal" }),
+ customMessage(COMPACTION_OUTCOME_CUSTOM_TYPE, { reason: "manual", outcome: "skipped" }),
+ ],
+ componentOptions,
+ );
+ const output = stripAnsi(components.flatMap((component) => component.render(80)).join("\n"));
+
+ expect(components[0]).toBeInstanceOf(SlashCommandMessageComponent);
+ expect(components[1]).toBeInstanceOf(SlashCommandResultMessageComponent);
+ expect(components[2]).toBeInstanceOf(CompactionOutcomeMessageComponent);
+ expect(output).toContain("Compaction skipped");
+ expect(output).toContain("Auto-compaction skipped");
+ expect(output.match(/\[Malformed session command message\]/g)).toHaveLength(2);
+ expect(output).toContain("[Malformed compaction outcome message]");
+ expect(output).not.toContain("durable display text");
+ });
+});
diff --git a/packages/coding-agent/test/session-manager-flush.test.ts b/packages/coding-agent/test/session-manager-flush.test.ts
index 33b7cd22f9..0feb728369 100644
--- a/packages/coding-agent/test/session-manager-flush.test.ts
+++ b/packages/coding-agent/test/session-manager-flush.test.ts
@@ -1,7 +1,51 @@
-import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import {
+ appendFileSync,
+ chmodSync,
+ type chownSync,
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ type renameSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ type writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { basename, dirname, join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
+
+type ChmodSync = typeof chmodSync;
+type ChownSync = typeof chownSync;
+type RenameSync = typeof renameSync;
+type WriteFileSync = typeof writeFileSync;
+
+const fsMocks = vi.hoisted(() => ({
+ actualWriteFileSync: undefined as WriteFileSync | undefined,
+ chmodSync: vi.fn<ChmodSync>(),
+ chownSync: vi.fn<ChownSync>(),
+ renameSync: vi.fn<RenameSync>(),
+ writeFileSync: vi.fn<WriteFileSync>(),
+}));
+vi.mock("node:fs", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:fs")>();
+ fsMocks.actualWriteFileSync = actual.writeFileSync;
+ fsMocks.chmodSync.mockImplementation(actual.chmodSync);
+ fsMocks.chownSync.mockImplementation(actual.chownSync);
+ fsMocks.renameSync.mockImplementation(actual.renameSync);
+ fsMocks.writeFileSync.mockImplementation(actual.writeFileSync);
+ return {
+ ...actual,
+ chmodSync: fsMocks.chmodSync,
+ chownSync: fsMocks.chownSync,
+ renameSync: fsMocks.renameSync,
+ writeFileSync: fsMocks.writeFileSync,
+ };
+});
+
import { SessionManager } from "../src/core/session-manager.js";
const tempDirs: string[] = [];
@@ -49,6 +93,116 @@ describe("SessionManager.flushNow", () => {
expect(custom.data).toEqual({ active: true, status: "active" });
});
+ it("preserves live bytes and cleans up the temp file when a rewrite fails", () => {
+ const dir = createTempDir();
+ const mgr = SessionManager.create(dir, join(dir, "sessions"));
+ mgr.appendCustomEntry("before_failure");
+ mgr.flushNow();
+ const file = mgr.getSessionFile()!;
+ const before = readFileSync(file);
+ const tempPrefix = `.${basename(file)}.`;
+
+ mgr.appendMessage({ role: "user", content: "pending", timestamp: Date.now() });
+ fsMocks.writeFileSync.mockImplementationOnce((path, data, options) => {
+ fsMocks.actualWriteFileSync!(path, Buffer.from(String(data)).subarray(0, 12), options);
+ throw new Error("disk full");
+ });
+
+ expect(() => mgr.flushNow()).toThrow("disk full");
+ expect(readFileSync(file)).toEqual(before);
+ expect(readdirSync(dirname(file)).filter((name) => name.startsWith(tempPrefix) && name.endsWith(".tmp"))).toEqual(
+ [],
+ );
+ });
+
+ it("preserves live-file metadata before atomically replacing it", () => {
+ const dir = createTempDir();
+ const mgr = SessionManager.create(dir, join(dir, "sessions"));
+ mgr.appendCustomEntry("before_metadata_check");
+ mgr.flushNow();
+ const file = mgr.getSessionFile()!;
+ chmodSync(file, 0o660);
+ const before = statSync(file);
+ fsMocks.chownSync.mockClear();
+ fsMocks.chownSync.mockImplementationOnce(() => undefined);
+ fsMocks.chmodSync.mockClear();
+ fsMocks.renameSync.mockClear();
+
+ mgr.appendMessage({ role: "user", content: "pending", timestamp: Date.now() });
+ mgr.flushNow();
+
+ const tempPath = fsMocks.chownSync.mock.calls[0]?.[0];
+ expect(tempPath).toEqual(expect.any(String));
+ expect(fsMocks.chownSync).toHaveBeenCalledWith(tempPath, before.uid, before.gid);
+ expect(fsMocks.chmodSync).toHaveBeenCalledWith(tempPath, before.mode & 0o777);
+ expect(fsMocks.renameSync).toHaveBeenCalledWith(tempPath, join(dirname(tempPath as string), basename(file)));
+ expect(fsMocks.chownSync.mock.invocationCallOrder[0]!).toBeLessThan(
+ fsMocks.chmodSync.mock.invocationCallOrder[0]!,
+ );
+ expect(fsMocks.chmodSync.mock.invocationCallOrder[0]!).toBeLessThan(
+ fsMocks.renameSync.mock.invocationCallOrder[0]!,
+ );
+ const after = statSync(file);
+ expect({ mode: after.mode & 0o777, uid: after.uid, gid: after.gid }).toEqual({
+ mode: before.mode & 0o777,
+ uid: before.uid,
+ gid: before.gid,
+ });
+ });
+
+ it("preserves live bytes and cleans the temp file when restoring ownership fails", () => {
+ const dir = createTempDir();
+ const mgr = SessionManager.create(dir, join(dir, "sessions"));
+ mgr.appendCustomEntry("before_ownership_failure");
+ mgr.flushNow();
+ const file = mgr.getSessionFile()!;
+ const before = readFileSync(file);
+ const tempPrefix = `.${basename(file)}.`;
+ const permissionError = Object.assign(new Error("operation not permitted"), { code: "EPERM" });
+ fsMocks.chownSync.mockImplementationOnce(() => {
+ throw permissionError;
+ });
+ fsMocks.renameSync.mockClear();
+
+ mgr.appendMessage({ role: "user", content: "pending", timestamp: Date.now() });
+
+ expect(() => mgr.flushNow()).toThrow(permissionError);
+ expect(fsMocks.renameSync).not.toHaveBeenCalled();
+ expect(readFileSync(file)).toEqual(before);
+ expect(readdirSync(dirname(file)).filter((name) => name.startsWith(tempPrefix) && name.endsWith(".tmp"))).toEqual(
+ [],
+ );
+ });
+
+ it("rewrites a cross-directory symlink target without replacing the alias", () => {
+ const dir = createTempDir();
+ const targetDir = join(dir, "targets");
+ const aliasDir = join(dir, "aliases");
+ mkdirSync(targetDir);
+ mkdirSync(aliasDir);
+ const target = join(targetDir, "session.jsonl");
+ const alias = join(aliasDir, "session.jsonl");
+ fsMocks.actualWriteFileSync!(
+ target,
+ `${JSON.stringify({
+ type: "session",
+ version: 2,
+ id: "symlink-session",
+ timestamp: "2026-01-01T00:00:00.000Z",
+ cwd: dir,
+ })}\n`,
+ );
+ chmodSync(target, 0o640);
+ symlinkSync(target, alias);
+
+ const mgr = SessionManager.open(alias);
+
+ expect(mgr.getSessionFile()).toBe(alias);
+ expect(lstatSync(alias).isSymbolicLink()).toBe(true);
+ expect(JSON.parse(readFileSync(target, "utf8")).version).toBe(3);
+ expect(statSync(target).mode & 0o777).toBe(0o640);
+ });
+
it("is a no-op for in-memory (non-persisted) sessions", () => {
const mgr = SessionManager.inMemory("/tmp");
mgr.appendCustomEntry("thread_goal_state", { active: true });
@@ -162,3 +316,113 @@ describe("SessionManager.flushNow", () => {
});
});
});
+
+function createPersistedSessionForRollbackTest(): { mgr: SessionManager; file: string; before: Buffer } {
+ const dir = createTempDir();
+ const mgr = SessionManager.create(dir, join(dir, "sessions"));
+ mgr.appendMessage({ role: "user", content: "hi", timestamp: Date.now() });
+ mgr.appendMessage({
+ role: "assistant",
+ content: [{ type: "text", text: "hello" }],
+ api: "openai-completions",
+ provider: "openai",
+ model: "test",
+ usage: {
+ input: 1,
+ output: 1,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 2,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop",
+ timestamp: Date.now(),
+ });
+ const file = mgr.getSessionFile()!;
+ return { mgr, file, before: readFileSync(file) };
+}
+
+function failNextOutcomeAppend(mgr: SessionManager, file: string): void {
+ const internals = mgr as unknown as { _persist(entry: unknown): void };
+ internals._persist = () => {
+ appendFileSync(file, '{"type":"custom_message","truncat');
+ throw new Error("append failed");
+ };
+}
+
+const failAfterPartialTempWrite: WriteFileSync = (path, data, options) => {
+ fsMocks.actualWriteFileSync!(path, Buffer.from(String(data)).subarray(0, 12), options);
+ throw new Error("repair failed");
+};
+
+describe("SessionManager.appendCustomMessageEntryWithRollback", () => {
+ it("flushes rollback-aware custom messages before the first assistant response", () => {
+ const dir = createTempDir();
+ const sessionDir = join(dir, "sessions");
+ const mgr = SessionManager.create(dir, sessionDir);
+
+ mgr.appendCustomMessageEntryWithRollback("compaction_outcome", "failed early", true);
+
+ const persisted = readFileSync(mgr.getSessionFile()!, "utf8");
+ expect(persisted).toContain('"customType":"compaction_outcome"');
+ });
+
+ it("repairs the session file immediately after a torn append", () => {
+ const dir = createTempDir();
+ const sessionDir = join(dir, "sessions");
+ const mgr = SessionManager.create(dir, sessionDir);
+ mgr.appendMessage({ role: "user", content: "hi", timestamp: Date.now() });
+ mgr.appendMessage({
+ role: "assistant",
+ content: [{ type: "text", text: "hello" }],
+ api: "openai-completions",
+ provider: "openai",
+ model: "test",
+ usage: {
+ input: 1,
+ output: 1,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 2,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop",
+ timestamp: Date.now(),
+ });
+ const file = mgr.getSessionFile()!;
+ const before = readFileSync(file, "utf8");
+
+ // Simulate a partial append: the fs write tears the file, then throws.
+ const internals = mgr as unknown as { _persist(entry: unknown): void };
+ const originalPersist = internals._persist.bind(mgr);
+ internals._persist = () => {
+ appendFileSync(file, '{"type":"custom_message","truncat');
+ throw new Error("disk full");
+ };
+ expect(() => mgr.appendCustomMessageEntryWithRollback("test.outcome", "details", false)).toThrow("disk full");
+ internals._persist = originalPersist;
+
+ // The rollback rewrites the file from the restored in-memory entries, so the
+ // durable session has no torn tail even if the process exits right after.
+ expect(readFileSync(file, "utf8")).toBe(before);
+ });
+
+ it("preserves old history when rollback repair fails", () => {
+ const { mgr, file, before } = createPersistedSessionForRollbackTest();
+ failNextOutcomeAppend(mgr, file);
+ fsMocks.writeFileSync.mockImplementationOnce(failAfterPartialTempWrite);
+
+ expect(() => mgr.appendCustomMessageEntryWithRollback("test.outcome", "details", false)).toThrow("append failed");
+ expect(readFileSync(file).subarray(0, before.length)).toEqual(before);
+ });
+
+ it("repairs a torn tail on the next successful retry", () => {
+ const { mgr, file, before } = createPersistedSessionForRollbackTest();
+ failNextOutcomeAppend(mgr, file);
+ fsMocks.writeFileSync.mockImplementationOnce(failAfterPartialTempWrite);
+ expect(() => mgr.appendCustomMessageEntryWithRollback("test.outcome", "details", false)).toThrow();
+
+ mgr.flushNow();
+ expect(readFileSync(file)).toEqual(before);
+ });
+});
diff --git a/packages/coding-agent/test/slash-commands.test.ts b/packages/coding-agent/test/slash-commands.test.ts
index fb204fac3c..6ff9b66fce 100644
--- a/packages/coding-agent/test/slash-commands.test.ts
+++ b/packages/coding-agent/test/slash-commands.test.ts
@@ -4,9 +4,13 @@ import {
BUILTIN_SLASH_COMMANDS,
builtinSlashCommandTakesArgument,
isBuiltinSlashCommandName,
+ isSessionSlashCommandName,
+ parseRefineCommandOptions,
+ parseSessionSlashCommand,
parseSlashCommand,
resolveBuiltinSlashCommandName,
resolveSlashCommand,
+ SESSION_SLASH_COMMAND_NAMES,
} from "../src/core/slash-commands.js";
describe("built-in slash commands", () => {
@@ -168,3 +172,72 @@ describe("slash command aliases", () => {
});
});
});
+
+describe("session slash commands", () => {
+ test("keeps the authoritative names and built-in execution metadata in sync", () => {
+ expect(
+ BUILTIN_SLASH_COMMANDS.filter((command) => command.execution === "session").map((command) => command.name),
+ ).toEqual([...SESSION_SLASH_COMMAND_NAMES]);
+ for (const name of SESSION_SLASH_COMMAND_NAMES) expect(isSessionSlashCommandName(name)).toBe(true);
+ expect(isSessionSlashCommandName("settings")).toBe(false);
+ });
+
+ test("splits at the first horizontal Unicode whitespace and preserves the raw text", () => {
+ for (const text of ["/goal ship it", "/goal\tship it", "/goal\u00a0ship it", "/goal\u2003ship it"]) {
+ expect(parseSlashCommand(text)).toEqual({ name: "goal", args: "ship it" });
+ expect(parseSessionSlashCommand(text)).toEqual({ name: "goal", args: "ship it", text });
+ }
+ expect(parseSlashCommand("/goal\t ship it ")).toEqual({ name: "goal", args: "ship it" });
+ for (const lineTerminator of ["\n", "\r", "\r\n", "\u2028", "\u2029"]) {
+ expect(parseSessionSlashCommand(`/goal${lineTerminator}ship it`)).toBeUndefined();
+ expect(parseSessionSlashCommand(`/goal\t${lineTerminator}ship it`)).toBeUndefined();
+ expect(parseSessionSlashCommand(`/autonomous\t${lineTerminator}on`)).toBeUndefined();
+ }
+ });
+
+ test("parses refine rollback ids and --global placement without consuming instruction text", () => {
+ expect(parseRefineCommandOptions("rollback refine_123")).toEqual({ rollbackId: "refine_123", global: false });
+ expect(parseRefineCommandOptions("rollback refine_456 --global")).toEqual({
+ rollbackId: "refine_456",
+ global: true,
+ });
+ expect(parseRefineCommandOptions("--global rollback refine_789")).toEqual({
+ rollbackId: "refine_789",
+ global: true,
+ });
+ expect(parseRefineCommandOptions("--global focus on validation")).toEqual({
+ instructions: "focus on validation",
+ global: true,
+ });
+ expect(parseRefineCommandOptions("update docs to explain --global")).toEqual({
+ instructions: "update docs to explain --global",
+ global: false,
+ });
+ for (const args of ["rollback", "rollback --global"]) {
+ expect(() => parseRefineCommandOptions(args)).toThrow("Usage: /refine rollback <refinement-id>");
+ }
+ });
+
+ test("classifies only exact leading session-owned commands", () => {
+ expect(parseSessionSlashCommand("/compact focus on tests")).toEqual({
+ name: "compact",
+ args: "focus on tests",
+ text: "/compact focus on tests",
+ });
+ expect(parseSessionSlashCommand("/refine")).toEqual({ name: "refine", args: "", text: "/refine" });
+ expect(parseSessionSlashCommand("/goal ship it")).toEqual({
+ name: "goal",
+ args: "ship it",
+ text: "/goal ship it",
+ });
+ expect(parseSessionSlashCommand("/autonomous status")).toEqual({
+ name: "autonomous",
+ args: "status",
+ text: "/autonomous status",
+ });
+ expect(parseSessionSlashCommand("Explain /compact")).toBeUndefined();
+ expect(parseSessionSlashCommand(" /compact")).toBeUndefined();
+ expect(parseSessionSlashCommand("/compaction")).toBeUndefined();
+ expect(parseSessionSlashCommand("/settings")).toBeUndefined();
+ });
+});
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 a9299e03c0..303b50eec1 100644
--- a/packages/coding-agent/test/suite/agent-session-autonomous.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-autonomous.test.ts
@@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fauxAssistantMessage } from "@earendil-works/pi-ai";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
addAutonomousUsage,
createAutonomousRuntimeState,
@@ -326,7 +326,9 @@ describe("AgentSession autonomous mode", () => {
suppressAutonomousContinuation: true,
});
sessionInternals._compactionAbortController = undefined;
- await harness.session.agent.continue();
+ expect(harness.session.resumeQueuedWork()).toBe(true);
+ await vi.waitFor(() => expect(harness.session.pendingMessageCount).toBe(0));
+ await harness.session.waitForSessionInputIdle();
expect(getAssistantTexts(harness)).toEqual(["Still failing."]);
expect(harness.session.getAutonomousStatus().continuationsUsed).toBe(0);
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 dbb19330ad..5df6b6cf64 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
@@ -421,6 +421,7 @@ describe("AgentSession bash and persistence characterization", () => {
await bashRun;
await steerDelivery;
await followUpDelivery;
+ await harness.session.waitForIdle();
const userTexts = harness.session.messages.filter((message) => message.role === "user").map(getMessageText);
expect(userTexts.findIndex((text) => text.includes("steer after bash"))).toBeLessThan(
@@ -430,26 +431,52 @@ describe("AgentSession bash and persistence characterization", () => {
});
it("flushes pending bash output before draining queued prompts", async () => {
- const harness = await createHarness();
+ let releaseToolExecution: (() => void) | undefined;
+ const toolRelease = new Promise<void>((resolve) => {
+ releaseToolExecution = resolve;
+ });
+ const waitTool: AgentTool = {
+ name: "wait",
+ label: "Wait",
+ description: "Wait for release",
+ parameters: Type.Object({}),
+ execute: async () => {
+ await toolRelease;
+ return { content: [{ type: "text", text: "released" }], details: {} };
+ },
+ };
+ const harness = await createHarness({ tools: [waitTool] });
harnesses.push(harness);
- harness.setResponses([fauxAssistantMessage("after bash")]);
+ harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
+ fauxAssistantMessage("turn complete"),
+ fauxAssistantMessage("after bash"),
+ ]);
+ const toolStarted = new Promise<void>((resolve) => {
+ const unsubscribe = harness.session.subscribe((event) => {
+ if (event.type === "tool_execution_start" && event.toolName === "wait") {
+ unsubscribe();
+ resolve();
+ }
+ });
+ });
const agentPrompt =
"Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_flush_bash\n\nqueued after bash";
const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_flush_bash");
- (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;
+
+ const turn = harness.session.prompt("start");
+ await toolStarted;
harness.session.recordBashResult("echo flushed", {
output: "flushed output",
exitCode: 0,
cancelled: false,
truncated: false,
});
- (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;
await harness.session.queueAgentMessagePrompt(agentPrompt, "followUp");
-
- await (
- harness.session as unknown as { _drainQueuedMessagesAfterBash(): Promise<void> }
- )._drainQueuedMessagesAfterBash();
+ releaseToolExecution?.();
+ await turn;
await delivery;
+ await harness.session.waitForIdle();
const bashIndex = harness.session.messages.findIndex((message) => message.role === "bashExecution");
const userIndex = harness.session.messages.findIndex(
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 a2b19d82e2..7b06cee50f 100644
--- a/packages/coding-agent/test/suite/agent-session-compaction.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-compaction.test.ts
@@ -1,6 +1,8 @@
+import { appendFileSync } from "node:fs";
import type { AgentMessage, ShouldStopAfterTurnContext } from "@earendil-works/pi-agent-core";
import { type AssistantMessage, fauxAssistantMessage, type Model, type ToolResultMessage } from "@earendil-works/pi-ai";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SessionManager } from "../../src/core/session-manager.js";
import { createHarness, getMessageText, type Harness } from "./harness.js";
type SessionWithCompactionInternals = {
@@ -11,6 +13,11 @@ type SessionWithCompactionInternals = {
) => Promise<void>;
_runAutoCompaction: (reason: "overflow" | "threshold" | "requested", willRetry: boolean) => Promise<void>;
_shouldStopAfterTurn: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
+ _persistCompactionOutcome: (
+ reason: "overflow" | "threshold" | "requested",
+ outcome: "skipped" | "cancelled" | "failed",
+ message: string,
+ ) => void;
};
function createUsage(totalTokens: number) {
@@ -145,6 +152,38 @@ describe("AgentSession compaction characterization", () => {
});
});
+ it("emits compaction lifecycle events when /compact was queued behind a running turn", async () => {
+ const harness = await createHarness({
+ settings: { compaction: { keepRecentTokens: 1 } },
+ persistSession: true,
+ });
+ harnesses.push(harness);
+ let releaseTurn: () => void = () => {};
+ const turnGate = new Promise<void>((resolve) => {
+ releaseTurn = resolve;
+ });
+ harness.setResponses([
+ async () => {
+ await turnGate;
+ return fauxAssistantMessage("slow response");
+ },
+ fauxAssistantMessage("model-generated summary"),
+ fauxAssistantMessage("model-generated turn summary"),
+ ]);
+ const running = harness.session.prompt("one");
+ // Queue the command while the turn streams, then let the turn finish.
+ const queued = harness.session.prompt("/compact", { streamingBehavior: "steer" });
+ releaseTurn();
+ await Promise.all([running, queued]);
+
+ const order = harness.events.map((event) => event.type);
+ expect(order.indexOf("compaction_start")).toBeGreaterThan(order.indexOf("agent_end"));
+ expect(harness.eventsOfType("compaction_start")).toEqual([expect.objectContaining({ reason: "manual" })]);
+ expect(harness.eventsOfType("compaction_end")).toEqual([
+ expect.objectContaining({ reason: "manual", aborted: false }),
+ ]);
+ });
+
it("reschedules a pending post-compaction continuation after successful manual compaction", async () => {
vi.useFakeTimers();
const harness = await createHarness({
@@ -181,6 +220,49 @@ describe("AgentSession compaction characterization", () => {
}
});
+ it("treats session-owned queued inputs as queued work after compaction", async () => {
+ const harness = await createHarness({
+ settings: { compaction: { keepRecentTokens: 1 } },
+ extensionFactories: [
+ (pi) => {
+ pi.on("session_before_compact", async (event) => ({
+ compaction: {
+ summary: "summary from extension",
+ firstKeptEntryId: event.preparation.firstKeptEntryId,
+ tokensBefore: event.preparation.tokensBefore,
+ details: { source: "extension" },
+ },
+ }));
+ },
+ ],
+ });
+ harnesses.push(harness);
+ const internals = harness.session as unknown as {
+ _cancelPostCompactionContinue(): void;
+ _scheduleAutoRefineAfterCompaction(willContinueAfterCompaction: boolean): void;
+ };
+ const scheduleAutoRefineSpy = vi.spyOn(internals, "_scheduleAutoRefineAfterCompaction");
+ try {
+ await harness.session.prompt("one");
+ await harness.session.prompt("two");
+ // 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);
+
+ await harness.session.compact();
+
+ // Session-owned queued work counts as queued: refine defers to the next
+ // turn boundary instead of running before the queued input's turn.
+ expect(scheduleAutoRefineSpy).toHaveBeenCalledWith(true);
+
+ pause.release();
+ } finally {
+ harness.session.clearQueue();
+ internals._cancelPostCompactionContinue();
+ }
+ });
+
it("throws when compacting without a model", async () => {
const harness = await createHarness();
harnesses.push(harness);
@@ -293,9 +375,7 @@ describe("AgentSession compaction characterization", () => {
expect(harness.session.getAutonomousStatus().continuationsUsed).toBe(1);
expect(sessionInternals._postCompactionContinuationMessages).toEqual([firstQueued]);
- expect(
- harness.session.agent.removeQueuedMessages((message) => message === firstQueued || message === secondQueued),
- ).toEqual([firstQueued]);
+ expect(harness.session.getFollowUpMessages()).toHaveLength(1);
});
it("clears queued autonomous continuations when threshold compaction is skipped", async () => {
@@ -340,7 +420,7 @@ describe("AgentSession compaction characterization", () => {
newMessages: [successfulAssistant, toolResult],
});
expect(shouldStop).toBe(true);
- expect(harness.session.agent.hasQueuedMessages()).toBe(true);
+ expect(harness.session.getFollowUpMessages()).toHaveLength(1);
expect(harness.session.getAutonomousStatus().continuationsUsed).toBe(1);
await sessionInternals._runAutoCompaction("threshold", false);
@@ -349,7 +429,7 @@ describe("AgentSession compaction characterization", () => {
expect(harness.session.getAutonomousStatus().continuationsUsed).toBe(0);
});
- it("emits a warning when auto-compaction has nothing to summarize", async () => {
+ it("emits a warning and persists the outcome outside model context when auto-compaction has nothing to summarize", async () => {
const harness = await createHarness();
harnesses.push(harness);
await harness.session.prompt("one");
@@ -357,6 +437,7 @@ describe("AgentSession compaction characterization", () => {
const endEvents: Array<{ errorMessage?: string; errorSeverity?: string }> = [];
harness.session.subscribe((event) => {
if (event.type === "compaction_end") {
+ expect(harness.session.messages.at(-1)).toMatchObject({ customType: "compaction_outcome" });
endEvents.push({ errorMessage: event.errorMessage, errorSeverity: event.errorSeverity });
}
});
@@ -367,6 +448,17 @@ describe("AgentSession compaction characterization", () => {
expect(endEvents).toHaveLength(1);
expect(endEvents[0].errorSeverity).toBe("warning");
expect(endEvents[0].errorMessage).toContain("Auto-compaction skipped");
+
+ // The unsuccessful outcome is disclosed as a durable custom message that stays out of model context.
+ const outcome = harness.session.messages.at(-1);
+ expect(outcome).toMatchObject({
+ role: "custom",
+ customType: "compaction_outcome",
+ content: endEvents[0].errorMessage,
+ display: true,
+ details: { reason: "threshold", outcome: "skipped" },
+ });
+ expect(harness.session.agent.convertToLlm([outcome!])).toEqual([]);
});
it("does not retry overflow recovery more than once", async () => {
@@ -388,11 +480,24 @@ describe("AgentSession compaction characterization", () => {
await sessionInternals._checkCompaction(overflowMessage);
await sessionInternals._checkCompaction({ ...overflowMessage, timestamp: Date.now() + 1 });
+ await sessionInternals._checkCompaction({ ...overflowMessage, timestamp: Date.now() + 2 });
expect(runAutoCompactionSpy).toHaveBeenCalledTimes(1);
- expect(compactionErrors).toContain(
- "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
- );
+ const message =
+ "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.";
+ expect(compactionErrors).toContain(message);
+ expect(harness.session.messages.at(-1)).toMatchObject({
+ role: "custom",
+ customType: "compaction_outcome",
+ content: message,
+ details: { reason: "overflow", outcome: "failed" },
+ });
+ expect(
+ harness.session.messages.filter(
+ (entry) =>
+ entry.role === "custom" && entry.customType === "compaction_outcome" && entry.content === message,
+ ),
+ ).toHaveLength(1);
});
it("ignores stale pre-compaction assistant usage on pre-prompt checks", async () => {
@@ -605,15 +710,16 @@ describe("AgentSession compaction characterization", () => {
continuationsUsed: 1,
gates: expect.objectContaining({ maxRetries: 5 }),
});
- expect(followUpSpy).toHaveBeenCalledTimes(1);
- const queuedText = getMessageText(followUpSpy.mock.calls[0]?.[0]);
+ expect(followUpSpy).not.toHaveBeenCalled();
+ const queuedText = harness.session.getFollowUpMessages()[0] ?? "";
expect(queuedText).toContain("Autonomous quality gate failed (attempt 1/5)");
expect(queuedText).toContain("gate failed");
await sessionInternals._runAutoCompaction("threshold", false);
await vi.advanceTimersByTimeAsync(100);
- expect(continueSpy).toHaveBeenCalledTimes(1);
+ expect(continueSpy).not.toHaveBeenCalled();
+ expect(harness.session.getFollowUpMessages()).toEqual([]);
});
it("keeps autonomous continuation bookkeeping when only steering queue is drained", async () => {
@@ -658,6 +764,62 @@ describe("AgentSession compaction characterization", () => {
expect(followUpSpy).toHaveBeenCalledWith(autonomousMessage);
});
+ it.each([
+ {
+ name: "untracked queued input",
+ text: "queued input",
+ response: "queued input handled",
+ tracked: false,
+ },
+ {
+ name: "post-compaction continuation",
+ text: "session-owned continuation",
+ response: "continuation handled",
+ tracked: true,
+ },
+ ])("does not continue again after the session pump handles $name", async ({ text, response, tracked }) => {
+ vi.useFakeTimers();
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const sessionInternals = harness.session as unknown as {
+ _schedulePostCompactionContinue(): void;
+ _postCompactionContinuationMessages: AgentMessage[];
+ _postCompactionContinuationScheduled: boolean;
+ _createPreparedPromptInput(
+ text: string,
+ images: undefined,
+ options: { message?: AgentMessage; resumeIfIdle: boolean },
+ ): unknown;
+ _enqueueSessionInput(input: unknown, schedule: "followUp"): boolean;
+ };
+ const continuation = {
+ role: "user",
+ content: [{ type: "text", text }],
+ timestamp: Date.now(),
+ } satisfies AgentMessage;
+ if (tracked) sessionInternals._postCompactionContinuationMessages = [continuation];
+ harness.setResponses([fauxAssistantMessage(response)]);
+ sessionInternals._enqueueSessionInput(
+ sessionInternals._createPreparedPromptInput(text, undefined, {
+ ...(tracked && { message: continuation }),
+ resumeIfIdle: tracked,
+ }),
+ "followUp",
+ );
+ const continueSpy = vi.spyOn(harness.session.agent, "continue");
+
+ sessionInternals._schedulePostCompactionContinue();
+ await vi.advanceTimersByTimeAsync(200);
+
+ expect(continueSpy).not.toHaveBeenCalled();
+ expect(sessionInternals._postCompactionContinuationScheduled).toBe(false);
+ expect(sessionInternals._postCompactionContinuationMessages).toEqual([]);
+ expect(harness.session.messages.at(-1)).toMatchObject({
+ role: "assistant",
+ content: [{ type: "text", text: response }],
+ });
+ });
+
it("keeps autonomous threshold continuations when post-compaction continue must retry", async () => {
vi.useFakeTimers();
const harness = await createHarness({
@@ -755,7 +917,6 @@ describe("AgentSession compaction characterization", () => {
harness.sessionManager.appendMessage(message);
}
harness.session.agent.state.messages = [oldUser, oldAssistant, currentUser, successfulAssistant, toolResult];
- const continueSpy = vi.spyOn(harness.session.agent, "continue").mockResolvedValue();
await sessionInternals._shouldStopAfterTurn({
message: successfulAssistant,
@@ -767,16 +928,16 @@ describe("AgentSession compaction characterization", () => {
},
newMessages: [successfulAssistant, toolResult],
});
- expect(harness.session.agent.hasQueuedMessages()).toBe(true);
+ expect(harness.session.getFollowUpMessages()).toHaveLength(1);
await harness.session.prompt("/autonomous off");
expect(harness.session.getAutonomousStatus().enabled).toBe(false);
- expect(harness.session.agent.hasQueuedMessages()).toBe(false);
+ expect(harness.session.getFollowUpMessages()).toEqual([]);
await sessionInternals._runAutoCompaction("threshold", false);
await vi.advanceTimersByTimeAsync(100);
- expect(continueSpy).not.toHaveBeenCalled();
+ expect(harness.session.getFollowUpMessages()).toEqual([]);
});
it("queues a failing autonomous gate continuation before post-turn threshold compaction", async () => {
@@ -818,9 +979,9 @@ describe("AgentSession compaction characterization", () => {
await sessionInternals._checkCompaction(successfulAssistant, false);
expect(runCompactionSpy).toHaveBeenCalledWith("threshold", false);
- expect(followUpSpy).toHaveBeenCalledTimes(1);
+ expect(followUpSpy).not.toHaveBeenCalled();
expect(harness.session.getAutonomousStatus().continuationsUsed).toBe(1);
- const queuedText = getMessageText(followUpSpy.mock.calls[0]?.[0]);
+ const queuedText = harness.session.getFollowUpMessages()[0] ?? "";
expect(queuedText).toContain("Autonomous quality gate failed (attempt 1/5)");
expect(queuedText).toContain("gate failed");
});
@@ -988,4 +1149,107 @@ describe("AgentSession compaction characterization", () => {
expect(belowThresholdSpy).not.toHaveBeenCalled();
expect(disabledSpy).not.toHaveBeenCalled();
});
+
+ it("rolls back failed outcome persistence without breaking the persisted branch", async () => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("persisted response")]);
+ await harness.session.prompt("persist this turn");
+
+ const internals = harness.session as unknown as SessionWithCompactionInternals;
+ const sessionFile = harness.sessionManager.getSessionFile()!;
+ const persistedLeafId = harness.sessionManager.getLeafId();
+ const persistedEntries = harness.sessionManager.getEntries();
+ vi.spyOn(harness.sessionManager, "_persist").mockImplementationOnce(() => {
+ appendFileSync(sessionFile, '{"type":"custom_message"');
+ throw new Error("disk full");
+ });
+
+ expect(() =>
+ internals._persistCompactionOutcome("requested", "failed", "Requested compaction failed"),
+ ).not.toThrow();
+ // The live outcome message discloses that it was not saved.
+ expect(harness.session.messages.at(-1)).toMatchObject({
+ role: "custom",
+ customType: "compaction_outcome",
+ content: expect.stringContaining("could not be saved to session history"),
+ details: { reason: "requested", outcome: "failed" },
+ });
+ // In-memory state is fully rolled back: no outcome entry, same leaf and entries.
+ expect(harness.sessionManager.getLeafId()).toBe(persistedLeafId);
+ expect(harness.sessionManager.getEntries()).toEqual(persistedEntries);
+
+ // The next append attaches to the persisted leaf and rewrites a coherent file.
+ const nextId = harness.sessionManager.appendCustomEntry("after_failed_outcome");
+ const reloaded = SessionManager.open(sessionFile);
+ expect(reloaded.getEntry(nextId)?.parentId).toBe(persistedLeafId);
+ expect(reloaded.getBranch().map((entry) => entry.id)).toEqual(
+ harness.sessionManager.getBranch().map((entry) => entry.id),
+ );
+ expect(reloaded.getEntries()).not.toContainEqual(
+ expect.objectContaining({ type: "custom_message", customType: "compaction_outcome" }),
+ );
+ // The unpersisted disclosure survives context rebuilds (e.g. thinking toggle).
+ const rebuilt = harness.session.buildSessionContext();
+ expect(rebuilt.messages.at(-1)).toMatchObject({
+ role: "custom",
+ customType: "compaction_outcome",
+ content: expect.stringContaining("could not be saved to session history"),
+ });
+
+ // Cross a millisecond boundary so the later turn's timestamp is strictly newer.
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ harness.setResponses([fauxAssistantMessage("later response")]);
+ await harness.session.prompt("later turn");
+ const reordered = harness.session.buildSessionContext().messages;
+ const outcomeIndex = reordered.findIndex(
+ (message) => message.role === "custom" && message.customType === "compaction_outcome",
+ );
+ const laterTurnIndex = reordered.findIndex(
+ (message) => message.role === "user" && getMessageText(message).includes("later turn"),
+ );
+ expect(outcomeIndex).toBeGreaterThanOrEqual(0);
+ expect(laterTurnIndex).toBeGreaterThan(outcomeIndex);
+ });
+
+ it("keeps an unpersisted outcome in agent state after a successful compaction", async () => {
+ const harness = await createHarness({
+ persistSession: true,
+ settings: { compaction: { keepRecentTokens: 1 } },
+ extensionFactories: [
+ (pi) => {
+ pi.on("session_before_compact", async (event) => ({
+ compaction: {
+ summary: "post-failure summary",
+ firstKeptEntryId: event.preparation.firstKeptEntryId,
+ tokensBefore: event.preparation.tokensBefore,
+ details: { source: "extension" },
+ },
+ }));
+ },
+ ],
+ });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("one response"), fauxAssistantMessage("two response")]);
+ await harness.session.prompt("one");
+ await harness.session.prompt("two");
+
+ const internals = harness.session as unknown as SessionWithCompactionInternals;
+ vi.spyOn(harness.sessionManager, "_persist").mockImplementationOnce(() => {
+ throw new Error("disk full");
+ });
+ internals._persistCompactionOutcome("requested", "failed", "Requested compaction failed");
+
+ // Compaction reloads agent.state.messages from the session file; the
+ // memory-only disclosure must survive.
+ await harness.session.compact();
+
+ expect(harness.session.messages).toContainEqual(
+ expect.objectContaining({
+ role: "custom",
+ customType: "compaction_outcome",
+ content: expect.stringContaining("could not be saved to session history"),
+ }),
+ );
+ });
});
diff --git a/packages/coding-agent/test/suite/agent-session-goal.test.ts b/packages/coding-agent/test/suite/agent-session-goal.test.ts
index 79c16c22b6..d5bb7b0c97 100644
--- a/packages/coding-agent/test/suite/agent-session-goal.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-goal.test.ts
@@ -459,6 +459,25 @@ describe("AgentSession goals", () => {
});
});
+ it("normalizes queued goal context text and images", async () => {
+ const harness = await createGoalHarness();
+ const image = { type: "image" as const, data: "image-data", mimeType: "image/png" };
+ let preparedText: string | undefined;
+ let preparedImages: unknown;
+ harness.setResponses([fauxAssistantMessage("goal handled")]);
+ vi.spyOn(harness.session.extensionRunner, "emitBeforeAgentStart").mockImplementationOnce(async (text, images) => {
+ preparedText = text;
+ preparedImages = images;
+ return undefined;
+ });
+
+ await harness.session.prompt("/goal inspect the image", { images: [image] });
+
+ expect(preparedText).toContain("<goal_context>");
+ expect(preparedText).not.toContain("[object Object]");
+ expect(preparedImages).toEqual([image]);
+ });
+
it("keeps active goals sticky across normal user prompts", async () => {
const waiting = createWaitingTool();
const harness = await createGoalHarness([waiting.tool]);
@@ -625,7 +644,9 @@ describe("AgentSession goals", () => {
await harness.session.prompt("/goal clear");
- expect(harness.session.messages).toEqual([]);
+ expect(
+ harness.session.messages.map((message) => (message.role === "custom" ? message.customType : message.role)),
+ ).toEqual(["session_slash_command", "session_slash_command_result"]);
expect(harness.eventsOfType("goal_update").at(-1)?.goal.status).toBe("idle");
expect(harness.getPendingResponseCount()).toBe(1);
});
@@ -634,13 +655,17 @@ describe("AgentSession goals", () => {
const harness = await createHarness({ withConfiguredAuth: false });
harnesses.push(harness);
- await expect(harness.session.prompt("/goal do task")).rejects.toThrow();
+ await harness.session.prompt("/goal do task");
expect(harness.session.goalState).toMatchObject({
active: false,
status: "idle",
});
- expect(harness.session.messages).toEqual([]);
+ expect(harness.session.messages.at(-1)).toMatchObject({
+ role: "custom",
+ customType: "session_slash_command_result",
+ details: { success: false },
+ });
});
it("completes a goal whose completing turn crosses the budget without a stale budget-limit steer", async () => {
@@ -714,11 +739,13 @@ describe("AgentSession goals", () => {
const promptPromise = harness.session.prompt("/goal --budget 10 do work");
try {
- await waitForCondition(() => harness.getPendingResponseCount() === 1);
+ await waitForCondition(() => harness.session.goalState.status === "budget_limited");
} finally {
releaseMessageEnd?.();
}
await promptPromise;
+ await harness.session.waitForIdle();
+ await vi.waitFor(() => expect(visibleAssistantTexts(harness)).toHaveLength(2));
expect(visibleAssistantTexts(harness)).toEqual(["Spent the budget.", "Wrapping up."]);
expect(harness.getPendingResponseCount()).toBe(1);
@@ -737,7 +764,12 @@ describe("AgentSession goals", () => {
harnesses.push(harness);
harness.setResponses([fauxAssistantMessage("unused")]);
- await expect(harness.session.prompt(command)).rejects.toThrow("Goal token budget must be a positive integer.");
+ await harness.session.prompt(command);
+ expect(harness.session.messages.at(-1)).toMatchObject({
+ role: "custom",
+ customType: "session_slash_command_result",
+ details: { success: false, error: "Goal token budget must be a positive integer." },
+ });
expect(harness.session.goalState).toMatchObject({
active: false,
@@ -834,7 +866,9 @@ describe("AgentSession goals", () => {
await harness.session.prompt("/goal status");
- expect(harness.session.messages).toEqual([]);
+ expect(
+ harness.session.messages.map((message) => (message.role === "custom" ? message.customType : message.role)),
+ ).toEqual(["session_slash_command", "session_slash_command_result"]);
expect(harness.eventsOfType("goal_update").at(-1)?.goal.status).toBe("idle");
expect(harness.getPendingResponseCount()).toBe(1);
});
diff --git a/packages/coding-agent/test/suite/agent-session-model-extension.test.ts b/packages/coding-agent/test/suite/agent-session-model-extension.test.ts
index 647566deca..cefe6831d3 100644
--- a/packages/coding-agent/test/suite/agent-session-model-extension.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-model-extension.test.ts
@@ -367,6 +367,39 @@ describe("AgentSession model and extension characterization", () => {
expect(getAssistantTexts(harness)).toContain("accepted");
});
+ it("keeps streaming injected prompts under turn admission when the turn becomes idle", async () => {
+ const toolStarted = createDeferred();
+ const finishTool = createDeferred();
+ const waitTool: AgentTool = {
+ name: "wait",
+ label: "Wait",
+ description: "Wait for release",
+ parameters: Type.Object({}),
+ execute: async () => {
+ toolStarted.resolve();
+ await finishTool.promise;
+ return { content: [{ type: "text", text: "released" }], details: {} };
+ },
+ };
+ const harness = await createHarness({ tools: [waitTool] });
+ harnesses.push(harness);
+ harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
+ fauxAssistantMessage("turn complete"),
+ fauxAssistantMessage("heartbeat"),
+ ]);
+
+ const turn = harness.session.prompt("start");
+ await toolStarted.promise;
+ await harness.session.promptHeartbeat(createHeartbeat(), { streamingBehavior: "followUp" });
+
+ finishTool.resolve();
+ await turn;
+ await harness.session.waitForIdle();
+
+ expect(getAssistantTexts(harness)).toEqual(["", "turn complete", "heartbeat"]);
+ });
+
it("includes nextTurn messages queued by pending model_select handlers in injected prompts", async () => {
const handlerStarted = createDeferred();
const finishHandler = createDeferred();
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 f61a127676..02d1c7592c 100644
--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts
@@ -5,13 +5,45 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
import { fauxAssistantMessage, fauxToolCall, type Model } from "@earendil-works/pi-ai";
import { Type } from "typebox";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { waitForPromptAdmission } from "../../src/core/agent-session.js";
import type { BashResult } from "../../src/core/bash-executor.js";
import type { PromptTemplate } from "../../src/core/prompt-templates.js";
import { createSyntheticSourceInfo } from "../../src/core/source-info.js";
import { createTestResourceLoader } from "../utilities.js";
import { createHarness, getAssistantTexts, getMessageText, getUserTexts, type Harness } from "./harness.js";
+import { createDeferred, createWaitingHarness, gatedHook } from "./scheduling.js";
+
+// acceptAgentMessagePrompt admission is asynchronous. Pause after agent.prompt has
+// synchronously claimed the run, but before its prompt messages become delivered.
+function gateNextAgentStart(harness: Harness): { reached: Promise<void>; release(): void } {
+ let markReached = () => {};
+ const reached = new Promise<void>((resolve) => {
+ markReached = resolve;
+ });
+ let release = () => {};
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let unsubscribe = () => {};
+ unsubscribe = harness.session.agent.subscribe(async (event) => {
+ if (event.type !== "agent_start") return;
+ unsubscribe();
+ markReached();
+ await gate;
+ });
+ return { reached, release };
+}
describe("AgentSession prompt characterization", () => {
+ it("observes already-running work when prompt admission is pre-aborted", async () => {
+ const abort = new AbortController();
+ abort.abort();
+ const work = Promise.reject(new Error("late idle failure"));
+
+ expect(() => waitForPromptAdmission(work, abort.signal)).toThrow("Prompt admission was cancelled");
+ await Promise.resolve();
+ });
+
const harnesses: Harness[] = [];
const tempDirs: string[] = [];
@@ -27,6 +59,89 @@ describe("AgentSession prompt characterization", () => {
}
});
+ it("cancels a prompt while direct-turn admission is paused", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const pause = harness.session.acquireQueuedWorkPause();
+ const controller = new AbortController();
+
+ const prompt = harness.session.prompt("cancel me", { signal: controller.signal });
+ controller.abort();
+
+ await expect(prompt).rejects.toThrow("Prompt admission was cancelled.");
+ expect(getUserTexts(harness)).toEqual([]);
+ pause.release();
+ });
+
+ it("releases direct-turn admission when cancellation lands immediately after acquisition", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const controller = new AbortController();
+ const internals = harness.session as unknown as {
+ _acquireDirectTurnAdmission(options?: { signal?: AbortSignal }): Promise<{ owner: object; release(): void }>;
+ };
+ const acquire = internals._acquireDirectTurnAdmission.bind(internals);
+ internals._acquireDirectTurnAdmission = async (options) => {
+ const admission = await acquire(options);
+ controller.abort();
+ return admission;
+ };
+
+ await expect(harness.session.prompt("cancel after acquire", { signal: controller.signal })).rejects.toThrow(
+ "Prompt admission was cancelled.",
+ );
+ expect(getUserTexts(harness)).toEqual([]);
+
+ internals._acquireDirectTurnAdmission = acquire;
+ harness.setResponses([fauxAssistantMessage("recovered")]);
+ await harness.session.prompt("second");
+ expect(getUserTexts(harness)).toEqual(["second"]);
+ });
+
+ it("releases direct-turn admission when ownership commit throws", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const commitError = new Error("commit failed");
+
+ await expect(
+ harness.session.prompt("first", {
+ admissionCommitted: () => {
+ throw commitError;
+ },
+ }),
+ ).rejects.toBe(commitError);
+ expect(getUserTexts(harness)).toEqual([]);
+
+ harness.setResponses([fauxAssistantMessage("recovered")]);
+ await harness.session.prompt("second");
+ expect(getUserTexts(harness)).toEqual(["second"]);
+ });
+
+ it("keeps a prompt session-owned when cancellation arrives after admission", async () => {
+ const harness = await createHarness({ models: [{ id: "slow-faux" }] });
+ harnesses.push(harness);
+ let releaseResponse = () => {};
+ const responseGate = new Promise<void>((resolve) => {
+ releaseResponse = resolve;
+ });
+ harness.setResponses([
+ async () => {
+ await responseGate;
+ return fauxAssistantMessage("owned");
+ },
+ ]);
+ const controller = new AbortController();
+
+ const prompt = harness.session.prompt("keep me", { signal: controller.signal });
+ await vi.waitFor(() => expect(getUserTexts(harness)).toEqual(["keep me"]));
+ controller.abort();
+ releaseResponse();
+ await prompt;
+
+ expect(getUserTexts(harness)).toEqual(["keep me"]);
+ expect(getAssistantTexts(harness)).toEqual(["owned"]);
+ });
+
it("prompts while idle and records a single text response", async () => {
const harness = await createHarness();
harnesses.push(harness);
@@ -261,48 +376,44 @@ describe("AgentSession prompt characterization", () => {
expect(getMessageText(harness.session.messages[0]!)).toBe("from extension");
});
- it("throws when prompted during streaming without a streamingBehavior", async () => {
- let releaseToolExecution: (() => void) | undefined;
- const toolRelease = new Promise<void>((resolve) => {
- releaseToolExecution = resolve;
- });
- const waitTool: AgentTool = {
- name: "wait",
- label: "Wait",
- description: "Wait for release",
- parameters: Type.Object({}),
- execute: async () => {
- await toolRelease;
- return {
- content: [{ type: "text", text: "released" }],
- details: {},
- };
- },
- };
- const harness = await createHarness({ tools: [waitTool] });
+ it("rejects an aborted prompt while streaming instead of enqueueing it", async () => {
+ const { harness, waitForToolStart, promptPromise, releaseToolExecution } = await createWaitingHarness();
harnesses.push(harness);
harness.setResponses([
fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
fauxAssistantMessage("done"),
]);
+ await waitForToolStart;
+ const controller = new AbortController();
+ controller.abort();
- const sawToolStart = new Promise<void>((resolve) => {
- const unsubscribe = harness.session.subscribe((event) => {
- if (event.type === "tool_execution_start") {
- unsubscribe();
- resolve();
- }
- });
- });
+ await expect(
+ harness.session.prompt("stale startup prompt", {
+ streamingBehavior: "followUp",
+ signal: controller.signal,
+ }),
+ ).rejects.toThrow("Prompt admission was cancelled.");
+ expect(harness.session.pendingMessageCount).toBe(0);
+
+ releaseToolExecution();
+ await promptPromise;
+ expect(getUserTexts(harness)).toEqual(["start"]);
+ });
- const promptPromise = harness.session.prompt("start");
- await sawToolStart;
+ it("throws when prompted during streaming without a streamingBehavior", async () => {
+ const { harness, waitForToolStart, promptPromise, releaseToolExecution } = await createWaitingHarness();
+ harnesses.push(harness);
+ harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
+ fauxAssistantMessage("done"),
+ ]);
+ await waitForToolStart;
await expect(harness.session.prompt("second")).rejects.toThrow(
"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
);
- releaseToolExecution?.();
+ releaseToolExecution();
await promptPromise;
});
@@ -568,6 +679,45 @@ stale injected extension instructions`,
expect(providerMessages).toContain("injected extension message preserved");
});
+ it("pumps a follow-up queued while an injected prompt owns the active turn", async () => {
+ const hook = gatedHook({ prompt: "injected prompt" });
+ const harness = await createHarness({ extensionFactories: [hook.factory] });
+ harnesses.push(harness);
+ const internals = harness.session as unknown as {
+ _promptInjectedMessage(
+ text: string,
+ message: {
+ role: "custom";
+ customType: string;
+ content: string;
+ display: boolean;
+ details: Record<string, never>;
+ timestamp: number;
+ },
+ ): Promise<void>;
+ };
+ harness.setResponses([fauxAssistantMessage("injected done"), fauxAssistantMessage("follow-up done")]);
+
+ const injectedPrompt = internals._promptInjectedMessage("injected prompt", {
+ role: "custom",
+ customType: "injected-test",
+ content: "injected prompt",
+ display: true,
+ details: {},
+ timestamp: Date.now(),
+ });
+ await hook.reached;
+ await harness.session.followUp("queued follow-up");
+ hook.release();
+
+ await injectedPrompt;
+ await harness.session.waitForIdle();
+
+ expect(getUserTexts(harness)).toEqual(["queued follow-up"]);
+ expect(getAssistantTexts(harness)).toEqual(["injected done", "follow-up done"]);
+ expect(harness.session.getFollowUpMessages()).toEqual([]);
+ });
+
it("preserves an empty extension system prompt across an injected refine handoff wait", async () => {
let sessionInternals: {
_refineInFlight?: Promise<void>;
@@ -735,24 +885,6 @@ stale post-hook extension instructions`,
expect(providerSystemPrompt).toContain("stale post-hook extension instructions");
});
- it("queues accepted agent messages while compacting", async () => {
- const harness = await createHarness();
- harnesses.push(harness);
- const sessionInternals = harness.session as unknown as {
- _compactionAbortController?: AbortController;
- };
- sessionInternals._compactionAbortController = new AbortController();
-
- await harness.session.acceptAgentMessagePrompt("agent-to-agent payload", {
- expandPromptTemplates: false,
- streamingBehavior: "followUp",
- queueIfBusy: true,
- });
-
- expect(harness.session.getFollowUpMessages()).toEqual(["agent-to-agent payload"]);
- expect(harness.getPendingResponseCount()).toBe(0);
- });
-
it("keeps pending nextTurn context separate from accepted agent messages queued while busy", async () => {
const harness = await createHarness();
harnesses.push(harness);
@@ -852,7 +984,7 @@ stale post-hook extension instructions`,
"Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_handoff_reject\n\nagent text",
{ expandPromptTemplates: false, queueIfBusy: true },
);
- await Promise.resolve();
+ await vi.waitFor(() => expect(harness.session.getPendingNextTurnMessageSnapshots()).toEqual([]));
sessionInternals._userBashRunning = true;
sessionInternals._refineInFlight = undefined;
releaseRefine?.();
@@ -875,37 +1007,6 @@ stale post-hook extension instructions`,
expect(sawRestoredContext).toBe(true);
});
- it("accepted agent messages return after delivery starts, before completion", async () => {
- const harness = await createHarness({ models: [{ id: "slow-faux" }] });
- harnesses.push(harness);
- const agentPrompt =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_after_preflight\n\nagent text";
- let releaseResponse: (() => void) | undefined;
- const responseGate = new Promise<void>((resolve) => {
- releaseResponse = resolve;
- });
- harness.setResponses([
- async () => {
- await responseGate;
- return fauxAssistantMessage("delivered");
- },
- ]);
-
- await harness.session.acceptAgentMessagePrompt(agentPrompt, { expandPromptTemplates: false });
- expect(getUserTexts(harness)).toEqual([agentPrompt]);
- expect(getAssistantTexts(harness)).toEqual([]);
- expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
- steering: [],
- followUp: [],
- });
- releaseResponse?.();
- await harness.session.agent.waitForIdle();
-
- expect(getUserTexts(harness)).toEqual([agentPrompt]);
- expect(getAssistantTexts(harness)).toEqual(["delivered"]);
- expect(harness.session.getFollowUpMessages()).toEqual([]);
- });
-
it("allows normal prompts while an accepted agent message is idle between retry attempts", async () => {
const harness = await createHarness();
harnesses.push(harness);
@@ -980,34 +1081,6 @@ stale post-hook extension instructions`,
expect(contextTexts[0]?.[2]).toContain("Ran `echo hi`");
expect(contextTexts[0]?.[3]).toBe("agent-to-agent payload");
expect(harness.session.hasPendingBashMessages).toBe(false);
- expect(typeof sessionInternals._flushPendingBashMessages).toBe("function");
- });
-
- it("does not clear accepted agent messages after delivery starts", async () => {
- const harness = await createHarness({
- extensionFactories: [
- (pi) => {
- pi.on("message_end", async () => {
- await new Promise((resolve) => setTimeout(resolve, 0));
- });
- },
- ],
- });
- harnesses.push(harness);
- const agentPrompt =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_after_assistant\n\nagent text";
- harness.setResponses([fauxAssistantMessage("delivered assistant response")]);
-
- await harness.session.acceptAgentMessagePrompt(agentPrompt, { expandPromptTemplates: false });
- await Promise.resolve();
- expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
- steering: [],
- followUp: [],
- });
- await harness.session.agent.waitForIdle();
-
- expect(getUserTexts(harness)).toEqual([agentPrompt]);
- expect(getAssistantTexts(harness)).toEqual(["delivered assistant response"]);
});
it("cleared accepted agent message cleanup does not remove messages from a newer prompt", async () => {
@@ -1035,11 +1108,14 @@ stale post-hook extension instructions`,
harness.setResponses([fauxAssistantMessage("never delivered"), fauxAssistantMessage("after clear response")]);
gateAgentStart = true;
+ const admission = gateNextAgentStart(harness);
const accepted = harness.session.acceptAgentMessagePrompt(agentPrompt, { expandPromptTemplates: false });
+ await admission.reached;
expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
steering: [],
followUp: [agentPrompt],
});
+ admission.release();
await expect(accepted).rejects.toThrow("cleared before delivery");
await harness.session.agent.waitForIdle();
@@ -1066,11 +1142,14 @@ stale post-hook extension instructions`,
);
harness.setResponses([fauxAssistantMessage("never delivered")]);
+ const admission = gateNextAgentStart(harness);
const accepted = harness.session.acceptAgentMessagePrompt(agentPrompt, { expandPromptTemplates: false });
+ await admission.reached;
expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
steering: [],
followUp: [agentPrompt],
});
+ admission.release();
await expect(accepted).rejects.toThrow("cleared before delivery");
await harness.session.agent.waitForIdle();
await (harness.session as unknown as { _agentEventQueue: Promise<void> })._agentEventQueue;
@@ -1131,63 +1210,101 @@ stale post-hook extension instructions`,
expect(sawCustomMessage).toBe(true);
});
- it("cleans up the aborted run's late events after clearing an accepted agent message", async () => {
+ it("promptAndWait queued behind an active turn stays pending through its own completion", async () => {
+ let releaseFirst: (() => void) | undefined;
+ let releaseSecond: (() => void) | undefined;
+ const firstGate = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ const secondGate = new Promise<void>((resolve) => {
+ releaseSecond = resolve;
+ });
const harness = await createHarness();
harnesses.push(harness);
- const agentPrompt =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_late_events\n\nagent text";
- harness.setResponses([fauxAssistantMessage("seed response")]);
- await harness.session.prompt("seed");
- harness.setResponses([fauxAssistantMessage("never delivered")]);
+ harness.setResponses([
+ async () => {
+ await firstGate;
+ return fauxAssistantMessage("first done");
+ },
+ async () => {
+ await secondGate;
+ return fauxAssistantMessage("second done");
+ },
+ ]);
- const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_late_events");
- const accepted = harness.session.acceptAgentMessagePrompt(agentPrompt, { expandPromptTemplates: false });
- expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
- steering: [],
- followUp: [agentPrompt],
- });
- await expect(accepted).rejects.toThrow("cleared before delivery");
- await expect(delivery).rejects.toThrow("cleared before delivery");
- await harness.session.agent.waitForIdle();
- await (harness.session as unknown as { _agentEventQueue: Promise<void> })._agentEventQueue;
+ const first = harness.session.prompt("first");
+ await vi.waitFor(() => expect(harness.session.isStreaming).toBe(true));
+ let settled = false;
+ const queued = harness.session
+ .promptAndWait("second", { streamingBehavior: "followUp", queueIfBusy: true, resumeIfIdle: true })
+ .then(() => {
+ settled = true;
+ });
+ await vi.waitFor(() => expect(harness.session.getFollowUpMessages()).toEqual(["second"]));
+ expect(settled).toBe(false);
- await expect(harness.session.waitForAgentMessagePromptDelivery("agentmsg_late_events")).rejects.toThrow(
- "cleared before delivery",
- );
- // The aborted run's late message events must not re-persist the cleared message.
- const persistedRoles = harness.sessionManager
- .getEntries()
- .filter((entry) => entry.type === "message")
- .map((entry) => entry.message.role);
- expect(persistedRoles).toEqual(["user", "assistant"]);
- expect(getUserTexts(harness)).toEqual(["seed"]);
- expect(getAssistantTexts(harness)).toEqual(["seed response"]);
- expect(harness.session.agent.state.errorMessage).toBeUndefined();
- expect(
- (harness.session as unknown as { _acceptedAgentMessagePrompt?: unknown })._acceptedAgentMessagePrompt,
- ).toBeUndefined();
+ releaseFirst?.();
+ await vi.waitFor(() => expect(getUserTexts(harness)).toEqual(["first", "second"]));
+ expect(settled).toBe(false);
+
+ releaseSecond?.();
+ await Promise.all([first, queued]);
+ expect(settled).toBe(true);
+ expect(getAssistantTexts(harness)).toEqual(["first done", "second done"]);
+ });
+
+ it("drops generated prompt-wait outcome entries after completion", async () => {
+ let releaseFirst: (() => void) | undefined;
+ const firstGate = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([
+ async () => {
+ await firstGate;
+ return fauxAssistantMessage("first done");
+ },
+ fauxAssistantMessage("second done"),
+ ]);
+ const internals = harness.session as unknown as { _agentMessageOutcomes: Map<string, unknown> };
+
+ const first = harness.session.prompt("first");
+ await vi.waitFor(() => expect(harness.session.isStreaming).toBe(true));
+ // Queued delivery settles the sticky delivered flag; a generated id must
+ // still be dropped after completion or long-lived daemons grow one outcome
+ // entry per prompt.
+ const queued = harness.session.promptAndWait("second", { streamingBehavior: "followUp", queueIfBusy: true });
+ releaseFirst?.();
+ await Promise.all([first, queued]);
+
+ const keys = [...internals._agentMessageOutcomes.keys()];
+ expect(keys.filter((key) => key.startsWith("prompt-wait:"))).toEqual([]);
});
- it("handles autonomous slash commands when template expansion is disabled", async () => {
+ it("handles tab-separated autonomous slash commands when template expansion is disabled", async () => {
const harness = await createHarness();
harnesses.push(harness);
- await harness.session.prompt("/autonomous on", { expandPromptTemplates: false });
+ await harness.session.prompt("/autonomous on", { expandPromptTemplates: false });
expect(harness.session.getAutonomousStatus().enabled).toBe(true);
expect(harness.getPendingResponseCount()).toBe(0);
expect(harness.session.messages.some((message) => message.role === "custom")).toBe(true);
});
- it("handles goal slash commands when template expansion is disabled", async () => {
+ it("sends multiline goal and autonomous variants to the model", async () => {
const harness = await createHarness();
harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("first"), fauxAssistantMessage("second")]);
- await harness.session.prompt("/goal status", { expandPromptTemplates: false });
+ await harness.session.prompt("/goal\t\nship it", { expandPromptTemplates: false });
+ await harness.session.prompt("/autonomous\t\non", { expandPromptTemplates: false });
- expect(harness.eventsOfType("goal_update")).toHaveLength(1);
- expect(harness.getPendingResponseCount()).toBe(0);
- expect(getAssistantTexts(harness)).toEqual([]);
+ expect(harness.session.goalState.status).toBe("idle");
+ expect(harness.session.getAutonomousStatus().enabled).toBe(false);
+ expect(getUserTexts(harness)).toEqual(["/goal\t\nship it", "/autonomous\t\non"]);
+ expect(getAssistantTexts(harness)).toEqual(["first", "second"]);
});
it("does not run built-in slash commands immediately while queueIfBusy backpressure is active", async () => {
@@ -1198,32 +1315,20 @@ stale post-hook extension instructions`,
};
sessionInternals._compactionAbortController = new AbortController();
- await expect(
- harness.session.prompt("/autonomous on", {
- queueIfBusy: true,
- streamingBehavior: "followUp",
- }),
- ).rejects.toThrow("Agent has queued work");
- sessionInternals._compactionAbortController = undefined;
+ await harness.session.prompt("/autonomous on", {
+ queueIfBusy: true,
+ streamingBehavior: "followUp",
+ });
expect(harness.session.getAutonomousStatus().enabled).toBe(false);
- expect(harness.session.getFollowUpMessages()).toEqual([]);
+ expect(harness.session.getFollowUpMessages()).toEqual(["/autonomous on"]);
+ sessionInternals._compactionAbortController = undefined;
+ expect(harness.session.resumeQueuedWork()).toBe(true);
+ await harness.session.waitForSessionInputIdle();
+ expect(harness.session.getAutonomousStatus().enabled).toBe(true);
expect(harness.getPendingResponseCount()).toBe(0);
});
- it("keeps built-in slash commands literal for accepted agent messages", async () => {
- const harness = await createHarness();
- harnesses.push(harness);
- harness.setResponses([fauxAssistantMessage("literal")]);
-
- await harness.session.acceptAgentMessagePrompt("/autonomous on", { expandPromptTemplates: false });
- await harness.session.agent.waitForIdle();
-
- expect(harness.session.getAutonomousStatus().enabled).toBe(false);
- expect(getUserTexts(harness)).toEqual(["/autonomous on"]);
- expect(getAssistantTexts(harness)).toEqual(["literal"]);
- });
-
it("queues accepted agent messages without expanding slash commands or prompt templates", async () => {
const template: PromptTemplate = {
name: "review",
@@ -1264,6 +1369,386 @@ stale post-hook extension instructions`,
expect(harness.getPendingResponseCount()).toBe(0);
});
+ it("keeps an ordinary direct prompt fenced until its primary message starts", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("done")]);
+ await harness.session.sendCustomMessage(
+ { customType: "earlier-next-turn", content: "earlier", display: true, details: {} },
+ { deliverAs: "nextTurn" },
+ );
+ const earlierStarted = createDeferred();
+ const earlierStartGate = createDeferred();
+ const primaryStarted = createDeferred();
+ const unsubscribe = harness.session.agent.subscribe(async (event) => {
+ if (event.type !== "message_start") return;
+ if (event.message.role === "user" && getMessageText(event.message) === "ordinary prompt") {
+ primaryStarted.resolve();
+ return;
+ }
+ if (event.message.role === "custom" && event.message.customType === "earlier-next-turn") {
+ earlierStarted.resolve();
+ await earlierStartGate.promise;
+ }
+ });
+
+ const prompt = harness.session.prompt("ordinary prompt");
+ await earlierStarted.promise;
+ let checkpointReleased = false;
+ const checkpoint = harness.session.waitForSessionInputCheckpoint().then(() => {
+ checkpointReleased = true;
+ });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(checkpointReleased).toBe(false);
+
+ earlierStartGate.resolve();
+ await primaryStarted.promise;
+ await checkpoint;
+ await prompt;
+ unsubscribe();
+ });
+ it("promptUntilAccepted returns at ownership commit without draining queued work", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const commandStarted = createDeferred();
+ const commandGate = createDeferred();
+ vi.spyOn(harness.session, "refine").mockImplementation(async () => {
+ commandStarted.resolve();
+ await commandGate.promise;
+ return {
+ id: "refine_accepted",
+ summary: "s",
+ rationale: "r",
+ expectedOutcome: "o",
+ appliedEdits: [],
+ harnessStatePath: "/tmp/harness_state.json",
+ };
+ });
+
+ await harness.session.promptUntilAccepted("/refine --local");
+ await commandStarted.promise;
+ expect(harness.session.isStreaming).toBe(false);
+
+ commandGate.resolve();
+ await harness.session.waitForSessionInputIdle();
+ });
+
+ it("keeps the restart checkpoint waiting while a queued session command executes", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const commandStarted = createDeferred();
+ const commandGate = createDeferred();
+ vi.spyOn(harness.session, "refine").mockImplementation(async () => {
+ commandStarted.resolve();
+ await commandGate.promise;
+ return {
+ id: "refine_checkpoint",
+ summary: "s",
+ rationale: "r",
+ expectedOutcome: "o",
+ appliedEdits: [],
+ harnessStatePath: "/tmp/harness_state.json",
+ };
+ });
+ const pause = harness.session.acquireQueuedWorkPause();
+ const completion = harness.session.promptAndWait("/refine --local");
+ pause.release();
+ await commandStarted.promise;
+
+ let checkpointReleased = false;
+ const checkpoint = harness.session.waitForSessionInputCheckpoint().then(() => {
+ checkpointReleased = true;
+ });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(checkpointReleased).toBe(false);
+
+ commandGate.resolve();
+ await completion;
+ await checkpoint;
+ expect(checkpointReleased).toBe(true);
+ });
+
+ it("keeps the restart checkpoint fenced between queued handoff and message dispatch", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("queued done")]);
+ // Gate agent.prompt itself to hold the window between the handedOff
+ // phase flip and dispatch open.
+ const dispatchGate = createDeferred();
+ const originalPrompt = harness.session.agent.prompt.bind(harness.session.agent);
+ const promptSpy = vi
+ .spyOn(harness.session.agent, "prompt")
+ .mockImplementation(async (messages: Parameters<typeof originalPrompt>[0]) => {
+ promptSpy.mockRestore();
+ await dispatchGate.promise;
+ return originalPrompt(messages);
+ });
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.followUp("handed off", undefined, { resumeIfIdle: true });
+ pause.release();
+ await vi.waitFor(() => {
+ const active = (harness.session as unknown as { _activeSessionInput?: { kind: string; phase?: string } })
+ ._activeSessionInput;
+ expect(active?.kind).toBe("prompt");
+ expect(active?.phase).toBe("handedOff");
+ });
+
+ let checkpointReleased = false;
+ const checkpoint = harness.session.waitForSessionInputCheckpoint().then(() => {
+ checkpointReleased = true;
+ });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(checkpointReleased).toBe(false);
+
+ dispatchGate.resolve();
+ await checkpoint;
+ await harness.session.waitForIdle();
+ expect(getUserTexts(harness)).toEqual(["handed off"]);
+ });
+
+ it("keeps an injected direct prompt fenced until the injected message starts", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("done")]);
+ await harness.session.sendCustomMessage(
+ { customType: "earlier-next-turn", content: "earlier", display: true, details: {} },
+ { deliverAs: "nextTurn" },
+ );
+ const injectedMessage = {
+ role: "custom" as const,
+ customType: "injected-test",
+ content: "injected prompt",
+ display: true,
+ details: {},
+ timestamp: Date.now(),
+ };
+ const earlierStarted = createDeferred();
+ const earlierStartGate = createDeferred();
+ const injectedStarted = createDeferred();
+ const unsubscribe = harness.session.agent.subscribe(async (event) => {
+ if (event.type !== "message_start") return;
+ if (event.message === injectedMessage) {
+ injectedStarted.resolve();
+ return;
+ }
+ if (event.message.role === "custom" && event.message.customType === "earlier-next-turn") {
+ earlierStarted.resolve();
+ await earlierStartGate.promise;
+ }
+ });
+ const internals = harness.session as unknown as {
+ _promptInjectedMessage(text: string, message: typeof injectedMessage): Promise<void>;
+ };
+
+ const prompt = internals._promptInjectedMessage("injected prompt", injectedMessage);
+ await earlierStarted.promise;
+ let checkpointReleased = false;
+ const checkpoint = harness.session.waitForSessionInputCheckpoint().then(() => {
+ checkpointReleased = true;
+ });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(checkpointReleased).toBe(false);
+
+ earlierStartGate.resolve();
+ await injectedStarted.promise;
+ await checkpoint;
+ await prompt;
+ unsubscribe();
+ });
+
+ it("keeps a triggerTurn custom message fenced until its turn starts", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("done")]);
+ const customStarted = createDeferred();
+ const dispatchGate = createDeferred();
+ const originalPrompt = harness.session.agent.prompt.bind(harness.session.agent);
+ const promptCalled = createDeferred();
+ const promptSpy = vi
+ .spyOn(harness.session.agent, "prompt")
+ .mockImplementation(async (messages: Parameters<typeof originalPrompt>[0]) => {
+ promptSpy.mockRestore();
+ promptCalled.resolve();
+ await dispatchGate.promise;
+ return originalPrompt(messages);
+ });
+ const unsubscribe = harness.session.agent.subscribe((event) => {
+ if (event.type !== "message_start") return;
+ if (event.message.role === "custom" && event.message.customType === "trigger-turn-test") {
+ customStarted.resolve();
+ }
+ });
+
+ const send = harness.session.sendCustomMessage(
+ { customType: "trigger-turn-test", content: "run a turn", display: true, details: {} },
+ { triggerTurn: true },
+ );
+ await promptCalled.promise;
+ let checkpointReleased = false;
+ const checkpoint = harness.session.waitForSessionInputCheckpoint().then(() => {
+ checkpointReleased = true;
+ });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(checkpointReleased).toBe(false);
+
+ dispatchGate.resolve();
+ await customStarted.promise;
+ await checkpoint;
+ await send;
+ unsubscribe();
+ });
+
+ it("releases a queued prompt checkpoint after handoff while its turn remains active", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const responseGate = createDeferred<ReturnType<typeof fauxAssistantMessage>>();
+ harness.setResponses([() => responseGate.promise]);
+ const promptStarted = createDeferred();
+ const unsubscribe = harness.session.agent.subscribe((event) => {
+ if (event.type === "message_start" && event.message.role === "user") promptStarted.resolve();
+ });
+
+ await harness.session.restoreFollowUpMessage("queued prompt");
+ expect(harness.session.resumeQueuedWork()).toBe(true);
+ await promptStarted.promise;
+
+ await expect(harness.session.waitForSessionInputCheckpoint(AbortSignal.timeout(1000))).resolves.toBeUndefined();
+ expect(harness.session.isStreaming).toBe(true);
+ responseGate.resolve(fauxAssistantMessage("done"));
+ await harness.session.waitForIdle();
+ unsubscribe();
+ });
+
+ it("aborts while a queued prompt is still preparing without consuming its snapshot", async () => {
+ const preparationReached = createDeferred();
+ const preparationGate = createDeferred();
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("before_agent_start", async () => {
+ preparationReached.resolve();
+ await preparationGate.promise;
+ });
+ },
+ ],
+ });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("done")]);
+ await harness.session.restoreFollowUpMessage("queued prompt");
+ expect(harness.session.resumeQueuedWork()).toBe(true);
+ await preparationReached.promise;
+ const controller = new AbortController();
+
+ const checkpoint = harness.session.waitForSessionInputCheckpoint(controller.signal);
+ controller.abort();
+
+ await expect(checkpoint).rejects.toThrow("Update restart preparation cancelled");
+ expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: ["queued prompt"] });
+ preparationGate.resolve();
+ await harness.session.waitForIdle();
+ });
+
+ it("aborts while an extension event is pending without flushing or cancelling its queue", async () => {
+ const extensionReached = createDeferred();
+ const extensionGate = createDeferred();
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("message_start", async (event) => {
+ if (event.message.role !== "user") return;
+ extensionReached.resolve();
+ await extensionGate.promise;
+ });
+ },
+ ],
+ });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("done")]);
+ const prompt = harness.session.prompt("pending extension event");
+ await extensionReached.promise;
+ const checkpointInternals = harness.session as unknown as {
+ _activeSessionInput?: unknown;
+ _directPromptSectionCount: number;
+ };
+ expect(checkpointInternals._activeSessionInput).toBeUndefined();
+ expect(checkpointInternals._directPromptSectionCount).toBe(0);
+ const eventQueue = (harness.session as unknown as { _agentEventQueue: Promise<void> })._agentEventQueue;
+ let queueDrained = false;
+ void eventQueue.then(() => {
+ queueDrained = true;
+ });
+ const flushNow = vi.spyOn(harness.sessionManager, "flushNow");
+ const controller = new AbortController();
+ const removeEventListener = vi.spyOn(controller.signal, "removeEventListener");
+
+ const checkpoint = harness.session.waitForSessionInputCheckpoint(controller.signal);
+ controller.abort();
+
+ await expect(checkpoint).rejects.toThrow("Update restart preparation cancelled");
+ expect(queueDrained).toBe(false);
+ expect(flushNow).not.toHaveBeenCalled();
+ expect(removeEventListener).toHaveBeenCalledWith("abort", expect.any(Function));
+ extensionGate.resolve();
+ await prompt;
+ await eventQueue;
+ expect(queueDrained).toBe(true);
+ expect(flushNow).not.toHaveBeenCalled();
+ });
+
+ it("propagates a snapshotted event queue rejection without flushing", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ (harness.session as unknown as { _agentEventQueue: Promise<void> })._agentEventQueue = Promise.reject(
+ new Error("event queue failed"),
+ );
+ const flushNow = vi.spyOn(harness.sessionManager, "flushNow");
+
+ await expect(harness.session.waitForSessionInputCheckpoint()).rejects.toThrow("event queue failed");
+ expect(flushNow).not.toHaveBeenCalled();
+ });
+
+ it("releases the direct prompt section when an injected dispatch fails", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const internals = harness.session as unknown as {
+ _promptInjectedMessage(
+ text: string,
+ message: {
+ role: "custom";
+ customType: string;
+ content: string;
+ display: boolean;
+ details: Record<string, never>;
+ timestamp: number;
+ },
+ ): Promise<void>;
+ };
+ vi.spyOn(harness.session.agent, "prompt").mockRejectedValue(new Error("dispatch failed"));
+
+ await expect(
+ internals._promptInjectedMessage("injected prompt", {
+ role: "custom",
+ customType: "injected-test",
+ content: "injected prompt",
+ display: true,
+ details: {},
+ timestamp: Date.now(),
+ }),
+ ).rejects.toThrow("dispatch failed");
+
+ // A leaked section would keep update-restart checkpoints waiting forever.
+ await expect(harness.session.waitForSessionInputCheckpoint(AbortSignal.timeout(1000))).resolves.toBeUndefined();
+ });
+
+ it("releases the direct prompt section when an ordinary dispatch fails", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ vi.spyOn(harness.session.agent, "prompt").mockRejectedValue(new Error("dispatch failed"));
+
+ await expect(harness.session.prompt("ordinary prompt")).rejects.toThrow("dispatch failed");
+ await expect(harness.session.waitForSessionInputCheckpoint(AbortSignal.timeout(1000))).resolves.toBeUndefined();
+ });
+
it("throws when prompting without a model", async () => {
const harness = await createHarness();
harnesses.push(harness);
@@ -1280,4 +1765,93 @@ stale post-hook extension instructions`,
`No API key found for ${harness.getModel().provider}.`,
);
});
+
+ it("S7: accepted agent messages queue while busy, deliver before completion, and clean up when cleared", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const busyPrompt = (id: string, body: string) =>
+ `Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: ${id}\n\n${body}`;
+
+ // Phase 1: accept while streaming -> queues instead of interrupting.
+ const busyGate = createDeferred();
+ harness.setResponses([
+ async () => {
+ await busyGate.promise;
+ return fauxAssistantMessage("busy done");
+ },
+ fauxAssistantMessage("queued accepted done"),
+ ]);
+ const running = harness.session.prompt("keep busy");
+ await vi.waitFor(() => expect(harness.session.isStreaming).toBe(true));
+ const queuedAgentPrompt = busyPrompt("agentmsg_s7_busy", "queued while busy");
+ await harness.session.acceptAgentMessagePrompt(queuedAgentPrompt, {
+ expandPromptTemplates: false,
+ streamingBehavior: "followUp",
+ queueIfBusy: true,
+ });
+ expect(harness.session.getFollowUpMessages()).toEqual([queuedAgentPrompt]);
+ busyGate.resolve();
+ await running;
+ await harness.session.waitForIdle();
+ expect(getUserTexts(harness)).toEqual(["keep busy", queuedAgentPrompt]);
+
+ // Phase 2: accept while idle returns after delivery, before completion; delivered is uncleareable.
+ const responseGate = createDeferred();
+ harness.setResponses([
+ async () => {
+ await responseGate.promise;
+ return fauxAssistantMessage("delivered");
+ },
+ ]);
+ const directAgentPrompt = busyPrompt("agentmsg_s7_direct", "direct delivery");
+ await harness.session.acceptAgentMessagePrompt(directAgentPrompt, { expandPromptTemplates: false });
+ expect(getUserTexts(harness)).toContain(directAgentPrompt);
+ expect(getAssistantTexts(harness)).not.toContain("delivered");
+ expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_s7_direct"))).toEqual({
+ steering: [],
+ followUp: [],
+ });
+ responseGate.resolve();
+ await harness.session.agent.waitForIdle();
+ expect(getAssistantTexts(harness)).toContain("delivered");
+ expect(getUserTexts(harness)).toContain(directAgentPrompt);
+
+ // Phase 3: built-in slash commands stay literal.
+ harness.setResponses([fauxAssistantMessage("literal")]);
+ await harness.session.acceptAgentMessagePrompt("/autonomous on", { expandPromptTemplates: false });
+ await harness.session.agent.waitForIdle();
+ expect(harness.session.getAutonomousStatus().enabled).toBe(false);
+ expect(getUserTexts(harness)).toContain("/autonomous on");
+
+ // Phase 4: clear during admission rejects both waiters; late events must not re-persist.
+ const persistedBefore = harness.sessionManager.getEntries().filter((entry) => entry.type === "message").length;
+ harness.setResponses([fauxAssistantMessage("never delivered")]);
+ const clearedAgentPrompt = busyPrompt("agentmsg_s7_cleared", "cleared during admission");
+ const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_s7_cleared");
+ const admission = gateNextAgentStart(harness);
+ const accepted = harness.session.acceptAgentMessagePrompt(clearedAgentPrompt, {
+ expandPromptTemplates: false,
+ });
+ await admission.reached;
+ expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_s7_cleared"))).toEqual({
+ steering: [],
+ followUp: [clearedAgentPrompt],
+ });
+ admission.release();
+ await expect(accepted).rejects.toThrow("cleared before delivery");
+ await expect(delivery).rejects.toThrow("cleared before delivery");
+ await harness.session.agent.waitForIdle();
+ await (harness.session as unknown as { _agentEventQueue: Promise<void> })._agentEventQueue;
+ const persistedAfter = harness.sessionManager.getEntries().filter((entry) => entry.type === "message").length;
+ expect(persistedAfter).toBe(persistedBefore);
+ expect(getUserTexts(harness)).not.toContain(clearedAgentPrompt);
+ expect(harness.session.agent.state.errorMessage).toBeUndefined();
+ expect(
+ (harness.session as unknown as { _acceptedAgentMessagePrompt?: unknown })._acceptedAgentMessagePrompt,
+ ).toBeUndefined();
+
+ harness.setResponses([fauxAssistantMessage("clean after")]);
+ await harness.session.prompt("normal prompt");
+ expect(getAssistantTexts(harness)).toContain("clean after");
+ });
});
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 3ecdb4dd46..9c9e825a83 100644
--- a/packages/coding-agent/test/suite/agent-session-queue.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-queue.test.ts
@@ -5,6 +5,13 @@ import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ AGENT_MESSAGE_SOURCE,
+ type AgentSessionMessagePayload,
+ createAgentSessionMessage,
+ createAgentSessionMessagePrompt,
+} from "../../src/core/agent-messages.js";
+import { createSessionSlashCommandMessage } from "../../src/core/messages.js";
import {
applyRefinementProposal,
getGlobalHarnessStateDir,
@@ -16,7 +23,9 @@ import {
type RefinementResult,
saveHarnessState,
} from "../../src/core/refinement/index.js";
+import { parseSessionSlashCommand } from "../../src/core/slash-commands.js";
import { createHarness, getAssistantTexts, getMessageText, getUserTexts, type Harness } from "./harness.js";
+import { createDeferred, createWaitingHarness, gatedHook, withStreaming } from "./scheduling.js";
type AutoRefineReason = "turn_interval" | "compact";
@@ -38,6 +47,11 @@ type AutoRefineInternals = {
_autoRefineBranchVersion: number;
};
+type SteeringStopInternals = {
+ _steeringStopPending: boolean;
+ _clearQueuedGoalContexts(): void;
+};
+
function emptyRefinementResult(): RefinementResult {
return {
id: "refine_test",
@@ -49,65 +63,24 @@ function emptyRefinementResult(): RefinementResult {
};
}
+function refinePlanJson(summary: string, edits: unknown[] = []): string {
+ return JSON.stringify({
+ summary,
+ rationale: `${summary} rationale`,
+ expectedOutcome: `${summary} outcome`,
+ edits,
+ });
+}
+
function createAutoRefineHarness(options: Parameters<typeof createHarness>[0] = {}): Promise<Harness> {
return createHarness({ ...options, persistSession: true });
}
-function setAgentStreaming(harness: Harness, isStreaming: boolean): void {
- (harness.session.agent.state as { isStreaming: boolean }).isStreaming = isStreaming;
+function agentPromptText(id: string, body: string): string {
+ return `Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: ${id}\n\n${body}`;
}
-async function createWaitingHarness(
- options: {
- tools?: AgentTool[];
- extensionFactories?: Harness["session"]["extensionRunner"] extends never
- ? never
- : Array<(pi: ExtensionAPI) => void>;
- } = {},
-): Promise<{
- harness: Harness;
- releaseToolExecution: () => void;
- promptPromise: Promise<void>;
- waitForToolStart: Promise<void>;
-}> {
- let releaseToolExecution: (() => void) | undefined;
- const toolRelease = new Promise<void>((resolve) => {
- releaseToolExecution = resolve;
- });
- const waitTool: AgentTool = {
- name: "wait",
- label: "Wait",
- description: "Wait for release",
- parameters: Type.Object({}),
- execute: async () => {
- await toolRelease;
- return {
- content: [{ type: "text", text: "released" }],
- details: {},
- };
- },
- };
- const harness = await createHarness({
- tools: [waitTool, ...(options.tools ?? [])],
- extensionFactories: options.extensionFactories,
- });
-
- const waitForToolStart = new Promise<void>((resolve) => {
- const unsubscribe = harness.session.subscribe((event) => {
- if (event.type === "tool_execution_start" && event.toolName === "wait") {
- unsubscribe();
- resolve();
- }
- });
- });
-
- return {
- harness,
- releaseToolExecution: () => releaseToolExecution?.(),
- promptPromise: harness.session.prompt("start"),
- waitForToolStart,
- };
-}
+const skipReviewer = vi.fn(async () => ({ shouldRefine: true, rationale: "durable lesson" }));
describe("AgentSession queue characterization", () => {
const harnesses: Harness[] = [];
@@ -131,156 +104,175 @@ describe("AgentSession queue characterization", () => {
expect(internals._assistantTurnsSinceAutoRefine).toBe(0);
});
- it("auto-refine review runs after the configured turn interval", async () => {
- const reviewer = vi.fn(async () => ({
- shouldRefine: true,
- rationale: "durable lesson found",
- instructions: "capture the durable lesson",
- }));
- const harness = await createAutoRefineHarness({
+ it.each([
+ {
+ name: "review runs after the configured turn interval",
settings: { autoRefine: { enabled: true, turnInterval: 2, cooldownMs: 0 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 2;
-
- await internals._maybeAutoRefine("turn_interval");
-
- expect(reviewer).toHaveBeenCalledWith(
- { reason: "turn_interval", turnsSinceLastReview: 2 },
- expect.any(AbortSignal),
- );
- expect(refine).toHaveBeenCalledWith(
- expect.objectContaining({ instructions: expect.stringContaining("capture the durable lesson") }),
- );
- expect(refine).toHaveBeenCalledWith(
- expect.objectContaining({ instructions: expect.stringContaining("local harness entries") }),
- );
- expect(refine).toHaveBeenCalledWith(
- expect.objectContaining({ instructions: expect.stringContaining("Do not promote anything global") }),
- );
- expect(internals._assistantTurnsSinceAutoRefine).toBe(0);
- });
-
- it("auto-refine compact hook does not require the turn interval", async () => {
- const reviewer = vi.fn(async () => ({ shouldRefine: false, rationale: "nothing durable" }));
- const harness = await createAutoRefineHarness({
+ turns: 2,
+ reason: "turn_interval" as AutoRefineReason,
+ review: {
+ shouldRefine: true,
+ rationale: "durable lesson found",
+ instructions: "capture the durable lesson",
+ },
+ expectedReviewContext: { reason: "turn_interval", turnsSinceLastReview: 2 },
+ refineFragments: ["capture the durable lesson", "local harness entries", "Do not promote anything global"],
+ turnsAfter: 0,
+ compactPendingAfter: undefined as boolean | undefined,
+ scheduleCalledWith: undefined as AutoRefineReason | undefined,
+ queuedMessages: false,
+ },
+ {
+ name: "compact hook does not require the turn interval",
settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 0;
-
- await internals._maybeAutoRefine("compact");
-
- expect(reviewer).toHaveBeenCalledWith({ reason: "compact", turnsSinceLastReview: 0 }, expect.any(AbortSignal));
- expect(refine).not.toHaveBeenCalled();
- });
-
- it("falls back to turn-interval review when compact auto-refine is disabled", async () => {
- const reviewer = vi.fn(async () => ({ shouldRefine: false, rationale: "nothing durable" }));
- const harness = await createAutoRefineHarness({
+ turns: 0,
+ reason: "compact" as AutoRefineReason,
+ review: { shouldRefine: false, rationale: "nothing durable" },
+ expectedReviewContext: { reason: "compact", turnsSinceLastReview: 0 },
+ refineFragments: undefined as string[] | undefined,
+ turnsAfter: undefined as number | undefined,
+ compactPendingAfter: undefined,
+ scheduleCalledWith: undefined,
+ queuedMessages: false,
+ },
+ {
+ name: "falls back to turn-interval review when compact auto-refine is disabled",
settings: { autoRefine: { enabled: true, compact: false, turnInterval: 2, cooldownMs: 0 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 2;
-
- await internals._maybeAutoRefine("compact");
-
- expect(reviewer).toHaveBeenCalledWith(
- { reason: "turn_interval", turnsSinceLastReview: 2 },
- expect.any(AbortSignal),
- );
- expect(internals._compactAutoRefinePending).toBe(false);
- });
-
- it("declined compact review preserves an already-due turn interval", async () => {
- const reviewer = vi.fn(async () => ({ shouldRefine: false, rationale: "nothing compact-specific" }));
- const harness = await createAutoRefineHarness({
+ turns: 2,
+ reason: "compact" as AutoRefineReason,
+ review: { shouldRefine: false, rationale: "nothing durable" },
+ expectedReviewContext: { reason: "turn_interval", turnsSinceLastReview: 2 },
+ refineFragments: undefined,
+ turnsAfter: undefined,
+ compactPendingAfter: false as boolean | undefined,
+ scheduleCalledWith: undefined,
+ queuedMessages: false,
+ },
+ {
+ name: "declined compact review preserves an already-due turn interval",
settings: { autoRefine: { enabled: true, turnInterval: 2, cooldownMs: 0 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 2;
- const scheduleAutoRefine = vi.spyOn(internals, "_scheduleAutoRefine").mockImplementation(() => {});
-
- await internals._maybeAutoRefine("compact");
-
- expect(internals._assistantTurnsSinceAutoRefine).toBe(2);
- expect(scheduleAutoRefine).toHaveBeenCalledWith("turn_interval");
- });
-
- it("auto-refine compact hook waits for planned post-compaction continuation", async () => {
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- const scheduleAutoRefine = vi.spyOn(internals, "_scheduleAutoRefine").mockImplementation(() => {});
-
- internals._scheduleAutoRefineAfterCompaction(true);
-
- expect(internals._compactAutoRefinePending).toBe(true);
- expect(scheduleAutoRefine).not.toHaveBeenCalled();
-
- internals._scheduleAutoRefineAfterAgentEnd();
-
- expect(internals._compactAutoRefinePending).toBe(true);
- expect(scheduleAutoRefine).toHaveBeenCalledWith("compact");
- expect(scheduleAutoRefine).toHaveBeenCalledTimes(1);
- });
-
- it("auto-refine compact hook waits until the scheduled post-compaction continuation starts", async () => {
+ turns: 2,
+ reason: "compact" as AutoRefineReason,
+ review: { shouldRefine: false, rationale: "nothing compact-specific" },
+ expectedReviewContext: undefined as { reason: string; turnsSinceLastReview: number } | undefined,
+ refineFragments: undefined,
+ turnsAfter: 2,
+ compactPendingAfter: undefined,
+ scheduleCalledWith: "turn_interval" as AutoRefineReason | undefined,
+ queuedMessages: false,
+ },
+ {
+ name: "queued follow-up messages do not make an idle agent active",
+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },
+ turns: 1,
+ reason: "turn_interval" as AutoRefineReason,
+ review: {
+ shouldRefine: true,
+ rationale: "durable lesson found",
+ instructions: "capture the durable lesson",
+ },
+ expectedReviewContext: { reason: "turn_interval", turnsSinceLastReview: 1 },
+ refineFragments: [],
+ turnsAfter: undefined,
+ compactPendingAfter: undefined,
+ scheduleCalledWith: undefined,
+ queuedMessages: true,
+ },
+ ])(
+ "auto-refine $name",
+ async ({
+ settings,
+ turns,
+ reason,
+ review,
+ expectedReviewContext,
+ refineFragments,
+ turnsAfter,
+ compactPendingAfter,
+ scheduleCalledWith,
+ queuedMessages,
+ }) => {
+ const reviewer = vi.fn(async () => review);
+ const harness = await createAutoRefineHarness({ settings, autoRefineReviewer: reviewer });
+ harnesses.push(harness);
+ const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
+ const internals = harness.session as unknown as AutoRefineInternals;
+ internals._assistantTurnsSinceAutoRefine = turns;
+ const scheduleAutoRefine = vi.spyOn(internals, "_scheduleAutoRefine").mockImplementation(() => {});
+ if (queuedMessages) vi.spyOn(harness.session.agent, "hasQueuedMessages").mockReturnValue(true);
+
+ await internals._maybeAutoRefine(reason);
+
+ if (expectedReviewContext !== undefined) {
+ expect(reviewer).toHaveBeenCalledWith(expectedReviewContext, expect.any(AbortSignal));
+ }
+ if (refineFragments === undefined) {
+ expect(refine).not.toHaveBeenCalled();
+ } else {
+ expect(refine).toHaveBeenCalled();
+ for (const fragment of refineFragments) {
+ expect(refine).toHaveBeenCalledWith(
+ expect.objectContaining({ instructions: expect.stringContaining(fragment) }),
+ );
+ }
+ }
+ if (turnsAfter !== undefined) expect(internals._assistantTurnsSinceAutoRefine).toBe(turnsAfter);
+ if (compactPendingAfter !== undefined) expect(internals._compactAutoRefinePending).toBe(compactPendingAfter);
+ if (scheduleCalledWith !== undefined) expect(scheduleAutoRefine).toHaveBeenCalledWith(scheduleCalledWith);
+ },
+ );
+
+ it.each([
+ {
+ name: "waits for planned post-compaction continuation",
+ act: (internals: AutoRefineInternals, expectSchedule: (called: boolean) => void) => {
+ internals._scheduleAutoRefineAfterCompaction(true);
+ expect(internals._compactAutoRefinePending).toBe(true);
+ expectSchedule(false);
+ internals._scheduleAutoRefineAfterAgentEnd();
+ expect(internals._compactAutoRefinePending).toBe(true);
+ },
+ },
+ {
+ name: "waits until the scheduled post-compaction continuation starts",
+ act: (internals: AutoRefineInternals, expectSchedule: (called: boolean) => void) => {
+ internals._compactAutoRefinePending = true;
+ internals._postCompactionContinuationScheduled = true;
+ internals._scheduleAutoRefineAfterAgentEnd();
+ expectSchedule(false);
+ internals._postCompactionContinuationScheduled = false;
+ internals._scheduleAutoRefineAfterAgentEnd();
+ },
+ },
+ {
+ name: "runs immediately when no post-compaction continuation is planned",
+ act: (internals: AutoRefineInternals) => {
+ internals._scheduleAutoRefineAfterCompaction(false);
+ expect(internals._compactAutoRefinePending).toBe(false);
+ },
+ },
+ ])("auto-refine compact hook $name", async ({ act }) => {
const harness = await createAutoRefineHarness({
settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },
});
harnesses.push(harness);
const internals = harness.session as unknown as AutoRefineInternals;
const scheduleAutoRefine = vi.spyOn(internals, "_scheduleAutoRefine").mockImplementation(() => {});
- internals._compactAutoRefinePending = true;
- internals._postCompactionContinuationScheduled = true;
-
- internals._scheduleAutoRefineAfterAgentEnd();
-
- expect(scheduleAutoRefine).not.toHaveBeenCalled();
- internals._postCompactionContinuationScheduled = false;
- internals._scheduleAutoRefineAfterAgentEnd();
+ act(internals, (called) =>
+ called ? expect(scheduleAutoRefine).toHaveBeenCalled() : expect(scheduleAutoRefine).not.toHaveBeenCalled(),
+ );
expect(scheduleAutoRefine).toHaveBeenCalledWith("compact");
expect(scheduleAutoRefine).toHaveBeenCalledTimes(1);
});
- it("auto-refine compact hook runs immediately when no post-compaction continuation is planned", async () => {
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- const scheduleAutoRefine = vi.spyOn(internals, "_scheduleAutoRefine").mockImplementation(() => {});
-
- internals._scheduleAutoRefineAfterCompaction(false);
-
- expect(internals._compactAutoRefinePending).toBe(false);
- expect(scheduleAutoRefine).toHaveBeenCalledWith("compact");
- });
-
it("runs a turn-interval review after a concurrent compact review declines", async () => {
vi.useFakeTimers();
- let releaseCompactReview: (() => void) | undefined;
- const compactReviewGate = new Promise<void>((resolve) => {
- releaseCompactReview = resolve;
- });
+ const compactReviewGate = createDeferred();
const reviewer = vi.fn(async ({ reason }: { reason: AutoRefineReason }) => {
if (reason === "compact") {
- await compactReviewGate;
+ await compactReviewGate.promise;
}
return { shouldRefine: false, rationale: `${reason} found nothing durable` };
});
@@ -299,7 +291,7 @@ describe("AgentSession queue characterization", () => {
expect(internals._turnIntervalAutoRefinePending).toBe(true);
- releaseCompactReview?.();
+ compactReviewGate.resolve();
await compactReview;
await vi.runOnlyPendingTimersAsync();
@@ -360,112 +352,55 @@ describe("AgentSession queue characterization", () => {
}
});
- it("keeps scheduled post-compaction continuation when manual compaction is skipped", async () => {
+ it.each([
+ { name: "requestAbort", abort: (harness: Harness) => harness.session.requestAbort() },
+ {
+ name: "abortForUpdateRestart",
+ abort: (harness: Harness) => harness.session.abortForUpdateRestart(),
+ },
+ ])("cancels scheduled post-compaction continuation at $name without dropping queued input", async ({ abort }) => {
vi.useFakeTimers();
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },
- });
+ const harness = await createAutoRefineHarness();
harnesses.push(harness);
const internals = harness.session as unknown as AutoRefineInternals;
+ const continueAgent = vi.spyOn(harness.session.agent, "continue").mockResolvedValue();
+
try {
internals._schedulePostCompactionContinue();
+ await harness.session.followUp("queued across abort");
- await expect(harness.session.compact()).rejects.toThrow("Session is too short to compact");
+ abort(harness);
+ await vi.advanceTimersByTimeAsync(100);
- expect(internals._postCompactionContinuationScheduled).toBe(true);
+ expect(continueAgent).not.toHaveBeenCalled();
+ expect(internals._postCompactionContinuationScheduled).toBe(false);
+ expect(harness.session.getFollowUpMessages()).toEqual(["queued across abort"]);
} finally {
- internals._cancelPostCompactionContinue();
vi.useRealTimers();
}
});
- it("does not run scheduled auto-refine after branch navigation", async () => {
+ it("keeps scheduled post-compaction continuation when session-input pump compaction skips without aborting", async () => {
vi.useFakeTimers();
const harness = await createAutoRefineHarness({
settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },
});
harnesses.push(harness);
const internals = harness.session as unknown as AutoRefineInternals;
- const maybeAutoRefine = vi.spyOn(internals, "_maybeAutoRefine").mockResolvedValue();
try {
- internals._scheduleAutoRefine("compact");
- await internals._invalidatePendingAutoRefineForBranchChange();
- await vi.runAllTimersAsync();
+ internals._schedulePostCompactionContinue();
+
+ await expect(harness.session.compact(undefined, { skipAbort: true })).rejects.toThrow(
+ "Session is too short to compact",
+ );
- expect(maybeAutoRefine).not.toHaveBeenCalled();
+ expect(internals._postCompactionContinuationScheduled).toBe(true);
} finally {
+ internals._cancelPostCompactionContinue();
vi.useRealTimers();
}
});
- it("auto-refine compact hook defers an approved refine if the agent becomes active during review", async () => {
- let finishReview: (() => void) | undefined;
- const reviewStarted = new Promise<void>((resolve) => {
- finishReview = resolve;
- });
- const reviewer = vi.fn(async () => {
- await reviewStarted;
- setAgentStreaming(harness, true);
- return { shouldRefine: true, rationale: "durable lesson" };
- });
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
-
- const autoRefinePromise = internals._maybeAutoRefine("compact");
- expect(reviewer).toHaveBeenCalledWith({ reason: "compact", turnsSinceLastReview: 0 }, expect.any(AbortSignal));
- finishReview?.();
- await autoRefinePromise;
-
- expect(refine).not.toHaveBeenCalled();
- expect(internals._pendingAutoRefineReview).toBeDefined();
- expect(internals._compactAutoRefinePending).toBe(false);
- });
-
- it("auto-refine turn interval defers an approved refine if the agent becomes active during review", async () => {
- let finishReview: (() => void) | undefined;
- const reviewStarted = new Promise<void>((resolve) => {
- finishReview = resolve;
- });
- const reviewer = vi.fn(async () => {
- await reviewStarted;
- setAgentStreaming(harness, true);
- return { shouldRefine: true, rationale: "durable lesson" };
- });
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 2, cooldownMs: 60_000 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 2;
- const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
-
- const autoRefinePromise = internals._maybeAutoRefine("turn_interval");
- expect(reviewer).toHaveBeenCalledWith(
- { reason: "turn_interval", turnsSinceLastReview: 2 },
- expect.any(AbortSignal),
- );
- finishReview?.();
- await autoRefinePromise;
-
- expect(refine).not.toHaveBeenCalled();
- expect(internals._pendingAutoRefineReview).toBeDefined();
-
- setAgentStreaming(harness, false);
- await internals._maybeAutoRefine("turn_interval");
-
- expect(reviewer).toHaveBeenCalledTimes(1);
- expect(refine).toHaveBeenCalledWith(
- expect.objectContaining({ instructions: expect.stringContaining("durable lesson") }),
- );
- expect(internals._pendingAutoRefineReview).toBeUndefined();
- });
-
it("auto-refine pending review uses the in-progress guard and catches refine failures", async () => {
const harness = await createAutoRefineHarness({
settings: { autoRefine: { enabled: true, turnInterval: 2, cooldownMs: 60_000 } },
@@ -528,15 +463,12 @@ describe("AgentSession queue characterization", () => {
});
it("does not refine when a review resolves after the session is disposed", async () => {
- let finishReview: (() => void) | undefined;
- const reviewGate = new Promise<void>((resolve) => {
- finishReview = resolve;
- });
+ const reviewGate = createDeferred();
const signals: Array<AbortSignal | undefined> = [];
const reviewer = vi.fn(
async (_context: { reason: AutoRefineReason; turnsSinceLastReview: number }, signal?: AbortSignal) => {
signals.push(signal);
- await reviewGate;
+ await reviewGate.promise;
return { shouldRefine: true, rationale: "durable lesson" };
},
);
@@ -554,7 +486,7 @@ describe("AgentSession queue characterization", () => {
const entriesBeforeDispose = harness.sessionManager.getEntries().length;
harness.session.dispose();
expect(signals[0]?.aborted).toBe(true);
- finishReview?.();
+ reviewGate.resolve();
await autoRefinePromise;
expect(refine).not.toHaveBeenCalled();
@@ -610,45 +542,25 @@ describe("AgentSession queue characterization", () => {
it("serializes concurrent refine calls", async () => {
const harness = await createAutoRefineHarness();
harnesses.push(harness);
- let releaseFirstPlan: (() => void) | undefined;
- const firstPlanGate = new Promise<void>((resolve) => {
- releaseFirstPlan = resolve;
- });
- let firstPlanStarted: (() => void) | undefined;
- const firstPlanStartedPromise = new Promise<void>((resolve) => {
- firstPlanStarted = resolve;
- });
+ const firstPlanGate = createDeferred();
+ const firstPlanStartedPromise = createDeferred();
harness.setResponses([
async () => {
- firstPlanStarted?.();
- await firstPlanGate;
- return fauxAssistantMessage(
- JSON.stringify({
- summary: "first",
- rationale: "first refine",
- expectedOutcome: "first finished",
- edits: [],
- }),
- );
+ firstPlanStartedPromise.resolve();
+ await firstPlanGate.promise;
+ return fauxAssistantMessage(refinePlanJson("first"));
},
- fauxAssistantMessage(
- JSON.stringify({
- summary: "second",
- rationale: "second refine",
- expectedOutcome: "second finished",
- edits: [],
- }),
- ),
+ fauxAssistantMessage(refinePlanJson("second")),
]);
const firstRefine = harness.session.refine({ instructions: "first refine" });
- await firstPlanStartedPromise;
+ await firstPlanStartedPromise.promise;
const secondRefine = harness.session.refine({ instructions: "second refine" });
await Promise.resolve();
expect(harness.getPendingResponseCount()).toBe(1);
- releaseFirstPlan?.();
+ firstPlanGate.resolve();
await firstRefine;
await secondRefine;
@@ -658,33 +570,22 @@ describe("AgentSession queue characterization", () => {
it("does not persist or reconnect an in-flight refine after dispose", async () => {
const harness = await createAutoRefineHarness();
harnesses.push(harness);
- let releasePlan: (() => void) | undefined;
- const planGate = new Promise<void>((resolve) => {
- releasePlan = resolve;
- });
- let planStarted: (() => void) | undefined;
- const planStartedPromise = new Promise<void>((resolve) => {
- planStarted = resolve;
- });
+ const planGate = createDeferred();
+ const planStartedPromise = createDeferred();
harness.setResponses([
async () => {
- planStarted?.();
- await planGate;
+ planStartedPromise.resolve();
+ await planGate.promise;
return fauxAssistantMessage(
- JSON.stringify({
- summary: "stale refine",
- rationale: "the session was disposed before apply",
- expectedOutcome: "nothing is persisted",
- edits: [
- {
- action: "create",
- kind: "memory",
- id: "stale_after_dispose",
- title: "Stale after dispose",
- content: "This must not be saved.",
- },
- ],
- }),
+ refinePlanJson("stale refine", [
+ {
+ action: "create",
+ kind: "memory",
+ id: "stale_after_dispose",
+ title: "Stale after dispose",
+ content: "This must not be saved.",
+ },
+ ]),
);
},
]);
@@ -693,114 +594,155 @@ describe("AgentSession queue characterization", () => {
const entriesBeforeDispose = harness.sessionManager.getEntries().length;
const refine = harness.session.refine({ instructions: "write stale state" });
- await planStartedPromise;
+ await planStartedPromise.promise;
harness.session.dispose();
- releasePlan?.();
+ planGate.resolve();
await expect(refine).rejects.toThrow();
expect(reconnect).not.toHaveBeenCalled();
expect(harness.sessionManager.getEntries()).toHaveLength(entriesBeforeDispose);
});
- it("clears pending auto-refine state when navigating to another branch", async () => {
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },
+ it("waits for an active direct prompt before navigating", async () => {
+ const waiting = await createWaitingHarness();
+ const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ harnesses.push(harness);
+ harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
+ fauxAssistantMessage("done"),
+ ]);
+ await waitForToolStart;
+ const target = harness.sessionManager.getEntries().find((entry) => entry.type === "message");
+ expect(target).toBeDefined();
+ let navigated = false;
+ const navigation = harness.session.navigateTree(target!.id).then(() => {
+ navigated = true;
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(navigated).toBe(false);
+
+ releaseToolExecution();
+ await promptPromise;
+ await navigation;
+ expect(navigated).toBe(true);
+ });
+
+ it("keeps queued work paused until tree navigation events settle", async () => {
+ const treeEvent = createDeferred();
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("session_tree", async () => treeEvent.promise);
+ },
+ ],
});
harnesses.push(harness);
- harness.setResponses([fauxAssistantMessage("one"), fauxAssistantMessage("two")]);
+ harness.setResponses([fauxAssistantMessage("one"), fauxAssistantMessage("queued")]);
await harness.session.prompt("first");
- await harness.session.prompt("second");
- const targetEntry = harness.sessionManager
- .getEntries()
- .find((entry) => entry.type === "message" && entry.message.role === "user");
- expect(targetEntry).toBeDefined();
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 5;
- internals._compactAutoRefinePending = true;
- internals._pendingAutoRefineReview = {
- reason: "compact",
- review: { shouldRefine: true, rationale: "old branch" },
- };
+ const target = harness.sessionManager.getEntries().find((entry) => entry.type === "message");
+ expect(target).toBeDefined();
- await harness.session.navigateTree(targetEntry!.id, { summarize: false });
+ const navigation = harness.session.navigateTree(target!.id, { summarize: false });
+ await harness.session.followUp("after navigation", undefined, { resumeIfIdle: true });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(getUserTexts(harness)).not.toContain("after navigation");
- expect(internals._compactAutoRefinePending).toBe(false);
- expect(internals._pendingAutoRefineReview).toBeUndefined();
- expect(internals._assistantTurnsSinceAutoRefine).toBe(0);
+ treeEvent.resolve();
+ await navigation;
+ await vi.waitFor(() => expect(getUserTexts(harness)).toContain("after navigation"));
});
- it("does not apply stale auto-refine cooldown when a review completes after branch navigation", async () => {
- let finishReview: (() => void) | undefined;
- const reviewStarted = new Promise<void>((resolve) => {
- finishReview = resolve;
- });
- const reviewer = vi.fn(async () => {
- await reviewStarted;
- return { shouldRefine: true, rationale: "old branch" };
+ it("queueIfBusy enqueues behind pending work instead of draining it first", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("first done"), fauxAssistantMessage("second done")]);
+ withStreaming(harness, true);
+ await harness.session.followUp("already queued", undefined, { queueKey: "existing" });
+ withStreaming(harness, false);
+
+ let queuedAtPreflight: boolean | undefined;
+ await harness.session.prompt("respects the queue", {
+ queueIfBusy: true,
+ streamingBehavior: "followUp",
+ preflightResult: (_success, queued) => {
+ queuedAtPreflight ??= queued;
+ },
});
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 2, cooldownMs: 60_000 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 2;
- const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
- const beforeReviewAt = internals._lastAutoRefineReviewAt;
-
- const autoRefinePromise = internals._maybeAutoRefine("turn_interval");
- expect(reviewer).toHaveBeenCalledWith(
- { reason: "turn_interval", turnsSinceLastReview: 2 },
- expect.any(AbortSignal),
- );
- await internals._invalidatePendingAutoRefineForBranchChange();
- finishReview?.();
- await autoRefinePromise;
+ await harness.session.waitForIdle();
- expect(refine).not.toHaveBeenCalled();
- expect(internals._lastAutoRefineReviewAt).toBe(beforeReviewAt);
- expect(internals._assistantTurnsSinceAutoRefine).toBe(0);
- expect(internals._pendingAutoRefineReview).toBeUndefined();
+ expect(queuedAtPreflight).toBe(true);
+ expect(getUserTexts(harness)).toEqual(["already queued", "respects the queue"]);
});
- it("auto-refine is skipped for sessions without a local harness directory", async () => {
- const reviewer = vi.fn(async () => ({ shouldRefine: true, rationale: "durable lesson" }));
+ it("invalidates queued prompt preparation on branch navigation", async () => {
+ let pause: { release(): void } | undefined;
const harness = await createHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },
- autoRefineReviewer: reviewer,
+ extensionFactories: [
+ (pi) => {
+ pi.on("before_agent_start", async (event) => {
+ if (event.prompt === "queued" && !pause) pause = harness.session.acquireQueuedWorkPause();
+ });
+ },
+ ],
});
harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 1;
- const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
- const scheduleAutoRefine = vi.spyOn(internals, "_scheduleAutoRefine").mockImplementation(() => {});
-
- await internals._maybeAutoRefine("turn_interval");
- internals._scheduleAutoRefineAfterCompaction(false);
- internals._scheduleAutoRefineAfterAgentEnd();
-
- expect(reviewer).not.toHaveBeenCalled();
- expect(refine).not.toHaveBeenCalled();
- expect(scheduleAutoRefine).not.toHaveBeenCalled();
- });
-
- it("auto-refine is skipped for subagent sessions", async () => {
- const reviewer = vi.fn(async () => ({ shouldRefine: true, rationale: "durable lesson" }));
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },
- rlmDepth: 1,
- autoRefineReviewer: reviewer,
- });
+ harness.setResponses([fauxAssistantMessage("one")]);
+ await harness.session.prompt("first");
+ const target = harness.sessionManager.getEntries().find((entry) => entry.type === "message");
+ expect(target).toBeDefined();
+
+ withStreaming(harness, true);
+ await harness.session.followUp("queued", undefined, { resumeIfIdle: true });
+ withStreaming(harness, false);
+ await vi.waitFor(() => expect(pause).toBeDefined());
+ await harness.session.waitForSessionInputIdle();
+ const queued = (harness.session as unknown as { _followUpMessages: { preparation?: unknown }[] })
+ ._followUpMessages;
+ await vi.waitFor(() => expect(queued[0]?.preparation).toBeDefined());
+
+ const navigation = harness.session.navigateTree(target!.id, { summarize: false });
+ pause?.release();
+ pause = undefined;
+ await navigation;
+
+ expect(queued[0]?.preparation).toBeUndefined();
+ });
+
+ it.each([
+ {
+ name: "sessions without a local harness directory",
+ makeHarness: () =>
+ createHarness({
+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },
+ autoRefineReviewer: skipReviewer,
+ }),
+ expectRefineChecked: true,
+ },
+ {
+ name: "subagent sessions",
+ makeHarness: () =>
+ createAutoRefineHarness({
+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },
+ rlmDepth: 1,
+ autoRefineReviewer: skipReviewer,
+ }),
+ expectRefineChecked: false,
+ },
+ ])("auto-refine is skipped for $name", async ({ makeHarness, expectRefineChecked }) => {
+ skipReviewer.mockClear();
+ const harness = await makeHarness();
harnesses.push(harness);
const internals = harness.session as unknown as AutoRefineInternals;
internals._assistantTurnsSinceAutoRefine = 1;
+ const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
const scheduleAutoRefine = vi.spyOn(internals, "_scheduleAutoRefine").mockImplementation(() => {});
await internals._maybeAutoRefine("turn_interval");
internals._scheduleAutoRefineAfterCompaction(false);
internals._scheduleAutoRefineAfterAgentEnd();
- expect(reviewer).not.toHaveBeenCalled();
+ expect(skipReviewer).not.toHaveBeenCalled();
+ if (expectRefineChecked) expect(refine).not.toHaveBeenCalled();
expect(scheduleAutoRefine).not.toHaveBeenCalled();
});
@@ -818,282 +760,126 @@ describe("AgentSession queue characterization", () => {
expect(internals._compactAutoRefinePending).toBe(true);
});
- it("auto-refine review obeys the cooldown", async () => {
- const reviewer = vi.fn(async () => ({ shouldRefine: true, rationale: "durable lesson" }));
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 60_000 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 1;
- internals._lastAutoRefineReviewAt = Date.now();
-
- await internals._maybeAutoRefine("turn_interval");
-
- expect(reviewer).not.toHaveBeenCalled();
- });
-
- it("auto-refine preserves a turn-interval checkpoint when cooldown is active", async () => {
- const reviewer = vi.fn(async () => ({ shouldRefine: true, rationale: "durable lesson" }));
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 60_000 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 1;
- internals._lastAutoRefineReviewAt = Date.now();
-
- await internals._maybeAutoRefine("turn_interval");
-
- expect(reviewer).not.toHaveBeenCalled();
- expect(internals._turnIntervalAutoRefinePending).toBe(true);
- });
-
- it("auto-refine preserves a compact checkpoint when cooldown is active", async () => {
- const reviewer = vi.fn(async () => ({ shouldRefine: true, rationale: "durable lesson" }));
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 60_000 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._lastAutoRefineReviewAt = Date.now();
-
- await internals._maybeAutoRefine("compact");
-
- expect(reviewer).not.toHaveBeenCalled();
- expect(internals._compactAutoRefinePending).toBe(true);
- });
-
- it("queued follow-up messages do not make an idle agent active for auto-refine", async () => {
- const reviewer = vi.fn(async () => ({
- shouldRefine: true,
- rationale: "durable lesson found",
- instructions: "capture the durable lesson",
- }));
- const harness = await createAutoRefineHarness({
- settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },
- autoRefineReviewer: reviewer,
- });
- harnesses.push(harness);
- const internals = harness.session as unknown as AutoRefineInternals;
- internals._assistantTurnsSinceAutoRefine = 1;
- vi.spyOn(harness.session.agent, "hasQueuedMessages").mockReturnValue(true);
- const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
-
- await internals._maybeAutoRefine("turn_interval");
-
- expect(reviewer).toHaveBeenCalledWith(
- { reason: "turn_interval", turnsSinceLastReview: 1 },
- expect.any(AbortSignal),
- );
- expect(refine).toHaveBeenCalled();
- });
-
- it("strips local display prefixes before applying local refine edits", async () => {
- const harness = await createAutoRefineHarness();
- harnesses.push(harness);
- const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;
- process.env.PRIME_AGENT_CODING_AGENT_DIR = `${harness.tempDir}/agent`;
- try {
- const globalDir = getGlobalHarnessStateDir();
- const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir())!;
- const globalState = loadHarnessState(globalDir, "global");
- const localState = loadHarnessState(localDir, "local");
- applyRefinementProposal(
- globalState,
- {
- summary: "Global shared memory",
- rationale: "seed",
- expectedOutcome: "seeded",
- edits: [
- {
- action: "create",
- kind: "memory",
- id: "shared",
- title: "Shared",
- content: "Global content",
- },
- ],
- },
- { id: "seed_global", scope: "global" },
- );
- applyRefinementProposal(
- localState,
- {
- summary: "Local shared memory",
- rationale: "seed",
- expectedOutcome: "seeded",
- edits: [
- {
- action: "create",
- kind: "memory",
- id: "shared",
- title: "Shared",
- content: "Local content",
- },
- ],
- },
- { id: "seed_local", scope: "local" },
- );
- saveHarnessState(globalDir, globalState);
- saveHarnessState(localDir, localState);
- harness.setResponses([
- fauxAssistantMessage(
- JSON.stringify({
- summary: "Update local shared memory",
- rationale: "The local display id was selected from merged state.",
- expectedOutcome: "Only the local entry changes.",
- edits: [
- {
- action: "update",
- kind: "memory",
- id: "local:shared",
- title: "Shared",
- content: "Updated local content",
- },
- ],
- }),
- ),
- ]);
-
- const result = await harness.session.refine({ instructions: "update the local shared memory" });
-
- expect(result.appliedEdits[0]).toMatchObject({ id: "shared", applied: true });
- expect(loadHarnessState(localDir, "local").entries.memory.shared.content).toBe("Updated local content");
- expect(loadHarnessState(globalDir, "global").entries.memory.shared.content).toBe("Global content");
- } finally {
- if (previousAgentDir === undefined) {
- delete process.env.PRIME_AGENT_CODING_AGENT_DIR;
- } else {
- process.env.PRIME_AGENT_CODING_AGENT_DIR = previousAgentDir;
- }
- }
- });
-
- it("strips global display prefixes before applying local refine edits", async () => {
- const harness = await createAutoRefineHarness();
- harnesses.push(harness);
- const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;
- process.env.PRIME_AGENT_CODING_AGENT_DIR = `${harness.tempDir}/agent`;
- try {
- const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir())!;
- const localState = loadHarnessState(localDir, "local");
- applyRefinementProposal(
- localState,
- {
- summary: "Local memory",
- rationale: "seed",
- expectedOutcome: "seeded",
- edits: [
- {
- action: "create",
- kind: "memory",
- id: "shared",
- title: "Shared",
- content: "Local content",
- },
- ],
- },
- { id: "seed_local", scope: "local" },
- );
- saveHarnessState(localDir, localState);
- harness.setResponses([
- fauxAssistantMessage(
- JSON.stringify({
- summary: "Update local memory",
- rationale: "The display id came from merged state.",
- expectedOutcome: "The local entry changes without a prefixed id.",
- edits: [
- {
- action: "update",
- kind: "memory",
- id: "global:shared",
- title: "Shared",
- content: "Updated local content",
- },
- ],
- }),
- ),
- ]);
-
- const result = await harness.session.refine({ instructions: "update local memory" });
+ it.each([
+ { reason: "turn_interval" as AutoRefineReason, turns: 1, pendingFlag: "_turnIntervalAutoRefinePending" as const },
+ { reason: "compact" as AutoRefineReason, turns: 0, pendingFlag: "_compactAutoRefinePending" as const },
+ ])(
+ "auto-refine review obeys the cooldown and preserves a $reason checkpoint",
+ async ({ reason, turns, pendingFlag }) => {
+ const reviewer = vi.fn(async () => ({ shouldRefine: true, rationale: "durable lesson" }));
+ const harness = await createAutoRefineHarness({
+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 60_000 } },
+ autoRefineReviewer: reviewer,
+ });
+ harnesses.push(harness);
+ const internals = harness.session as unknown as AutoRefineInternals;
+ internals._assistantTurnsSinceAutoRefine = turns;
+ internals._lastAutoRefineReviewAt = Date.now();
- expect(result.appliedEdits[0]).toMatchObject({ id: "shared", applied: true });
- expect(loadHarnessState(localDir, "local").entries.memory.shared.content).toBe("Updated local content");
- expect(loadHarnessState(localDir, "local").entries.memory["global:shared"]).toBeUndefined();
- } finally {
- if (previousAgentDir === undefined) {
- delete process.env.PRIME_AGENT_CODING_AGENT_DIR;
- } else {
- process.env.PRIME_AGENT_CODING_AGENT_DIR = previousAgentDir;
- }
- }
- });
+ await internals._maybeAutoRefine(reason);
- it("strips global display prefixes before applying global refine edits", async () => {
- const harness = await createAutoRefineHarness();
- harnesses.push(harness);
- const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;
- process.env.PRIME_AGENT_CODING_AGENT_DIR = `${harness.tempDir}/agent`;
- try {
- const globalDir = getGlobalHarnessStateDir();
- const globalState = loadHarnessState(globalDir, "global");
- applyRefinementProposal(
- globalState,
- {
- summary: "Global shared memory",
- rationale: "seed",
- expectedOutcome: "seeded",
- edits: [
+ expect(reviewer).not.toHaveBeenCalled();
+ expect(internals[pendingFlag]).toBe(true);
+ },
+ );
+
+ it.each([
+ {
+ name: "local display prefixes before applying local refine edits",
+ seedGlobal: true,
+ seedLocal: true,
+ editId: "local:shared",
+ refineOptions: { instructions: "update the local shared memory" },
+ updatedContent: "Updated local content",
+ expectLocalContent: "Updated local content" as string | undefined,
+ expectGlobalContent: "Global content" as string | undefined,
+ },
+ {
+ name: "global display prefixes before applying local refine edits",
+ seedGlobal: false,
+ seedLocal: true,
+ editId: "global:shared",
+ refineOptions: { instructions: "update local memory" },
+ updatedContent: "Updated local content",
+ expectLocalContent: "Updated local content" as string | undefined,
+ expectGlobalContent: undefined as string | undefined,
+ },
+ {
+ name: "global display prefixes before applying global refine edits",
+ seedGlobal: true,
+ seedLocal: false,
+ editId: "global:shared",
+ refineOptions: { instructions: "update the global shared memory", global: true },
+ updatedContent: "Updated global content",
+ expectLocalContent: undefined as string | undefined,
+ expectGlobalContent: "Updated global content" as string | undefined,
+ },
+ ])(
+ "strips $name",
+ async ({
+ seedGlobal,
+ seedLocal,
+ editId,
+ refineOptions,
+ updatedContent,
+ expectLocalContent,
+ expectGlobalContent,
+ }) => {
+ const harness = await createAutoRefineHarness();
+ harnesses.push(harness);
+ const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ process.env.PRIME_AGENT_CODING_AGENT_DIR = `${harness.tempDir}/agent`;
+ try {
+ const globalDir = getGlobalHarnessStateDir();
+ const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir())!;
+ const seedMemory = (scope: "global" | "local", dir: string, content: string) => {
+ const state = loadHarnessState(dir, scope);
+ applyRefinementProposal(
+ state,
{
- action: "create",
- kind: "memory",
- id: "shared",
- title: "Shared",
- content: "Global content",
+ summary: `${scope} shared memory`,
+ rationale: "seed",
+ expectedOutcome: "seeded",
+ edits: [{ action: "create", kind: "memory", id: "shared", title: "Shared", content }],
},
- ],
- },
- { id: "seed_global", scope: "global" },
- );
- saveHarnessState(globalDir, globalState);
- harness.setResponses([
- fauxAssistantMessage(
- JSON.stringify({
- summary: "Update global shared memory",
- rationale: "The global display id was selected from the overview.",
- expectedOutcome: "Only the global entry changes.",
- edits: [
- {
- action: "update",
- kind: "memory",
- id: "global:shared",
- title: "Shared",
- content: "Updated global content",
- },
- ],
- }),
- ),
- ]);
+ { id: `seed_${scope}`, scope },
+ );
+ saveHarnessState(dir, state);
+ };
+ if (seedGlobal) seedMemory("global", globalDir, "Global content");
+ if (seedLocal) seedMemory("local", localDir, "Local content");
+ harness.setResponses([
+ fauxAssistantMessage(
+ JSON.stringify({
+ summary: "Update shared memory",
+ rationale: "The display id was selected from merged state.",
+ expectedOutcome: "Only the targeted entry changes.",
+ edits: [
+ { action: "update", kind: "memory", id: editId, title: "Shared", content: updatedContent },
+ ],
+ }),
+ ),
+ ]);
- const result = await harness.session.refine({
- instructions: "update the global shared memory",
- global: true,
- });
+ const result = await harness.session.refine(refineOptions);
- expect(result.appliedEdits[0]).toMatchObject({ id: "shared", applied: true });
- expect(loadHarnessState(globalDir, "global").entries.memory.shared.content).toBe("Updated global content");
- } finally {
- if (previousAgentDir === undefined) {
- delete process.env.PRIME_AGENT_CODING_AGENT_DIR;
- } else {
- process.env.PRIME_AGENT_CODING_AGENT_DIR = previousAgentDir;
+ expect(result.appliedEdits[0]).toMatchObject({ id: "shared", applied: true });
+ if (expectLocalContent !== undefined) {
+ expect(loadHarnessState(localDir, "local").entries.memory.shared.content).toBe(expectLocalContent);
+ expect(loadHarnessState(localDir, "local").entries.memory["global:shared"]).toBeUndefined();
+ }
+ if (expectGlobalContent !== undefined) {
+ expect(loadHarnessState(globalDir, "global").entries.memory.shared.content).toBe(expectGlobalContent);
+ }
+ } finally {
+ if (previousAgentDir === undefined) {
+ delete process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ } else {
+ process.env.PRIME_AGENT_CODING_AGENT_DIR = previousAgentDir;
+ }
}
- }
- });
+ },
+ );
it("rolls back copied local refinement history against the original local harness state", async () => {
const original = await createAutoRefineHarness();
@@ -1126,20 +912,15 @@ describe("AgentSession queue characterization", () => {
saveHarnessState(branchedLocalDir, branchedState);
original.setResponses([
fauxAssistantMessage(
- JSON.stringify({
- summary: "Create original local memory",
- rationale: "seed",
- expectedOutcome: "Original local entry exists.",
- edits: [
- {
- action: "create",
- kind: "memory",
- id: "remember_me",
- title: "Original memory",
- content: "Original content should be rolled back.",
- },
- ],
- }),
+ refinePlanJson("Create original local memory", [
+ {
+ action: "create",
+ kind: "memory",
+ id: "remember_me",
+ title: "Original memory",
+ content: "Original content should be rolled back.",
+ },
+ ]),
),
]);
@@ -1170,56 +951,37 @@ describe("AgentSession queue characterization", () => {
const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;
process.env.PRIME_AGENT_CODING_AGENT_DIR = `${harness.tempDir}/agent`;
try {
- let releasePlan: (() => void) | undefined;
- const planGate = new Promise<void>((resolve) => {
- releasePlan = resolve;
- });
- let planStarted: (() => void) | undefined;
- const planStartedPromise = new Promise<void>((resolve) => {
- planStarted = resolve;
- });
- let releasePrompt: (() => void) | undefined;
- const promptGate = new Promise<void>((resolve) => {
- releasePrompt = resolve;
- });
- let promptStarted: (() => void) | undefined;
- const promptStartedPromise = new Promise<void>((resolve) => {
- promptStarted = resolve;
- });
+ const planGate = createDeferred();
+ const planStartedPromise = createDeferred();
+ const promptGate = createDeferred();
+ const promptStartedPromise = createDeferred();
let promptSignal: AbortSignal | undefined;
harness.setResponses([
async () => {
- planStarted?.();
- await planGate;
- return fauxAssistantMessage(
- JSON.stringify({
- summary: "no-op",
- rationale: "nothing to change",
- expectedOutcome: "unchanged",
- edits: [],
- }),
- );
+ planStartedPromise.resolve();
+ await planGate.promise;
+ return fauxAssistantMessage(refinePlanJson("no-op"));
},
async (_context, options) => {
promptSignal = options?.signal;
- promptStarted?.();
- await promptGate;
+ promptStartedPromise.resolve();
+ await promptGate.promise;
return fauxAssistantMessage("prompt reply");
},
]);
const refinePromise = harness.session.refine({ instructions: "background refine" });
- await planStartedPromise;
+ await planStartedPromise.promise;
const promptPromise = harness.session.prompt("hello during refine");
- await promptStartedPromise;
+ await promptStartedPromise.promise;
// With backgrounded refine planning, the prompt does NOT wait for the
// planning LLM pass. It starts immediately and streams its response
// while planning is still in flight. The application phase waits for
// the agent to be idle before disconnecting and applying.
expect(harness.getPendingResponseCount()).toBe(0);
- releasePlan?.();
+ planGate.resolve();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
expect(promptSignal?.aborted).toBe(false);
@@ -1230,7 +992,7 @@ describe("AgentSession queue characterization", () => {
await new Promise<void>((resolve) => setTimeout(resolve, 0));
expect(refineSettled).toBe(false);
- releasePrompt?.();
+ promptGate.resolve();
await refinePromise;
await promptPromise;
@@ -1453,558 +1215,1329 @@ describe("AgentSession queue characterization", () => {
}
});
- it("dispatches extension commands immediately when prompted while idle", async () => {
- const commandRuns: string[] = [];
+ it("admits extension commands immediately while completion tracks the handler", async () => {
+ let release: (() => void) | undefined;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
const harness = await createHarness({
extensionFactories: [
(pi) => {
- pi.registerCommand("testcmd", {
- description: "Test command",
- handler: async (args) => {
- commandRuns.push(args);
+ pi.registerCommand("testcmd", { description: "Test", handler: async () => gate });
+ pi.registerCommand("fail", {
+ description: "Fail",
+ handler: async () => {
+ throw new Error("extension exploded");
},
});
},
],
});
harnesses.push(harness);
+ const extensionErrors: string[] = [];
+ harness.session.bindExtensions({ onError: (error) => extensionErrors.push(error.error) });
- await harness.session.prompt("/testcmd hello world");
-
- expect(commandRuns).toEqual(["hello world"]);
- expect(harness.getPendingResponseCount()).toBe(0);
+ await expect(harness.session.promptUntilAccepted("/testcmd")).resolves.toBeUndefined();
+ let completed = false;
+ const completion = harness.session.promptAndWait("/testcmd").then(() => {
+ completed = true;
+ });
+ await Promise.resolve();
+ expect(completed).toBe(false);
+ release?.();
+ await completion;
+ await expect(harness.session.promptAndWait("/fail")).rejects.toThrow("extension exploded");
+ expect(extensionErrors).toEqual(["extension exploded"]);
expect(harness.session.messages).toEqual([]);
});
- it("delivers extension-origin steering messages before the next LLM call", async () => {
- let extensionApi: ExtensionAPI | undefined;
- const waiting = await createWaitingHarness({
- extensionFactories: [
- (pi) => {
- extensionApi = pi;
- },
- ],
- });
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("removes goal context while its steering handoff is still preparing", async () => {
+ const hook = gatedHook({ prompt: "stale goal context" });
+ const harness = await createHarness({ extensionFactories: [hook.factory] });
harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("must not run")]);
+ const pause = harness.session.acquireQueuedWorkPause();
+ withStreaming(harness, true);
+ await harness.session.sendCustomMessage(
+ { customType: "goal_context", content: "stale goal context", display: true },
+ { triggerTurn: true, deliverAs: "steer" },
+ );
+ withStreaming(harness, false);
+ pause.release();
+ await hook.reached;
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- (context) => {
- const sawSteer = context.messages.some(
- (message) => message.role === "user" && getMessageText(message) === "steer now",
- );
- return fauxAssistantMessage(sawSteer ? "saw steer" : "missing steer");
- },
- ]);
-
- await waitForToolStart;
- await new Promise((resolve) => setTimeout(resolve, 0));
-
- extensionApi?.sendUserMessage("steer now", { deliverAs: "steer" });
- releaseToolExecution();
- await promptPromise;
+ (harness.session as unknown as SteeringStopInternals)._clearQueuedGoalContexts();
+ hook.release();
+ await harness.session.waitForIdle();
- expect(getUserTexts(harness)).toEqual(["start", "steer now"]);
- expect(getAssistantTexts(harness)).toContain("saw steer");
+ expect(
+ harness.session.messages.some((message) => message.role === "custom" && message.customType === "goal_context"),
+ ).toBe(false);
+ expect(harness.getPendingResponseCount()).toBe(1);
});
- it("coalesces follow-up messages with the same queue key", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("releases restart checkpoint waiters when preparation hands off", async () => {
+ const hook = gatedHook({ prompt: "checkpoint handoff" });
+ const harness = await createHarness({ extensionFactories: [hook.factory] });
harnesses.push(harness);
-
+ let releaseResponse = () => {};
harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("done"),
+ async () => {
+ await new Promise<void>((resolve) => {
+ releaseResponse = resolve;
+ });
+ return fauxAssistantMessage("done");
+ },
]);
- await waitForToolStart;
- await harness.session.prompt("heartbeat", {
- streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:one",
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.steer("checkpoint handoff", undefined, { resumeIfIdle: true });
+ pause.release();
+ await hook.reached;
+
+ let checkpointSettled = false;
+ const checkpoint = harness.session.waitForSessionInputCheckpoint().then(() => {
+ checkpointSettled = true;
});
- await harness.session.prompt("heartbeat", {
- streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:one",
+ await Promise.resolve();
+ expect(checkpointSettled).toBe(false);
+ hook.release();
+ await vi.waitFor(() => expect(checkpointSettled).toBe(true));
+ releaseResponse();
+ await checkpoint;
+ await harness.session.waitForIdle();
+ });
+
+ it("keeps steering stop pending while a steering handoff is still preparing", async () => {
+ const hook = gatedHook({ prompt: "active steering" });
+ const harness = await createHarness({ extensionFactories: [hook.factory] });
+ harnesses.push(harness);
+ const internals = harness.session as unknown as SteeringStopInternals;
+ harness.setResponses([fauxAssistantMessage("delivered")]);
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.steer("active steering", undefined, { resumeIfIdle: true });
+ 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"]);
+ expect(internals._steeringStopPending).toBe(true);
+ expect(harness.session.clearQueue()).toEqual({ steering: ["active steering"], followUp: [] });
+ expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: [] });
+ expect(internals._steeringStopPending).toBe(false);
+
+ hook.release();
+ await harness.session.waitForIdle();
+ expect(internals._steeringStopPending).toBe(false);
+ expect(getUserTexts(harness)).toEqual([]);
+ });
+
+ it("keeps owned inputs visible in counts, previews, and queue updates until delivery", 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] });
+ }
});
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.followUp("owned prompt", undefined, { resumeIfIdle: true });
+ pause.release();
+ await hook.reached;
- expect(harness.session.getFollowUpMessages()).toEqual(["heartbeat"]);
+ // 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"] });
- releaseToolExecution();
- await promptPromise;
+ hook.release();
+ await harness.session.waitForIdle();
+ expect(harness.session.pendingMessageCount).toBe(0);
+ expect(queueUpdates.at(-1)).toEqual({ steering: [], followUp: [] });
+ expect(getUserTexts(harness)).toEqual(["owned prompt"]);
});
- it("reports failed preflight when a duplicate follow-up queue key is not queued", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("stops counting cleared preparing inputs as pending", async () => {
+ const hook = gatedHook({ prompt: "cleared prompt" });
+ const harness = await createHarness({ extensionFactories: [hook.factory] });
harnesses.push(harness);
- const preflightResults: boolean[] = [];
+ harness.setResponses([fauxAssistantMessage("never delivered")]);
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.followUp("cleared prompt", undefined, { resumeIfIdle: true });
+ pause.release();
+ await hook.reached;
+ expect(harness.session.pendingMessageCount).toBe(1);
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("done"),
- ]);
- await waitForToolStart;
- await harness.session.prompt("heartbeat", {
- streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:one",
- });
- await harness.session.prompt("heartbeat", {
- streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:one",
- preflightResult: (didSucceed) => preflightResults.push(didSucceed),
- });
+ expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: ["cleared prompt"] });
+ expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.getFollowUpMessagePreviews()).toEqual([]);
- expect(preflightResults).toEqual([false]);
- expect(harness.session.getFollowUpMessages()).toEqual(["heartbeat"]);
- releaseToolExecution();
- await promptPromise;
+ hook.release();
+ await harness.session.waitForSessionInputIdle();
+ expect(getUserTexts(harness)).toEqual([]);
});
- it("keeps separate follow-up messages for different queue keys", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("queues a same-key follow-up once the prior owner has handed off", async () => {
+ const harness = await createHarness();
harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("first done"), fauxAssistantMessage("second done")]);
+ const dispatchGate = createDeferred();
+ const promptCalled = createDeferred();
+ const originalPrompt = harness.session.agent.prompt.bind(harness.session.agent);
+ const promptSpy = vi
+ .spyOn(harness.session.agent, "prompt")
+ .mockImplementation(async (messages: Parameters<typeof originalPrompt>[0]) => {
+ promptSpy.mockRestore();
+ promptCalled.resolve();
+ await dispatchGate.promise;
+ return originalPrompt(messages);
+ });
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.followUp("first heartbeat", undefined, { queueKey: "heartbeat", resumeIfIdle: true });
+ pause.release();
+ await promptCalled.promise;
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("first done"),
- fauxAssistantMessage("second done"),
- ]);
- await waitForToolStart;
- await harness.session.prompt("heartbeat one", {
- streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:one",
- });
- await harness.session.prompt("heartbeat two", {
- streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:two",
+ // The first prompt handed off to the turn; a same-key follow-up must queue
+ // for the next turn instead of coalescing into the committed one.
+ expect(await harness.session.followUp("second heartbeat", undefined, { queueKey: "heartbeat" })).toBe(true);
+ expect(harness.session.getFollowUpMessages()).toEqual(["second heartbeat"]);
+
+ dispatchGate.resolve();
+ await harness.session.waitForSessionInputIdle();
+ await harness.session.waitForIdle();
+ expect(getUserTexts(harness)).toEqual(["first heartbeat", "second heartbeat"]);
+ });
+
+ it("keeps cleared prompts out of the handoff snapshot during the refine wait", async () => {
+ let sessionInternals: { _refineInFlight?: Promise<void> };
+ let clearDuringRefineWait: (() => void) | undefined;
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("before_agent_start", async () => {
+ // Stall the pre-handoff refine wait and clear the queued agent
+ // message inside that window; the handoff snapshot must not
+ // deliver it.
+ let releaseRefine: (() => void) | undefined;
+ sessionInternals._refineInFlight = new Promise<void>((resolve) => {
+ releaseRefine = resolve;
+ });
+ setTimeout(() => {
+ clearDuringRefineWait?.();
+ sessionInternals._refineInFlight = undefined;
+ releaseRefine?.();
+ }, 0);
+ return {};
+ });
+ },
+ ],
});
+ harnesses.push(harness);
+ sessionInternals = harness.session as unknown as { _refineInFlight?: Promise<void> };
+ harness.setResponses([fauxAssistantMessage("kept response")]);
- expect(harness.session.getFollowUpMessages()).toEqual(["heartbeat one", "heartbeat two"]);
+ const clearedAgentMessage = agentPromptText("agentmsg_cleared", "cleared");
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.followUp("kept");
+ await harness.session.queueAgentMessagePrompt(clearedAgentMessage, "followUp", undefined);
+ harness.session.setFollowUpMode("all");
+ let cleared: { steering: string[]; followUp: string[] } | undefined;
+ clearDuringRefineWait = () => {
+ cleared = harness.session.clearQueuedUserMessagesMatching((text) => text === clearedAgentMessage);
+ };
+ pause.release();
+ await harness.session.waitForIdle();
- releaseToolExecution();
- await promptPromise;
+ expect(cleared).toEqual({ steering: [], followUp: [clearedAgentMessage] });
+ expect(getUserTexts(harness)).toEqual(["kept"]);
});
- it("removes only the matching coalesced follow-up when texts match", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("injects nextTurn custom messages into the next prompt", async () => {
+ const harness = await createHarness();
harnesses.push(harness);
+ let sawCustomMessage = false;
+
+ harness.setResponses([fauxAssistantMessage("seed")]);
+ await harness.session.prompt("seed");
+ vi.spyOn(
+ harness.session as unknown as { _checkCompaction(): Promise<boolean> },
+ "_checkCompaction",
+ ).mockImplementationOnce(async () => {
+ await harness.session.sendCustomMessage(
+ { customType: "next-turn", content: "carry this", display: true, details: {} },
+ { deliverAs: "nextTurn" },
+ );
+ return false;
+ });
harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("done"),
+ (context) => {
+ sawCustomMessage = context.messages.some(
+ (message) =>
+ message.role === "user" &&
+ typeof message.content !== "string" &&
+ message.content.some((part) => part.type === "text" && part.text === "carry this"),
+ );
+ return fauxAssistantMessage("done");
+ },
]);
- await waitForToolStart;
- await harness.session.prompt("same heartbeat", {
- streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:one",
- });
- await harness.session.prompt("same heartbeat", {
- streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:two",
- });
- expect(harness.session.removeQueuedFollowUp("heartbeat:one")).toBe(true);
- expect(harness.session.getFollowUpMessages()).toEqual(["same heartbeat"]);
+ await harness.session.prompt("normal prompt");
- releaseToolExecution();
- await promptPromise;
- expect(getUserTexts(harness)).toEqual(["start", "same heartbeat"]);
+ expect(sawCustomMessage).toBe(true);
+ expect(harness.session.messages.map((message) => message.role)).toEqual([
+ "user",
+ "assistant",
+ "custom",
+ "user",
+ "assistant",
+ ]);
});
- it("removes coalesced follow-up messages by queue key", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("clears the agent queue when a queue update listener clears a newly queued steering prompt", async () => {
+ const harness = await createHarness();
harnesses.push(harness);
+ const agentPrompt = agentPromptText("agentmsg_queue_update_clear", "clear during update");
+ const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_queue_update_clear");
+ let cleared = false;
+ const unsubscribe = harness.session.subscribe((event) => {
+ if (event.type === "queue_update" && !cleared) {
+ cleared = true;
+ harness.session.clearQueue();
+ }
+ });
+
+ await harness.session.queueAgentMessagePrompt(agentPrompt, "steer");
+ unsubscribe();
+ await expect(delivery).rejects.toThrow("cleared before delivery");
+ expect(harness.session.getSteeringMessages()).toEqual([]);
+ let sawClearedPrompt = false;
harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("done"),
+ (context) => {
+ sawClearedPrompt = context.messages.some(
+ (message) => message.role === "user" && getMessageText(message).includes("agentmsg_queue_update_clear"),
+ );
+ return fauxAssistantMessage("normal response");
+ },
]);
- await waitForToolStart;
- await harness.session.prompt("heartbeat", {
+ await harness.session.prompt("normal");
+
+ expect(sawClearedPrompt).toBe(false);
+ expect(getUserTexts(harness)).toEqual(["normal"]);
+ });
+
+ it("clearQueue and terminal preparation errors reject delivery and completion waiters", async () => {
+ // clearQueue while an active batch is preparing rejects every prompt's waiters.
+ let preparationStarted: (() => void) | undefined;
+ const waitForPreparation = new Promise<void>((resolve) => {
+ preparationStarted = resolve;
+ });
+ let pause: { release(): void } | undefined;
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("before_agent_start", async () => {
+ preparationStarted?.();
+ pause = harness.session.acquireQueuedWorkPause();
+ });
+ },
+ ],
+ });
+ harnesses.push(harness);
+ harness.session.setFollowUpMode("all");
+ withStreaming(harness, true);
+ const firstDelivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_clear_first");
+ const firstCompletion = harness.session.promptAndWait("clear first while preparing", {
+ agentMessageId: "agentmsg_clear_first",
+ streamingBehavior: "followUp",
+ resumeIfIdle: true,
+ });
+ const completion = harness.session.promptAndWait("clear second while preparing", {
streamingBehavior: "followUp",
- followUpQueueKey: "heartbeat:one",
+ resumeIfIdle: true,
});
+ const firstCompletionRejection = expect(firstCompletion).rejects.toThrow("cleared before delivery");
+ const completionRejection = expect(completion).rejects.toThrow("cleared before delivery");
+ withStreaming(harness, false);
+ await waitForPreparation;
+ expect(pause).toBeDefined();
- expect(harness.session.removeQueuedFollowUp("heartbeat:one")).toBe(true);
+ expect(harness.session.clearQueue()).toEqual({
+ steering: [],
+ followUp: ["clear first while preparing", "clear second while preparing"],
+ });
+ pause?.release();
+ await firstCompletionRejection;
+ await completionRejection;
+ await expect(firstDelivery).rejects.toThrow("cleared before delivery");
+ await harness.session.waitForSessionInputIdle();
+ expect(harness.session.getSteeringMessages()).toEqual([]);
expect(harness.session.getFollowUpMessages()).toEqual([]);
+ expect(getUserTexts(harness)).toEqual([]);
+
+ harness.setResponses([fauxAssistantMessage("later response")]);
+ await expect(
+ harness.session.promptAndWait("later prompt", { agentMessageId: "agentmsg_clear_first" }),
+ ).resolves.toBeUndefined();
+ expect(getUserTexts(harness)).toEqual(["later prompt"]);
+ expect(getAssistantTexts(harness)).toEqual(["later response"]);
+
+ // Terminal queued-prompt preparation errors reject both delivery and completion.
+ const errors: string[] = [];
+ const authHarness = await createHarness({ withConfiguredAuth: false });
+ harnesses.push(authHarness);
+ await authHarness.session.bindExtensions({ onError: (error) => errors.push(error.error) });
+ withStreaming(authHarness, true);
+ const delivery = authHarness.session.waitForAgentMessagePromptDelivery("agentmsg_terminal");
+ const terminalCompletion = authHarness.session.promptAndWait("cannot start", {
+ agentMessageId: "agentmsg_terminal",
+ streamingBehavior: "followUp",
+ resumeIfIdle: true,
+ });
+ const terminalRejection = expect(terminalCompletion).rejects.toThrow("No API key");
+ await vi.waitFor(() => expect(authHarness.session.getFollowUpMessages()).toEqual(["cannot start"]));
+ withStreaming(authHarness, false);
+ await authHarness.session.waitForSessionInputIdle();
- releaseToolExecution();
- await promptPromise;
- expect(getUserTexts(harness)).toEqual(["start"]);
+ await expect(delivery).rejects.toThrow("No API key");
+ await terminalRejection;
+ expect(authHarness.session.getFollowUpMessages()).toEqual([]);
+ expect(errors).toEqual([expect.stringContaining("No API key")]);
});
- it("delivers follow-up messages only after the current run finishes", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("keeps a second one-at-a-time input queued when both use the same message object", async () => {
+ const firstResponse = createDeferred();
+ const firstProviderStarted = createDeferred();
+ const harness = await createHarness();
harnesses.push(harness);
- const assistantSeenBeforeFollowUp: string[] = [];
-
+ harness.session.setFollowUpMode("one-at-a-time");
harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- (context) => {
- assistantSeenBeforeFollowUp.push(
- ...context.messages
- .filter((message) => message.role === "assistant")
- .map((message) =>
- message.content
- .filter((part): part is { type: "text"; text: string } => part.type === "text")
- .map((part) => part.text)
- .join("\n"),
- ),
- );
- return fauxAssistantMessage("follow-up response");
+ async () => {
+ firstProviderStarted.resolve();
+ await firstResponse.promise;
+ return fauxAssistantMessage("first done");
},
+ fauxAssistantMessage("second done"),
]);
+ const payload: AgentSessionMessagePayload = {
+ id: "agentmsg_same_object",
+ source: AGENT_MESSAGE_SOURCE,
+ message: "same object",
+ deliveryMode: "follow_up" as const,
+ target: { activeSessionId: "worker-active", sessionId: "worker-session" },
+ };
+ const message = createAgentSessionMessage(payload);
+ const prompt = createAgentSessionMessagePrompt(payload);
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.queueAgentMessagePrompt(prompt, "followUp", message);
+ await harness.session.queueAgentMessagePrompt(prompt, "followUp", message);
+ pause.release();
+
+ await firstProviderStarted.promise;
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(harness.session.pendingMessageCount).toBe(1);
+ expect(harness.session.getFollowUpMessages()).toEqual([prompt]);
+ firstResponse.resolve();
+ await harness.session.waitForIdle();
- await waitForToolStart;
- await harness.session.followUp("after current run");
- releaseToolExecution();
- await promptPromise;
-
- expect(getUserTexts(harness)).toEqual(["start", "after current run"]);
- expect(assistantSeenBeforeFollowUp).toContain("");
- expect(getAssistantTexts(harness)).toContain("follow-up response");
+ expect(harness.session.pendingMessageCount).toBe(0);
+ expect(harness.session.messages.filter((item) => item === message)).toHaveLength(2);
+ expect(getAssistantTexts(harness)).toEqual(["first done", "second done"]);
});
- it("delivers multiple steering messages in order in one-at-a-time mode", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("releases external promptAndWait outcomes for pre-registered id reuse", async () => {
+ const harness = await createHarness();
harnesses.push(harness);
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("handled steer 1"),
- fauxAssistantMessage("handled steer 2"),
- ]);
+ for (let index = 0; index < 3; index++) {
+ const id = `agentmsg_completed_${index}`;
+ harness.setResponses([fauxAssistantMessage(`done ${index}`)]);
+ await expect(
+ harness.session.promptAndWait(`prompt ${index}`, { agentMessageId: id }),
+ ).resolves.toBeUndefined();
+ }
- await waitForToolStart;
- await harness.session.steer("steer 1");
- await harness.session.steer("steer 2");
- releaseToolExecution();
- await promptPromise;
+ const reusedId = "agentmsg_completed_0";
+ let delivered = false;
+ const delivery = harness.session.waitForAgentMessagePromptDelivery(reusedId).then(() => {
+ delivered = true;
+ });
+ await Promise.resolve();
+ expect(delivered).toBe(false);
- expect(getUserTexts(harness)).toEqual(["start", "steer 1", "steer 2"]);
- expect(getAssistantTexts(harness)).toEqual(["", "handled steer 1", "handled steer 2"]);
+ harness.setResponses([fauxAssistantMessage("reused done")]);
+ await harness.session.acceptAgentMessagePrompt(agentPromptText(reusedId, "reused prompt"));
+ await expect(delivery).resolves.toBeUndefined();
+ await harness.session.waitForIdle();
+ expect(getUserTexts(harness)).toHaveLength(4);
+ expect(getAssistantTexts(harness)).toHaveLength(4);
});
- it("delivers multiple follow-up messages in order in one-at-a-time mode", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("resolves pre-registered queued and direct agent-message delivery waiters once prompts start", async () => {
+ const blocked = createDeferred();
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("turn_start", async () => blocked.promise);
+ },
+ ],
+ });
harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("done")]);
+ withStreaming(harness, true);
+ const queuedDelivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_sync");
+ await harness.session.followUp("agent message", undefined, {
+ agentMessageId: "agentmsg_sync",
+ resumeIfIdle: true,
+ });
+ withStreaming(harness, false);
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("original turn complete"),
- fauxAssistantMessage("handled follow-up 1"),
- fauxAssistantMessage("handled follow-up 2"),
- ]);
-
- await waitForToolStart;
- await harness.session.followUp("follow-up 1");
- await harness.session.followUp("follow-up 2");
- releaseToolExecution();
- await promptPromise;
+ // Queued delivery resolves on message_start, before the gated turn completes.
+ await expect(queuedDelivery).resolves.toBeUndefined();
+ blocked.resolve();
+ await harness.session.waitForIdle();
- expect(getUserTexts(harness)).toEqual(["start", "follow-up 1", "follow-up 2"]);
- expect(getAssistantTexts(harness)).toEqual([
- "",
- "original turn complete",
- "handled follow-up 1",
- "handled follow-up 2",
- ]);
+ harness.setResponses([fauxAssistantMessage("direct reply")]);
+ const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_direct");
+ await harness.session.acceptAgentMessagePrompt(agentPromptText("agentmsg_direct", "direct delivery"));
+ await expect(delivery).resolves.toBeUndefined();
});
- it("delivers all steering messages in one batch in all mode", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("settles disposal and post-delivery handoff failures with distinct errors", async () => {
+ // Dispose rejects pending waiters with distinct delivery and completion errors.
+ const harness = await createHarness();
harnesses.push(harness);
- harness.session.setSteeringMode("all");
- let batchedUserMessages: string[] = [];
+ const agentPrompt = agentPromptText("agentmsg_dispose", "dispose me");
+ withStreaming(harness, true);
+ const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_dispose");
+ const completion = harness.session.promptAndWait(agentPrompt, {
+ agentMessageId: "agentmsg_dispose",
+ streamingBehavior: "followUp",
+ });
+ await vi.waitFor(() => expect(harness.session.getFollowUpMessages()).toEqual([agentPrompt]));
+ harness.session.dispose();
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- (context) => {
- batchedUserMessages = context.messages
- .filter((message) => message.role === "user")
- .map((message) => getMessageText(message));
- return fauxAssistantMessage("batched steer response");
- },
- ]);
+ await expect(delivery).rejects.toThrow("disposed before prompt delivery");
+ await expect(completion).rejects.toThrow("disposed before prompt completion");
- await waitForToolStart;
- await harness.session.steer("steer 1");
- await harness.session.steer("steer 2");
- releaseToolExecution();
- await promptPromise;
+ // A handoff failure after the prompt entered agent state rejects completion only.
+ const handoffHarness = await createHarness();
+ harnesses.push(handoffHarness);
+ const prompt = handoffHarness.session.agent.prompt.bind(handoffHarness.session.agent);
+ vi.spyOn(handoffHarness.session.agent, "prompt").mockImplementationOnce(async (messages) => {
+ await prompt(messages);
+ throw new Error("handoff failed after delivery");
+ });
+ withStreaming(handoffHarness, true);
+ const handoffCompletion = handoffHarness.session.promptAndWait("delivered then failed", {
+ streamingBehavior: "followUp",
+ });
+ await vi.waitFor(() => expect(handoffHarness.session.getFollowUpMessages()).toEqual(["delivered then failed"]));
+ withStreaming(handoffHarness, false);
- expect(batchedUserMessages).toEqual(["start", "steer 1", "steer 2"]);
- expect(getAssistantTexts(harness)).toEqual(["", "batched steer response"]);
+ expect(handoffHarness.session.resumeQueuedWork()).toBe(true);
+ await expect(handoffCompletion).rejects.toThrow("handoff failed after delivery");
+ expect(getUserTexts(handoffHarness)).toEqual(["delivered then failed"]);
+ expect(handoffHarness.session.getFollowUpMessages()).toEqual([]);
});
- it("delivers all follow-up messages in one batch in all mode", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("throws when queueing an extension command", async () => {
+ const queue = (harness: Harness) => harness.session.steer("/testcmd queued");
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.registerCommand("testcmd", {
+ description: "Test command",
+ handler: async () => {},
+ });
+ },
+ ],
+ });
harnesses.push(harness);
- harness.session.setFollowUpMode("all");
- let batchedUserMessages: string[] = [];
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("original turn complete"),
- (context) => {
- batchedUserMessages = context.messages
- .filter((message) => message.role === "user")
- .map((message) => getMessageText(message));
- return fauxAssistantMessage("batched follow-up response");
- },
- ]);
+ await expect(queue(harness)).rejects.toThrow(
+ 'Extension command "/testcmd" cannot be queued. Use prompt() or execute the command when not streaming.',
+ );
+ });
- await waitForToolStart;
- await harness.session.followUp("follow-up 1");
- await harness.session.followUp("follow-up 2");
- releaseToolExecution();
- await promptPromise;
+ it("rejects queued command delivery and completion when the invocation append fails", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ vi.spyOn(harness.sessionManager, "appendCustomMessageEntry").mockImplementationOnce(() => {
+ throw new Error("durable invocation append failed");
+ });
+ const pause = harness.session.acquireQueuedWorkPause();
+ const id = "agentmsg_command_append_failed";
+ const delivery = harness.session.waitForAgentMessagePromptDelivery(id);
+ const completion = harness.session.promptAndWait("/autonomous status", { agentMessageId: id });
- expect(batchedUserMessages).toEqual(["start", "follow-up 1", "follow-up 2"]);
- expect(getAssistantTexts(harness)).toEqual(["", "original turn complete", "batched follow-up response"]);
+ pause.release();
+ await expect(delivery).rejects.toThrow("durable invocation append failed");
+ await expect(completion).rejects.toThrow("durable invocation append failed");
+
+ // The failed append must roll back fully: no live-only command message and
+ // no unsaved leaf, so later durable entries persist cleanly.
+ expect(
+ harness.session.messages.some(
+ (message) => message.role === "custom" && message.customType.startsWith("session_slash_command"),
+ ),
+ ).toBe(false);
+ expect(
+ harness.sessionManager
+ .getBranch()
+ .some((entry) => entry.type === "custom" && entry.customType === "session_slash_command"),
+ ).toBe(false);
+ const followUpEntryId = harness.sessionManager.appendCustomMessageEntry("post-failure", "still writable", false);
+ expect(harness.sessionManager.getBranch().at(-1)?.id).toBe(followUpEntryId);
});
- it("queues custom messages with deliverAs steer while streaming", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("does not record a benign compaction skip as a command failure", async () => {
+ const harness = await createHarness();
harnesses.push(harness);
- let sawCustomMessage = false;
+ let compactionEndErrorSeverity: string | undefined;
+ harness.session.subscribe((event) => {
+ if (event.type === "compaction_end") compactionEndErrorSeverity = event.errorSeverity;
+ });
- harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- (context) => {
- sawCustomMessage = context.messages.some(
- (message) =>
- message.role === "user" &&
- typeof message.content !== "string" &&
- message.content.some((part) => part.type === "text" && part.text === "steer custom"),
- );
- return fauxAssistantMessage("done");
- },
- ]);
+ // Too-short session: compact() throws CompactionSkippedError.
+ await harness.session.prompt("/compact");
- await waitForToolStart;
- await harness.session.sendCustomMessage(
- { customType: "queue-test", content: "steer custom", display: true, details: { value: 1 } },
- { deliverAs: "steer" },
+ const commandMessages = harness.session.messages.filter(
+ (message): message is Extract<(typeof harness.session.messages)[number], { role: "custom" }> =>
+ message.role === "custom" && message.customType.startsWith("session_slash_command"),
);
- releaseToolExecution();
- await promptPromise;
+ expect(commandMessages.map((message) => message.customType)).toEqual(["session_slash_command"]);
+ expect(compactionEndErrorSeverity).toBe("warning");
+ });
+
+ it("serializes concurrent trigger-turn custom messages", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("first"), fauxAssistantMessage("second")]);
+
+ await Promise.all([
+ harness.session.sendCustomMessage(
+ { customType: "first", content: "first", display: false },
+ { triggerTurn: true },
+ ),
+ harness.session.sendCustomMessage(
+ { customType: "second", content: "second", display: false },
+ { triggerTurn: true },
+ ),
+ ]);
- expect(sawCustomMessage).toBe(true);
expect(
- harness.session.messages.some((message) => message.role === "custom" && message.customType === "queue-test"),
- ).toBe(true);
+ harness.session.messages.filter((message) => message.role === "custom").map((message) => message.content),
+ ).toEqual(["first", "second"]);
});
- it("queues custom messages with deliverAs followUp while streaming", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("pumps follow-up work admitted during a trigger-turn custom message", async () => {
+ const harness = await createHarness();
harnesses.push(harness);
- let sawCustomMessage = false;
-
+ let queued = false;
harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("original turn complete"),
- (context) => {
- sawCustomMessage = context.messages.some(
- (message) =>
- message.role === "user" &&
- typeof message.content !== "string" &&
- message.content.some((part) => part.type === "text" && part.text === "follow-up custom"),
- );
- return fauxAssistantMessage("done");
+ async () => {
+ queued = await harness.session.restoreFollowUpMessage("queued during custom turn");
+ return fauxAssistantMessage("custom done");
},
+ fauxAssistantMessage("follow-up done"),
]);
- await waitForToolStart;
await harness.session.sendCustomMessage(
- { customType: "queue-test", content: "follow-up custom", display: true, details: { value: 1 } },
- { deliverAs: "followUp" },
+ { customType: "trigger", content: "trigger", display: false },
+ { triggerTurn: true },
);
- releaseToolExecution();
- await promptPromise;
+ await harness.session.waitForIdle();
- expect(sawCustomMessage).toBe(true);
- expect(
- harness.session.messages.some((message) => message.role === "custom" && message.customType === "queue-test"),
- ).toBe(true);
+ expect(queued).toBe(true);
+ expect(getUserTexts(harness)).toEqual(["queued during custom turn"]);
+ expect(getAssistantTexts(harness)).toEqual(["custom done", "follow-up done"]);
});
- it("injects nextTurn custom messages into the next prompt", async () => {
+ it("rechecks queued-work pauses acquired at the direct-admission boundary", async () => {
const harness = await createHarness();
harnesses.push(harness);
- let sawCustomMessage = false;
+ harness.setResponses([fauxAssistantMessage("direct done")]);
+ const internals = harness.session as unknown as {
+ _acquireTurnAdmission(): Promise<{ owner: symbol; release(): void }>;
+ };
+ const acquireTurnAdmission = internals._acquireTurnAdmission.bind(internals);
+ let pause: { release(): void } | undefined;
+ let first = true;
+ internals._acquireTurnAdmission = async () => {
+ const admission = await acquireTurnAdmission();
+ if (first) {
+ first = false;
+ pause = harness.session.acquireQueuedWorkPause();
+ }
+ return admission;
+ };
+ const prompt = harness.session.prompt("direct");
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(getUserTexts(harness)).toEqual([]);
+ pause?.release();
+ await prompt;
+ expect(getUserTexts(harness)).toEqual(["direct"]);
+ });
- await harness.session.sendCustomMessage(
- { customType: "next-turn", content: "carry this", display: true, details: {} },
- { deliverAs: "nextTurn" },
+ it("rejects disposal while direct admission waits behind a pause", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const pause = harness.session.acquireQueuedWorkPause();
+ const release = vi.spyOn(pause, "release");
+ const prompt = vi.spyOn(harness.session.agent, "prompt");
+ const trigger = harness.session.sendCustomMessage(
+ { customType: "trigger", content: "trigger", display: false },
+ { triggerTurn: true },
);
+ await new Promise<void>((resolve) => setImmediate(resolve));
- harness.setResponses([
- (context) => {
- sawCustomMessage = context.messages.some(
- (message) =>
- message.role === "user" &&
- typeof message.content !== "string" &&
- message.content.some((part) => part.type === "text" && part.text === "carry this"),
- );
- return fauxAssistantMessage("done");
- },
- ]);
-
- await harness.session.prompt("normal prompt");
+ harness.session.dispose();
+ await expect(trigger).rejects.toThrow("session is disposing or disposed");
- expect(sawCustomMessage).toBe(true);
- expect(harness.session.messages.map((message) => message.role)).toEqual(["custom", "user", "assistant"]);
+ expect(prompt).not.toHaveBeenCalled();
+ expect(release).not.toHaveBeenCalled();
});
- it("updates pendingMessageCount and removes queued text before message_start is emitted", async () => {
- const waiting = await createWaitingHarness();
- const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ it("rejects a post-disposal direct call without prompting the agent", async () => {
+ const harness = await createHarness();
harnesses.push(harness);
- const countsAtQueuedMessageStart: number[] = [];
+ const prompt = vi.spyOn(harness.session.agent, "prompt");
+ harness.session.dispose();
+ await expect(
+ harness.session.sendCustomMessage(
+ { customType: "trigger", content: "trigger", display: false },
+ { triggerTurn: true },
+ ),
+ ).rejects.toThrow("session is disposing or disposed");
+ expect(prompt).not.toHaveBeenCalled();
+ });
+
+ it.each(["queued", "preparing"] as const)(
+ "keeps a coalesced duplicate with its $phase agent-message owner",
+ async (phase) => {
+ const prepared = createDeferred<void>();
+ const releasePreparation = createDeferred<void>();
+ const harness = await createHarness({
+ extensionFactories:
+ phase === "preparing"
+ ? [
+ (pi) => {
+ pi.on("before_agent_start", async () => {
+ prepared.resolve();
+ await releasePreparation.promise;
+ });
+ },
+ ]
+ : [],
+ });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("accepted done")]);
+ const pause = phase === "queued" ? harness.session.acquireQueuedWorkPause() : undefined;
+ const id = `agentmsg_${phase}_coalesced_owner`;
+ withStreaming(harness, true);
+ const earlyDelivery = harness.session.waitForAgentMessagePromptDelivery(id);
+
+ const completion = harness.session.promptAndWait("accepted", {
+ streamingBehavior: "followUp",
+ followUpQueueKey: "same",
+ agentMessageId: id,
+ resumeIfIdle: true,
+ });
+ if (phase === "queued") {
+ await vi.waitFor(() => expect(harness.session.getFollowUpMessages()).toEqual(["accepted"]));
+ } else {
+ withStreaming(harness, false);
+ await prepared.promise;
+ // Owned by the pump during preparation, still reported as pending.
+ expect(harness.session.getFollowUpMessages()).toEqual(["accepted"]);
+ }
+ await expect(
+ harness.session.restoreFollowUpMessage("duplicate", undefined, { queueKey: "same", agentMessageId: id }),
+ ).resolves.toBe(false);
+
+ withStreaming(harness, false);
+ pause?.release();
+ releasePreparation.resolve();
+ await expect(earlyDelivery).resolves.toBeUndefined();
+ await expect(completion).resolves.toBeUndefined();
+ expect(getUserTexts(harness)).toEqual(["accepted"]);
+ },
+ );
+
+ it("retains active preparation while blocking duplicate and direct admission", async () => {
+ let hookRuns = 0;
+ let pause: { release(): void } | undefined;
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("before_agent_start", async (event) => {
+ if (event.prompt === "queued") {
+ hookRuns++;
+ pause = harness.session.acquireQueuedWorkPause();
+ }
+ });
+ },
+ ],
+ });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("queued done"), fauxAssistantMessage("direct done")]);
+ withStreaming(harness, true);
+ await harness.session.followUp("queued", undefined, { queueKey: "same", resumeIfIdle: true });
+ withStreaming(harness, false);
+ await vi.waitFor(() => expect(pause).toBeDefined());
+
+ expect(await harness.session.followUp("duplicate", undefined, { queueKey: "same" })).toBe(false);
+ const direct = harness.session.prompt("direct");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(getUserTexts(harness)).toEqual([]);
+ pause?.release();
+ await direct;
+
+ expect(hookRuns).toBe(1);
+ expect(getUserTexts(harness)).toEqual(["queued", "direct"]);
+ });
+
+ it("stops before another turn when more steering remains", async () => {
+ const tool: AgentTool = {
+ name: "instant",
+ label: "Instant",
+ description: "Returns immediately",
+ parameters: Type.Object({}),
+ execute: async () => ({ content: [{ type: "text", text: "done" }], details: {} }),
+ };
+ const harness = await createHarness({ tools: [tool] });
+ harnesses.push(harness);
harness.setResponses([
- fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
- fauxAssistantMessage("done"),
+ fauxAssistantMessage(fauxToolCall("instant", {}), { stopReason: "toolUse" }),
+ fauxAssistantMessage("second handled"),
]);
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.steer("first", undefined, { resumeIfIdle: true });
+ await harness.session.steer("second", undefined, { resumeIfIdle: true });
+ pause.release();
+ await harness.session.waitForIdle();
- harness.session.subscribe((event) => {
- if (
- event.type === "message_start" &&
- event.message.role === "user" &&
- getMessageText(event.message) === "queued"
- ) {
- countsAtQueuedMessageStart.push(harness.session.pendingMessageCount);
- }
- });
+ expect(getUserTexts(harness)).toEqual(["first", "second"]);
+ expect(getAssistantTexts(harness)).toEqual(["", "second handled"]);
+ });
- await waitForToolStart;
- await harness.session.steer("queued");
- expect(harness.session.pendingMessageCount).toBe(1);
- releaseToolExecution();
- await promptPromise;
+ it.each([
+ {
+ action: "refine",
+ run: (harness: Harness) => harness.session.refine({}, { skipAbort: true }),
+ },
+ {
+ action: "compact",
+ run: (harness: Harness) => harness.session.compact(undefined, { skipAbort: true }),
+ },
+ ])("rejects skip-abort $action while a turn is active", async ({ action, run }) => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ withStreaming(harness, true);
- expect(countsAtQueuedMessageStart).toEqual([0]);
- expect(harness.session.pendingMessageCount).toBe(0);
+ await expect(run(harness)).rejects.toThrow(`Cannot ${action} without aborting while the agent is running.`);
});
- it("clears only internally queued agent-message prompts", async () => {
+ it("defers work queued after direct admission until the direct handoff", async () => {
const harness = await createHarness();
harnesses.push(harness);
- const spoofed =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_spoof\n\nordinary user text";
- const real =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_real\n\nreal agent text";
+ harness.setResponses([fauxAssistantMessage("direct done"), fauxAssistantMessage("queued done")]);
+ const internals = harness.session as unknown as {
+ _acquireDirectTurnAdmission(options?: { allowStreaming?: boolean }): Promise<{
+ owner: symbol;
+ release(): void;
+ }>;
+ };
+ const acquireDirectTurnAdmission = internals._acquireDirectTurnAdmission.bind(internals);
+ let queuedAtBoundary = false;
+ internals._acquireDirectTurnAdmission = async (options = {}) => {
+ const admission = await acquireDirectTurnAdmission(options);
+ if (!queuedAtBoundary) {
+ queuedAtBoundary = true;
+ await harness.session.followUp("queued", undefined, { resumeIfIdle: true });
+ }
+ return admission;
+ };
- await harness.session.followUp(spoofed);
- await harness.session.queueAgentMessagePrompt(real, "followUp");
+ await harness.session.prompt("direct");
+ await harness.session.waitForIdle();
- expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
- steering: [],
- followUp: [real],
- });
- expect(harness.session.getFollowUpMessages()).toEqual([spoofed]);
+ expect(getUserTexts(harness)).toEqual(["direct", "queued"]);
});
- it("clears internally queued agent-message steering prompts by message identity", async () => {
+ it("serializes an extension command behind an unrelated navigation owner", async () => {
+ let targetId: string | undefined;
+ const navigationGate = createDeferred();
+ let navigationStarts = 0;
+ let commandNavigated = false;
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("session_before_tree", async () => {
+ if (navigationStarts++ === 0) await navigationGate.promise;
+ });
+ pi.registerCommand("back", {
+ description: "Navigate back",
+ handler: async (_args, ctx) => {
+ await ctx.navigateTree(targetId!, { summarize: false });
+ commandNavigated = true;
+ },
+ });
+ },
+ ],
+ });
+ harnesses.push(harness);
+ await harness.session.bindExtensions({
+ commandContextActions: {
+ waitForIdle: () => harness.session.waitForIdle(),
+ newSession: async () => ({ cancelled: false }),
+ fork: async () => ({ cancelled: false }),
+ navigateTree: async (target, options) => harness.session.navigateTree(target, options),
+ switchSession: async () => ({ cancelled: false }),
+ reload: async () => {},
+ },
+ });
+ harness.setResponses([fauxAssistantMessage("one"), fauxAssistantMessage("two")]);
+ await harness.session.prompt("one");
+ targetId = harness.sessionManager.getEntries().find((entry) => entry.type === "message")?.id;
+ expect(targetId).toBeDefined();
+ await harness.session.prompt("two");
+ const secondId = harness.sessionManager.getLeafId();
+
+ const unrelatedNavigation = harness.session.navigateTree(targetId!, { summarize: false });
+ await vi.waitFor(() => expect(navigationStarts).toBe(1));
+ const extensionCommand = harness.session.prompt("/back");
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(commandNavigated).toBe(false);
+
+ navigationGate.resolve();
+ await unrelatedNavigation;
+ await extensionCommand;
+ expect(commandNavigated).toBe(true);
+ expect(navigationStarts).toBe(2);
+ expect(harness.sessionManager.getLeafId()).not.toBe(secondId);
+ });
+
+ it("waitForIdle observes a run that starts at its final idle boundary", async () => {
+ const responseGate = createDeferred();
+ const waitForResponseStart = createDeferred();
const harness = await createHarness();
harnesses.push(harness);
- const sharedText =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_shared\n\nshared text";
-
- await harness.session.steer(sharedText);
- await harness.session.queueAgentMessagePrompt(sharedText, "steer");
+ harness.setResponses([
+ async () => {
+ waitForResponseStart.resolve();
+ await responseGate.promise;
+ return fauxAssistantMessage("late done");
+ },
+ ]);
+ const agentWaitForIdle = harness.session.agent.waitForIdle.bind(harness.session.agent);
+ let waitCalls = 0;
+ vi.spyOn(harness.session.agent, "waitForIdle").mockImplementation(async () => {
+ await agentWaitForIdle();
+ if (waitCalls++ === 0) void harness.session.agent.prompt("late run");
+ });
- expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
- steering: [sharedText],
- followUp: [],
+ let idle = false;
+ const waiting = harness.session.waitForIdle().then(() => {
+ idle = true;
});
- expect(harness.session.getSteeringMessages()).toEqual([sharedText]);
+ await waitForResponseStart.promise;
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(idle).toBe(false);
+
+ responseGate.resolve();
+ await waiting;
+ expect(idle).toBe(true);
});
+ it("parses queued refine rollback ids and global placement without consuming instruction text", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ const refine = vi.spyOn(harness.session, "refine").mockResolvedValue(emptyRefinementResult());
- it("clears the agent queue when a queue update listener clears a newly queued steering prompt", async () => {
+ for (const [command, options] of [
+ ["/refine rollback refine_123", { rollbackId: "refine_123", global: false }],
+ ["/refine rollback refine_456 --global", { rollbackId: "refine_456", global: true }],
+ ["/refine --global rollback refine_789", { rollbackId: "refine_789", global: true }],
+ ["/refine --global focus on validation", { instructions: "focus on validation", global: true }],
+ [
+ "/refine update docs to explain --global",
+ { instructions: "update docs to explain --global", global: false },
+ ],
+ ] as const) {
+ await harness.session.prompt(command);
+ expect(refine).toHaveBeenLastCalledWith(options, { skipAbort: true });
+ }
+ });
+
+ it("reports a missing queued refine rollback id without invoking refine", async () => {
const harness = await createHarness();
harnesses.push(harness);
- const agentPrompt =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_queue_update_clear\n\nclear during update";
- const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_queue_update_clear");
- let cleared = false;
- const unsubscribe = harness.session.subscribe((event) => {
- if (event.type === "queue_update" && !cleared) {
- cleared = true;
- harness.session.clearQueue();
- }
+ const refine = vi.spyOn(harness.session, "refine");
+
+ await harness.session.prompt("/refine rollback");
+
+ expect(refine).not.toHaveBeenCalled();
+ expect(
+ harness.session.messages.some(
+ (message) =>
+ message.role === "custom" &&
+ message.customType === "session_slash_command_result" &&
+ message.content === "Command failed: Usage: /refine rollback <refinement-id>",
+ ),
+ ).toBe(true);
+ });
+});
+
+describe("AgentSession scheduler scenarios", () => {
+ const harnesses: Harness[] = [];
+
+ afterEach(() => {
+ while (harnesses.length > 0) {
+ harnesses.pop()?.cleanup();
+ }
+ });
+
+ it("S1: delivers mid-run steering, follow-up, command, and custom inputs in order", async () => {
+ let extensionApi: ExtensionAPI | undefined;
+ const waiting = await createWaitingHarness({
+ extensionFactories: [
+ (pi) => {
+ extensionApi = pi;
+ },
+ ],
});
+ const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
+ harnesses.push(harness);
+ harness.session.setFollowUpMode("all");
- await harness.session.queueAgentMessagePrompt(agentPrompt, "steer");
- unsubscribe();
- await expect(delivery).rejects.toThrow("cleared before delivery");
- expect(harness.session.getSteeringMessages()).toEqual([]);
+ const countsAtUserMessageStart: Array<{ text: string; pending: number }> = [];
+ harness.session.subscribe((event) => {
+ if (event.type === "message_start" && event.message.role === "user") {
+ countsAtUserMessageStart.push({
+ text: getMessageText(event.message),
+ pending: harness.session.pendingMessageCount,
+ });
+ }
+ });
- let sawClearedPrompt = false;
+ let batchedUsers: string[] | undefined;
+ let batchSawImage = false;
harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
(context) => {
- sawClearedPrompt = context.messages.some(
- (message) => message.role === "user" && getMessageText(message).includes("agentmsg_queue_update_clear"),
+ const sawSteer = context.messages.some(
+ (message) => message.role === "user" && getMessageText(message) === "s1",
);
- return fauxAssistantMessage("normal response");
+ return fauxAssistantMessage(sawSteer ? "handled s1" : "missing s1");
+ },
+ (context) => {
+ const sawCustom = context.messages.some(
+ (message) =>
+ message.role === "user" &&
+ typeof message.content !== "string" &&
+ message.content.some((part) => part.type === "text" && part.text === "steer custom"),
+ );
+ return fauxAssistantMessage(sawCustom ? "handled steer custom" : "missing steer custom");
+ },
+ fauxAssistantMessage("handled extension steer"),
+ fauxAssistantMessage("f1 done"),
+ (context) => {
+ batchedUsers = context.messages
+ .filter((message) => message.role === "user")
+ .map((message) => getMessageText(message));
+ batchSawImage = context.messages.some(
+ (message) =>
+ message.role === "user" &&
+ typeof message.content !== "string" &&
+ message.content.some((part) => part.type === "image" && part.data === "image-data"),
+ );
+ return fauxAssistantMessage("f2 batch done");
},
]);
- await harness.session.prompt("normal");
- expect(sawClearedPrompt).toBe(false);
- expect(getUserTexts(harness)).toEqual(["normal"]);
+ // Phase 1: queue all input kinds while the run is gated.
+ await waitForToolStart;
+ await harness.session.steer("s1");
+ await harness.session.sendCustomMessage(
+ { customType: "queue-test", content: "steer custom", display: true, details: {} },
+ { deliverAs: "steer" },
+ );
+ expect(extensionApi).toBeDefined();
+ extensionApi?.sendUserMessage("extension steer", { deliverAs: "steer" });
+ await harness.session.followUp("f1");
+ await harness.session.prompt("/autonomous status", { streamingBehavior: "followUp" });
+ await harness.session.followUp("f2");
+ await harness.session.sendCustomMessage(
+ {
+ customType: "queue-test-follow-up",
+ content: [
+ { type: "text", text: "follow-up custom" },
+ { type: "image", data: "image-data", mimeType: "image/png" },
+ ],
+ display: true,
+ details: {},
+ },
+ { deliverAs: "followUp" },
+ );
+
+ // Phase 2: queued work stays in session queues, not Agent queues.
+ expect(harness.session.agent.hasQueuedMessages()).toBe(false);
+ const pendingAfterQueueing = harness.session.pendingMessageCount;
+ expect(pendingAfterQueueing).toBeGreaterThan(0);
+ expect(harness.session.getFollowUpMessages()).toContain("f1");
+ expect(harness.session.getFollowUpMessages()).toContain("f2");
+
+ releaseToolExecution();
+ await promptPromise;
+ await harness.session.waitForIdle();
+
+ // Phase 3: steering inside the run, follow-ups after it, f2 + custom batched (all mode).
+ expect(getAssistantTexts(harness)).toEqual([
+ "",
+ "handled s1",
+ "handled steer custom",
+ "handled extension steer",
+ "f1 done",
+ "f2 batch done",
+ ]);
+ expect(getUserTexts(harness)).toEqual(["start", "s1", "extension steer", "f1", "f2"]);
+ expect(batchedUsers).toContain("f2");
+ expect(batchedUsers).toContain("follow-up custom");
+ expect(batchSawImage).toBe(true);
+
+ // Phase 4: the command is a durable hard boundary between f1 and f2.
+ const rows = harness.session.messages.map((message) =>
+ message.role === "custom" ? `custom:${message.customType}` : `${message.role}`,
+ );
+ const userTexts = harness.session.messages.map((message) =>
+ message.role === "user" ? getMessageText(message) : undefined,
+ );
+ const f1Index = userTexts.indexOf("f1");
+ const f2Index = userTexts.indexOf("f2");
+ const commandIndex = rows.indexOf("custom:session_slash_command");
+ expect(commandIndex).toBeGreaterThan(f1Index);
+ expect(commandIndex).toBeLessThan(f2Index);
+ expect(rows).toContain("custom:autonomous_status");
+ expect(rows).toContain("custom:queue-test");
+ 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);
+ const queuedStarts = countsAtUserMessageStart.filter((entry) => entry.text !== "start");
+ expect(queuedStarts.length).toBeGreaterThan(0);
+ for (const entry of queuedStarts) {
+ expect(entry.pending).toBeLessThan(pendingAfterQueueing);
+ }
+ for (let i = 1; i < queuedStarts.length; i++) {
+ expect(queuedStarts[i]!.pending).toBeLessThanOrEqual(queuedStarts[i - 1]!.pending);
+ }
});
- it("settles late agent-message delivery waiters", async () => {
- const harness = await createHarness();
+ it("S2: edits queued work mid-run with coalescing, removal APIs, and steering-stop reconciliation", async () => {
+ const waiting = await createWaitingHarness();
+ const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
harnesses.push(harness);
- const deliveryInternals = harness.session as unknown as {
- waitForAgentMessagePromptDelivery(agentMessageId: string): Promise<void>;
- _resolveAgentMessageDelivery(agentMessageId: string): void;
- _rejectAgentMessageDelivery(agentMessageId: string, error: Error): void;
- };
+ const internals = harness.session as unknown as SteeringStopInternals;
+ const removedTexts = ["first", "second", "same heartbeat", "clear me"];
+ let continuationSawRemoved = false;
+ harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
+ (context) => {
+ continuationSawRemoved = context.messages.some(
+ (message) =>
+ message.role === "user" && removedTexts.some((text) => getMessageText(message).includes(text)),
+ );
+ return fauxAssistantMessage("continued clean");
+ },
+ fauxAssistantMessage("keep me done"),
+ fauxAssistantMessage("spoof done"),
+ ]);
+ await waitForToolStart;
- deliveryInternals._resolveAgentMessageDelivery("agentmsg_delivered");
- await expect(deliveryInternals.waitForAgentMessagePromptDelivery("agentmsg_delivered")).resolves.toBeUndefined();
+ // Phase 1: keyed follow-ups coalesce per key.
+ const preflights: boolean[] = [];
+ await harness.session.prompt("same heartbeat", { streamingBehavior: "followUp", followUpQueueKey: "hb:one" });
+ await harness.session.prompt("same heartbeat", { streamingBehavior: "followUp", followUpQueueKey: "hb:two" });
+ await harness.session.prompt("same heartbeat", {
+ streamingBehavior: "followUp",
+ followUpQueueKey: "hb:two",
+ preflightResult: (didSucceed: boolean) => preflights.push(didSucceed),
+ });
+ expect(preflights).toEqual([false]);
+ expect(harness.session.getFollowUpMessages()).toEqual(["same heartbeat", "same heartbeat"]);
+ await harness.session.followUp("keep me", undefined, { queueKey: "hb:keep" });
+
+ // Phase 2: steering never coalesces.
+ await harness.session.steer("first", undefined, { queueKey: "same-steer" });
+ await harness.session.steer("second", undefined, { queueKey: "same-steer" });
+ expect(harness.session.getSteeringMessages()).toEqual(["first", "second"]);
+ expect(internals._steeringStopPending).toBe(true);
+ const agentPrompt = agentPromptText("agentmsg_s2_clear", "clear me");
+ const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_s2_clear");
+ await harness.session.queueAgentMessagePrompt(agentPrompt, "steer");
- deliveryInternals._rejectAgentMessageDelivery("agentmsg_failed", new Error("cleared before delivery"));
- await expect(deliveryInternals.waitForAgentMessagePromptDelivery("agentmsg_failed")).rejects.toThrow(
- "cleared before delivery",
+ // Phase 3: keyed duplicates reject both agent-message outcome legs.
+ const dupDelivery = expect(harness.session.waitForAgentMessagePromptDelivery("agentmsg_s2_dup")).rejects.toThrow(
+ "equivalent follow-up is already pending",
);
+ await expect(
+ harness.session.promptAndWait("another duplicate", {
+ streamingBehavior: "followUp",
+ followUpQueueKey: "hb:two",
+ agentMessageId: "agentmsg_s2_dup",
+ }),
+ ).rejects.toThrow("equivalent follow-up is already pending");
+ await dupDelivery;
+ await expect(
+ harness.session.restoreFollowUpMessage("restored duplicate", undefined, {
+ queueKey: "hb:two",
+ agentMessageId: "agentmsg_s2_restored",
+ }),
+ ).resolves.toBe(false);
+
+ // Phase 4: removal APIs.
+ expect(harness.session.removeQueuedFollowUp("hb:one")).toBe(true);
+ expect(harness.session.removeQueuedFollowUp("hb:one")).toBe(false);
+ expect(harness.session.getFollowUpMessages()).toEqual(["same heartbeat", "keep me"]);
+ const followUpAgentPrompt = agentPromptText("agentmsg_s2_follow", "clear me too");
+ await harness.session.queueAgentMessagePrompt(followUpAgentPrompt, "followUp");
+ const spoofedPlain = agentPromptText("agentmsg_spoof", "ordinary user text");
+ await harness.session.followUp(spoofedPlain);
+ expect(harness.session.clearQueuedUserMessagesMatching((text) => text.includes("agentmsg_"))).toEqual({
+ steering: [agentPrompt],
+ followUp: [followUpAgentPrompt],
+ });
+ await expect(delivery).rejects.toThrow("cleared before delivery");
+
+ // Phase 5: steering-stop reconciliation.
+ expect(harness.session.getSteeringMessages()).toEqual(["first", "second"]);
+ expect(internals._steeringStopPending).toBe(true);
+ expect(harness.session.removeQueuedFollowUp("same-steer")).toBe(true);
+ expect(harness.session.getSteeringMessages()).toEqual([]);
+ expect(internals._steeringStopPending).toBe(false);
+ expect(harness.session.removeQueuedFollowUp("hb:two")).toBe(true);
+ expect(harness.session.getFollowUpMessages()).toEqual(["keep me", spoofedPlain]);
+ expect(harness.session.clearQueuedUserMessagesMatching((text) => text === spoofedPlain)).toEqual({
+ steering: [],
+ followUp: [],
+ });
+ expect(harness.session.getFollowUpMessages()).toEqual(["keep me", spoofedPlain]);
+
+ // Phase 6: the run continues without any removed input.
+ releaseToolExecution();
+ await promptPromise;
+ await harness.session.waitForIdle();
+ 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);
});
- it("keeps queued agent-message delivery waiters pending on abort until the message is delivered", async () => {
- const harness = await createHarness();
+ it("S3: pause-lease preparation journey with anchor re-preparation and direct handoff", async () => {
+ const firstPreparation = createDeferred();
+ const prepared: string[] = [];
+ const directGate = gatedHook({ prompt: "direct" });
+ const harness = await createHarness({
+ extensionFactories: [
+ (pi) => {
+ pi.on("before_agent_start", async (event) => {
+ if (event.prompt === "direct") return;
+ prepared.push(event.prompt);
+ if (prepared.length === 1) await firstPreparation.promise;
+ return { systemPrompt: `${event.systemPrompt}\nprepared:${event.prompt}` };
+ });
+ },
+ directGate.factory,
+ ],
+ });
harnesses.push(harness);
- const agentPrompt =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_abort\n\nsurvive the abort";
- harness.setResponses([fauxAssistantMessage("x".repeat(20_000))]);
-
- const sawMessageUpdate = new Promise<void>((resolve) => {
- const unsubscribe = harness.session.subscribe((event) => {
- if (event.type === "message_update") {
- unsubscribe();
- resolve();
- }
- });
+ harness.session.setFollowUpMode("all");
+ const responseGate = createDeferred();
+ let providerSystemPrompt = "";
+ harness.setResponses([
+ async (context) => {
+ providerSystemPrompt = context.systemPrompt ?? "";
+ await responseGate.promise;
+ return fauxAssistantMessage("remaining response");
+ },
+ fauxAssistantMessage("direct done"),
+ fauxAssistantMessage("late queued done"),
+ ]);
+
+ // Phase 1: a pause lease holds queued work.
+ const removedAgentMessage = agentPromptText("agentmsg_remove", "remove");
+ const keptAgentMessage = agentPromptText("agentmsg_keep", "keep");
+ const pause = harness.session.acquireQueuedWorkPause();
+ await harness.session.followUp("ordinary");
+ await harness.session.queueAgentMessagePrompt(removedAgentMessage, "followUp", undefined);
+ await harness.session.queueAgentMessagePrompt(keptAgentMessage, "followUp", undefined);
+ await harness.session.followUp("last anchor", undefined, { queueKey: "heartbeat:one" });
+ expect(prepared).toEqual([]);
+ expect(getUserTexts(harness)).toEqual([]);
+
+ // Phase 2: release starts preparation with the last message as batch anchor.
+ pause.release();
+ await vi.waitFor(() => expect(prepared).toEqual(["last anchor"]));
+
+ // Phase 3: removals during preparation re-prepare around the new anchor.
+ expect(harness.session.clearQueuedUserMessagesMatching((text) => text === removedAgentMessage)).toEqual({
+ steering: [],
+ followUp: [removedAgentMessage],
});
- const promptPromise = harness.session.prompt("hi");
- await sawMessageUpdate;
+ expect(harness.session.removeQueuedFollowUp("heartbeat:one")).toBe(true);
+ firstPreparation.resolve();
+ await vi.waitFor(() => expect(providerSystemPrompt).not.toBe(""));
+ expect(harness.session.removeQueuedFollowUp("heartbeat:one")).toBe(false);
+ expect(prepared).toEqual(["last anchor", keptAgentMessage]);
+ expect(providerSystemPrompt).toContain(`prepared:${keptAgentMessage}`);
+ expect(providerSystemPrompt).not.toContain("prepared:last anchor");
+ responseGate.resolve();
+ await harness.session.waitForIdle();
+ expect(getUserTexts(harness)).toEqual(["ordinary", keptAgentMessage]);
+
+ // Phase 4: a direct prompt blocks queued work admitted behind it.
+ const direct = harness.session.prompt("direct");
+ await directGate.reached;
+ await harness.session.followUp("late queued", undefined, { resumeIfIdle: true });
+ expect(getUserTexts(harness)).toEqual(["ordinary", keptAgentMessage]);
+ directGate.release();
+ await direct;
+ await harness.session.waitForIdle();
+ expect(getUserTexts(harness)).toEqual(["ordinary", keptAgentMessage, "direct", "late queued"]);
+ });
+
+ it("S4: restart abort snapshots queued work and restores it, envelopes as commands", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ let providerCalls = 0;
+ const firstGate = createDeferred();
+ harness.setResponses([
+ async () => {
+ await firstGate.promise;
+ return fauxAssistantMessage("first done");
+ },
+ () => {
+ providerCalls++;
+ return fauxAssistantMessage("must not run");
+ },
+ ]);
- await harness.session.queueAgentMessagePrompt(agentPrompt, "followUp");
+ // Phase 1: queue a follow-up, a command with images, and an agent-message prompt mid-run.
+ const first = harness.session.prompt("first");
+ await vi.waitFor(() => expect(harness.session.isStreaming).toBe(true));
+ await harness.session.followUp("queued for restart");
+ const image = { type: "image" as const, mimeType: "image/png", data: "image-data" };
+ await harness.session.prompt("/goal inspect image", { streamingBehavior: "followUp", images: [image] });
+ const agentPrompt = agentPromptText("agentmsg_abort", "survive the abort");
const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_abort");
+ await harness.session.queueAgentMessagePrompt(agentPrompt, "followUp");
let deliverySettled = false;
void delivery.then(
() => {
@@ -2014,84 +2547,206 @@ describe("AgentSession queue characterization", () => {
deliverySettled = true;
},
);
- expect(harness.session.pendingMessageCount).toBe(1);
- await harness.session.abort();
- await promptPromise;
- await Promise.resolve();
-
- // The waiter still represents actual delivery, and the surviving queued message has not delivered yet.
+ // Phase 2: abortForUpdateRestart suspends the queue without starting a new turn.
+ harness.session.abortForUpdateRestart();
+ firstGate.resolve();
+ await first.catch(() => undefined);
+ await harness.session.agent.waitForIdle();
+ 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(deliverySettled).toBe(false);
- expect(harness.session.pendingMessageCount).toBe(1);
- expect(harness.session.getFollowUpMessages()).toEqual([agentPrompt]);
- harness.setResponses([fauxAssistantMessage("answer"), fauxAssistantMessage("handled follow-up")]);
- await harness.session.prompt("again");
+ // Phase 3: while suspended, triggerTurn rejects promptly.
+ const agentPromptSpy = vi.spyOn(harness.session.agent, "prompt");
+ await expect(
+ harness.session.sendCustomMessage(
+ { customType: "trigger", content: "trigger", display: false },
+ { triggerTurn: true },
+ ),
+ ).rejects.toThrow("queued session input is suspended");
+ expect(agentPromptSpy).not.toHaveBeenCalled();
+
+ // Phase 4: restore an envelope command and a literal slash message, then resume.
+ const command = parseSessionSlashCommand("/autonomous status");
+ expect(command).toBeDefined();
+ await harness.session.restoreFollowUpMessage(command!.text, undefined, {
+ agentMessageId: "agentmsg_restored_command",
+ customMessage: createSessionSlashCommandMessage(command!),
+ });
+ const mismatchedCommand = parseSessionSlashCommand("/autonomous on");
+ expect(mismatchedCommand).toBeDefined();
+ await harness.session.restoreFollowUpMessage(command!.text, undefined, {
+ customMessage: createSessionSlashCommandMessage(mismatchedCommand!),
+ });
+ await harness.session.restoreFollowUpMessage("/autonomous off", undefined, {
+ customMessage: {
+ role: "custom",
+ customType: "restored-literal",
+ content: "/autonomous off",
+ display: true,
+ timestamp: Date.now(),
+ },
+ });
+ harness.setResponses([
+ fauxAssistantMessage("queued handled"),
+ fauxAssistantMessage("agent prompt handled"),
+ fauxAssistantMessage("literal handled"),
+ ]);
+ expect(harness.session.resumeQueuedWork()).toBe(true);
+ await harness.session.waitForIdle();
+ // Phase 5: envelope ran as a command, the literal stayed literal, delivery settled.
+ expect(harness.session.getAutonomousStatus().enabled).toBe(false);
+ expect(
+ harness.session.messages.filter(
+ (message) =>
+ message.role === "custom" &&
+ message.customType === "session_slash_command" &&
+ (message.details as { command?: { text?: string } } | undefined)?.command?.text === command!.text,
+ ),
+ ).toHaveLength(1);
+ expect(
+ harness.session.messages.some(
+ (message) => message.role === "custom" && message.customType === "restored-literal",
+ ),
+ ).toBe(true);
await expect(delivery).resolves.toBeUndefined();
- expect(harness.session.pendingMessageCount).toBe(0);
+ expect(getUserTexts(harness)).toContain("queued for restart");
expect(getUserTexts(harness)).toContain(agentPrompt);
+ expect(harness.session.pendingMessageCount).toBe(0);
});
- it("resolves direct agent-message delivery waiters when the accepted prompt starts", async () => {
- const harness = await createHarness();
- harnesses.push(harness);
- const agentPrompt =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_direct\n\ndirect delivery";
- harness.setResponses([fauxAssistantMessage("direct reply")]);
-
- const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_direct");
- await harness.session.acceptAgentMessagePrompt(agentPrompt);
-
- await expect(delivery).resolves.toBeUndefined();
- });
-
- it("rejects queued agent-message delivery waiters on dispose", async () => {
+ it("S5: settles queued command delivery before gated completion and rejects completion on failure", async () => {
const harness = await createHarness();
harnesses.push(harness);
- const agentPrompt =
- "Agent-to-agent message received.\nSource: agent_message\nTo: Target, active target, session session-target\nMessage id: agentmsg_dispose\n\ndispose me";
- const delivery = harness.session.waitForAgentMessagePromptDelivery("agentmsg_dispose");
- await harness.session.queueAgentMessagePrompt(agentPrompt, "followUp");
- harness.session.dispose();
-
- await expect(delivery).rejects.toThrow("cleared before delivery");
- });
-
- it("throws when queueing an extension command with steer", async () => {
- const harness = await createHarness({
- extensionFactories: [
- (pi) => {
- pi.registerCommand("testcmd", {
- description: "Test command",
- handler: async () => {},
- });
- },
- ],
+ // Phase 1: delivery settles at the durable append, completion stays gated.
+ const started = createDeferred<void>();
+ const release = createDeferred<void>();
+ vi.spyOn(harness.session, "refine")
+ .mockImplementationOnce(async () => {
+ started.resolve();
+ await release.promise;
+ return emptyRefinementResult();
+ })
+ .mockRejectedValueOnce(new Error("refine execution failed"));
+ const pause = harness.session.acquireQueuedWorkPause();
+ const id = "agentmsg_gated_command";
+ const delivery = harness.session.waitForAgentMessagePromptDelivery(id);
+ let completionSettled = false;
+ const completion = harness.session.promptAndWait("/refine --local", { agentMessageId: id }).finally(() => {
+ completionSettled = true;
});
- harnesses.push(harness);
-
- await expect(harness.session.steer("/testcmd queued")).rejects.toThrow(
- 'Extension command "/testcmd" cannot be queued. Use prompt() or execute the command when not streaming.',
+ pause.release();
+ await started.promise;
+ await expect(delivery).resolves.toBeUndefined();
+ expect(completionSettled).toBe(false);
+ release.resolve();
+ await expect(completion).resolves.toBeUndefined();
+
+ // Phase 2: execution failure is delivered but rejects completion.
+ const failedPause = harness.session.acquireQueuedWorkPause();
+ const failedId = "agentmsg_failed_command";
+ const failedDelivery = harness.session.waitForAgentMessagePromptDelivery(failedId);
+ const failedCompletion = harness.session.promptAndWait("/refine --local", { agentMessageId: failedId });
+ failedPause.release();
+ await expect(failedDelivery).resolves.toBeUndefined();
+ await expect(failedCompletion).rejects.toThrow("refine execution failed");
+ });
+
+ it("S6: auto-refine reviews after real turns, defers while busy, and drops reviews on navigation", async () => {
+ const review2Gate = createDeferred();
+ const review3Gate = createDeferred();
+ const reviewer = vi.fn(
+ async (context: { reason: string; turnsSinceLastReview: number }, _signal?: AbortSignal) => {
+ if (reviewer.mock.calls.length === 2) await review2Gate.promise;
+ if (reviewer.mock.calls.length === 3) await review3Gate.promise;
+ return { shouldRefine: true, rationale: "durable lesson", instructions: `lesson ${context.reason}` };
+ },
);
- });
-
- it("throws when queueing an extension command with followUp", async () => {
- const harness = await createHarness({
- extensionFactories: [
- (pi) => {
- pi.registerCommand("testcmd", {
- description: "Test command",
- handler: async () => {},
- });
- },
- ],
+ const harness = await createAutoRefineHarness({
+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },
+ autoRefineReviewer: reviewer,
});
harnesses.push(harness);
+ const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ process.env.PRIME_AGENT_CODING_AGENT_DIR = `${harness.tempDir}/agent`;
+ try {
+ const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir())!;
+ const memoryIds = () => {
+ try {
+ return Object.keys(loadHarnessState(localDir, "local").entries.memory ?? {});
+ } catch {
+ return [];
+ }
+ };
+ const busyGate = createDeferred();
+ harness.setResponses([
+ fauxAssistantMessage("first done"),
+ fauxAssistantMessage(
+ refinePlanJson("First auto refine", [
+ { action: "create", kind: "memory", id: "auto_one", title: "One", content: "First lesson." },
+ ]),
+ ),
+ fauxAssistantMessage("second done"),
+ async () => {
+ await busyGate.promise;
+ return fauxAssistantMessage("busy done");
+ },
+ fauxAssistantMessage(
+ refinePlanJson("Second auto refine", [
+ { action: "create", kind: "memory", id: "auto_two", title: "Two", content: "Second lesson." },
+ ]),
+ ),
+ fauxAssistantMessage("fourth done"),
+ ]);
- await expect(harness.session.followUp("/testcmd queued")).rejects.toThrow(
- 'Extension command "/testcmd" cannot be queued. Use prompt() or execute the command when not streaming.',
- );
+ // Phase 1: interval review approves and the refine applies durably.
+ await harness.session.prompt("first");
+ await vi.waitFor(() => expect(memoryIds()).toContain("auto_one"));
+ expect(reviewer).toHaveBeenCalledTimes(1);
+ expect(reviewer.mock.calls[0]![0]).toEqual({ reason: "turn_interval", turnsSinceLastReview: 1 });
+
+ // Phase 2: review resolves while busy -> refine defers.
+ await harness.session.prompt("second");
+ await vi.waitFor(() => expect(reviewer).toHaveBeenCalledTimes(2));
+ const busyPrompt = harness.session.prompt("busy");
+ await vi.waitFor(() => expect(harness.session.isStreaming).toBe(true));
+ review2Gate.resolve();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(memoryIds()).not.toContain("auto_two");
+
+ // Phase 3: the pending review executes at idle without a second review.
+ busyGate.resolve();
+ await busyPrompt;
+ await vi.waitFor(() => expect(memoryIds()).toContain("auto_two"));
+ expect(reviewer).toHaveBeenCalledTimes(2);
+
+ // Phase 4: branch navigation discards the in-flight review.
+ await harness.session.prompt("fourth");
+ await vi.waitFor(() => expect(reviewer).toHaveBeenCalledTimes(3));
+ const target = harness.sessionManager
+ .getEntries()
+ .find((entry) => entry.type === "message" && entry.message.role === "user");
+ expect(target).toBeDefined();
+ const navigation = harness.session.navigateTree(target!.id, { summarize: false });
+ review3Gate.resolve();
+ await navigation;
+ await harness.session.waitForIdle();
+ expect(memoryIds()).toEqual(["auto_one", "auto_two"]);
+ expect(harness.getPendingResponseCount()).toBe(0);
+ } finally {
+ if (previousAgentDir === undefined) {
+ delete process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ } else {
+ process.env.PRIME_AGENT_CODING_AGENT_DIR = previousAgentDir;
+ }
+ }
});
});
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 d2318889f5..e8c636a553 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
@@ -25,6 +25,7 @@ type SerializedInternals = {
abort: AbortController,
): Promise<unknown>;
_serializedRefine: boolean;
+ _steeringStopPending: boolean;
_pendingRequestedRefine: { instructions?: string; global?: boolean } | undefined;
_assistantTurnsSinceAutoRefine: number;
_lastAutoRefineReviewAt: number;
@@ -299,6 +300,31 @@ describe("Serialized agent-callable refine", () => {
}
});
+ it("services a pending refine.run before stopping for steering", async () => {
+ const harness = await createHarness({
+ persistSession: true,
+ serializedRefine: true,
+ settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },
+ });
+ harnesses.push(harness);
+ const internals = harness.session as unknown as SerializedInternals;
+ const { applyRefine } = mockSerializedRefine(harness);
+ internals._pendingRequestedRefine = { instructions: "capture a lesson" };
+ internals._steeringStopPending = true;
+ const compactionSpy = vi
+ .spyOn(
+ internals as unknown as { _shouldStopForThresholdCompaction: (ctx: unknown) => Promise<boolean> },
+ "_shouldStopForThresholdCompaction",
+ )
+ .mockResolvedValue(false);
+
+ const shouldStop = await internals._shouldStopAfterTurn(makeCtx("turn"));
+
+ expect(applyRefine).toHaveBeenCalledTimes(1);
+ expect(compactionSpy).toHaveBeenCalledTimes(1);
+ expect(shouldStop).toBe(true);
+ });
+
it("agent-callable refine.run starts background planning immediately in serialized mode", async () => {
const harness = await createHarness({
persistSession: true,
@@ -1662,7 +1688,7 @@ describe("P0 concurrency regressions", () => {
}
});
- it("serialized threshold compaction: background plan applied before compaction fires", async () => {
+ it("steering waits for interval refine and threshold compaction boundaries", async () => {
// Verify that when threshold compaction would fire, the serialized
// checkpoint runs FIRST, draining the background plan, so the
// compaction model call cannot overlap an in-flight refine.
@@ -1679,6 +1705,7 @@ describe("P0 concurrency regressions", () => {
});
harnesses.push(harness);
const internals = harness.session as unknown as SerializedInternals;
+ internals._steeringStopPending = true;
let planResolved = false;
let applyFinished = false;
diff --git a/packages/coding-agent/test/suite/harness.ts b/packages/coding-agent/test/suite/harness.ts
index d55fc1bf18..5e3ec41007 100644
--- a/packages/coding-agent/test/suite/harness.ts
+++ b/packages/coding-agent/test/suite/harness.ts
@@ -222,7 +222,9 @@ export async function createHarness(options: HarnessOptions = {}): Promise<Harne
session.dispose();
fauxProvider.unregister();
if (existsSync(tempDir)) {
- rmSync(tempDir, { recursive: true });
+ // Spawned fixture processes may still be flushing their final registry
+ // writes; retry briefly instead of failing the suite on ENOTEMPTY.
+ rmSync(tempDir, { recursive: true, force: true, maxRetries: 40, retryDelay: 50 });
}
},
};
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 5d45e26c20..a739109da6 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
@@ -4,21 +4,52 @@ import { fauxAssistantMessage } from "@earendil-works/pi-ai";
import { afterEach, describe, expect, it, vi } from "vitest";
import { getDaemonUpdateRestartManifestPath } from "../../../src/config.js";
import type { AgentSessionRuntime } from "../../../src/core/agent-session-runtime.js";
-import type { AgentCronJobStore, AgentCronScheduler } from "../../../src/core/cron-jobs.js";
-import type { CustomMessage } from "../../../src/core/messages.js";
+import type { AgentCronJob, AgentCronJobStore, AgentCronScheduler } from "../../../src/core/cron-jobs.js";
+import { type CustomMessage, createSessionSlashCommandMessage } from "../../../src/core/messages.js";
+import { parseSessionSlashCommand } from "../../../src/core/slash-commands.js";
import type { BashOperations } from "../../../src/core/tools/bash.js";
import type { ActiveSessionState, DaemonSocketClient } from "../../../src/modes/daemon/active-session-state.js";
import { AgentDaemon } from "../../../src/modes/daemon/daemon-mode.js";
import type { DaemonUpdateRestartManifest } from "../../../src/modes/daemon/daemon-protocol.js";
+import { MutationDrainLatch } from "../../../src/modes/daemon/mutation-drain-latch.js";
import { prepareDaemonUpdateRestart } from "../../../src/package-manager-cli.js";
-import { createHarness, getUserTexts, type Harness } from "../harness.js";
+import { createHarness, getMessageText, getUserTexts, type Harness } from "../harness.js";
+import { createDeferred } from "../scheduling.js";
type AgentDaemonUpdateInternals = {
sessions: Map<string, ActiveSessionState>;
cronStore: AgentCronJobStore;
cronScheduler: AgentCronScheduler;
+ runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;
prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest>;
+ beginUpdateRestartTransaction(owner?: DaemonSocketClient): NonNullable<AgentDaemonUpdateInternals["updateRestart"]>;
+ runUpdateRestartPreparation(
+ transaction: NonNullable<AgentDaemonUpdateInternals["updateRestart"]>,
+ ): Promise<DaemonUpdateRestartManifest>;
+ prepareUpdateRestartCheckpoint(
+ transaction: NonNullable<AgentDaemonUpdateInternals["updateRestart"]>,
+ ): Promise<DaemonUpdateRestartManifest>;
handleLine(client: DaemonSocketClient, line: string): Promise<void>;
+ handleWorkerCommand(client: DaemonSocketClient, command: { id: string; type: string }): Promise<void>;
+ mutationDrain: { begin(): void; end(): void };
+ updateRestart?: {
+ id: symbol;
+ abort: AbortController;
+ phase: "preparing" | "fencing" | "prepared" | "publishing";
+ manifest?: DaemonUpdateRestartManifest;
+ owner?: DaemonSocketClient;
+ deferredClientEnv: Array<{
+ client: DaemonSocketClient;
+ state: ActiveSessionState;
+ env: Record<string, string>;
+ }>;
+ };
+ supervisorClaims: Map<DaemonSocketClient, unknown>;
+ revokeSupervisorClaim(client: DaemonSocketClient): boolean;
+ shutdown(exitCode: number): Promise<never>;
+ getShutdownClosingReason(): "update" | "shutdown";
+ cancelPreparedUpdateRestart(transactionId?: symbol): void;
+ commitPreparedUpdateRestart(transactionId: symbol): Promise<DaemonUpdateRestartManifest>;
};
type QueueInternals = {
@@ -52,12 +83,6 @@ type QueueInternals = {
};
};
-type AgentInternals = {
- _state: {
- isStreaming: boolean;
- };
-};
-
function createState(
harness: Harness,
activeSessionId: string,
@@ -67,6 +92,7 @@ function createState(
const runtime = {
session: harness.session,
metadata,
+ cwd: harness.tempDir,
runtimeConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
diagnostics: [],
dispose: async () => {
@@ -84,6 +110,41 @@ function createState(
};
}
+function createDaemonInternals(
+ harness: Harness,
+ options: { sessionDir?: string; worker?: boolean } = {},
+): AgentDaemonUpdateInternals {
+ const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
+ defaultSessionConfig: {
+ cwd: harness.tempDir,
+ agentDir: harness.tempDir,
+ ...(options.sessionDir ? { sessionDir: options.sessionDir } : {}),
+ },
+ ...(options.worker ? { worker: { authenticationToken: "token" } } : {}),
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ return daemon as unknown as AgentDaemonUpdateInternals;
+}
+
+function createWriteClient(writes: string[], options: { id?: string; attached?: string[] } = {}): DaemonSocketClient {
+ return {
+ id: options.id ?? "client-1",
+ socket: {
+ destroyed: false,
+ write: vi.fn((chunk: string) => {
+ writes.push(chunk);
+ return true;
+ }),
+ } as unknown as DaemonSocketClient["socket"],
+ attachedActiveSessionIds: new Set(options.attached ?? []),
+ detachInput: vi.fn(),
+ supportsExtensionUi: false,
+ capabilities: new Set(),
+ } as DaemonSocketClient;
+}
+
function hasArchivedState(harness: Harness): boolean {
return harness.sessionManager
.getEntries()
@@ -119,6 +180,386 @@ describe("issue #4257 update restart resume", () => {
}
});
+ it.each([
+ [undefined, "shutdown"],
+ ["preparing", "shutdown"],
+ ["fencing", "shutdown"],
+ ["prepared", "shutdown"],
+ ["publishing", "update"],
+ ] as const)("uses %s restart phase as %s shutdown", async (phase, expected) => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ const internals = createDaemonInternals(harness);
+ if (phase) {
+ internals.updateRestart = {
+ id: Symbol("update-restart"),
+ abort: new AbortController(),
+ phase,
+ deferredClientEnv: [],
+ };
+ }
+
+ expect(internals.getShutdownClosingReason()).toBe(expected);
+ });
+
+ it("waits for the admitted prompt event checkpoint before preparing restart", async () => {
+ let releaseAssistantMessageEnd: (() => void) | undefined;
+ const assistantMessageEndBlocked = new Promise<void>((resolve) => {
+ releaseAssistantMessageEnd = resolve;
+ });
+ const harness = await createHarness({
+ persistSession: true,
+ extensionFactories: [
+ (pi) => {
+ pi.on("message_end", async (event) => {
+ if (event.message.role === "assistant") {
+ await assistantMessageEndBlocked;
+ }
+ });
+ },
+ ],
+ });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("restart response")]);
+ let promptAdmitted = false;
+ const originalPrompt = harness.session.agent.prompt.bind(harness.session.agent);
+ vi.spyOn(harness.session.agent, "prompt").mockImplementation((...args) => {
+ promptAdmitted = true;
+ return originalPrompt(...args);
+ });
+ await harness.session.restoreFollowUpMessage("admitted restart input");
+ expect(harness.session.resumeQueuedWork()).toBe(true);
+ await vi.waitFor(() => expect(promptAdmitted).toBe(true));
+
+ const internals = createDaemonInternals(harness);
+ internals.sessions.set(
+ "active-1",
+ createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
+ );
+ let checkpointWaitEntered = false;
+ const originalCheckpointWait = harness.session.waitForSessionInputCheckpoint.bind(harness.session);
+ vi.spyOn(harness.session, "waitForSessionInputCheckpoint").mockImplementation((signal) => {
+ checkpointWaitEntered = true;
+ return originalCheckpointWait(signal);
+ });
+ let prepareSettled = false;
+ const prepare = internals.prepareUpdateRestart().then((manifest) => {
+ prepareSettled = true;
+ return manifest;
+ });
+ await vi.waitFor(() => expect(checkpointWaitEntered).toBe(true));
+ await harness.session.restoreFollowUpMessage("paused restart input");
+ await vi.waitFor(() =>
+ expect(
+ harness.sessionManager
+ .getEntries()
+ .some(
+ (entry) =>
+ entry.type === "message" &&
+ entry.message.role === "user" &&
+ getMessageText(entry.message) === "admitted restart input",
+ ),
+ ).toBe(true),
+ );
+ expect(prepareSettled).toBe(false);
+
+ releaseAssistantMessageEnd?.();
+ const manifest = await prepare;
+
+ expect(manifest.sessions).toHaveLength(1);
+ expect(manifest.sessions[0]).toMatchObject({
+ queue: { steering: [], nextTurn: [] },
+ 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(
+ harness.sessionManager
+ .getEntries()
+ .some(
+ (entry) =>
+ entry.type === "message" &&
+ entry.message.role === "assistant" &&
+ getMessageText(entry.message) === "restart response",
+ ),
+ ).toBe(true);
+ });
+
+ it.each([
+ { name: "worker cancel releases a prepare blocked on an executing mutation", release: "cancel" },
+ { name: "standalone prepare waits for an executing daemon mutation", release: "drain" },
+ ] as const)("$name", async ({ release }) => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ const internals = createDaemonInternals(harness, { worker: true });
+ internals.mutationDrain.begin();
+ const writes: string[] = [];
+ const client = {
+ id: "supervisor",
+ socket: {
+ destroyed: false,
+ write: (chunk: string) => {
+ writes.push(chunk);
+ return true;
+ },
+ },
+ } as unknown as DaemonSocketClient;
+
+ if (release === "cancel") {
+ const prepare = internals.handleWorkerCommand(client, { id: "prepare", type: "worker_prepare_update" });
+ await vi.waitFor(() => expect(internals.updateRestart).toBeDefined());
+ await internals.handleWorkerCommand(client, { id: "cancel", type: "worker_cancel_update" });
+ await prepare;
+
+ expect(internals.updateRestart).toBeUndefined();
+ expect(writes.join(" ")).toContain("Update restart preparation cancelled");
+ expect(writes.join(" ")).toContain('"command":"worker_cancel_update","success":true');
+ return;
+ }
+ let settled = false;
+ const prepare = internals.prepareUpdateRestart().then((manifest) => {
+ settled = true;
+ return manifest;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+
+ internals.mutationDrain.end();
+ await prepare;
+ expect(settled).toBe(true);
+ });
+
+ it("fences and drains a mutation admitted at the first drain boundary before checkpointing", async () => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ const internals = createDaemonInternals(harness);
+ const mutationDrain = new MutationDrainLatch();
+ const transaction = {
+ id: Symbol("update-restart"),
+ abort: new AbortController(),
+ phase: "preparing" as const,
+ deferredClientEnv: [],
+ };
+ internals.updateRestart = transaction;
+ const firstDrain = createDeferred();
+ const originalWaitForDrain = mutationDrain.waitForDrain.bind(mutationDrain);
+ vi.spyOn(mutationDrain, "waitForDrain").mockImplementationOnce(async (...args) => {
+ await originalWaitForDrain(...args);
+ mutationDrain.begin();
+ firstDrain.resolve();
+ });
+ Reflect.set(internals, "mutationDrain", mutationDrain);
+ const checkpoint = vi.spyOn(internals, "prepareUpdateRestartCheckpoint").mockResolvedValue({
+ createdAt: "now",
+ sessions: [],
+ });
+
+ const prepare = internals.runUpdateRestartPreparation(transaction);
+ await firstDrain.promise;
+ await Promise.resolve();
+
+ expect(internals.updateRestart?.phase).toBe("fencing");
+ expect(checkpoint).not.toHaveBeenCalled();
+
+ mutationDrain.end();
+ await prepare;
+ expect(checkpoint).toHaveBeenCalledOnce();
+ });
+
+ it("waits for an already-claimed one-shot dispatch and runs it exactly once", async () => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("scheduled response")]);
+ const promptSpy = vi.spyOn(harness.session, "promptUntilAccepted");
+ const state = createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() });
+ const internals = createDaemonInternals(harness);
+ internals.sessions.set(state.activeSessionId, state);
+ const now = new Date("2026-01-01T12:00:00.000Z");
+ const job = internals.cronStore.create({
+ activeSessionId: state.activeSessionId,
+ sessionId: harness.session.sessionId,
+ sessionFile: harness.session.sessionFile ?? "",
+ cwd: harness.tempDir,
+ scheduleText: "in 1m",
+ prompt: "claimed before restart",
+ now,
+ });
+ let markDispatchReached = () => {};
+ const dispatchReached = new Promise<void>((resolve) => {
+ markDispatchReached = resolve;
+ });
+ let releaseDispatch = () => {};
+ const dispatchGate = new Promise<void>((resolve) => {
+ releaseDispatch = resolve;
+ });
+ const originalRunCronJob = internals.runCronJob.bind(internals);
+ let runResult: "skipped" | undefined;
+ vi.spyOn(internals, "runCronJob").mockImplementation(async (claimedJob) => {
+ markDispatchReached();
+ await dispatchGate;
+ runResult = await originalRunCronJob(claimedJob);
+ return runResult;
+ });
+
+ const dispatch = internals.cronScheduler.runDue(new Date("2026-01-01T12:01:00.000Z"));
+ await dispatchReached;
+ let prepareSettled = false;
+ const prepare = internals.prepareUpdateRestart().then((manifest) => {
+ prepareSettled = true;
+ return manifest;
+ });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(prepareSettled).toBe(false);
+
+ releaseDispatch();
+ await dispatch;
+ await prepare;
+ expect(runResult).toBeUndefined();
+ expect(promptSpy).toHaveBeenCalledOnce();
+ expect(promptSpy).toHaveBeenCalledWith(
+ "claimed before restart",
+ expect.objectContaining({ streamingBehavior: "followUp", source: "rpc" }),
+ );
+ expect(internals.cronStore.list().find((candidate) => candidate.id === job.id)).toMatchObject({
+ status: "completed",
+ runCount: 1,
+ });
+ });
+
+ type OwnershipContext = {
+ internals: AgentDaemonUpdateInternals;
+ makeClient: (id: string) => DaemonSocketClient;
+ writes: string[];
+ };
+
+ it.each<{ name: string; run: (context: OwnershipContext) => Promise<void> }>([
+ ...(["worker_commit_update", "worker_cancel_update"] as const).map((type) => ({
+ name: `rejects ${type} from a different prepare owner`,
+ run: async ({ internals, makeClient, writes }: OwnershipContext) => {
+ const owner = makeClient("owner");
+ await internals.handleWorkerCommand(owner, { id: "prepare", type: "worker_prepare_update" });
+ await internals.handleWorkerCommand(makeClient("other"), { id: "foreign", type });
+ expect(writes.at(-1)).toContain("belongs to another supervisor");
+ expect(internals.updateRestart?.phase).toBe("prepared");
+ await internals.handleWorkerCommand(owner, { id: "cleanup", type: "worker_cancel_update" });
+ },
+ })),
+ {
+ name: "rejects a duplicate worker commit while publishing",
+ run: async ({ internals, makeClient, writes }) => {
+ const owner = makeClient("owner");
+ await internals.handleWorkerCommand(owner, { id: "prepare", type: "worker_prepare_update" });
+ const transaction = internals.updateRestart;
+ expect(transaction).toBeDefined();
+ transaction!.phase = "publishing";
+
+ await internals.handleWorkerCommand(owner, { id: "duplicate", type: "worker_commit_update" });
+
+ expect(writes.at(-1)).toContain("already committing");
+ transaction!.phase = "prepared";
+ internals.cancelPreparedUpdateRestart(transaction?.id);
+ },
+ },
+ {
+ name: "finishes cancelled transaction cleanup after a failed publish",
+ run: async ({ internals, makeClient }) => {
+ const owner = makeClient("owner");
+ await internals.handleWorkerCommand(owner, { id: "prepare", type: "worker_prepare_update" });
+ const transaction = internals.updateRestart;
+ expect(transaction).toBeDefined();
+ vi.spyOn(internals, "commitPreparedUpdateRestart").mockImplementationOnce(async () => {
+ internals.cancelPreparedUpdateRestart(transaction?.id);
+ throw new Error("publish failed");
+ });
+
+ await internals.handleWorkerCommand(owner, { id: "commit", type: "worker_commit_update" });
+
+ expect(internals.updateRestart).toBeUndefined();
+ },
+ },
+ {
+ name: "finishes publishing then exits when its owning supervisor is replaced",
+ run: async ({ internals, makeClient }) => {
+ const owner = makeClient("owner");
+ internals.supervisorClaims.set(owner, {});
+ await internals.handleWorkerCommand(owner, { id: "prepare", type: "worker_prepare_update" });
+ const transaction = internals.updateRestart;
+ expect(transaction).toBeDefined();
+ const publish = createDeferred<DaemonUpdateRestartManifest>();
+ vi.spyOn(internals, "commitPreparedUpdateRestart").mockImplementationOnce(() => publish.promise);
+ const shutdown = vi.spyOn(internals, "shutdown").mockImplementation(() => new Promise<never>(() => {}));
+
+ const commit = internals.handleWorkerCommand(owner, { id: "commit", type: "worker_commit_update" });
+ await vi.waitFor(() => expect(transaction?.phase).toBe("publishing"));
+ internals.revokeSupervisorClaim(owner);
+ expect(transaction?.phase).toBe("publishing");
+ publish.resolve(transaction!.manifest!);
+ await commit;
+ await new Promise<void>((resolve) => setImmediate(resolve));
+
+ expect(shutdown).toHaveBeenCalledWith(0);
+ },
+ },
+ {
+ name: "does not let stale standalone cleanup clear a newer publishing owner",
+ run: async ({ internals }) => {
+ const newerTransaction = {
+ id: Symbol("newer-update-restart"),
+ abort: new AbortController(),
+ phase: "publishing" as const,
+ deferredClientEnv: [],
+ };
+ vi.spyOn(internals, "commitPreparedUpdateRestart").mockImplementationOnce(async () => {
+ internals.updateRestart = newerTransaction;
+ throw new Error("stale publish failed");
+ });
+
+ await expect(internals.prepareUpdateRestart()).rejects.toThrow("stale publish failed");
+
+ expect(internals.updateRestart).toBe(newerTransaction);
+ },
+ },
+ {
+ name: "rejects drain mutations but admits reads after this worker publishes its prepare snapshot",
+ run: async ({ internals, makeClient, writes }) => {
+ const owner = makeClient("owner");
+ await internals.handleWorkerCommand(owner, { id: "prepare", type: "worker_prepare_update" });
+ await internals.handleLine(
+ owner,
+ JSON.stringify({ id: "abort", type: "abort", activeSessionId: "missing" }),
+ );
+ expect(writes.at(-1)).toContain("Daemon is preparing an update restart");
+ await internals.handleLine(owner, JSON.stringify({ id: "late-list", type: "list" }));
+ expect(JSON.parse(writes.at(-1) ?? "{}")).toMatchObject({ id: "late-list", success: true });
+ await internals.handleWorkerCommand(owner, { id: "cancel", type: "worker_cancel_update" });
+ },
+ },
+ ])("$name", async ({ run }) => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ const internals = createDaemonInternals(harness);
+ const writes: string[] = [];
+ const makeClient = (id: string) =>
+ ({
+ id,
+ socket: {
+ destroyed: false,
+ write: (chunk: string) => {
+ writes.push(chunk);
+ return true;
+ },
+ },
+ }) as unknown as DaemonSocketClient;
+ await run({ internals, makeClient, writes });
+ });
+
it("captures a restart manifest and aborts running bash without archiving the session", async () => {
const harness = await createHarness({ persistSession: true });
harnesses.push(harness);
@@ -160,13 +601,7 @@ describe("issue #4257 update restart resume", () => {
},
},
);
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(state.activeSessionId, state);
const schedulerStopSpy = vi.spyOn(internals.cronScheduler, "stop");
const now = new Date("2026-01-01T12:00:00.000Z");
@@ -275,20 +710,7 @@ describe("issue #4257 update restart resume", () => {
await internals.prepareUpdateRestart();
const writes: string[] = [];
- const client: DaemonSocketClient = {
- id: "client-1",
- socket: {
- destroyed: false,
- write: vi.fn((chunk: string) => {
- writes.push(chunk);
- return true;
- }),
- } as unknown as DaemonSocketClient["socket"],
- attachedActiveSessionIds: new Set(),
- detachInput: vi.fn(),
- supportsExtensionUi: false,
- capabilities: new Set(),
- };
+ const client = createWriteClient(writes);
await internals.handleLine(client, JSON.stringify({ id: "late-create", type: "create" }));
@@ -309,41 +731,31 @@ describe("issue #4257 update restart resume", () => {
const image: ImageContent = { type: "image", data: "ZmFrZQ==", mimeType: "image/png" };
const content: (TextContent | ImageContent)[] = [{ type: "text", text: "queued work" }, image];
const queuedContext = createCustomMessage("queued context");
- const message: UserMessage = { role: "user", content, timestamp: Date.now() };
const followUpContent: TextContent[] = [{ type: "text", text: "heartbeat" }];
const followUpContext = createCustomMessage("follow-up context");
- const followUpMessage: UserMessage = {
- role: "user",
- content: followUpContent,
- timestamp: Date.now(),
- };
const customFollowUp = createCustomMessage("custom heartbeat");
- const queueInternals = parentHarness.session as unknown as QueueInternals;
- queueInternals._steeringMessages = [
- {
- text: "queued work",
- queueKey: "heartbeat:steer",
- agentMessageId: "agentmsg_steer",
- prefixMessages: [queuedContext],
- message,
- },
- ];
- queueInternals._followUpMessages = [
- {
- text: "heartbeat",
- queueKey: "heartbeat:job-1",
- agentMessageId: "agentmsg_followup",
- prefixMessages: [followUpContext],
- message: followUpMessage,
- },
- {
- text: "custom heartbeat",
- queueKey: "heartbeat:custom",
- agentMessageId: "agentmsg_custom",
- prefixMessages: [],
- message: customFollowUp,
- },
- ];
+ await parentHarness.session.restoreSteeringMessage("queued work", [image], {
+ queueKey: "heartbeat:steer",
+ agentMessageId: "agentmsg_steer",
+ content,
+ prefixMessages: [queuedContext],
+ });
+ await parentHarness.session.restoreFollowUpMessage("heartbeat", undefined, {
+ queueKey: "heartbeat:job-1",
+ agentMessageId: "agentmsg_followup",
+ content: followUpContent,
+ prefixMessages: [followUpContext],
+ });
+ await parentHarness.session.restoreFollowUpMessage("custom heartbeat", undefined, {
+ queueKey: "heartbeat:custom",
+ agentMessageId: "agentmsg_custom",
+ customMessage: customFollowUp,
+ });
+ const command = parseSessionSlashCommand("/autonomous on");
+ const commandMessage = createSessionSlashCommandMessage(command!);
+ await parentHarness.session.restoreFollowUpMessage("/autonomous on", undefined, {
+ customMessage: commandMessage,
+ });
childHarness.session.recordBashResult("echo child", {
output: "child",
exitCode: 0,
@@ -351,13 +763,7 @@ describe("issue #4257 update restart resume", () => {
truncated: false,
});
- const daemon = new AgentDaemon(`${parentHarness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: parentHarness.tempDir, agentDir: parentHarness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(parentHarness);
internals.sessions.set(
"parent-active",
createState(
@@ -412,6 +818,13 @@ describe("issue #4257 update restart resume", () => {
agentMessageId: "agentmsg_custom",
customMessage: customFollowUp,
},
+ {
+ message: "/autonomous on",
+ customMessage: expect.objectContaining({
+ customType: "session_slash_command",
+ details: { command },
+ }),
+ },
],
},
shouldResume: true,
@@ -450,7 +863,7 @@ describe("issue #4257 update restart resume", () => {
timestamp: Date.now(),
};
const queueInternals = harness.session as unknown as QueueInternals;
- queueInternals._pendingNextTurnMessages = [pendingNextTurn];
+ harness.session.restorePendingNextTurnMessages([pendingNextTurn]);
queueInternals._acceptedAgentMessagePrompt = {
text: "accepted work",
agentMessageId: "agentmsg_accepted",
@@ -465,13 +878,7 @@ describe("issue #4257 update restart resume", () => {
cleared: false,
};
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
@@ -502,25 +909,14 @@ describe("issue #4257 update restart resume", () => {
{ type: "text", text: "queued context" },
{ type: "text", text: "queued follow-up" },
];
- const queueInternals = harness.session as unknown as QueueInternals;
- queueInternals._followUpMessages = [
- {
- text: "queued follow-up",
- queueKey: "heartbeat:job-1",
- agentMessageId: "agentmsg_followup",
- prefixMessages: [],
- message: { role: "user", content: followUpContent, timestamp: Date.now() },
- },
- ];
+ await harness.session.restoreFollowUpMessage("queued follow-up", undefined, {
+ queueKey: "heartbeat:job-1",
+ agentMessageId: "agentmsg_followup",
+ content: followUpContent,
+ });
const sessionDir = `${harness.tempDir}/sessions`;
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir, sessionDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness, { sessionDir });
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
@@ -547,16 +943,10 @@ describe("issue #4257 update restart resume", () => {
it("materializes busy in-memory drafts before update restart", async () => {
const harness = await createHarness({ persistSession: false });
harnesses.push(harness);
- (harness.session.agent as unknown as AgentInternals)._state.isStreaming = true;
+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;
const sessionDir = `${harness.tempDir}/sessions`;
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir, sessionDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness, { sessionDir });
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
@@ -588,7 +978,7 @@ describe("issue #4257 update restart resume", () => {
timestamp: Date.now(),
};
const queueInternals = harness.session as unknown as QueueInternals;
- queueInternals._pendingNextTurnMessages = [pendingNextTurn];
+ harness.session.restorePendingNextTurnMessages([pendingNextTurn]);
queueInternals._acceptedAgentMessagePrompt = {
text: "accepted work",
agentMessageId: "agentmsg_accepted",
@@ -603,13 +993,7 @@ describe("issue #4257 update restart resume", () => {
cleared: false,
};
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
@@ -631,33 +1015,14 @@ describe("issue #4257 update restart resume", () => {
const harness = await createHarness({ persistSession: true });
harnesses.push(harness);
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
);
const writes: string[] = [];
- const client: DaemonSocketClient = {
- id: "client-1",
- socket: {
- destroyed: false,
- write: vi.fn((chunk: string) => {
- writes.push(chunk);
- return true;
- }),
- } as unknown as DaemonSocketClient["socket"],
- attachedActiveSessionIds: new Set(["active-1"]),
- detachInput: vi.fn(),
- supportsExtensionUi: false,
- capabilities: new Set(),
- };
+ const client = createWriteClient(writes, { attached: ["active-1"] });
const restoredMessage = createCustomMessage("restored next turn");
await internals.handleLine(
@@ -684,13 +1049,7 @@ describe("issue #4257 update restart resume", () => {
harnesses.push(harness);
harness.setResponses([fauxAssistantMessage("accepted restored prompt")]);
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
@@ -701,20 +1060,7 @@ describe("issue #4257 update restart resume", () => {
{ type: "text", text: "accepted work" },
];
const writes: string[] = [];
- const client: DaemonSocketClient = {
- id: "client-1",
- socket: {
- destroyed: false,
- write: vi.fn((chunk: string) => {
- writes.push(chunk);
- return true;
- }),
- } as unknown as DaemonSocketClient["socket"],
- attachedActiveSessionIds: new Set(["active-1"]),
- detachInput: vi.fn(),
- supportsExtensionUi: false,
- capabilities: new Set(),
- };
+ const client = createWriteClient(writes, { attached: ["active-1"] });
await internals.handleLine(
client,
@@ -745,19 +1091,12 @@ describe("issue #4257 update restart resume", () => {
const harness = await createHarness({ persistSession: true });
harnesses.push(harness);
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
);
- const queueInternals = harness.session as unknown as QueueInternals;
const restoredSteerContent: TextContent[] = [
{ type: "text", text: "restored steer context" },
{ type: "text", text: "restored steer" },
@@ -767,30 +1106,12 @@ describe("issue #4257 update restart resume", () => {
{ type: "text", text: "restored follow-up" },
];
const restoredPrefix = createCustomMessage("restored custom prefix");
- queueInternals._followUpMessages = [
- {
- text: "existing",
- queueKey: "heartbeat:job-1",
- agentMessageId: "agentmsg_existing",
- prefixMessages: [],
- message: { role: "user", content: [{ type: "text", text: "existing" }], timestamp: Date.now() },
- },
- ];
+ await harness.session.restoreFollowUpMessage("existing", undefined, {
+ queueKey: "heartbeat:job-1",
+ agentMessageId: "agentmsg_existing",
+ });
const writes: string[] = [];
- const client: DaemonSocketClient = {
- id: "client-1",
- socket: {
- destroyed: false,
- write: vi.fn((chunk: string) => {
- writes.push(chunk);
- return true;
- }),
- } as unknown as DaemonSocketClient["socket"],
- attachedActiveSessionIds: new Set(["active-1"]),
- detachInput: vi.fn(),
- supportsExtensionUi: false,
- capabilities: new Set(),
- };
+ const client = createWriteClient(writes, { attached: ["active-1"] });
await internals.handleLine(
client,
@@ -872,32 +1193,13 @@ describe("issue #4257 update restart resume", () => {
]);
await harness.session.prompt("start");
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
);
const writes: string[] = [];
- const client: DaemonSocketClient = {
- id: "client-1",
- socket: {
- destroyed: false,
- write: vi.fn((chunk: string) => {
- writes.push(chunk);
- return true;
- }),
- } as unknown as DaemonSocketClient["socket"],
- attachedActiveSessionIds: new Set(["active-1"]),
- detachInput: vi.fn(),
- supportsExtensionUi: false,
- capabilities: new Set(),
- };
+ const client = createWriteClient(writes, { attached: ["active-1"] });
await internals.handleLine(
client,
@@ -963,32 +1265,13 @@ describe("issue #4257 update restart resume", () => {
harness.setResponses([fauxAssistantMessage("handled continuation"), fauxAssistantMessage("handled follow-up")]);
harness.session.agent.state.messages.push(createCustomMessage("update interrupted"));
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
);
const writes: string[] = [];
- const client: DaemonSocketClient = {
- id: "client-1",
- socket: {
- destroyed: false,
- write: vi.fn((chunk: string) => {
- writes.push(chunk);
- return true;
- }),
- } as unknown as DaemonSocketClient["socket"],
- attachedActiveSessionIds: new Set(["active-1"]),
- detachInput: vi.fn(),
- supportsExtensionUi: false,
- capabilities: new Set(),
- };
+ const client = createWriteClient(writes, { attached: ["active-1"] });
await internals.handleLine(
client,
@@ -1021,8 +1304,10 @@ describe("issue #4257 update restart resume", () => {
}),
);
- await new Promise((resolve) => setTimeout(resolve, 0));
- await harness.session.agent.waitForIdle();
+ await vi.waitFor(() =>
+ expect(getUserTexts(harness)).toEqual(["restored steer", "restored follow-up", "continue interrupted work"]),
+ );
+ await harness.session.waitForSessionInputIdle();
const responses = writes
.join("")
@@ -1034,7 +1319,7 @@ describe("issue #4257 update restart resume", () => {
expect.objectContaining({ id: "follow-up-1", command: "follow_up", success: true }),
expect.objectContaining({ id: "prompt-1", command: "prompt", success: true }),
]);
- expect(getUserTexts(harness)).toEqual(["continue interrupted work", "restored steer", "restored follow-up"]);
+ expect(getUserTexts(harness)).toEqual(["restored steer", "restored follow-up", "continue interrupted work"]);
expect(harness.session.getSteeringQueueSnapshots()).toEqual([]);
expect(harness.session.getFollowUpQueueSnapshots()).toEqual([]);
});
@@ -1045,32 +1330,13 @@ describe("issue #4257 update restart resume", () => {
harness.setResponses([fauxAssistantMessage("handled restored follow-up")]);
harness.session.agent.state.messages.push(createCustomMessage("update interrupted"));
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
);
const writes: string[] = [];
- const client: DaemonSocketClient = {
- id: "client-1",
- socket: {
- destroyed: false,
- write: vi.fn((chunk: string) => {
- writes.push(chunk);
- return true;
- }),
- } as unknown as DaemonSocketClient["socket"],
- attachedActiveSessionIds: new Set(["active-1"]),
- detachInput: vi.fn(),
- supportsExtensionUi: false,
- capabilities: new Set(),
- };
+ const client = createWriteClient(writes, { attached: ["active-1"] });
await internals.handleLine(
client,
@@ -1107,36 +1373,46 @@ describe("issue #4257 update restart resume", () => {
expect(harness.session.getFollowUpQueueSnapshots()).toEqual([]);
});
+ it("adopts attach env after a fenced update preparation rolls back", async () => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ const internals = createDaemonInternals(harness);
+ const state = createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() });
+ internals.sessions.set(state.activeSessionId, state);
+ const transaction = internals.beginUpdateRestartTransaction();
+ transaction.phase = "fencing";
+ const writes: string[] = [];
+ const client = createWriteClient(writes);
+
+ await internals.handleLine(
+ client,
+ JSON.stringify({
+ id: "attach-1",
+ type: "attach",
+ activeSessionId: state.activeSessionId,
+ env: { HERDR_PANE_ID: "w1:p1", PATH: "/ignored" },
+ }),
+ );
+
+ expect(state.clientEnv).toBeUndefined();
+ expect(state.clients.has(client)).toBe(true);
+ expect(transaction.deferredClientEnv).toHaveLength(1);
+ internals.cancelPreparedUpdateRestart(transaction.id);
+ expect(state.clientEnv).toEqual({ HERDR_PANE_ID: "w1:p1" });
+ expect(transaction.deferredClientEnv).toEqual([]);
+ });
+
it("reports resume_queue failure when no work can resume", async () => {
const harness = await createHarness({ persistSession: true });
harnesses.push(harness);
- const daemon = new AgentDaemon(`${harness.tempDir}/daemon.sock`, {
- defaultSessionConfig: { cwd: harness.tempDir, agentDir: harness.tempDir },
- createRuntime: async () => {
- throw new Error("unexpected runtime creation");
- },
- });
- const internals = daemon as unknown as AgentDaemonUpdateInternals;
+ const internals = createDaemonInternals(harness);
internals.sessions.set(
"active-1",
createState(harness, "active-1", { kind: "top-level", createdAt: Date.now() }),
);
const writes: string[] = [];
- const client: DaemonSocketClient = {
- id: "client-1",
- socket: {
- destroyed: false,
- write: vi.fn((chunk: string) => {
- writes.push(chunk);
- return true;
- }),
- } as unknown as DaemonSocketClient["socket"],
- attachedActiveSessionIds: new Set(["active-1"]),
- detachInput: vi.fn(),
- supportsExtensionUi: false,
- capabilities: new Set(),
- };
+ const client = createWriteClient(writes, { attached: ["active-1"] });
await internals.handleLine(
client,
@@ -1150,6 +1426,6 @@ describe("issue #4257 update restart resume", () => {
const response = JSON.parse(writes.join("").trim());
expect(response).toMatchObject({ id: "resume-1", command: "resume_queue", success: false });
- expect(JSON.stringify(response)).toContain("No messages to continue from");
+ expect(JSON.stringify(response)).toContain("No queued work to resume");
});
});
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 7eb1f98d09..7f2d173c2a 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
@@ -178,14 +178,14 @@ describe("ENG-4482 heartbeat injected prompt UI", () => {
it("resets overflow recovery state when heartbeat prompt turns start", async () => {
const harness = await createHarness();
harnesses.push(harness);
- const sessionInternals = harness.session as unknown as { _overflowRecoveryAttempted: boolean };
- sessionInternals._overflowRecoveryAttempted = true;
+ const sessionInternals = harness.session as unknown as { _overflowRecovery: string };
+ sessionInternals._overflowRecovery = "attempted";
harness.setResponses([fauxAssistantMessage("heartbeat handled")]);
await harness.session.promptHeartbeat(createHeartbeat());
await harness.session.agent.waitForIdle();
- expect(sessionInternals._overflowRecoveryAttempted).toBe(false);
+ expect(sessionInternals._overflowRecovery).toBe("idle");
});
it("keeps pending nextTurn context separate from queued heartbeat prompts", async () => {
@@ -303,7 +303,21 @@ describe("ENG-4482 heartbeat injected prompt UI", () => {
await harness.session.promptHeartbeat(createHeartbeat(), { streamingBehavior: "followUp" });
expect(harness.session.getFollowUpMessagePreviews()).toEqual([heartbeatPreview]);
- expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: [heartbeatText] });
+ const internals = harness.session as unknown as {
+ _activeSessionInput: {
+ kind: "prompt";
+ lane: "followUp";
+ phase: "preparing";
+ items: Array<{ text: string }>;
+ };
+ };
+ internals._activeSessionInput = {
+ kind: "prompt",
+ lane: "followUp",
+ phase: "preparing",
+ items: [{ text: "preparing" }],
+ };
+ expect(harness.session.clearQueue()).toEqual({ steering: [], followUp: ["preparing", heartbeatText] });
releaseToolExecution?.();
await promptPromise;
diff --git a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
index a35e69e39d..ea7be4c5dc 100644
--- a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
@@ -379,7 +379,7 @@ describe("ENG-4509 side questions", () => {
const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
defaultEditor,
- editor: { setText, addToHistory },
+ editor: { getText: () => "", setText, addToHistory },
promptStashState: { stash: undefined },
clearShortcutGuide: vi.fn(),
sideQuestionComponent: {},
@@ -406,7 +406,7 @@ describe("ENG-4509 side questions", () => {
const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
defaultEditor,
- editor: { setText: vi.fn(), addToHistory },
+ editor: { getText: () => "", setText: vi.fn(), addToHistory },
promptStashState: { stash: undefined },
clearShortcutGuide: vi.fn(),
sideQuestionComponent: {},
@@ -441,7 +441,7 @@ describe("ENG-4509 side questions", () => {
const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
defaultEditor,
- editor: { setText: vi.fn(), addToHistory: vi.fn() },
+ editor: { getText: () => "", setText: vi.fn(), addToHistory: vi.fn() },
promptStashState: { stash: undefined },
clearShortcutGuide: vi.fn(),
sideQuestionComponent: { addTurn },
@@ -482,7 +482,7 @@ describe("ENG-4509 side questions", () => {
const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
defaultEditor,
- editor: { setText: vi.fn(), addToHistory: vi.fn() },
+ editor: { getText: () => "", setText: vi.fn(), addToHistory: vi.fn() },
promptStashState: { stash: undefined },
clearShortcutGuide: vi.fn(),
sideQuestionComponent: { finishBash },
@@ -628,7 +628,7 @@ describe("ENG-4509 side questions", () => {
const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
defaultEditor,
- editor: { setText, addToHistory: vi.fn() },
+ editor: { getText: () => "", setText, addToHistory: vi.fn() },
promptStashState: { stash: undefined },
clearShortcutGuide: vi.fn(),
sideQuestionComponent: { addTurn },
@@ -659,7 +659,7 @@ describe("ENG-4509 side questions", () => {
const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
defaultEditor,
- editor: { setText, addToHistory: vi.fn() },
+ editor: { getText: () => "", setText, addToHistory: vi.fn() },
promptStashState: { stash: undefined },
clearShortcutGuide: vi.fn(),
sideQuestionComponent: {},
@@ -688,7 +688,7 @@ describe("ENG-4509 side questions", () => {
const defaultEditor: { onSubmit?: (text: string) => Promise<void> } = {};
const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
defaultEditor,
- editor: { setText, addToHistory: vi.fn() },
+ editor: { getText: () => "", setText, addToHistory: vi.fn() },
promptStashState: { stash: undefined },
clearShortcutGuide: vi.fn(),
sideQuestionComponent: { addTurn },
@@ -786,7 +786,7 @@ describe("ENG-4509 side questions", () => {
const chatContainer = new Container();
const fakeThis = Object.assign(Object.create(InteractiveMode.prototype), {
defaultEditor,
- editor: { setText: vi.fn(), addToHistory: vi.fn() },
+ editor: { getText: () => "", setText: vi.fn(), addToHistory: vi.fn() },
promptStashState: { stash: undefined },
clearShortcutGuide: vi.fn(),
sideQuestionComponent: { addBash, finishBash },
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 69c1cd1acc..af90265b0c 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
@@ -1,4 +1,4 @@
-import type { AgentMessage, AgentTool } from "@earendil-works/pi-agent-core";
+import type { AgentTool } from "@earendil-works/pi-agent-core";
import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
import { Type } from "typebox";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
@@ -19,11 +19,6 @@ type StateRestoreHost = {
_onIpythonStateRestored(result: RestoreResult): void;
};
-type QueueDrainHost = {
- _followUpMessages: Array<{ prefixMessages: CustomMessage[]; message: AgentMessage }>;
- _drainQueuedMessagesAfterBash(): Promise<void>;
-};
-
function stripAnsi(text: string): string {
return text.replace(/\u001b\[[0-9;]*m/g, "");
}
@@ -123,23 +118,7 @@ describe("ENG-4530 IPython state restore message", () => {
expect(render(component)).not.toContain("alpha");
});
- it("shows an accurate fixed label when restoration starts a fresh kernel", () => {
- const message: CustomMessage<IpythonStateRestoredDetails> = {
- role: "custom",
- customType: IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
- content: "restore details",
- display: true,
- details: { restored: false },
- timestamp: Date.now(),
- };
- const component = new InjectedPromptMessageComponent(message);
-
- expect(render(component)).toContain("◆ Started fresh IPython kernel");
- component.setExpanded(true);
- expect(render(component)).not.toContain("restore details");
- });
-
- it("does not requeue prefixes already delivered before a drain failure", async () => {
+ it("retries only undelivered input after partial scheduler delivery", async () => {
const harness = await createHarness();
harnesses.push(harness);
await harness.session.sendCustomMessage(
@@ -154,22 +133,37 @@ describe("ENG-4530 IPython state restore message", () => {
(harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;
await harness.session.prompt("queued prompt", { streamingBehavior: "followUp" });
(harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;
-
- const queueHost = harness.session as unknown as QueueDrainHost;
- const queued = queueHost._followUpMessages[0];
- const deliveredPrefix = queued?.prefixMessages[0];
- if (!queued || !deliveredPrefix) {
- throw new Error("Expected queued restore context");
- }
- vi.spyOn(harness.session.agent, "prompt").mockImplementation(async () => {
- harness.session.agent.state.messages.push(deliveredPrefix);
+ vi.spyOn(harness.session.agent, "prompt").mockImplementationOnce(async (messages) => {
+ const batch = Array.isArray(messages) ? messages : [messages];
+ harness.session.agent.state.messages.push(batch[0]);
+ harness.session.acquireQueuedWorkPause();
throw new Error("partial delivery failed");
});
- const followUp = vi.spyOn(harness.session.agent, "followUp");
- await queueHost._drainQueuedMessagesAfterBash();
+ harness.session.resumeQueuedWork();
+ await harness.session.waitForSessionInputIdle();
+
+ const [queued] = harness.session.getFollowUpQueueSnapshots();
+ expect(queued).toMatchObject({ text: "queued prompt" });
+ expect(queued?.prefixMessages).toBeUndefined();
+ expect(harness.session.messages).toEqual([
+ expect.objectContaining({ customType: IPYTHON_STATE_RESTORED_CUSTOM_TYPE }),
+ ]);
+ });
- expect(queued.prefixMessages).toEqual([]);
- expect(followUp).toHaveBeenCalledWith([queued.message]);
+ it("shows an accurate fixed label when restoration starts a fresh kernel", () => {
+ const message: CustomMessage<IpythonStateRestoredDetails> = {
+ role: "custom",
+ customType: IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
+ content: "restore details",
+ display: true,
+ details: { restored: false },
+ timestamp: Date.now(),
+ };
+ const component = new InjectedPromptMessageComponent(message);
+
+ expect(render(component)).toContain("◆ Started fresh IPython kernel");
+ component.setExpanded(true);
+ expect(render(component)).not.toContain("restore details");
});
});
diff --git a/packages/coding-agent/test/suite/regressions/4600-supervisor-singleton.test.ts b/packages/coding-agent/test/suite/regressions/4600-supervisor-singleton.test.ts
index 363e5ba989..3ea258b171 100644
--- a/packages/coding-agent/test/suite/regressions/4600-supervisor-singleton.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4600-supervisor-singleton.test.ts
@@ -90,6 +90,16 @@ afterEach(async () => {
await waitForExit(handle).catch(() => undefined);
}
}
+ // A worker or fixture can publish a replacement owner while the first cleanup
+ // sweep is stopping processes. Discover and stop that exact identity only after
+ // every tracked fixture handle has exited, before removing harness directories.
+ for (const registryDir of cleanupRegistryDirs) {
+ registerOwnerRecordsForCleanup(registryDir);
+ }
+ await cleanupRegisteredProcesses();
+ for (const registryDir of cleanupRegistryDirs) {
+ await removeDeadFixtureOwnerRecords(registryDir);
+ }
handles.clear();
cleanupProcesses.clear();
cleanupRegistryDirs.clear();
@@ -414,7 +424,7 @@ function cleanupProcessState(identity: CleanupProcessIdentity): "exited" | "matc
return observedStartId === identity.processStartId ? "matching" : "exited";
}
-function removeDeadFixtureOwnerRecords(registryDir: string): void {
+async function removeDeadFixtureOwnerRecords(registryDir: string): Promise<void> {
for (const owner of listOwnerRecords(registryDir)) {
if (!owner.processStartId) {
throw new Error(`Cannot clean owner ${owner.generation} without an exact process-start identity`);
@@ -424,11 +434,12 @@ function removeDeadFixtureOwnerRecords(registryDir: string): void {
processStartId: owner.processStartId,
label: `supervisor ${owner.generation}`,
};
- const state = cleanupProcessState(identity);
- if (state !== "exited") {
- throw new Error(
- `Refusing to clean ${identity.label} owner for ${identity.pid} (${identity.processStartId}): ${state}`,
- );
+ // A supervisor that just acknowledged shutdown can stay observable for a
+ // moment; wait for the exact identity to exit instead of refusing outright.
+ if (cleanupProcessState(identity) !== "exited") {
+ registerCleanupProcess(identity);
+ cleanupSupervisorSockets.add(owner.socketPath);
+ await cleanupRegisteredProcesses();
}
const current = readOwnerRecord(registryDir, owner.generation);
@@ -719,10 +730,13 @@ describe("ENG-4600 daemon supervisor ownership", () => {
client.close();
await waitForExit(legacyCleanup);
await waitForCleanupProcessExit(workerCleanupIdentity);
- await waitForCleanupProcessExit(successorCleanupIdentity);
+ // Under a fully loaded CI shard, the replacement supervisor can remain
+ // observable after shutdown longer than the helper's general cleanup bound.
+ // Extend only this exact generation/pid/process-start identity's polled wait.
+ await waitForCleanupProcessExit(successorCleanupIdentity, 60_000);
registerOwnerRecordsForCleanup(paths.registryDir);
await cleanupRegisteredProcesses(client);
- removeDeadFixtureOwnerRecords(paths.registryDir);
+ await removeDeadFixtureOwnerRecords(paths.registryDir);
expect(listOwnerRecords(paths.registryDir)).toEqual([]);
} finally {
await connection?.dispose().catch(() => undefined);
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 4beae8dc3f..12b0987706 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
@@ -129,7 +129,9 @@ async function waitForTerminalStatus(agentDir: string, timeoutMs = 120_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (existsSync(directory)) {
- for (const name of readdirSync(directory)) {
+ // The writer stages "<name>.json.<pid>.<uuid>.tmp" files in this directory
+ // before its atomic rename; parsing one mid-write reads torn JSON.
+ for (const name of readdirSync(directory).filter((entry) => entry.endsWith(".json"))) {
const path = join(directory, name);
const status = readDaemonUpdateRestartStatus(path);
if (status && (status.phase === "complete" || status.phase === "failed" || status.phase === "skipped")) {
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 8f28fc748c..3ed0e9b9b4 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
@@ -5,6 +5,7 @@ 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 { DaemonSupervisor } from "../../../src/modes/daemon/daemon-supervisor.js";
+import { MutationDrainLatch } from "../../../src/modes/daemon/mutation-drain-latch.js";
import { createHarness } from "../harness.js";
const fastModel = {
@@ -34,6 +35,7 @@ describe("ENG-4620 fast mode child agents", () => {
workers: new Map(),
clients: new Set(),
protocolClientIds: new WeakMap(),
+ mutationDrain: new MutationDrainLatch(),
handleCommand,
write,
log: vi.fn(),
@@ -48,7 +50,7 @@ describe("ENG-4620 fast mode child agents", () => {
await supervisor.handleLine(client, JSON.stringify(command));
- expect(handleCommand).toHaveBeenCalledWith(client, command);
+ expect(handleCommand.mock.calls[0]?.slice(0, 2)).toEqual([client, command]);
expect(write).toHaveBeenCalledWith(
client,
expect.objectContaining({ command: "set_service_tier", success: true }),
diff --git a/packages/coding-agent/test/suite/regressions/4685-daemon-client-modes.test.ts b/packages/coding-agent/test/suite/regressions/4685-daemon-client-modes.test.ts
index 65f6c1361f..a0da85d256 100644
--- a/packages/coding-agent/test/suite/regressions/4685-daemon-client-modes.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4685-daemon-client-modes.test.ts
@@ -75,6 +75,13 @@ async function runCli(
[ENV_AGENT_DIR]: options.agentDir,
PI_SKIP_VERSION_CHECK: "1",
PRIME_AGENT_INTERNAL_LEGACY_OWNED_WORKER_FRONTEND: "0",
+ PRIME_AGENT_INTERNAL_DAEMON_WORKER: undefined,
+ PRIME_AGENT_INTERNAL_DAEMON_WORKER_TOKEN: undefined,
+ PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID: undefined,
+ PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET: undefined,
+ PRIME_AGENT_INTERNAL_DAEMON_WORKER_RECOVERY_JOURNAL: undefined,
+ RLM_DEPTH: undefined,
+ RLM_MAX_DEPTH: undefined,
...options.environment,
},
stdio: ["pipe", "pipe", "pipe"],
diff --git a/packages/coding-agent/test/suite/scheduling.ts b/packages/coding-agent/test/suite/scheduling.ts
new file mode 100644
index 0000000000..7d6f8cf07a
--- /dev/null
+++ b/packages/coding-agent/test/suite/scheduling.ts
@@ -0,0 +1,100 @@
+import type { AgentTool } from "@earendil-works/pi-agent-core";
+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
+import { Type } from "typebox";
+import { createHarness, type Harness } from "./harness.js";
+
+/** A promise with its resolve/reject functions exposed. */
+export interface Deferred<T = void> {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+ reject: (error: Error) => void;
+}
+
+export function createDeferred<T = void>(): Deferred<T> {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+/**
+ * A before_agent_start gate as an extension factory: `reached` resolves when the
+ * hook first runs (optionally filtered by prompt), `release()` lets gated runs
+ * proceed, and `runs` records the prompts the hook observed.
+ */
+export function gatedHook(options: { prompt?: string } = {}): {
+ factory: (pi: ExtensionAPI) => void;
+ reached: Promise<void>;
+ release: () => void;
+ runs: string[];
+} {
+ const reached = createDeferred();
+ const gate = createDeferred();
+ const runs: string[] = [];
+ return {
+ factory: (pi) => {
+ pi.on("before_agent_start", async (event) => {
+ if (options.prompt !== undefined && event.prompt !== options.prompt) return;
+ runs.push(event.prompt);
+ reached.resolve();
+ await gate.promise;
+ });
+ },
+ reached: reached.promise,
+ release: gate.resolve,
+ runs,
+ };
+}
+
+/** Force the harness agent's streaming flag, replacing the `as { isStreaming: boolean }` cast idiom. */
+export function withStreaming(harness: Harness, on: boolean): void {
+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = on;
+}
+
+export interface WaitingHarness {
+ harness: Harness;
+ releaseToolExecution: () => void;
+ promptPromise: Promise<void>;
+ waitForToolStart: Promise<void>;
+}
+
+/**
+ * Harness whose first turn calls a gated "wait" tool: the run stays streaming
+ * until `releaseToolExecution()` is called, so tests can queue inputs mid-run.
+ */
+export async function createWaitingHarness(
+ options: { tools?: AgentTool[]; extensionFactories?: Array<(pi: ExtensionAPI) => void> } = {},
+): Promise<WaitingHarness> {
+ const toolRelease = createDeferred();
+ const waitTool: AgentTool = {
+ name: "wait",
+ label: "Wait",
+ description: "Wait for release",
+ parameters: Type.Object({}),
+ execute: async () => {
+ await toolRelease.promise;
+ return { content: [{ type: "text", text: "released" }], details: {} };
+ },
+ };
+ const harness = await createHarness({
+ tools: [waitTool, ...(options.tools ?? [])],
+ extensionFactories: options.extensionFactories,
+ });
+ const waitForToolStart = new Promise<void>((resolve) => {
+ const unsubscribe = harness.session.subscribe((event) => {
+ if (event.type === "tool_execution_start" && event.toolName === "wait") {
+ unsubscribe();
+ resolve();
+ }
+ });
+ });
+ return {
+ harness,
+ releaseToolExecution: toolRelease.resolve,
+ promptPromise: harness.session.prompt("start"),
+ waitForToolStart,
+ };
+}